I would not throw NullPointerException; it indicate that you are trying to use a variable which is null. Throw IllegalArgumentException instead; it indicated that arguments provided are not in a legal state.

And I personally don't like nesting too much loops and conditions. Try to separate them into smaller methods. When you put a block of code into a method, you are documenting it with the method name. Same applies for long conditions.

For example,

node.right != null && !stack.isEmpty() && node.right == stack.peek()

takes a while to "decipher". When you put it into the method isParentOfSubtree(...), it is obvious.

Also consider using some logger instead of System.out.


Recurse on complex Perl data structure, applying needed rules

Is there an obvious reason why you don't use a cross-sectional Path tracer?

For instance, with Data::Dpath, seems like it could do what you want without too much fuss.

Your complicated example is quite trivial to extract nodes by ORACLE_ID at arbitrary depths.

use strict;
use warnings;

use Data::DPath qw( dpath );
use Data::Dump qw( pp );

$ENV{ORACLE_SID} = 6;

my $struct = {
  a => {
    b => {
      c => {
        x => {
          y => {
            name       => "In Hash",
            ORACLE_SID => $ENV{ORACLE_SID}
          },
          z => {
            name       => "Non Target",
            ORACLE_SID => 5,
          }
        },
        aa => [ { ORACLE_SID => $ENV{ORACLE_SID}, name => "In Array" } ],    # just to make things interesting
      }
    },
  },
};

# find all nodes no matter how deep that have a child, which, themselves
# contains a hash with a key "ORACLE_SID"

my (@oracles) = dpath( '//ORACLE_SID[value eq ' . $ENV{ORACLE_SID} . ']/..' )->match($struct);
pp(@oracles);

#(
#  { name => "In Hash", ORACLE_SID => 6 },
#  { name => "In Array", ORACLE_SID => 6 },
#)

That at very least, makes the most of your logic extraneous, and the essentials of "what data are you querying" and "What are you doing with that data" become more clear to the code reader.


If height param is not number - then log and set to default

I usually only use ternaries if I can keep my code clean and at the same time keep the ternary under 2-3 lines. That's just me, but I would make a few small changes to increase readability.

class Example1 {
  constructor(height) {
    this.defaultHeight = 100;

    this.height = typeof height === 'number' ? height :
      (() => {
        console.log(height, 'is not a number');
        return this.defaultHeight;
      })();

  }
}


Vertically placing the words in a string

I assume you are only trying to work with ASCII characters, but I would like to point out a few Unicode-related failure modes, which can be exhibited by the following code:

String[] funkyStrings = {
    "foo bar",
    "foo ba\u0308r",
    "\ud835\udcbb\u2134\u2134 \ud835\udcb7\ud835\udcb6\ud835\udcc7"
};
for (String str : funkyStrings) {
    System.out.println(str);
    toVerticalWords(str);
}

The first string produces ordinary output:

foo bar
f b
o a
o r

The second string contains a grapheme cluster that is made up from multiple code points – the a and an accent ̈ which together create the glyph ä (← that's the precomposed form showing how it should look, as not all fonts handle combined characters correctly)

foo bär
f b
o a
o ̈
 r

The third string uses mathematical glyphs which have code points beyond U+FFFF. Because Java is slightly Unicode-retarded and can't deal with such high code points properly, its chars are actually UTF-16 code units (16 bit wide, far to small for what we are dealing with here). Therefore, higher code points have to be specified as a pair of surrogate halves. The encoding for U+1D4BB is d835 dcbb in UTF-16BE. This now produces the following output:

ℴℴ
? ?
? ?
ℴ ?
ℴ ?
 ?
 ?

Only the ℴ is displayed correctly, because it has a lower code point of U+2134. For the other characters, the surrogate halves are separated from each other, leading to invalid characters.

Not shown here: how fullwidth and halfwidth charaters can mess up your vertical layout.

The moral of the story: code points, UTF-16 code units, characters and glyphs are different things. Dealing with them correctly is excessively difficult, and I don't know about any suitable tools. If you are not prepared to deal correctly with any input you may encounter, then check that the input conforms to a subset you are comfortable with.

for (char c : str) {
    if (c > 0x7F) {
        throw new IllegalArgumentException("The input string may only contain ASCII code points");
    }
}


Consider in the following:

public Database(String dbName) {
    this.dbName = dbName;
}

I would check for a null dbName being passed in. Note that you pass this reference and then simply store it. Consequently, if it's null, you won't find out until later (perhaps, much later). You then have to work out at what point that was set to null.
Will you change dbName ? If not, make it final. It'll stop you changing it inadvertently later on. Immutability is often a good idea. It makes the class more robust and thread-safety easier to achieve. Perhaps not a requirement here, but who knows ? It's easier to relax a restriction rather than apply it after-the-fact.


Here is an update of what I've done:

I decided to make the code I provided earlier into a jQuery plugin. I reviewed jQuery plugins that I've used in the past then re-designed my code the JavaScript way. By using common feature in the JavaScript language such as the call method and utilizing object properties and prototypes.

I wrote it so you can call this jQuery plugin by simply entering in the element you want to have the effect apply to and then inputting your own customized values for the pause time, write time, delete time and sentence array.

Here is a sample of how to do that:

  $('.automatic-typing').automaticTyping({
    writeTime   :  60,
    deleteTime  :  40,
    pauseTime   :  750,
    sentences   : ['Enter in a sentence here',
                  'Another here',
                  '... As many as you want.'
                   ]
  });

Here is the re-designed code:

(function($) {
  "use strict";
  var methods = {
    init: function(options){

      options = $.extend({
        writeTime         :   60,
        deleteTime        :   60,
        pauseTime         :   1000,
        sentences         :   [
       'if you are seeing this',
       'you have not set your own values'
        ],
        charArray         :   [], //do not set this value and values below this point
        sentencesIndex    :   0,
        charIndex         :   0,
        distance          :   0
      }, options);

      this.each(function(){

        options = $.extend(true, {}, options); //deep copy the options object for every element
        options.charArray = options.sentences[0].split("");
        methods.loopCharacters.call(this, options);

      });

    },

    loopSentences: function(options){

      options.sentencesIndex = (options.sentencesIndex + 1) % options.sentences.length;
      options.charIndex = options.distance;
      options.charArray = options.sentences[options.sentencesIndex].split("");
      methods.loopCharacters.call(this, options);

    },

    loopCharacters: function(options){

      var i = options.charIndex;
      var len = options.charArray.length;
      var timer = options.writeTime;

      if (i === len) {
        timer = options.pauseTime;
      }

      setTimeout((function() {
        if (i === len) {
          methods.setDistance.call(this, options);
          return methods.deleteCharacters.call(this, options);
        }

        $(this).append(options.charArray[options.charIndex]);
        options.charIndex++;
        methods.loopCharacters.call(this, options);

      }).bind(this), timer);

    },

    deleteCharacters: function(options){

      setTimeout((function() {
        var currentSentence = $(this).text();

        if (currentSentence.length === options.distance) {
          return methods.loopSentences.call(this, options);
        }

        $(this).text(currentSentence.slice(0, currentSentence.length - 1));
        methods.deleteCharacters.call(this, options);

      }).bind(this), options.deleteTime);

    },

    setDistance: function(options){

      var nextSentenceIndex = options.sentencesIndex + 1;
      var cArr = options.charArray;
      var nextcArr = options.sentences[nextSentenceIndex % options.sentences.length].split('');
      var counter = 0;

      for (var i = 0; i <= cArr.length; i++) {
        if (cArr[i] === nextcArr[i]) {
      counter++;
        } else { break; }
      }

      if (cArr[counter] !== " " && counter !== 0) {
        while (true) {
      if (cArr[--counter] === " ") { break; }
        }
      }

      options.distance = counter;
    }

  };

  $.fn.automaticTyping = function(method){

    if ( typeof method === 'object' ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.');
    }

  };

})(jQuery);


Responses

  Does the code make sense to you?

Yes, for the most part. I am still becoming acquainted with the game play and hacks.

  anything I could make better or more efficient?

In general, using an integer 0/1 instead of boolean would lead to faster performance1. To change the value, the bitwise NOT operator (i.e. ~) can be used. Note that applying NOT on a signed integer will yield -` but that is still a truthy value. While it was asked more than 6 years ago, this post has some interesting discussion on that matter.

var wrathCookieSwitchOn = 0;
var cookieSwitchOn = 0;

var wrathSwitch = function() {
  wrathCookieSwitchOn = ~wrathCookieSwitchOn;
  console.log("WrathCookieSwitchOn is set to " + wrathCookieSwitchOn);
}

function checkWrathCookieSwitchOn() {
  if (wrathCookieSwitchOn) {
    console.log('wrathCookieSwitchOn',wrathCookieSwitchOn);
  }
}
wrathSwitch();
checkWrathCookieSwitchOn();
wrathSwitch();
checkWrathCookieSwitchOn();

Other thoughts

Ternary vs Short-circuiting logical operators

As I mentioned in an answer to your previous post, the ternary could be simplified from:

(shimmer.type == "golden") && (shimmer.wrath == 0 || wrathCookieSwitchOn) ? shimmer.pop() : 0;

To:

(shimmer.type == "golden") && (shimmer.wrath == 0 || wrathCookieSwitchOn) && shimmer.pop();

While it only saves about 2 keystrokes, it is essentially like removing an else clause from an if statement.

Variable declaration

The declaration of the timer variable SpecialCookieClicker is within the true block of the if statement. While hoisting allows the variable to exist throughout the function,
"it is recommended to always declare variables at the top of their scope"2 and then assign the value later (e.g..

var flipCookieSwitch = function(){
    var SpecialCookieClicker; //declare here
    cookieSwitchOn = !cookieSwitchOn;
    if (cookieSwitchOn) {
        SpecialCookieClicker = setInterval(/*function */, 500); //assign here
    }
}

While it should be the case that SpecialCookieClicker will always be assigned before the else block, it may be wise to guard against the scenario of an undefined value (e.g. due to cosmic rays) and ensure it is at least truthy before calling clearInterval().

SpecialCookieClicker && clearInterval(SpecialCookieClicker);

Variable names

The word On in variables wrathCookieSwitchOn and cookieSwitchOn convey the sense that the switch is on when the variable is true. Without the word On it could still be considered semantically the same - so one could argue that the names could be shortened to wrathCookieSwitch and cookieSwitch without any loss of semantics

ES-6

Presuming you aren't using IE, you should be able to utilize ES-6 features, like const for values that shouldn't be re-assigned and let for variables that can change. Then the one-liner for that function to pop shimmers can be simplified with an arrow function:

Game.shimmers.forEach((shimmer) => (shimmer.type == "golden") && (shimmer.wrath == 0 || wrathCookieSwitchOn) && shimmer.pop(), 500);

1https://jsperf.com/bool-vs-int/8

2https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting


"Utility" libraries
It's time to take the training wheels off, so to speak. You need to stop using cs50.h and replace it with standard calls to the C libraries. The implementation for get_string has a careful, dynamically-allocated buffer algorithm that is really not necessary for most purposes and can be replaced with simpler calls that use a fixed-size buffer. Advantages of a fixed-size buffer, other than extremely reduced complexity, include that it can enforce "domain-specific limits" (i.e. your product name cannot exceed 128 characters, or whatever) where get_string cannot. get_string is especially overkill for your yes/no prompt.
For an overrun-safe, simple method that is a fixed-buffer replacement for get_string, consider fgets.
Spelling
untill -> until
Memory leaks
You call get_string in a loop, which allocates a new buffer every time; and you never free it. So this will happily eat all of your RAM if you let it.
Comparisons
! (strcmp(newBottles, "y") == 0)

should just be
strcmp(newBottles, "y") != 0

New structure initialization
It's somewhat unusual to be returning a structure instance from get_newBottle, though it isn't the end of the world. More typical is to see either

initialization of an existing structure passed by pointer, or
allocation and initialization of a new structure via malloc then returning a pointer.

This impacts performance more for huge structures, but it's still a good idea to learn.


Build a time struct for current time in UTC

Being brutally honest with you: your comments are useless. All of them could be erased. In special, this one is also misleading:

now = time( NULL ); /* NULL is a control character */

Wut? No NULL is not a control character. You can pass a time_t pointer to time() and get the output written to the given variable, or you can pass NULL and get the output from the returned value. It has nothing to do with 'control characters', whatever that means.

Just yesterday I answered this question that had the same problem with noisy comments. I'll quote my own answer:

  Don't write noisy and obvious comments. The overall rule about code
  commenting is to use them to explain why you solved a problem in a
  given way, or to give any extra information (web links, mathematical
  formulas, etc) that will aid the understanding of a piece of code.
  Explaining what the code is doing should not be necessary if the code is well written. Well written code is self explanatory.

Apart from that, I would also give print_struct_parts() a better name that reflects what kind of struct it is printing. print_time() comes to mind...

Maybe also consider taking a FILE stream as parameter so that the caller is not bound to stdout.


Keeping an observable collection up to date

After studying your code snippet for a bit here's what I came up with.

I wouldn't call them iterators. They're really acting more as indexing operators that doubles as a loop counter. Furthermore, they're always incremented in sync and they have the exact same initial value.

int oi = 0; // old list iterator
int ni = 0; // new list iterator

So I would replace with simply:

int i = 0;

The second loop for trimming the extra elements:

while (oldList.Count > ni)
{
  oldList.RemoveAt(ni);
}

The post-condition for i after the first loop has to be equal to newList.Count otherwise we would still be looping the first while. Thusly, changing the condition to this is clearer:

while (oldList.Count > newList.Count)

After tracing your UpdateMarketOrderList method, the discernible end effect, from what I can tell, just seems to be a replacement of the oldList with the newList. If that's really the desired end consequence of running this function, why not simplify it, succinctly to this instead?

public static void UpdateMarketOrderList( ObservableCollection<MarketOrder> oldList,
                                          List<MarketOrder> newList )
{
    oldList.Clear();

    for(int i = 0; i < newList.Count; ++i)
    {
        oldList.Add(newList[i]);
    }
}

Then again you didn't specify in your question what the pre/post-conditions are for UpdateMarketOrderList, which is something that does matter.

After reading OP's comment that fired change events are important, I would refactor the main loop like this:

    while (i < newList.Count)
    {
        if (i == oldList.Count ||
            oldList[i].Price > newList[i].Price)
        {
            oldList.Insert(i, newList[ni]);
        }
        else if (oldList[i].Price < newList[i].Price)
        {
            oldList.RemoveAt(i);
            continue;
        }
        else if (oldList[i].Quantity != newList[i].Quantity)
              // && oldList[i].Price == newList[i].Price
        {
            Debug.Assert(oldList[i].Price == newList[i].Price);
            oldList[i].Quantity = newList[i].Quantity;
        }

        ++i;
    }

With this refactor you decrease the indent level and tighten the loop a bit while preserving existing behavior. The key thing to realize is that RemoveAt doesn't increment the loop counter. Your previous code did that in a slightly less direct manner.

My gut feeling is that this could be refactored further still but without a good idea of the expected side-effects and other requirements for this method, it will be difficult to refactor this safely.


SO golang example with infinite for / channel workers

You wrote:
func doStuff(datachan <-chan map[string]string, reschan chan<- int) {
    for {
        data, ok := <-datachan
        if !ok {
            log.Print("Channel closed.")
            break
        }
        log.Printf("Data had %d length: %+v", len(data), data)
        reschan <- len(data)
    }
    return
}

I don't understand why you didn't write:
func doStuff(datachan <-chan map[string]string, reschan chan<- int) {
    for data := range datachan {
        log.Printf("Data had %d length: %+v", len(data), data)
        reschan <- len(data)
    }
    log.Print("Channel closed.")
}


What is the common API endpoint architecture using DTO?

How about:
class PostController extends AbstractController
{
    public function store(PostStoreRequest $request): Response
    {
        $dataStruct = app(PostDataStruct::class)->fill($request->validated());

        return app(UserPostHandlerInterface::class)->createPost($dataStruct);
    }
}

PostStoreRequest validates data
PostDataStruct stores contents and has a method that fill all the data for you.
Your code looks a bit like Laravel so I utilized Laravels app container. This way you will have an easier time mocking objects in phpunit.
Within Kernel file forException Handlers, you can define how certain exceptions are handled. i.e. if you call throw new SystemExceptionError('my message') - in the Kernel file state that SystemExceptionError should have HTTP status 500.


using namespace std; is a bad habit to get into, as it can lead to name-collisions and other issues. It's best to explicitly qualify the names we need where necessary, e.g. std::cout.

A few more line-breaks would be useful in the code. Think of code with a specific purpose as a paragraph when writing text. For example, this could be considered one "paragraph", so should have an empty line after it.
 std::cout << "From what height do we drop the ball? (In meters): ";
 double h;
 std::cin >> h;

We have several similarly named variables h, high and hi. This makes the code harder to understand.

Variables that don't change should be marked const. (e.g. g).

Variables should generally be declared as close to the point of use as possible, set to immediately useful values, and not reused (unless they consume significant resources). For example, t, v, high and h can all be declared where they are set inside the loop.

s does not appear to be used.

We have no way to reset the static time variable in timeFallingBall(). This means we can't call fallingBall a second time, to drop another ball. We can easily just increment t in the fallingBall function instead.

while (h) translates to while (h != 0). Since h is a double with a calculated value, it's a bad idea to compare it with an exact number. We should use while (h > 0.0) instead, or while (true) since we handle the exit condition inside the loop.

In C++, number literals have specific types: 0 is an int, 0.f is a float, 0.0 is a double. When comparing or assigning to variables, it's best to use the literal style of the correct variable type, rather than relying on conversions.

std::endl outputs a newline, but also flushes the output stream unnecessarily. We can output "\n" to get a newline without the flush.

Note that given the constant downwards acceleration, the maximum velocity is always going to be the velocity when the ball hits the ground. So we don't really need to keep track of it.

(Obviously the 1 second resolution makes the max speed output rather incorrect).

Applying the above, I'd probably go with something like:
void fallingBall()
{
    std::cout << "From what height do we drop the ball? (In meters): ";
    double h_start;
    std::cin >> h_start;

    if (h_start <= 0.0)
    {
        std::cout << "The ball is already on the ground!\n";
        return;
    }

    const double g = 9.81;

    double t = 0.0;

    while (true)
    {
        t += 1.0;

        const double h_current = h_start - 0.5 * g * t * t;
        const double v_current = g * t;

        if (h_current <= 0.0)
        {
            std::cout << "After second " << t << ", the ball has reached the ground! Maximum speed: " << v_current << " m/s\n";
            break;
        }

        std::cout << "After second " << t << ", the ball is at a distance of " << h_current << " m from the ground at a speed: " << v_current << " m/s\n";
    }
}


Member list reveals member information on click (#1)

You're double-wrapping elements in jQuery. blContent and blCurrentContent are already jQuery objects, so doing $(blContent) isn't necessary. It's common practice to prefix jQuery collections with a dollar sign $.

Other than that your code looks fine, but you could use toggleClass and exclude the current sibling element from the previous collection:

var $blContent = $('.block-list__content').addClass('hidden');

$('.block-list__link').click(function(e) {
  e.preventDefault();
  var $content = $(this)
    .siblings('.block-list__content')
    .toggleClass('hidden visible');
  $blContent
    .not($content)
    .removeClass('visible')
    .addClass('hidden');
});

Your code: http://jsbin.com/duqeb/1/edit
Updated code: http://jsbin.com/geboq/4/edit


How do I divide Dao and Dao-Cache into different modules?

Well if you want to distinct classes, you should create two classes:
class CahedDao {
  AppCache cache;
  getByKey(String)
}

class DbDao {
  getByKeyFromDb(String)
}

Notes:
A. Codereview is to review working code, if you want to solve a problem you should better ask on stackexchange.
B. There are some issues in your code. Thanks to the DI and (bad) field injection you did not got them.


Is this a good algorithm to unflat js objects?

Nice code!

You should point out assumptions in a comment. You could document, for instance, that if the first encountered subproperty of a property is numeric, it's treated as an array.
I would rename messages to something like value. property is fine, but you could also consider key.
Right now, your code won't work with direct arrays. The following messageObject won't produce the expected result:

messageObject = {
    'array.0': 'Code',
    'array.1': 'Review'
};

There are some very specific edge cases: messageObject = { 'constructor.name': 'renatoargh' } will return an empty object. I'm not really sure what can be done about this though...
Finally, just for fun, you can use something like var key = property.splice(-1); to eliminate the second if in your for loop. Of course, after the loop, you'd have to add currentNode[key] = messages;.


Ruby on rails action code could be shorter

A lot of these logic could be moved to model. Rails provides lot of helpers for validation in your model.

class Item
  validate :fund_vs_price, :fund_greater_than_zero

  def fund_vs_price
    errors.add(:fund, "Fund amount should not exceed price difference") if fund > price
  end

  def fund_greater_than_zero
    errors.add(:fund, "No money specified.")
  end

  #overriding setter to do a sum every time it is assigned a value
  def fund=(value)
    write_attribute(:fund, fund.to_f + value)
  end
end

With that, the controller becomes really simple.

def addFund
    @item.fund = prams[:fund]
    if @item.save
       respond_to do |format|

         format.html { redirect_to @item, success: 'Fund  added' }
         format.json {render :json =>{:status =>1,
          :error=>"Done"}}
       end
    else
      respond_to do |format|

       format.html { redirect_to @item, error: @item.errors[:fund].join("\n") }
       format.json {render :json =>{:status =>0,
        :error=> @item.errors[:fund].join("\n")}}
      end
    end
  end

If your model becomes too big to maintain, you can always use ActiveSupport concerns to separate it out into different modules. For eg, you could move everything related to validation into a separate module.

There might be some logical errors in the above code since its not tested. But it will give you an idea


Checking whether users have a role that allows them to index sheets

[Improved with flat_map thanks to @tokland.]

How about:

def index?
  user.roles.flat_map { |role| role.activities['sheet'] }.include?('index')
end

In Ruby, it is almost never necessary to set a temporary variable to empty and iterate over an object, given the power of methods like map, reduce, find, all?, etc. I don't see the need to use uniq! since it doesn't change whether index will be present or not. It's unclear why you're checking for nil on the first sheet_activities (since you can't guarantee what will be first without sorting), but if you just want to return false when sheet_activities are nil, the above will already do so.

Also note that Rubocop likes single quotes when you're not interpolating.


A faster way to compute largest prime factor (Again, but a lot better)

It's buggy. Consider input 8.

Also, consider an input which is a very large prime. E.g. 2147483647. Your current code would take about 2147483645 trial divisions. It's possible to do it with only 46340 trial divisions while keeping the code very simple. Can you see how?

   Hint: 46340 is the square root, rounded down.

And that's easily optimised to 23171. Can you see how?

   Hint: only one prime is even.


General Observations
Welcome to code review, nice first question. I would leave the licensing information out since stack exchange uses the Creative Commons Attribution-ShareAlike license.
The comment block at the top is rather helpful otherwise. FYI, this compiles fine on Windows 10 in Visual Studio 2019 Professional, but doesn't link (usleep() is undefined).
Some of the code is a little difficult to read as there is vertical crowding, you might want to insert a few blank lines inside main() between logic blocks.
Avoid Global Variables
It is very difficult to read, write, debug and maintain programs that use global variables. Global variables can be modified by any function within the program and therefore require each function to be examined before making changes in the code. In C and C++ global variables impact the namespace and they can cause linking errors if they are defined in multiple files. The answers in this stackoverflow question provide a fuller explanation.
Declare and Initialize the Variables Where They are Needed
In the original version of C variables needed to be declared at the top of the logic block where they were used, this is no longer true, declare them as necessary.
void main(void) {
    char inst[] =
    {
        '>',
        '<',
        '^',
        'V'
    };

    system("clear"); //clear screen
    srand(time(NULL)); //initialize random generator; TODO: port to C++ and use TRNG instead
    printf("\e[?25l"); //disable cursor
    //TODO: Implement program input and conditional commands

    unsigned char tape[TAPE_SIZE_X][TAPE_SIZE_Y];
    int x = 336;
    int y = 67;

    while (1) {
        ...
    }
}

Let the Compiler Do More of the Work
In the code example above there is no size defined for the array inst[], the compiler will fill this in based on the number of initialization values in the array. This makes it easier to write and maintain the code since the size doesn't need to be modified each time an instruction is added.
Magic Numbers
There are Magic Numbers in the main() function (336 and 67), it might be better to create symbolic constants for them to make the code more readable and easier to maintain. You already define symbolic constants for TAPE_SIZE_X and TAPE_SIZE_Y the code would be more readable and understandable if the initialization values for x and y used symbolic constants, in this case you could possibly make the initialization half of the tape size for x and y.
Numeric constants in code are sometimes referred to as Magic Numbers, because there is no obvious meaning for them. There is a discussion of this on stackoverflow.
Complexity
The function main() is too complex (does too much). As programs grow in size the use of main() should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.
There is also a programming principle called the Single Responsibility Principle that applies here. The Single Responsibility Principle states:

that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.

There are at least multiple functions in main().

//TODO: Implement program input and conditional commands
Set up the screen
The contents of the while (1) loop also seem to be multiple functions

Default Cases for switch Statements
While it isn't necessary in the current code, to prevent undefined behavior it is best to have a default case for every switch statement:
        switch (inst[rand() % 4]) { //MOVE
        case '>':
            x = x + 1;
            break;
        case '<':
            x = x - 1;
            break;
        case '^':
            y = y + 1;
            break;
        case 'V':
            y = y - 1;
            break;
        default :
            printf("Unknown instruction in switch\n");
            return 1;
        }

Possible Optimization
The second switch statement could be replaced with a table of values and that would improve performance.
        char* control_sequence[] =
        {
            "\x1B[40m ",
            "\x1B[41m ",
            "\x1B[43m ",
            "\x1B[42m ",
            "\x1B[46m ",
            "\x1B[44m ",
            "\x1B[45m ",
            "\x1B[47m ",
        };

        printf("%s", control_sequence[tape[x][y]]);
        fflush(stdout); //flush stdout to prevent abnormal lag in printing to screen

Readability and Maintainability
As mentioned in the general observations, this section of code is very hard to read and even harder to maintain:
        if (x >= TAPE_SIZE_X) x = 0; //TOROID CODES FOR OOB CURSOR
        else if (x < 0) x = TAPE_SIZE_X - 1;
        if (y >= TAPE_SIZE_Y) y = 0;
        else if (y < 0) y = TAPE_SIZE_Y - 1;
        tape[x][y] = tape[x][y] + 1; // ADD 1
        if (tape[x][y] == 8) tape[x][y] = 0;
        usleep(16667); // CAP SPEED TO 60FPS : 1/60 seconds = 16666.666... microseconds
        printf("\33[%d;%dH", y, x); //print @ cursor position

In languages like C, C++ or Java put action code such as x = 0; on its own line, preferably in braces, that makes the action easier to find, and with the braces easier to maintain by adding more statements later:
        if (x >= TAPE_SIZE_X)
        {
            x = 0;
        }
        else if (x < 0)
        {
            x = TAPE_SIZE_X - 1;
        }
        if (y >= TAPE_SIZE_Y)
        {
            y = 0;
        }
        else if (y < 0)
        {
            y = TAPE_SIZE_Y - 1;
        }

        tape[x][y] = tape[x][y] + 1; // ADD 1
        if (tape[x][y] == 8)
        {
            tape[x][y] = 0;
        }

        usleep(16667); // CAP SPEED TO 60FPS : 1/60 seconds = 16666.666... microseconds
        printf("\33[%d;%dH", y, x); //print @ cursor position

An example of how hard the original code is to read is that I missed the magic number 8 in the discussion of magic numbers above.


You should get out of the habit of printing results instead of returning them; if you return the function is reusable. Remember that you can return multiple values with:

    return ''.join(key), ''.join(l)

I would personally suggest returning a string directly from keygen.

You don't need to convert y to a list, and probably should name it better (eg. ascii). It would be better as a global constant.

encrypt and decrypt can be unified by making key optional and reversing the arguments when decrypting relative to encrypting; it's symmetric after all.

import random

ASCII = 'abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()_-+={}[]|\:;?/~`"" '

def keygen():
    l = list(ASCII)
    random.shuffle(l)
    return ''.join(l)

def cipher(x, key=None, backwards=False):
    if key is None:
        key = keygen()

    z = dict(zip(key, ASCII) if backwards else zip(ASCII, key))

    l = []
    for match in list(x):
        l.append(match.replace(match, z[match]))

    return key, ''.join(l)

Since keygen is so easy to call as

encrypt(x, keygen())

I wouldn't make key have a default. This gives the simpler:

import random

ASCII = 'abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()_-+={}[]|\:;?/~`"" '

def keygen():
    l = list(ASCII)
    random.shuffle(l)
    return ''.join(l)

def cipher(x, key, backwards=False):
    z = dict(zip(key, ASCII) if backwards else zip(ASCII, key))

    l = []
    for match in list(x):
        l.append(match.replace(match, z[match]))

    return key, ''.join(l)

Looking at

    l = []
    for match in list(x):
        l.append(match.replace(match, z[match]))

we have a lot of inefficiencies. You should just do

    for match in x:

and then

        l.append(z[match])

since the replace is a no-op.

This can be a list comprehension:

    l = [z[match] for match in x]

This is now just

import random

ASCII = 'abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()_-+={}[]|\:;?/~`"" '

def keygen():
    l = list(ASCII)
    random.shuffle(l)
    return ''.join(l)

def cipher(x, key, backwards=False):
    z = dict(zip(key, ASCII) if backwards else zip(ASCII, key))

    l = [z[match] for match in x]
    return ''.join(l)

You can then replace some of the challenge with str.translate and str.maketrans:

import random

ASCII = 'abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()_-+={}[]|\:;?/~`"" '

def keygen():
    l = list(ASCII)
    random.shuffle(l)
    return ''.join(l)

def cipher(x, key, backwards=False, base_chars=ASCII):
    if backwards:
        base_chars, key = key, base_chars

    return x.translate(str.maketrans(base_chars, key))

The bug

There is a duplicate character in ASCII. This can, and does, break things

                                                                      ↓↓
ASCII = 'abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()_-+={}[]|\:;?/~`"" '
                                                                      ↑↑

Personally, your best best is just to use string.ascii_lowercase + string.digits + string.punctuation, despite it being slightly different to the above. This gives

import random
import string

ASCII = string.ascii_lowercase + string.digits + string.punctuation

def keygen():
    l = list(ASCII)
    random.shuffle(l)
    return ''.join(l)

def cipher(x, key, backwards=False, base_chars=ASCII):
    if backwards:
        base_chars, key = key, base_chars

    return x.translate(str.maketrans(base_chars, key))

Of course, don't roll your own crypto.


For anything related to building URL query strings from key-values pairs, you should let urllib.parse.urlencode do the work for you. It can also handle quoting and other special cases for you. To do that, you have to convert your data to a dictionary.

This is easy if you start with a pd.Series:

from urllib.parse import urlencode

def build_url_params(serie):
    parameters = serie[~pd.isnull(serie)].to_dict()
    return urlencode(parameters)

Then you just need to provide Series to this function instead of tuples:

def populate_url_params(df):
    df['URL parameters'] = df.apply(build_url_params, axis=1)

if __name__ == '__main__':
    df = pd.read_csv('urlbuilder.csv', encoding='utf-8-sig', engine='python')
    populate_url_params(df)
    print(df)

Or if you want to go the manual iteration route, you can use df.iterrows() instead of df.itertuples().


How can I layout this class to make it easier to use for API developers?

not very sure about your placement class, whether it's a pure class designed to encapsulate options, or a win-form.

If it's the former, i would suggest you use Polymorphism to have certain abstract layer, a quick sample:

At your side:

public abstract class Placement
{
    public int XOffset { get; set; }
    public int YOffset { get; set; }

    public class FrmField:Placement
    {
        public string FieldName { get; set; }
        public int Instance { get; set; }
    }

    public class TextSearch:Placement
    {
        public TextSearch(){}
        public string Text { get; set; }
        public int Instance { get; set; }
    }

    public class PageCoord : Placement
    {
        public string PageNumber { get; set; }
    }
}

public class SomeObjRequriePlacement
{
    public void DoSomething(Placement pla)
    {
        // this class and method may be a winform that do something based on given options
    }
}

Other dev using your api:

public class TestAtDev
{
    public void TestGeneric()
    {
        Placement pla = null;
        if (false) //some condition
        {
            pla = new Placement.FrmField() { FieldName = "", Instance = 1, XOffset = 1, YOffset = 2 };
        }
        else if (true) // some condition
        {
            pla = new Placement.PageCoord() { PageNumber = "xxx", XOffset = 1, YOffset = 2 };
        }
        else
        {
            pla = new Placement.TextSearch() { Text = "", XOffset = 1, YOffset = 2 };
        }

        var someObj = new SomeObjRequriePlacement();
        someObj.DoSomething(pla);
    }
}

if your Placement class is already an UI components, i would then suggest you separate the options away and wrap them as PlacementOption and use it in your placement class.

and if necessary, you may define an interface to make the code more independent. And Generic (like Type constraint) could make your code even tidier.

EDIT:

use type constraint to have strong typed object where necessary - but the basic implementation of the placement is still the same.

public abstract class HandlePlacement<T> where T:Placement
{
    public virtual void DoWork(T thePlacement) { }
}

public class HandleTextSearch : HandlePlacement<Placement.TextSearch>
{
    public override void DoWork(Placement.TextSearch thePlacement)
    {
        // do some specific work for text search option
    }
}

/*implementations for other placement options*/
/* ... */

public class TestAtDev
{
    public void DoTextSearch()
    {
        Placement.TextSearch ts = new Placement.TextSearch() { XOffset = 0, YOffset = 1, Instance = 2, Text = "" };
        HandlePlacement<Placement.TextSearch> hanlder = new HandleTextSearch();
        hanlder.DoWork(ts);
    }
}

another sample:

public abstract class SomeHandler
{
    public virtual void DoWork() { }
}

public abstract class SomeHandler<T>:SomeHandler where T : Placement
{
    protected SomeHandler(T thePlacement)
    {
        this.Placement = thePlacement;
    }

    protected T Placement { get; set; }
}

public class SomeHandlerForTextSearch : SomeHandler<Placement.TextSearch>
{
    public SomeHandlerForTextSearch(Placement.TextSearch ts):base(ts){}

    public override void DoWork()
    {
        // some specific handling for text search
    }
}

public class SomeHandlerForPageCoord : SomeHandler<Placement.PageCoord>
{
    public SomeHandlerForPageCoord(Placement.PageCoord pc) : base(pc) { }

    public override void DoWork()
    {
        // some specific handling for page coordinates
    }
}

public class TestAtDev2
{
    public void DoSomeTest()
    {
        SomeHandler h = null;
        if (true) // some condition
        {
            h = new SomeHandlerForTextSearch(new Placement.TextSearch() { XOffset = 1, YOffset = 2, Instance = 3, Text = "test" });
        }
        else if (true) // some condition
        {
            h = new SomeHandlerForPageCoord(new Placement.PageCoord() { XOffset = 1, YOffset = 2, PageNumber = "PageNo." });
        }
        h.DoWork();
    }
}


C++ application calling C# Dll marshalling strings

I would have expected the values to drop back down? Or do we have to wait for the garbage collector?

That's not how the GC works. AFAIK, it only returns memory to the OS if the OS says it'as low on memory. The assumption is that if the OS doesn't need the memory, then it's better to keep the memory as a part of the managed heap, so that the GC doesn't need to run that often.

using namespace std;

This is generally considered a bad practice in C++, since the std namespace contains many simple names that you might want to use yourself.

#import "C:\\Documents and Settings\\Administrator\\My Documents\\Visual Studio 2008\\Projects\\COMCallable\\COMCallable\\bin\\Release\\COMCallable.tlb" raw_interfaces_only

I think that both projects should be part of the same solution and in under the same parent directory. That way, this path can be relative, which will make it much short and it will also work if you copy the whole solution to another computer.

MyNetInterfacePtr pComObject;

I think this shouldn't be a global variable. If you need to pass the object from one function to another, use parameters.

HRESULT hr = S_OK;

hr = CoInitialize(NULL);

There is no reason to initialize hr if you're going to overwrite the value right away anyway.

And if you know that a function can fail, you should check whether it failed or not, not just ignore the HRESULT.

if(pComObject == NULL)

pComObject has to be NULL at this point, so there is no reason for this check.

while(true)
{
    Sleep(1000);
}

If you want to wait forever, the documentation says you should be able to use Sleep(INIFINITE);.

char *c = NULL;

if(pComObject != NULL)
{
    pComObject->TestMethodString(&c);
}

I don't know much about memory management in COM, but this certainly looks like a memory leak. pComObject can't know when are you done using it, so it can't deallocate it itself and you also don't deallocate it.

sprintf(numstr, "%ld", i);

The documentation says:

  Using sprintf, there is no way to limit the number of characters written, which means that code using sprintf is susceptible to buffer overruns.

By my count, 21 characters should be enough here, but I would probably use the safer version anyway, just to be sure.

if(pComObject != NULL)
{
    pComObject->AddString((char *)s.c_str());
}

So, if pComObject is NULL, this function doesn't do anything? I think that's a bad design, when something bad happens, the user should learn about it ASAP, not weeks later when they find out that their database is full of bogus data (or whatever).

sb = null;
sb = new StringBuilder();

That first line is completely unnecessary. If you're going to set the field to a new value anyway, setting it to null first won't change anything.

I don't understand the design of that class. What is the purpose of StartString and EndString? Practically, both do exactly the same thing, because of the null check in AddString().

You could provide just a single Reset() method that sets sb to a new StringBuilder and that would be enough. You could also remove the null check from AddString(), because sb would never be null.

Or even better, make MyNETClass single use. Instead of resetting, you would just create a new instance.


Taking advantage of the falsey and ineffective "" empty string

I wouldn't do it this way, because it does seem confusing. And not just because you are using truthiness (which I really wouldn't do, because it's hard to understand and just screams for bugs). It takes a while to see what happens when there is no POST value, what happens if a categories doesn't exist, etc.

You don't need multiple checks either though, just move all the code that belongs to category-doesnt-exists and category-exists into one block. If you also extract some code to functions, your code might look something like this:

if(!isset($_POST['category']) ||  $_POST['category'] == $Allcats ){
    displayAddForm("", $SELF);
    displayRentForm("", getAll());
} else if (<videos of that category doesnt exist>) {
    // message that video doesn't exist
    displayAddForm("", $SELF);
    displayRentForm("", getAll());
} else {
    $categorySelected = $_POST['category'];
    $hiddenCategory = "<input type='hidden' name='category' value='htmlspecialchars($categorySelected, ENT_QUOTES, 'UTF-8') '>";
    displayAddForm($hiddenCategory, $SELF);
    displayRentForm($hiddenCategory, getByCategoryId($categorySelected));
}

function getAll() {
    $mysqli->prepare("SELECT * FROM records");
    // return array of results
}

function getByCategoryId($id) {
    $vidStmt = $mysqli->prepare("SELECT * FROM records WHERE category=?");
    $vidStmt->bind_param("s",$categorySelected);
    // return array of results
}

function displayRentForm($hiddenCategory, $categories) {
    foreach($categories as $category){
        echo "<tr>
        <td> htmlspecialchars($name, ENT_QUOTES, 'UTF-8') $name <td> htmlspecialchars($category, ENT_QUOTES, 'UTF-8')  <td> htmlspecialchars($length, ENT_QUOTES, 'UTF-8')  <td>
        <form class='rent' action = htmlspecialchars($SELF, ENT_QUOTES, 'UTF-8')  method ='post'>
          $hiddenCategory
          <input type='hidden' name='ACTION' value='rent'>
          .... more fields ..
        </form>
        ";
    }
}

function displayAddForm($hiddenCategory, $SELF) {
    echo "<form id='addvideo' action = <?php echo htmlspecialchars($SELF, ENT_QUOTES, 'UTF-8') ; ?> method ='post'>" .
        $hiddenCategory .
        "<input type='hidden' name='ACTION' value='addvideo'>
        <input type="submit" value="ADD VIDEO">
        Name:<input type="text" name="name">
        <!--  more fields.... -->
    </form>";
}

It's not perfect, but I you get the idea.

XSS

You shouldn't write vulnerable code, even for academic work. It's bad practice, and it normalizes unsecure code; you get used to writing it, and other people get used to reading it.

Always protect against XSS when echoing variable data, eg:

$hiddenCategory = "<input type='hidden' name='category' value='" . htmlspecialchars($categorySelected, ENT_QUOTES, 'UTF-8') . "'>";

And

<form id='addvideo' action = '<?php echo htmlspecialchars($SELF, ENT_QUOTES, 'UTF-8'); ?>' method ='post'>

Misc

Don't mix " and ' so much. Something like <input type='hidden' name='ACTION' value='addvideo'><input type="submit" value="ADD VIDEO"> is hard to read, and harder to change than uniformly quoted code (you can see this in my code example above, where I didn't bother to correct it).
Your indentation is off, making your code harder to read.


Improving Least Recently Used implementation in Java

Bug
If the input consisted of the same page number over and over, your program would return multiple faults instead of 1, because you made this condition be first:

     if(arl.size()<n)
     { ++pf;arl.add(f);}

You should switch the first and second conditions:
     if(arl.contains(f)) {
         arl.remove(arl.indexOf(f));
         arl.add(f);
     } else if(arl.size()<n) {
         ++pf;
         arl.add(f);
     } else {
         arl.remove(0);
         arl.add(f);
         ++pf;
     }


Find all occurrences of the word "the" without using regex

Just some ideas:

The code should work as it is and is OK if performance doesn't matter, or the searched strings are small and occurrences few.

You don't need to call both contains(...) and indexOf(...); this iterates through the string twice.
The substring method copies the whole remaining string into a new string.

Easiest way is to call indexOf(String s, int fromIndex), with the start index parameter.

You can also build a state machine, representing how many letters of "the" have been found sequentially. Then analyze the string char by char.

Also keep in mind that your search will not work for repeating character sequences: if you search for "thethe" instead, and your searched text contains "thethethe", it will be found only once, although it occurs twice. Because your next index skips the entire search phrase when found (here by hardcoded "3"). It depends on what the demands are in your case, and what to do with such search phrases.


Storage class, dependency injection and singletons

Read this post before using the singleton pattern:  https://stackoverflow.com/a/4596323/1908639

You might find that it increases your initial development speed; however, the downsides tend to increase with the size/complexity of the project.  I have personally maintained code that used singletons, and I found it difficult to test/reuse.

If you think there are any major advantages to the singleton approach, I would be interested in hearing them.  I have not been able to find any beneficial use-cases in PHP web development, but I am definitely interested in hearing about them, if they exist.

Also, passing objects by reference should not be necessary in PHP 5 (source):

  In PHP 5 there is a new Object Model. PHP's handling of objects has been completely rewritten, allowing for better performance and more features. In previous versions of PHP, objects were handled like primitive types (for instance integers and strings). The drawback of this method was that semantically the whole object was copied when a variable was assigned, or passed as a parameter to a method. In the new approach, objects are referenced by handle, and not by value (one can think of a handle as an object's identifier).


Returning data reference with mutex lock guard struct

Overview
This is not a good solution.
You are basically setting up a busy wait on the mutex.
You should be using a condition variable to give the OS the opportunity to reassign the processor to do other work.
Returning the LockedData is just making this much more complex than it needs to be. Use a get/release set of methods (but make them private) then use RAII to call get/release so that it is done correctly.
Code Review
class Chunk
{
    // I put private member variables at the top.
    // When writting the constructor I want to double check that
    // I have correctly set up all members.
    // I put all private methods at the bottom.
    // Not everybody agrees with me on this. But its what I like. :-)
    private:
        mutable std::shared_ptr<std::mutex> chunkMutex;
        std::shared_ptr<vector<float>> chunkData;

    public:

        // Use the initializer list to set up members
        Chunk(){
            // I don't think these need to be shared dynamically like this.
            // Just make them members of chunk.
            chunkData = std::make_shared<vector<XMFLOAT3>>();
            chunkMutex = std::make_shared<std::mutex>();
        };

        // don't use `inline` here (it means nothing).
        // Dont add && on the return type it does nothing.
        inline LockedData const&& RequestChunkData()const { return LockedData(*chunkData,chunkMutex); };

};

How I would do it:
class ChunkAccess;
class Chunk
{
    private:

        std::mutex              chunkMutex;
        std::condition_variable chunkCondition;
        std::vector<float>      chunkData;
        bool                    inUse;

    public:
        Chunk()
            : inUse(false)
        {}
    private:
        friend class ChunkAccess;
        void getUniqueAccesses()
        {
            std::lock_guard<mutex>  lock(chunkMutex);
            chunkCondition.wait(lock, [&inUse](){return !inUse;});
            inUse = true;
        }
        void releaseUniqueAccesses()
        {
            std::lock_guard<mutex>  lock(chunkMutex);
            inUse = false;
            chunkCondition.notify_one();
        }
};
class ChunkAccess
{
    private:
        Chunk&  chunk;
    public:
        ChunkAccess(Chunk& chunk)
            : chunk(chunk)
        {
            chunk.getUniqueAccesses();
        }
        ~ChunkAccess()
        {
            chunk.releaseUniqueAccesses();
        }
        // Don't want multiple access objects so prevent copy.
        ChunkAccess(ChunkAccess const&)           = delete;
        ChunkAccess operator=(ChunkAccess const&) = delete;
        // With a bit of tinkering you can make this moveable.

        // Simplify data accesses
        float&       operator[](std::size_t index)       {return chunk.chunkData[index];}
        float const& operator[](std::size_t index) const {return chunk.chunkData[index];}
};

int main()
{
    Chunk         data;
    ChunkAccess   dataAccess(data);

    std::cout << dataAccess[3] << "\n";
}

How I could do (Option 2)
class Chunk
{
    private:

        std::mutex              chunkMutex;
        std::vector<float>      chunkData;

    public:
        Chunk()
            : inUse(false)
        {}

        void access(std::function<void(std::vector<float>&)> const& action)
        {
            std::lock_guard<mutex>  lock(chunkMutex);
            action(chunkData);
        }
};

int main()
{
    Chunk         data;
    data.access([](std::vector<float>& value){
        std::cout << value[3] << "\n";
    });
}


Creating a list of list after traversing binary search tree in level order

Nicely done. I especially like how you used the size of the queue to know how many items are there on the level. I have only minor improvement ideas.

You can simplify this declaration:

List<List<Integer>> list = new LinkedList<List<Integer>>();

Using the diamond operator <>, like you already did at other places:

List<List<Integer>> list = new LinkedList<>();

The code is deeply indented. You could reduce the indent level by eliminating the else branch of the outermost condition:

    if (root == null) {
        return list;
    }
    Queue<TreeNode> q = new LinkedList<>();
    q.add(root);
    // ...

The while loop could be written as a for loop. The benefit is that it will be harder to forget to decrement size.

Lastly, some of the names could be better.

Instead of "layers", I propose singular "layer"
Instead of "size", I propose "count"


There are plenty of rock-paper-scissors implementations in java on this site.  I'll try to keep my suggestions at a beginner level, though.

First, I should point out that your "play again?" mechanism doesn't actually work: you ask the question, but never do anything with the result.    Putting the "play again?" prompt in its own class doesn't make much sense; it can just be a function.  That function should return a boolean result — true to play again, false to quit.  In main(), the while (b != 0) loop would best be written as a do-while loop, since you want to run the game at least once without asking.  b is a poor variable name; playAgain would be much more helpful.

The main lesson that I think you should learn from this exercise is object-oriented thinking.  Instead of input and randomNumber, how about thinking about a HumanPlayer and a RandomComputerPlayer, both of which can return a choice of "Rock", "Paper", or "Scissors" when asked to play()?  The code would better model the game.

To analyze the outcome, you have enumerated all 9 combinations.  Of those, three outcomes are ties, which can easily be detected.  It would also be better to group all of the winning outcomes and all of the losing outcomes together.

RockPaperScissors.java

import java.util.Random;
import java.util.Scanner;

public class RockPaperScissors {
    private static boolean playAgain(Scanner scanner) {
        System.out.println("Play again? Y(8), N(9)?");
        switch (scanner.nextInt()) {
        case 8:
            System.out.println("Rock, Paper, Scissors!");
            return true;
        default:
            System.out.println("Thanks for playing!");
            return false;
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        RPSPlayer computer = new RandomComputerPlayer(new Random());
        RPSPlayer human = new HumanPlayer(scanner);

        System.out.println("Rock Paper Scissors, by 200_success!");
        do {
            String comp = computer.play();
            String you = human.play();

            System.out.printf("%s vs. %s", comp, you);
            if (you.equals(comp)) {
                System.out.println(", IT'S A TIE!");
            } else if ( ("Rock".equals(you) && "Scissors".equals(comp)) ||
                        ("Scissors".equals(you) && "Paper".equals(comp)) ||
                        ("Paper".equals(you) && "Rock".equals(comp)) ) {
                System.out.println("! You win!");
            } else {
                assert (("Rock".equals(comp) && "Scissors".equals(you)) ||
                        ("Scissors".equals(comp) && "Paper".equals(you)) ||
                        ("Paper".equals(comp) && "Rock".equals(you)));
                System.out.println("! You lose!");
            }
        } while (playAgain(scanner));
    }
}

RPSPlayer.java

public interface RPSPlayer {
    String[] CHOICES = new String[] { "Rock", "Paper", "Scissors" };

    /**
     * Returns one of "Rock", "Paper", or "Scissors".
     */
    String play();
}

HumanPlayer.java

import java.util.Scanner;

public class HumanPlayer implements RPSPlayer {
    private final Scanner scanner;

    public HumanPlayer(Scanner scanner) {
        this.scanner = scanner;
    }

    public String play() {
        System.out.println("Select 1, 2, or 3 for Rock, Paper, Scissors");
        int choice = this.scanner.nextInt();
        // Keeping things simple, not doing any validation here
        return CHOICES[choice - 1];
    }
}

RandomComputerPlayer.java

import java.util.Random;

public class RandomComputerPlayer implements RPSPlayer {
    private final Random random;

    public RandomComputerPlayer(Random random) {
        this.random = random;
    }

    public String play() {
        return CHOICES[this.random.nextInt(CHOICES.length)];
    }
}


Combine as many RUN statements as possible to reduce the number of layers (and size of the image). Each RUN command makes a new layer.

For example,

RUN apt-get update && apt-get install --yes software-properties-common git gcc-snapshot

After these, you should clean the cache with apt-get autoremove && apt-get autoclean.

For example,

RUN apt-get update && apt-get install --yes software-properties-common git gcc-snapshot && apt-get autoremove && apt-get autoclean

This saves space on the image.

FROM ubuntu:latest is not best practice. Sometimes something works with FROM ubuntu:16.04, but not FROM ubuntu:18.04 (for example, software compatibility).


As a few people have pointed out, there is actually nothing really wrong with this code.

I mean, there needs to be some naming standardization, most notably any public property should be capital.

I would also advise a backing field for each property making the constructor a bit cleaner:

_hours = hours;
_payrate = payrate;
_lastName = lastName;

That being said from a design point of view, it is best to mirror your objects to real world  objects.

Is a PayRateCalculator actually a PayCheck?  Would it not make more sense to have a paycheck of some kind, once you have your details assigned you can return the paycheck as a separate thing?

The means with which you generate the paycheck should stand alone from the paycheck itself,
allowing the possibility in future of having multiple calculation methods or doing something interesting with the paycheck object.

Although again, these are just design considerations as your application scales.

There is nothing inherently wrong with your code, which is well-written, decently-named and functional.

Well done.


Indent your code!
Naming convention

Only use English

paivitys -> update -> though really this should be with a subject, so updateObjekt?
dataa -> data
arvvoja -> values
paivitaselekt -> updateSelection

Dont mispel

ssellecct -> selectElement
oppttion -> option

Use lowerCamelCase

infoarray -> infoArray
chosenid -> chosenId
choseninfo -> chosenInfo

myFunction -> this is an unfortunate name, it does not say anything about its functionality
The names of your HTML elements id's can be improved

Dont mix var and const/let
Don't console.log() in production code
Comments should improve understanding, //------ does not do that, just use newlines/whitespace
Dont assign onclick events in html with onclick, use addEventLister()
It seems people is a global variable, don't create global variables
It seems you create people and infoarray, then assign people to infoarray, and then never use people again. It does not seem to make sense


RESTful API echo server using Python bottles

The code looks a bit incomplete, e.g. shouldn't there be a main method
somewhere?

I added the following to get it to run for now:

if __name__ == "__main__":
    run()

It's good practice to have the __name__ check in there instead of just
executing, because then you're still able to import the file elsewhere
without it automatically executing code.

Okay, so with that out of the way, there's commented out code that
should be there:  Either it's correct, then it should replace the
uncommented code, or it's not, then it should be deleted.  To me,
reading that just confuses me what the purpose is, or was.

And then there's two functions, which are identical ... why is that?  I
suppose that's a feature of the framework that allows you to have both
functions because of the annotations, but generally do not do that and
give them separate names, at least something like
data_get/data_post.

The specification is pretty vague, what are you supposed to echo, the
POST body, or the URL parameters?  Because then I don't get what the
GET one is supposed to be doing.  With that in mind I'd delete it.

So, then, trying it out:

> curl -d '{"data": 1}' -H "Content-Type: application/json" -v http://localhost:8080/data
{"method": "POST", "data": {"data": 1}}%

Seems to work.

(Also, since there's a single endpoint that echoes data ... there's
little REST here.  I'm not sure what other best practices are meant to
be followed for this exercise.)

I've no idea how you'd get an exception in there, but in any case,
raise ValueError isn't super helpful, it says exactly nothing about
what went wrong.  Consider adding some information like raise
ValueError("Couldn't format data.").  Note that in this particular
situation there's little that adds information, maybe don't catch the
exception then.

At that point it might look like this:

@post("/data")
def data():
    response.content_type = "application/json"
    return dumps({"method": request.method, "data": request.json})

However, then I was thinking, maybe this framework does the JSON
formatting for us.  And it does:

@post("/data")
def data():
    return {"method": request.method, "data": request.json}

Probably can't get it much smaller than that actually.  And then you can
delete a lot of imports too:

from bottle import run, request, post
from json import dumps

Hope that helps.  In general it's good to let readers know all you can,
like "which dependencies do I need" and "how do I run this", including
example invocations.


Get elementary values from a flagged enum

The way to test for a power of two, where x is an unsigned integer type is

( x != 0 ) && ( ( x & ( x - 1 ) ) == 0 )

To understand why this works, it's fairly easy to see that if x is a power of two, then x & (x -1 ) is zero.

If x is not a power of two, then only the bits up to the first non-zero bit are changed when you subtract one, and that is not the most significant bit, so the most significant bit is not cleared, and so x & (x - 1 ) is non-zero, as required.

Zero is a special case - it's not a power of two, so an extra test is needed, also ( x - 1 ) overflows if x is zero.


Getting names/values of multiple properties

If you want to iterate through all of the properties then reflection will help you to do that. You can find more at MS docs
Something like this:

public TModel Get<TParam>(TParam param)
{
        var allParams = typeof(TParam).GetProperties().Select(p => $"{p.Name} ='{p.GetValue(param)}'");
        var condition = string.Join(" AND ", allParams);

        using (OracleConnection connection = new OracleConnection(GetConnectionString()))
        {
            connection.Open();

            // GetTableName() returns table name of TModel
            var query = $"SELECT * FROM {GetTableName()} WHERE {condition}";

            var output = connection.Query<TModel>(query);
            return output.FirstOrDefault();
        }
}

But you have to think how to escape SQL injections. Because the value of query variable in current implementation could have potential vulnerabilities.


$scope.navigationTabs = [
  new NAV("file","/file","File","fa fa-file-o", "active"),
  ...
]

All this piece of code does is define an instance of a NAV with the specified properties. It's not sharing methods, no inheritance, making the use of a constructor overkill. This is no different from doing:

$scope.navigationTabs = [
{ id: "file", key: "/file", value: "File", icon: "fa fa-file-o", active: "active" }

The above method throws away the need for a constructor, names your properties verbosely, and order of appearance doesn't matter. If you want defaults, a factory function that merges your object with a default one does the same thing. It may just be replacing your constructor, but you still keep the perks of using an object.

function createNav(settings){
  return Object.assign({
    // defaults here
  }, settings);
}

Taking this further, you can just store the objects in an array, and run map through it to create the tabs. This way, you avoid always calling the function and concentrate on just the data.

var navItems = [
  { id: "file", key: "/file", value: "File", icon: "fa fa-file-o", active: "active" },
  ....
];

$scope.navigationTabs = navItems.map(createNav);

console.log("navigating to url: " + nav.key);

Consider avoiding console.log when debugging. Use the browser's developer tools instead. Should you really want to log, use Angular's $log service as it safely detects the presence of console.

I would recommend that the directive be like a standalone component and written like:

<menu-bar menu-items="someVarWithMenuItems"></menu-bar>

In this manner, you make the directive portable, letting the enclosing controller decide what the menu items are. Another idea would be to have another directive and let the consumer write it this way:

<menu-bar>
  <menu-item ...props...>tab text</menu-item>
  <menu-item ...props...>tab text</menu-item>
  <menu-item ...props...>tab text</menu-item>
</menu-bar>

This way, you can just let the consumer drop in the scripts and not have to worry about them. They can just declare the tabs in the markup.


Sort a strings collection by a search term

1) Regex

You could generate a Pattern instance (regex) to check for exact matching instead of doing String and split acrobatics. If I understand it correctly, you are looking for occurrences of 'name' that are neighbored by 'start of line', 'end of line' or 'whitespace'. For example, if you were to search for "doge" like that, you could use the following regex: (?:^|\\s)(doge)(?:$|\\s)
The fat examples would be matched:
doge
dogeX
X doge X
Xdoge
XdogeX

In Java, you'd do it like this:

Pattern p = Pattern.compile("(?:^|\\s)("+search+")(?:$|\\s)");
if(p.matcher(candidate).find()) { } else { }

Compiling Patterns is slow, so only do it once per method call. If your itemsList is small, it's possible that your raw, manual checking is faster, but if that is the case performance should be no issue anyways.

2) Tree

A specialized Infix Tree that takes care of spaces (And you are looking for infix, not suffix, right?) is naturally the vastly superior solution if you can pay the performance costs of creating and maintaining it. If you decide to use an Infix Tree and you are not satisfied, you could write a Java InfixHashMap which provides O(1) lookup speed. (InfixDictionary: Data structure for Infix string lookup)

3) Functional Java 8

And since you are obviously using Java 8, give up on anonymous classes and go all the way:

    Comparator<T> comparator = (t1,t2)->{
        Integer n1Length = itemNameExtractor.apply(t1).length();
        Integer n2Length = itemNameExtractor.apply(t2).length();
        return n1Length.compareTo(n2Length);
    };


Structure:

Instead of having a function encompass everything, consider using a prototype constructor, or if you can use ECMAScript 2015, use the class structure.

By using the prototype structure your code would look something like the following:

var AppStorage = function(name){
    this.prefix = name;
}
AppStorage.prototype.saveItem = function(key, value){

}
AppStorage.prototype.getItem = function(key){

}
AppStorage.prototype.removeItem = function(key){

}
var AS = new AppStorage('myName');
AS.getItem('thing');

Which removes the need for blocks like the following:

return {
    set: function (key, value) {
        return saveItem(key, value);
    },
    get: function () {
        return getItem(key, item);
    },
    remove: function () {

    }

Things to improve upon:

console.error: instead of that, use throw new Error() instead.
There's a consistent use of extraneous empty lines, remove them. They're pointless and waste space.
When you return the aliases for the functions, the remove function is left empty, if that is the desired case, then it should simply be removed, otherwise, you forgot to link the remove function.
window.localStorage && window['localStorage']: uh, that's identical; you can access object properties via the . method, or [''] method.
prefix + '_' + key: it would be easier/better to just append the underscore when you define the prefix initially.
removeItem is the only function that doesn't just return false if localStorage does not exist. Consider incorporating the error message in every function, or just check for localStorage on initialisation.

With those changes in mind...

... here's your updated code:

var AppStorage = function(name) {
    if (!(this instanceof AppStorage)) {
        throw new Error("AppStorage must be invoked with new!");
    }
    if (!window.localStorage){
        throw new Error("Browser does not support HTML5 Web Storage");
    }
    this.prefix = name + '_';
}
AppStorage.prototype.save = function(key, value) {
    if (!key || !value) {
        throw new Error("Missing parameters \"key\" and \"value\"");
    }
    try {
        localStorage.setItem(this.prefix + key, JSON.stringify(value));
    } catch (e) {
        return false;
    }
};
AppStorage.prototype.get = function(key) {
    if (!key) {
        throw new Error("Missing parameter \"key\"");
    }
    try {
        localStorage.getItem(this.prefix + key);
    } catch (e) {
        return false;
    }
};

AppStorage.prototype.remove = function(key) {
    if (!key) {
        throw new Error("Missing parameter \"key\"");
    }
    try {
        return localStorage.removeItem(this.prefix + key);
    } catch (e) {
        return false;
    }
};
var as = new AppStorage('MyApp');


Active record pattern for a subscription service website

Avoid hacking the code, if possible. Instead, you should have a test environment with a testing database. Database::getInstance() should use a configuration file containing the database connection parameters. It should configure itself to use the testing database when running unit tests.


Batch retrieve formatted address along with geometry (lat/long) and output to csv

Use the csv library

x.writerows(custom_tuple(row) for row in data['results'])

Grabbing mutable data from the global scope is, I'm pretty sure, poor form. You should pass data as an argument to search_output.

Just pass in data['results'] as results, not the whole data object.
Consider calling it output_search_results.
Consider using precise type hints.
The existing argument search is being used as a file-name, so call it filename.

Pass the csv-writer object in as an argument to output_search_results.

Maybe this means introducing a middle-layer function to create the csv-writer; that's fine.
This is going to let you call output_search_results multiple times after opening the file once.

Encapsulate the code that fetches data from google in its own function.

Maybe even in its own class, if you're going to try to make more intelligent handlers for the failure cases.
Now you can easily build the functionality to fetch a "next page" of results based on the next-page-token. It'll be a sibling to the above function, or maybe an option to it.

From here you can either pass data['next_page_token'] as another (optional) parameter to output_search_results, which will call itself recursively, or you can call it in a while loop as you grab each next page.
You'll probably need to add some safety measures, such as what to do if a file already exists, etc.


Render the area of circle using HTML and JavaScript

To answer your questions directly:

Yes.
Maybe. Depends on what you define as "better".

First, though: Don't use bracketed (aka subscripting) access to properties when regular dot notation works, e.g.:

window.Math.PI

is exactly the same as:

window['Math']['PI']

but a lot simpler.

Secondly, don't bother with window when there's no need. window is the global object in a browser's JS runtime, so you can just say

Math.PI

The exception to this is if you have variable shadowing, but that's outside the scope of this review.

Now, to tackle question 2 first, you could do this:

function calcCircleArea(r) {
    if(r >= 0) {
        return Math.PI * r * r;
    }
    return "invalid input";
}

It's quite subtle, but instead of having an else branch, you just.. don't have an else branch. If the first condition is true, the function returns the area - the rest of the function never runs. But if it's false, we skip straight past the if block. The point of this is to ensure that the function always returns something. It already did that - there was nothing wrong with your code - but here it's even more explicit.

However, you could argue that handling invalid input is the less common option, hence that should be the thing to short-circuit the function, and return early:

function calcCircleArea(r) {
    if(r < 0) {
        return "invalid input";
    }
    return Math.PI * r * r;
}

In other words, you could assume good intentions (that the function will typically be called with proper arguments), and treat invalid input as the exception to the rule. However, you might be better served by having your function raise hell if its input is invalid. Right now you're returning something regardless of input, but maybe you want to completely bail out, if things aren't as expected (after all, a negative radius just doesn't make sense, so there's literally no good answer). Hence why I mentioned "exception to the rule", since exceptions, as concept, are made for that purpose. Now, exceptions are also a topic on their own, but in this case you could do:

function calcCircleArea(r) {
    if(r < 0) {
        throw "Invalid input";
    }
    return Math.PI * r * r;
}

throw works the same as return in the sense that the function just stops. But the caller has to handle it differently, or - if it's not handled - it'll bubble up as an error. But I digress.

Now, for question 1, yes, you can call the function from the HTML. In fact, you really should do that here, since you're currently using document.write in a script that's placed in the head element. Since document.write happens immediately, your HTML actually ends up looking like this:

<!doctype html>

        <meta charset="UTF-8">
        <title>Circle area</title>
r = 7; area = 153.93804002589985
r = 1.5; area = 7.0685834705770345
r = 20; area = 1256.6370614359173

because the browser reads the scripts, and runs it. Obviously, this isn't really valid HTML. Thankfully, a browser is very, very, very tolerant, and renders things just fine anyway, even if it makes no sense.

Now (still before actually answering your question), let me quickly point out that

it's <!DOCTYPE html> with all-capital DOCTYPE
since that doctype means HTML5, you don't need XHTML-style self-closed tags like
. Just write
.

Finally, to answer your question, remove the three document.write lines from your script, and use this HTML instead:

<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Circle area</title>

            r = 7; area =

            r = 1.5; area =

            r = 20; area =


Java and stacks: correct implementation?

Some small notes:

According to the Code Conventions for the Java Programming Language,

  if statements always use braces {}.

Omitting them is error-prone.
top, push and pop methods handle invalid client calls too generously. You shouldn't do that. Crash early. Does it make sense to pop from an empty stack? It is rather a bug in the client code. Instead of returning -1 or swallowing the client error throw an IllegalStateException or an EmptyStackException. See: The Pragmatic Programmer: From Journeyman to Master by Andrew Hunt and David Thomas: Dead Programs Tell No Lies. You could use guard clauses too:

public void push(final int e) {
    if (isFull()) {
        throw new IllegalStateException();
    }
    elements[numElements++] = e;
}

public int top() {
    if (isEmpty()) {
        throw new EmptyStackException();
    }
    return elements[numElements - 1];
}

public void pop() {
    if (isEmpty()) {
        throw new EmptyStackException();
    }
    numElements--;
}

I'd make the maximal number of elements configurable via the constructor:

private static final int DEFAULT_MAX_ELEMENTS = 10;

private final int maxElements;
private final int[] elements;
private int numElements;

public MyStack() {
    this(DEFAULT_MAX_ELEMENTS);
}

public MyStack(final int maxElements) {
    if (maxElements < 1) {
        throw new IllegalArgumentException("maxElements cannot be less than 1, was: " + maxElements);
    }
    this.maxElements = maxElements;
    elements = new int[maxElements];
}

The default value of int fields are 0, therefore numElements = 0; is unnecessary in the constructor.


Like @feersum mentioned in a comment, it's not clear what exactly you return.
I had to go through the entire implementation before I found out. You either need to explain it in a comment, or choose a more intuitive representation. Another thing that might help is the name of your methods (and class).

If for example you had the following method signature:

public class NQueensSolver {
    public static List<char[][]> findAllSolutions(int n){

You expect a list of all the possible boards. Where each board is represented by a grid of char.

Your method SolveNQueens could mean find all solutions, or just find 1. If it's just 1, it might mean you get a list of rows, containing a list of strings, each representing a single cell. The fact that we can interpret the return type like this makes it really confusing what is actually returned.

Your initial idea of using String[] might have worked slightly better even. Since then you could guess that a String is an entire row, and the [] combines the rows into an entire board. Then the List is more easily interpreted as a list of all solutions.

I prefer to decouple finding a solution with how to show it to the user. Since NQueens is a rather small problem, we can just stick with 1 class and have it provide both a method to solve the NQueens and another one to print it. No need to write a specific class to show the solution. (Except if you want to show it graphically for example).

The class will look something like this:

public class NQueensSolver {
    public static SOLUTIONS findAllSolutions(int n) {...}
    public static void printSolutions(SOLUTIONS solutions) {...}
}

The methods are static because we don't keep any state inside the class. All state for a solution is either inside the method or passed in via parameters.

Now let's look at what return type fits for the SOLUTIONS.
I'd say there are 2 ways to look at the problem. Depending on how you look at it you'll use a different representation.

1) You want to find for each cell of the board whether or not it contains a queen.
2) For each row, you want to find in what column the queen is placed.

For case (1) you probably want to represent it by a boolean[][]. Since [][] means a 2D array of cells. And for each cell you say it contains a queen (true) or not (false). Alternatively you could also use a char and represent it with a . or Q like you did.

For case (2) you need a list of numbers. So either List<Integer> or int[]. This means the solution {1,3,0,2} could be printed as:

. Q . .
. . . Q
Q . . .
. . Q .

Since the way you actually solved it was by using the (2) representation, let's go with that.

Because we're putting all solutions in a List I peronally prefer to use List<int[]> over List<List<Integer>>. But both can work.

So now our method becomes:

/**
* Returns a list with all solutions. Each solution is represented by an array of rows.
* Where the number says for that row, in which column the queen is placed.
*/
public static List<int[]> findAllSolutions(int n){...}

Notice how I also put a comment above explaining how the solutions are represented.

Let's look at your main solving method:

private void nQueens(int n, int row, Deque<Integer> colPlacement,
                    List<Deque<Integer>> result){

This in itself works fine, but we're going to have to transform our result to List<int[]. So instead let's try to collect our result in the wanted type from the start.

Same for the colPlacement. This is our partial solution, but we can start by reserving exactly n numbers from the start and change those during the search.

This means our new method signature becomes:

private static void solve(int n, int currentRow, int[] currentSolution,
                          List<int[]> result){ ...}

We also don't really need a separate method to call this.

public static List<int[]> findAllSolutions(int n) {
    List<int[]> resultCollector = new ArrayList<int[]>();
    solve(n, 0, new int[n], resultCollector);
    return resultCollector;
}

A minor things to note here: new int[n] initialises the array to all 0. Otherwise we would have had use the Arrays.fill() like you already did for the .s.

Before we go to the solve(...) implementation, let's first look at the isValid(...) method.

Since we no longer work with Deque the signature is going to change to take an int[] partialSolution instead. But we can't do partialSolution.lenght (instead of deque.size()) anymore to find out what row we want to check. So let's also pass int currentRow as a parameter.

private static boolean isValid(int[] partialSolution, int currentRow){
    for (int i = 0 ; i < currentRow ; i++){
        int diff = Math.abs(partialSolution[i] - partialSolution[currentRow]);
        if (diff == 0 || diff == currentRow-i){
            return false;
        }
    }
    return true;
}

Note that i changed the ++i inside the for to i++. This is what people usually write.

Now let's look at what needs to change in the solve method.

private static void solve(int n, int currentRow, int[] currentSolution,
                          List<int[]> result){
    if(n == currentRow){
        result.add(Arrays.copyOf(currentSolution,n));
        return;
    }

    for(int col=0 ; col < n ; col++){
        currentSolution[currentRow] = col;
        if(isValid(currentSolution, currentRow)){
           solve(n, row+1, currentSolution, result);
        }
    }
}

We still need to make a copy when adding the solution to the result. Only now it's a copy of an array.
I added the return; inside the if, so we don't need the explicit else anymore which saves us a level of indentation.
Instead of adding the new column number to the Deque, we just set it in it's place in the solution array.
And don't forget to also pass the currentRow to the new isValid method call.

All that's left is to write the printSolutions() method so we can actually see the solutions. These are just some simple loops:

public static void printSolutions(List<int[]> solutions){
    for(int[] solution : solutions){
        for(int row = 0; row < solution.length; row++){
            for(int col = 0; col < solution.length; col++){
                if(solution[row]==col){
                    System.out.print("Q ");
                } else {
                    System.out.print(". ");
                }
            }
            System.out.println();
        }
        System.out.println();
        System.out.println();
    }
}

Running this simple main method shows that everthing works (given no copy-paste mistakes):

public static void main(String[] args) throws Exception {
    printSolutions(findAllSolutions(4));
}

. Q . .
. . . Q
Q . . .
. . Q .

. . Q .
Q . . .
. . . Q
. Q . .


Lightshot Print Screen key linux handler

Instruct shell how to treat unset variables

set -o nounset

In this script, there should not be possible to encounter an unbound variable, so setting this will prove useful for debugging.

Redirection style

 9     test "$1" -eq "$1" 2>/dev/null

in contrast with:

23     if test -x /usr/bin/tput && tput setaf 1 > /dev/null 2>&1

It should be unified either with, or without a space.

Constants should be moved to the top

61 lightshot_key="Print"
62 lightshot_name="Lightshot"

It is obvious, that everyone might not want to use Print, so this really has to be moved to the top in order for each user to quickly customize the keyboard combination for the print screen.

Those constants should be commented and clarified

In order for the users to quickly know, how to define key combinations, there should be some example added.

Consider replacing echo with printf

28         echo "$bold$red$2 Exit code = $1.$nocolor" 1>&2
29     else
30         echo "$2 Exit code = $1." 1>&2

Basically, it's a portability (and reliability) issue. Read more about this topic in this answer.

Problematic code

I notice now, there is a new line inside these strings:

70 is_number "$lightshot_pid" || print_error_and_exit 7 "lightshot_pid: The argument is not a number!\\nLightshot is most probably not running."
78 is_number "$lightshot_wnd" || print_error_and_exit 8 "lightshot_wnd: The argument is not a number!\\nLightshot is most probably not running."

Which according to Shellcheck.net:

  echo won't expand escape sequences

Read more about this topic in this article.

This code, as it is, works though, in spite of this error. Tested in bash version 4.3.48(1)-release and POSIX dash version 0.5.8-2.1ubuntu2.

Better variable naming convention

These are of little value to a foreign script reader:

61 lightshot_key="Print"
62 lightshot_name="Lightshot"

There are only two constants. Why not to give them some real meaning, this would further enhance the script reader's experience.

The variables:

67 lightshot_pid
75 lightshot_wnd

could use some love too.

Tell the user what arguments are (not) expected

50 test "$#" -gt 0 && print_error_and_exit 1 "$0: You have passed some unexpected argument(s) to the script!"

Let's add there something like:

  No arguments expected!

Problematic space in the comments (block separators)

12 # ------------------------------------------------------------------------------

There should be no space between # and -, because imagine, that you have a larger project than this, having these block separators will prevent you from searching for long arguments beginning (--).

Re-consider using smileys in the output and using grammar shortcuts

44     command -v "$1" > /dev/null 2>&1 || print_error_and_exit 6 "check_for_prerequisite(): I require $1 but it's not installed :-("

It may look a little unprofessional. Hard to say without knowing the people reading your script, though. (It might be totally OK for personal usage.) This script will likely be spread across the internet, so better not use that. Also, avoid using grammar shortcuts like:

  it's

xdotool: documenting all passed arguments would be greatly appreciated by the script readers (and the order of arguments in lightshot_wnd could be better a little)

75 lightshot_wnd=$(xdotool search --limit 1 --all --pid "$lightshot_pid" --name "$lightshot_name")

Re-writen code would look as follows

#!/bin/sh

# treat unset variables as an error when substituting
set -o nounset

# global constants for an easy set-up:
    # lightshot_printscreen_hotkey: set this to the same hotkey which you have set up in Lightshot
    #                               example: for left control and print screen key -> type Control_L+Print
lightshot_printscreen_hotkey="Print"
    # lightshot_process_name: do not change this one, it is a case-sensitive name of the Lightshot process
lightshot_process_name="Lightshot"

#------------------------------------------------------------------------------

is_number()
{
    # check if exactly one argument has been passed
    test "$#" -eq 1 || print_error_and_exit 5 "is_number(): There has not been passed exactly one argument!"

    # check if the argument is an integer
    test "$1" -eq "$1" 2> /dev/null
}

#------------------------------------------------------------------------------

print_error_and_exit()
{
    # check if exactly two arguments have been passed
    test "$#" -eq 2 || print_error_and_exit 3 "print_error_and_exit(): There have not been passed exactly two arguments!"

    # check if the first argument is a number
    is_number "$1" || print_error_and_exit 4 "print_error_and_exit(): The argument #1 is not a number!"

    # check if we have color support
    if test -x /usr/bin/tput && tput setaf 1 > /dev/null 2>&1
    then
        bold=$(tput bold)
        red=$(tput setaf 1)
        nocolor=$(tput sgr0)
        printf "%s%s%s Exit code = %s.%s\\n" "$bold" "$red" "$2" "$1" "$nocolor" 1>&2
    else
        printf "%s Exit code = %s.\\n" "$2" "$1" 1>&2
    fi

    exit "$1"
}

#------------------------------------------------------------------------------

check_for_prerequisite()
{
    # check if exactly one argument has been passed
    test "$#" -eq 1 || print_error_and_exit 2 "check_for_prerequisite(): There has not been passed exactly one argument!"

    # check if the argument is a program which is installed
    command -v "$1" > /dev/null 2>&1 || print_error_and_exit 6 "check_for_prerequisite(): I require $1 but it is not installed!"
}

#------------------------------------------------------------------------------

# check if no arguments have been passed to the script
test "$#" -gt 0 && print_error_and_exit 1 "$0: You have passed some unexpected argument(s) to the script. No arguments expected!"

#------------------------------------------------------------------------------

# check for prerequisites
check_for_prerequisite "pgrep"
check_for_prerequisite "xdotool"

#------------------------------------------------------------------------------

# get the Lightshot process id
lightshot_process_id=$(pgrep "$lightshot_process_name")

# test if a process id has been successfully acquired
is_number "$lightshot_process_id" || print_error_and_exit 7 "lightshot_process_id: The argument is not a number! Lightshot is most probably not running."

#------------------------------------------------------------------------------

# get the window id from the Lightshot process id
    #--all   : Require that all conditions be met.
    #--limit : Stop searching after finding N matching windows.
    #--pid   : Match windows that belong to a specific process id.
    #--name  : Match against the window name. This is the same string that is displayed in the window titlebar.
lightshot_window_id=$(xdotool search --all --limit 1 --pid "$lightshot_process_id" --name "$lightshot_process_name")

# test if a window id has been successfully acquired
is_number "$lightshot_window_id" || print_error_and_exit 8 "lightshot_window_id: The argument is not a number! Lightshot is most probably not running."

#------------------------------------------------------------------------------

# simulate the above pre-defined print screen hotkey press on the Lightshot window
xdotool key --window "$lightshot_window_id" "$lightshot_printscreen_hotkey"


Reading a sequence of characters and dynamically splitting into multiple arrays

First obvious thing: Why do you do the almost same thing twice?

for (char c : chars) {
    if (Character.isUpperCase(c)) {
        characterList.add(c);
    } else if (Character.isLowerCase(c)) {
        characterList.add(c);
    } else if (Character.isDigit(c)) {
        characterList.add(c);
    }
}

...and...

for (Character character : characterList) {
    if (Character.isUpperCase(character)) {
        uppercaseStringBuilder.append(character);
    } else if (Character.isLowerCase(character)) {
        lowercaseStringBuilder.append(character);
    } else if (Character.isDigit(character)) {
        numericStringBuilder.append(character);
    }
}

You are going through an array, check if you want the character and add it to a list. Then you go through that list and make the same check again to put the character in different lists / StringBuilders. You can simply remove the last of these loops and add the characters directly from the array to the stringbuilders.

Also your output would be pretty much the same if you simple wrote, for example...

System.out.println(uppercaseStringBuilder.toString());

I guess, with Java8, your problem could be solved nicely (or not so nicely, since char primitives are a little bit tricky there) via Streams.


Reverse Dictionary: Group from child array elements and get its minimum key

Indeed, you could use GroupBy but I think it's easier to solve with the query syntax because we also need the item from the first list to sort by its Id. Without it, we would need to do additional lookups like you do.

var result =
    from item in items // from + from = SelectMany
    from child in item.Children
    orderby item.Id // sort in ascending order
    group item.Id by child into g // group by child
    select (Child: g.Key, MinId: g.First()); // the first item in each group is the min-id

If you use select g instead, you'll get IGrouping<char, int> which you can easily turn into a dictionary or a lookup.


Trying to avoid a double full scan with aggregates in query

No, I cannot see a better way. The group-by constraints are different for the selects, so there is no way to merge them in to one.

The remainder of your code looks good, except I am concerned about your % calculations.... are they accurate?

(vary.Variance_Count / COUNT(tot.item_num) * 100) AS DECIMAL(10,2)

That looks like it will be integer arithmetic all the way through, I would instead write it as:

(100.0 * vary.Variance_Count / COUNT(tot.item_num)) AS DECIMAL(10,2)


Group students by grade and having max age

in your code, you have getter and setter for id. But those methods are not used. I have posted a similar question before. And multiple people told me "we shouldn't have dead code."

Since you want to return List of Student, I would construct the HashMap to map from string(grade) to Student instead of string to integer (where you will lose the student id).


Encoding variable-length quanties for MIDI

If an argument doesn't fit in the desired range an ArgumentOutOfRangeException should be thrown instead of an Exception.

    for (int i = 3; i >= 0; i--)
    {
        result[i] = (byte)(n & 0x7f);

        if(i < 3)
            result[i] |= 0x80;

        n >>= 7;

        if (n < 1)
            break;
    }

This can be rewritten to remove the if(i < 3) by starting the loop at 2. The check if (n < 1) can be placed in the loop condition like

result[3] = (byte)(n & 0x7f);
n >>= 7;

for (int i = 2; (i >= 0) || (n > 0); i--)
{
    result[i] = ((byte)(n & 0x7f)) | 0x80;
    n >>= 7;
}

You have some magic numbers in your code. The values 0x0fffffff, 128, 0x7f, 0x80 and 7 should be extracted to descriptive named constants.

Also there isn't explicitly written anything in any guidelines about braces {} for single instruction if statements I would encourage you to always use them to make your code less error prone.

You shouldn't shorten variables / parameter names. It is easier to read if the passed in parameter is named quantity instead of q.

The fact that you are taking care about the Endianess of the system should be stated in a xml documentation.


Finding the largest product of four consecutive numbers in a grid

It's OK to use max(), reimplementing it yourself won't save time, especially since the Python version is possibly faster if it's written in C. It's possible to be more concise and clearer though: max(hori + verti + dia + diarev).
You should use a list of list to represent a matrix, not a list of dictionaries. As cat_baxter points out, d = [map(int, row.split()) for row in open('20x20.txt').read().splitlines()] is enough to populate d. However if you're not familiar with list comprehensions and map, it's OK to use normal loops.
Python doesn't really have constants, but a convention is to do VERTI = "verti" and then use VERTI everywher, denoting that it is a constant ("verti" is not a good name, by the way, "vertical" is better. Use code completion.)
try: ... except: ... is bad practice, you need to catch specific exceptions (KeyError in this case). And you need to understand why those errors are thrown! This could be a bug in your code.