Improving Matlab function within big simulation

Vectorization

If you look at all the calls to mean, you see that what you are calculating in each loop is a "Cumulative moving average", but in the oposite direction of what one usually would do.

A cumulative moving average can be calculated quite simply using the cumulative sum, cumsum, and dividing by the number of elements. Since you're starting with all elements and up with only one, we need to flip it.

The running mean, (or cumulative moving average) can be calculated like this:

First flip dens upside down
Take the cumulative sum of it
Divide each element by the number of elements counted
Flip it back up

Thus:

running_mean = flipud(cumsum(flipud(dens))./(1:numel(dens)).');

Now, we need to find which element is larger, the cumulative sum, or the original density variable. You are not including the first element of the cumulative sum, and you are appending dens(end) at the end of the vector.

The maximum value of each row of a matrix can be found using max(A,[],2), where the number two represent the second dimension (columns). So, the values we want to use are:

max([running_mean(2:end), dens(2:end)],[],2)

In addition, we need to append the last element, so:

output = [max([running_mean(2:end), dens(2:end)],[],2); dens(end)];

To summarize, the entire operation requires no loops, one call to cumsum, and one call to max. In addition we need to flip it twice, but that takes virtually no time.

In total, your function can be written like this:

function output = my_function(vector)

n = numel(vector);    % numel, not length
output = zeros(n,1)   % prior to R2015b, use: output(n,1) = 0

% Create an anonymous function called density:
density = @(vector) 1000*(1 - (vector+288.9414)./(508929.2.*(vector+68.12963)).*(vector-3.9863).^2);

% Calculate the density:
dens = density(vector);

% Calculate the running mean, and create the final output vector:
running_mean = flipud(cumsum(flipud(dens))./(1:numel(dens)).');
output = [max([running_mean(2:end), dens(2:end)],[],2); dens(end)];

end

Time in Octave shows the improvement, as a function of vector size. For vectors with only ten elements, the execution time is 25% of the original code.

Review of your code:

Don't use input as a variable name! input is used to ask users for a command line input. Using it as a variable name makes the function useless, but will also potentially create strange errors or warnings. (I called it vector in this review. You should pick a more descriptive name)

The same goes with max, mean, length etc. Don't use function names as variable names.
Your input is a vector, so no need to specify that you always want the first column. Use linear indexing instead of subscripts. It's much faster, and you won't mess up the dimensions (oops, it was a column vector, not a row vector).
Don't use size(vector,1), and don't use length(vector), use numel(vector). It's faster and more robust.
You are pre-allocating output. Very good! That's a common bottleneck.
output = vector*0; is clever. Prior to Matlab R2015b zeros(n,1) was actually far from the fastest way to create a vector of zeros! In fact, output(n,1) = 0 was up to 500 times faster! This is because zeros creates a matrix, then fills the elements with zeros, where as the latter just creates a matrix, where the values are zero by default.
In your loop, don't use i as the iterator, it is used for the imaginary unit (sqrt(-1)). It's common to use for instance ii, jj etc.
If your density function is only what you have posted there, then you can simply create an anonymous function inside the main function:

density = @(vector) 1000*(1 - (vector+288.9414)./(508929.2.*(vector+68.12963)).*(vector-3.9863).^2);

Call it like:

dens = density(vector);

Review of reviews:

There are a few things I don't like about the other reviews that I want to point out:

"You don't need to specify that 1 when indexing a vector, MATLAB knows". Many Matlab users use max(A), when they want to find the maximum value of all columns in a matrix. It's much simpler than max(A, [], 1). You might however come into trouble if A has varying number of rows (and matrices often do). Because the moment that matrix has only one row, max(A) will give the maximum value of the entire vector, instead of each (one row) column. This can give you a major headache!
"Why not use length?" Well, in this case, length is much better than size, but numel should still be the preferred choice. length is better than size for two reasons. Using size limits the function to only work on column vectors only, and will fail on row vectors. Second, numel is much faster than length for large vectors, and both are much faster than size for all vectors.
"Don't use the profiler, use tic/toc". True, the profiler includes the time it takes to run itself, but it's still the easiest way to identify bottlenecks. For exact timing however, don't use tic/toc. timeit was introduced in Matlab R2013b, and is much better than tic/toc. If you are using an older version, the function is available at the File Exchange. tic/toc is also dangerous, because it will reset the timer if tic is called inside another function. Have a look at this question on SO from three years ago.


IMHO, the best way is the second example, but with some improvements:

#!/usr/bin/perl
use strict;
use warnings;

open my $fh, '<', 'DUMP' or die $!;
while(<$fh>) {
    print $_;
    print "\n" unless $. % 4;
}

There're no needs to temporary store in an array, and use the $. variable instead of a counter.

$. contains the current line number for the last filehandle accessed, see perlvar

If you want a separte function that returns the chunck:

#!/usr/bin/perl
use strict;
use warnings;

sub getChunck {
    my $file = shift;
    my @chunck;
    open my $fh, '<', $file or die "Unable to open '$file': $!";
    while(<$fh>) {
        push @chunck, $_;
        push @chunck, "\n" unless $. % 4;
    }
    return @chunck;
}

my @chunck = getChunck('DUMP');


When you use a control-flow library, you don't poll. That's what the callbacks are for. They get called when operations complete. That's how you know you're done.

Let's start by eliminating dependencies as they are black boxes, and we don't really know how they are built. If you use newer versions of Node.js, you can use Promises which should pretty much replace async. As for request, you can simply use Node's http.get to read the remote file.

All your API calls can also be transformed into promise-returning functions. If you can't find an existing module that already does it for you, you can simply wrap the call in a Promise and call resolve or reject accordingly. What I normally suggest is to split operations into a promise-returning function, and leave it to the caller to chain them up. In this case, log manages the sequence of readFile and insertToDb.

function insertToDb(body){
  return new Promise((resolve, reject) => {
    var time = Date.now();
    var query = `insert into testAPI (name) values ('${time}${body}')`;
    connection.query(query, (err, rows, fields) => {
      if(err) reject(err);
      else resolve(body);
    });
  });
}

function readFile(file){
  return new Promise((resolve, reject) => {
    http.get(url, body => {
      if(error) reject(error);
      else resolve(body);
    });
  });
}

function log(file){
  return readFile(file)
    .then(fileData => {
      // Now we have read the file, time to insert to db
      return insertToDb(fileData);
    }, error => {
      // Failed to read file
    })
    .then(fileData => {
      // Insert succeeded, we conclude by resolving with the file contents
      return fileData;
    }, error => {
      // DB operation failed
    });
}

async.map simply just calls each value against an iterator then calls the callback when everything's done. This is something easily done with array.map and Promise.all. We can use array.map to call log and collect the returned promises to an array, then we use Promise.all to wait for all promises to resolve.

Promise.all(inputData.map(file => log(file))).then(results => {
  // results[0] -> "file1" body
  // results[1] -> "file2" body
  // results[2] -> "file3" body

  console.log('finished');
}, () => {
  // Something failed
});

Now reading a remote file 9999 times (and over HTTP) and writing to the db 9999 times in rapid succession is the real bottleneck here. You're essentially flooding both servers. Even on localhost, servers still have CPU and memory constraints. No matter how you make this script run faster, the script will run no faster than the slowest of the two.

I believe what you're simply doing is trying to log changes of the file into the DB. I suggest you read and insert at a slower interval, like say every 5 seconds. That should give the servers enough time to breathe. Besides, do you really need to read the file in a way that reads are milliseconds apart. That's some file you got there.

Other alternatives would be to stream the data instead of reading the file at an interval. For the DB, try looking into solutions like Redis.

A few other things:

You can use Template Strings instead of string concatenation to build strings.
Instead of new Date().getTime(), use Date.now(). Does the same thing without creating a new Date object.
fetch isn't really "fetching", it appears to read a file and store it to the DB. It's technically "logging". Name your variables and functions properly.


SQL update scripts taking too much memory and doesn't free it up

As it seems you execute the SqlCommand only if flag == true so the first thing you should do is place a guard clause at the top of the method.
The SqlCommand object implements the IDisposable interface, therefor you should enclose it in an using statement which takes care of the disposing of this object.
the default value of the CommandType property is CommandType.Text so there is no need to assign it.
there is a overloaded constructor, which takes the connection and the querystring so you should use it.
Execute is not a compound word, so you shouldn't use PascalCase for this word. The method should be named ExecuteCommand().
a variable named flag does not describe what its purpose is. Much better would be shouldBeExecuted.
you should always use braces {} although they are optional for single line if statements. Omiting them will lead to potential error prone code.

Applying these points will lead to

private void ExecuteCommand(SqlConnection conn, string script, bool shouldBeExecuted)
{
    if (!shouldBeExecuted) { return; }

    using (SqlCommand command = new SqlCommand(script, conn))
    {
        command.ExecuteNonQuery();
    }
}


Bash script - compile and run c++ code for coding competitions

#!/bin/bash

I don't see why you're using Bash for this - there should be no problem using standard POSIX shell.

if [ -z $1 ]; then

I would recommend "$1" there, even though extra arguments will cause [ to return false for other reasons.  Passing as a single argument won't emit any error messages.

  echo -e "Please choose an input file"

echo -e isn't portable, and isn't necessary here anyway.

FILE="$1"
FILE_IN="${FILE%.*}.in"

Avoid all-caps names for variables in your own program - these are generally reserved for environment variables which change programs' behaviour.

clear

I think that's a bit rude - some of us like to be able to compare results against the previous run.  If I want to clear before I run, I can type that easily.

echo -e "\033[32mCompiling...\033[0m"

Don't embed terminal-specific escape codes like that!  Even though most recent terminals support the ANSI escapes, there are others - and if you redirect to file, you don't want it littered with control characters.  Use tput to generate the correct escapes for your $TERM (and slightly more readable code).

TMPFILE=$(mktemp /tmp/run-cpp.XXXXXXXXXX)

That's not a very descriptive variable name.  It's more informative to say what it's for (the executable to create).  And why hard-code /tmp as the directory?  Prefer $TMPDIR if set (perhaps systems with per-user temp directories, or with a choice of fast or large temporary storage).

WARNING_FLAGS="-Wuninitialized -Wmaybe-uninitialized"

That's quite a lax set of warnings.  If you care about the quality of your source, add a few more.  I suggest -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Weffc++.  If you only care about performance, then perhaps -Wall -Wextra -Wno-parentheses -Warray-bounds might be sufficient.
Since we use this variable only once, perhaps we should inline its use, thereby not triggering a Shellcheck warning where we (correctly) expand it without quotes.

g++ $FILE -std=c++17 $WARNING_FLAGS -O3 -o $TMPFILE

"$FILE" here, too.  I'd write "$TMPFILE" even though we constructed it to be a safe name.

if [ $? -eq 0 ]; then

Anti-pattern - just use the preceding command directly after if.  Or, enable the -e flag of the shell, to just exit if the compilation fails.

  echo -e "\033[32mRunning...\033[0m"

tput again.

  if [ -f $FILE_IN ]; then

Quotes again.

    $TMPFILE < $FILE_IN
  else
    $TMPFILE
  fi

As we don't use stdin, we could just redirect stdin using exec, and not need two different commands.

  ERROR=$?
fi
rm $TMPFILE 2> /dev/null

Why didn't we remove the temporary file if we exited early?

exit $ERROR

We wouldn't need to store the error if we made removing the temp-file an exit trap.

Modified code
#!/bin/sh
# Compiles and runs C++ source code. A corresponding file
# ending with .in will be used as input, if present

set -eu

if [ $# -ne 1 ] || [ -z "$1" ]
then
  echo "Usage: $0 SOURCE"
  exit 1
fi

executable=$(mktemp -t run-cpp.XXXXXXXXXX)
trap 'rm $executable' EXIT

green=$(tput setaf 2)
normal=$(tput sgr0)

echo "${green}Compiling...${normal}"
g++ -o "$executable" -std=c++17 -O3                     \
    -Wall -Wextra -Wwrite-strings -Wno-parentheses      \
    -Wpedantic -Warray-bounds -Weffc++                  \
    "$1"

echo "${green}Running...${normal}"
input=${1%.*}.in
if [ -f "$input" ]
then exec <"$input"
fi

"$executable"

You might also be interested in my approach to a similar situation, which uses Make rather than shell.


Properly storing error messages and displaying them with OOP

The big disadvantage of putting the validation to the setter is that you are never able to set invalid values. In most cases this is fine, but in some scenarios a valid user input differs from a more general valid field content. In addition the validation is also executed to internal setter uses where know that they are valid.

That said, I recommend setters to be only setters and not more.

The validation itself can be placed in a separate method or even in a separate class (depending on the complexity).

If you only want to display one error message, throwing an exception within the validation should be fine.

If you want to collect multiple error messages, you might want to build a generic validation class:

$valid=new Validation();
$valid->assertNotEmpty($name,"name","Insert a name please");
$valid->assertLength($name,3,50,"name","...");
...
if ($valid->hasErrors()) ...

You could extend this to a CourseValidation if you need it at multiple locations.

$valid=new CourseValidation($code,$name);
...


Short answer -- yes, data including state is immutable.

In traditional functional programming idiom data is immutable.  With this in mind, GenServer stores the current state internally.  When you implement the callback functions (handle_call, handle_cast, ...) the current state is passed to your callback function.  You then return a new state which then replaces the existing state inside the GenServer.  Depending on the data structure used for maintaining your state, only a portion of the new data may be "deeply" copied.

If I relate this directly to your question, I would not implement state as you have.  The GenServer wraps the state for you.  A more erlang/elixirish outline would be something like:

defmodule ModuleName do
  # api functions
  # place calls to cast, call, here
  def is_full?(server) do
    GenServer.call(server, {:check_full})
  end

  # callbacks
  # match ":check_full" call
  def handle_call({:check_full}, _from, state) do
    # perform your full check actions here
  end

  # match an ":add_user" call
  def handle_call({:add_user, {user_data}}, _from, state) do
    # perform your add_user actions here
  end

  # catch all
  def handle_call(request, _from, state) do
    # do something here, if you want, or omit as suits your style
  end
end

Certainly, you can also use guards instead of matching or use one giant handle_call function with a case or cond to separate out the pieces.  The method used above is clean and easy to understand.

I may have missed the point of the question --- the short answer was, yes, we pass the state around.  The longer answer was the GenServer can keep track of it for you.


Algorithm to find bucket and item indices from power of two bins?

I think your code is too complex and can be simplified.
Also, you wrote "using only primitive operations and values (i.e. not fancy array.map and such...", yet you use array.forEach.  Where is the "line"?
I hope this is what you are looking for.
Note:

up-to 32 -> one bucket
32 up-to 32*32 -> another bucket
3232 up-to 3232*32 -> another bucket
etc.

Only after done, I got @superb rain's [i >> 5, i & 31]...
Perhaps I'll implement that in the future.
However, my code allows for "bucket-of-buckets".
The heart of my code is the recursive function:
function recBucket(number, size) {
  if(number<size) return [number];
  else {
    var whole=Math.floor(number/size);
    return [recBucket(whole, size), number-whole*size].flat();
  }
};

Here is a snippet that uses and builds on that:

var numbers = [1, 2, 3, 31, 32, 33, 100, 201, 1023, 1024, 5555];

function recBucket(number, size) {
  if(number<size) return [number];
  else {
    var whole=Math.floor(number/size);
    return [recBucket(whole, size), number-whole*size].flat();
  }
};

console.log("as is:");
numbers.forEach(n=>console.log(n+" = "+recBucket(n, 32).join(":")));

function minBuckets(number, size, buckets) {
  var result=recBucket(number, size);
  while(result.length<buckets) result.unshift(0);
  return result;
};

console.log("min 2 buckets:");
numbers.forEach(n=>console.log(n+" = "+minBuckets(n, 32,2).join(":")));

console.log("min 4 buckets:");
numbers.forEach(n=>console.log(n+" = "+minBuckets(n, 32,4).join(":")));
.as-console-wrapper { max-height: 100% !important; top: 0; }


How to read a complete Unicode code point as String?

The javadoc of the read method states:

  Returns: The character read, as an integer in the range 0 to 65535
  (0x00-0xffff), or -1 if the end of the stream has been reached

The char primative is "a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive)."

(emphasis mine)

It would appear that your two C-style casts are safe.


Your class is not a class, self is totally missing. You have to rewrite the whole thing.
Internal methods start with one single underscore _roll.
You can access lists from the end with negative indices, len in unnesseccary.
Never change the internal state of a instance and return a value. Do the one or the other.
You can join with empty strings, if is unneccessary.
Open files with the with-statement. Never use the string representation of python objects like lists or dicts for other purposes than debugging.
Remember the naming conventions in PEP-8.

import random
import os

class Dice:
    def __init__(self, sides=1):
        self.sides = sides
        self.result = []
        self.total = 0

    def _roll(self):
        return random.randint(1, self.sides)

    def roll(self, times=1):
        self.result[:] = [self._roll() for time in range(times)]
        self.sum_result()

    def sum_result(self):
        self.total = sum(self.result)

    def save_result(self, directory=''):
        with open(os.path.join(directory, 'savedResult.txt'), 'a') as txt:
            txt.write('%s\n' % ', '.join(map(str, self.result)))

    def save_total(directory=''):
        with open(os.path.join(directory, 'savedTotal.txt'), 'a') as txt:
            txt.write('%d\n' % self.total)


JavaScript and jQuery check for image file and assign CSS

Basically every duplicated object can be made one object. And maybe use a function so you can call it when required.

If you use an IIFE like below, you can put this code in an external *.js file. It will then run asap without stalling other http requests while loading the page. Also pass in the jQuery object as a parameter so you can safely use $ instead.

The configuration separation allows you to easily change things when needed. They're also grouped and give you a better overview. Compared to the other objects the cfg variable is the "local global" so you can use cfg throughout your whole script.
The window object groups your functionality or component in one object. Basically one DOM object for a project is ideal imho. Allows you to access window.ComponentName in other files as well.
The activation is under your control. For the moment it uses the common DOM ready event and basically just runs the init() function.

// @param ($): jquery version x?
(function ($) {
    // 1. CONFIGURATION
    var cfg = {
        rowpageheader: '.RowPageHeader',
        rowfooter: '.RowFooter',
        options: {
            header: {
                'background-position': 'center top',
                'background-size': '100% auto',
                'background-repeat': 'no-repeat',
                'overflow': 'hidden'
            },
            footer: {
                'background-position': 'center top',
                'background-size': '2000px auto',
                'background-repeat': 'no-repeat',
                'overflow': 'hidden'
            }
        },
        path: {
            portal: 'Portals',
            images: 'Images'
        },
        misc: {
            portalcss: 'portal.css',
            imagequality: '_hd.jpg',
            footerbg: 'footer_bg.jpg'
        }
    };

    // 2. DOM OBJECT
    window.Images = {
        init: function () {
            this.cacheItems();
            this.activate();
        },

        cacheItems: function () {
            this.rowPageHeader = $(cfg.rowpageheader);
            this.rowFooter = $(cfg.rowfooter);
        },

        activate: function () {
            var cfgOptions = cfg.options,
                portalNum = this.getPortalNum(),
                pageName = this.getPageName();

            this.updateHeader(portalNum, pageName, cfgOptions.header);
            this.updateFooter(portalNum, cfgOptions.footer);
        },

        getPageName: function () {
            var loc = window.location.href,
                fileNameIndex = loc.lastIndexOf('/') + 1,
                dotIndex = loc.lastIndexOf('.');

            return loc.substring(fileNameIndex, dotIndex < fileNameIndex ? loc.length : dotIndex);
        },

        getPortalNum: function () {
            var head = document.head,
                portalcss = cfg.misc.portalcss,
                regexp = '/\/[0-9]+\/' + portalcss + '/',
                portalCss = head.innerHTML.match(regexp),
                portalNum = portalCss[0].replace('/', '');

            return portalNum.replace(portalcss, '');
        },

        updateHeader: function (portalNum, pageName, options) {
            var proj = this,
                cfgPath = cfg.path,
                headerUrl = [cfgPath.portal, portalNum, cfgPath.images, pageName, cfg.misc.imagequality];

            $.ajax({
                url: headerUrl.join('/')
            }).done(function () {
                var opt = $.extend(options, { backgroundImage: 'url(' + headerUrl + ')' });
                proj.rowPageHeader.css(opt);
            });
        },

        updateFooter: function (portalNum, options) {
            var proj = this,
                cfgPath = cfg.path,
                footerUrl = [cfgPath.portal, portalNum, cfgPath.images, cfg.misc.footerbg];

            $.ajax({
                url: footerUrl.join('/')
            }).done(function () {
                var opt = $.extend(options, { backgroundImage: 'url(' + footerUrl + ')' });
                proj.rowFooter.css(opt);
            });
        }
    };

    // 3. DOM READY
    $(function () {
        $(document).foundation();
        Images.init();
    });
} (jQuery));

Haven't checked if this works, but it should ^^


Creating an Enum with a Custom Type in Swift 4.x

The code is using Enum, but it's still using Struct.
The program may be buggy if the text value has character |. Suppose that "testFile1.txt|This is sample text" to "testFile1.txt|This is | sample text".

I have another approach with Enum in this case:

 enum Policy {
    case first
    case second
    case third

    var fileName: String {
        switch self {
        case .first: return "testFile1.txt"
        case .second: return "testFile2.txt"
        case .third: return "testFile3.txt"
        }
    }

    var text: String {
        switch self {
            case .first : return "This is sample text"
            case .second: return "This is more sample text"
            case .third: return "This is more sample text"
        }
    }
}
   print(Policy.first.text)


It looks like you're using TypeScript. TypeScript is great - it can turn difficult-to-debug runtime errors into trivially fixable compile errors. But for this sort of type checking to work:
Don't use any, since it effectively disables type checking for that expression. TSLint rule: no-any. Better to think about what the data structure will be, and type the expression appropriately.
Proper spelling is more professional and helps prevent bugs. Consider changing all the occurrences of ammount to amount.
Use an array instead of numerically indexed properties in an object, if at all possible - it'll make more sense as a data structure and will make iteration over it easier. For example, instead of having something like:
{type: 'Total', ammount1: 23, ammount2: 99, ammount3: 555},

would it be possible to tweak the user of the object to accept instead:
{type: 'Total', amounts: [23, 99, 555]}

? If I were you, I'd exert a significant amount of effort into making this change possible; it'd be a good structural improvement.
Use .map only when constructing an array by transforming every element of another array - if what you do inside the map is side-effects like .push, it would be more appropriate to use a generic iteration method like .forEach. But using .map and returning an object will make the code easier:

const data=[{totalQuantities:[{amount:23}],typeQuantities:[{type:{id:0,name:"Test"},singleQuantities:[{amount:45}]}]}];

const transformData = (data) => {
  const objTotal = {
    type: 'total',
    amounts: data.totalQuantities.map(({ amount }) => amount)
  };
  const typeQuantitiesObjs = data.typeQuantities.map(element => ({
    type: element.type.name,
    amounts: element.singleQuantities.map(({ amount }) => amount)
  }));
  return [objTotal, ...typeQuantitiesObjs];
};

console.log(transformData(data[0]));

TypeScript works really well when all of your data transformation is pure, as done in the above snippet. When you construct arrays and objects outright instead of mutating them inside a loop, TypeScript can often infer the resulting types automatically, which means that the code doesn't have much type-related syntax, and can look just like JavaScript (and so is easy to read) - despite still being type-safe.

so that the loop is not called twice

I think the two data sources are too different for this to be done in an easy-to-understand way: one uses type: 'total', the other uses type: element.type.name,. Also, one uses .totalQuantities to get the quantities, and the other uses .singleQuantities.
While it would be possible to refactor to avoid the repetition of { type: .., amounts: ... }, it would look somewhat convoluted; I wouldn't recommend it, it'll be harder to make sense of at a glance.
If the output objects must contain amount1 etc instead of a single array, I'd make a helper function that can transform an array of input quantities objects into a properly formatted object with Object.fromEntries, then call that function for both the total and the typeQuantities:

const data=[{totalQuantities:[{amount:23}],typeQuantities:[{type:{id:0,name:"Test"},singleQuantities:[{amount:45}]}]}];

const getAmounts = quantities => Object.fromEntries(
  quantities.map(
    ({ amount }, i) => ['amount' + (i + 1), amount]
  )
);
const transformData = (data) => {
  const objTotal = {
    type: 'total',
    ...getAmounts(data.totalQuantities)
  };
  const typeQuantitiesObjs = data.typeQuantities.map(element => ({
    type: element.type.name,
    ...getAmounts(element.singleQuantities)
  }));
  return [objTotal, ...typeQuantitiesObjs];
};

console.log(transformData(data[0]));


Telling the length of the highest common substring between 2 words

English please!

Identifiers and comments reallly really should be in English for all code you write.  Otherwise it will be hard to impossible to take part in the completely globalized IT world we're living in.

Break long lines

Your lines shouldn't be longer than 79 characters.  Break them before binary operators:

while i + lcs_temp < tamanho1 \
      and j + lcs_temp < tamanho2 \
      and string1[i + lcs_temp] == string2[j + lcs_temp]:

performance related comments still under construction ;)

Ok, I got a bit hooked up here, and I think I've got something usable out of it.  I'm though not yet posting the code as it's late here and currently really a mess, so I'll tidy up tomorrow and post it then.

Teaser (ignore the x-axis label):

Code for measurement, though killed after size 100 due to long runtime:

for size in chain(range(10, 100, 10), range(100, 1000, 100)):
    times = map(lambda v: timeit('lcsl_{}("abcdef" * {}, "cdofhij" * {})'.format(v, size, size),
                                 globals=globals(),
                                 setup='gc.collect(); gc.enable()',
                                 number=10),
                ('danieljour', 'mateus', 'aries', 'reti'))
    print(size, '\t', '\t'.join(map(str, times)))


1 Coding conventions

The Java coding conventions dictate that any for, if, while construct is preceded by a blank line. So instead of

int dummy = 10;
for (int i = 0; i < dummy; ++i) {
    ...
}

you should write

int dummy = 10;

for (int i = 0; i < dummy; ++i) {
    ...
}

Next, you have no space after the conditions of if statements: Instead of

if (testCondition()){
    ...
}

you should write

if (testCondition()) { // Note the space before '{'!
    ...
}

2 Algorithm

Printing to standard output in an algorithm is a no-no. Suppose you want to use your implementation in a real-world project. Apart from flooding the stdout, you waste time since calling System.out.print* goes down through the Java virtual machine straight to the OS, and is, thus, expensive. So, it would be nicer just return an integer whose value is the index of the leftmost element of the solution.

3 Summa summarum

All in all, I thought about this reimplementation:

public static int minSubArrayV2(final int[] array, final int targetSum) {
    if (targetSum == 0) {
        // Special case: return the index of the first array component whose
        // value is zero.
        for (int i = 0; i < array.length; ++i) {
            if (array[i] == 0) {
                return i;
            }
        }

        return -1;
    }

    if (targetSum > 0) {
        for (int startIndex = 0; startIndex < array.length; ++startIndex) {
            int sum = 0;

            for (int i = startIndex; i < array.length; ++i) {
                sum += array[i];

                if (sum > targetSum) {
                    break;
                } else if (sum == targetSum) {
                    return startIndex;
                }
            }
        }
    } else {
        for (int startIndex = 0; startIndex < array.length; ++startIndex) {
            int sum = 0;

            for (int i = startIndex; i < array.length; ++i) {
                sum += array[i];

                if (sum < targetSum) {
                    break;
                } else if (sum == targetSum) {
                    return startIndex;
                }
            }
        }
    }

    return -1;
}

Hope that helps.

A note

I spent about two hours thinking about how to improve the time complexity of your algorithm, and did not find any opportunity. However, you could spent \$\Theta(N^2)\$ for preprocessing the array, after which you can do queries in constant time. Consider the following:

public static Map<Integer, Integer> preprocessArray(final int[] array) {
    final Map<Integer, Integer> map = new HashMap<>();

    for (int startIndex = 0; startIndex < array.length; ++startIndex) {
        int sum = 0;

        for (int i = startIndex; i < array.length; ++i) {
            map.putIfAbsent(sum += array[i], startIndex);
        }
    }

    return map;
}

void foo(int[] array) {
    Map<Integer, Integer> map = preprocessArray(array);
    System.out.println(map.get(6));
}


Answering your question - yes, this is a correct solution (the algorithm is pretty simple), and yes, it is not the most efficient one.

The efficiency depends on the implementation of the priority queue. In your case, I assume this is PriorityQueue provided in java.util. The more efficient way uses what is called a Fibonacci Heap. Unfortunately, there is no implementation available in java.util, but there are plenty of implementations online (like this one). You can test your solution using one of them.

I will also suggest a couple of things you could implement to improve readability of your code.

Naming

In Java, methods should start with a lowercase character, unlike classes. So it is best practice to name your method findShortestPath.

Also, while frequent in mathematical notation, variable names like u and v can be confusing. These are Nodes in your case, so you can name them accordingly: currentNode, neighbourNode, or at least just current and neighbour.

Formatting

One of your loops contains only one statement, but I would strongly suggest adding brackets anyway or extracting the whole thing to a separate method (see below).

Additionally, consider:

for(Node v:neighbours)

for(Node v : neighbours)

It's a small thing, but most code formatters will do it this way, and it is easier to read.

The same goes for:

Node u=pq.poll();

Node u = pq.poll();

The same applies to mathematical operations, like:

v.getCost() > (u.getCost() + (graph.getCost(u, v))

If you are using an IDE like Eclipse or IntelliJ IDEA, there are features that format your code automatically.

Comments and methods

Comments are good if you are writing complex code that could be hard to understand without them. That's not the case here. Compare:

if(v.getCost()>(u.getCost()+(graph.getCost(u, v)))){ // if there is a cheaper one
    // do stuff
}

with

if(thereIsACheaperOne(u,v)){
    // do stuff
}

private boolean thereIsACheaperOne(Node u, Node v){
   return v.getCost()>(u.getCost()+(graph.getCost(u, v)))
}

When the method names you are using are meaningful, there is no need to comment code - it comments itself. If you extract a lot of statements like this, reading the algorithm becomes really easy. It becomes a short list of easy to understand calls, instead of lots of mathematical operations here and there.

And if you are unsure about what a certain step does, you can just read one specific method body.

A good rule for naming the method could be what I just done - just name the method just like you would phrase the comment.

In general, one method should be doing one thing and one thing only.

pq.remove(v);  //remove it
pq.add(v);  // add it again

Comments like these are pretty much useless. Anyone with a minimum knowledge about programming will know what this code does. These comments make the code messy.

And more...

In your code, you use graph.getAdj() twice. Now, what will happen, if something (e.g. another thread) changes the graph after you added all your nodes, but before you started calculating distances? I suggest that you create a local final variable in your method:

final <WhateverTypeItIs> adjacencyStructure = graph.getAdj()

This way, you are sure that you are working on the same copy of the adjacency structure (be it a list, or matrix) everywhere in your method.

You could also consider adding exception handling to your method instead of checking for source == null. And why are you only checking source? What happens if graph is null?

I would separate this into two parts: first, try to get all the variables needed and then call a separate method that is the algorithm itself. All this in a try-catch block. You could easily catch the NullPointerException and inform the user that either source or graph is not set up properly. Or, better, add a bit more logic to that to ensure which of these is not set up properly.


Per my comment, follow the style guide - for example, there should be whitespace around = when assigning, and after commas:

i, k = 0, end - start

content is not a good name for your function. You should be more descriptive of what it actually does (perhaps filter_content?) and add a docstring providing more information. Throughout your code there are temporary variables with cryptic names (s_list? lst?) that could be changed to make things much clearer - I was wondering why flg isn't Boolean, and it turns out that it isn't actually a flag.

Your approach to removing HTML tags (picking through the whole page character by character) is particularly prone to error; what if one of the attributes within a tag contains '>'? For a good standard library solution, see here.

The conversion to lowercase is, frankly, ludicrous:

i=0
while i<len(lst):
    lst[i]=lst[i].lower()
    i+=1

you had the whole string (called, confusingly, s_list) to hand just two lines beforehand, and

s_list = s_list.lower()

is so much simpler.

As you're making a set to remove duplication:

lst=list(set(lst))

why not keep the set, instead of converting back to list, and use it to do the filtering, too? For example, use set.difference_update:

>>> words = set('this is a sentence to filter'.split())
>>> words.difference_update(['a', 'to', 'this', 'is'])
>>> words
set(['sentence', 'filter'])

Your other function could be simplified significantly:

def page_content(url):
    with urllib.urlopen(url) as f:
        return f.read()


Removing duplicates from an unsorted linked list

This review is two-fold: once, in case you have to uphold your restriction and then what changes if you allow extra space.

Review

Comments: they are simply missing. You need at least some javadoc, and for non-trivial methods like this some more never hurts. Oh, and skip the usual excuses about how this code is somehow special and doesn't need comments.
Clarity and Intent: if (current.equals(head)) reads like you are comparing the actual nodes, while duplicity is a matter of equal node values. You may have overwritten the equals method accordingly (I assume so for the sake of correctness), but I would prefer to clearly portray your original intent here by comparing the actual values.
Efficiency and readability: As the answer by zdd points out you could save one pointer, but that's kind of pointless. I prefer your version as its much clearer to a reader what current, prev and next are. However,efficiency is not going to get below O(n^2) with this approach.

Efficiency Improvement

You said that you need a solution "without using extra memory". What you really meant of course is a solution "with only a constant amount of additional memory" (your pointers require memory as well after all). What you did not require, however, is that this operation has to leave the list elements' ordering intact. Therefore, a faster approach in O(n log(n)) would be to first sort the list (in-place to satisfy the memory requirement), then simply walk through the list comparing only neighbors (another O(n)). While this does not make much difference of course for smaller lists, the memory requirement indicates much larger lists, and then the difference between O(n^2) and O(n log(n)) may well be the difference between another problem and a solution.


Finding all possible paths between two points in a grid using recursion

No optimization will make this run effectively for large inputs because fundamentally the "all paths problem" is hard. In short, as the size of the input increases incrementally, the number of paths increases exponentially. Your best option may be to ask "what is a similar question I can ask that will give me a useful answer for less computational expense."

In terms of code quality, using try-catch structures for branching is often considered bad form. In many languages this would be a performance issue, but from my 30 seconds of googling it appears the performance impact isn't huge in python.

One adjustment you could make is to parse the file into an adjacency matrix and then using a known algorithm to solve for your lists of paths.


I don't like that you've implemented logic in Main. Move the logic into a FizzBuzz method and call that from Main. (Even though it seems really silly for such a simple program, it's not best practice to have it there.)

I'm also not a fan of hard coding 15 as the "FizzBuzz" case. What if we decide that Fizz should be 2 and Buzz should be 5? Now 15 as your first case makes no sense and Mr. Maintainer has to figure out why 15 is a case at all. It's easier to understand and maintain if (i % 3 == 0 && i % 5 == 0) {.

This might be clearer if you consider 15,3, & 5 for what they really are. They're magic numbers and as such should be stored as constants. I don't know Obj-C, so I'll provide a pseudo code example of how I think it should be done.

const int fizz = 3
const int buzz = 5

if (value % fizz == 0 && value % buzz == 0) {
    Print("FizzBuzz")
} else if (value % fizz == 0) {
    Print("Fizz")
} else if (value % buzz == 0) {
    Print("Buzz")
} else {
    Print(value)
}

This allows us to easily update the conditions.

Or alternatively (thanks to Nhgrif and David K)

int fizzbuzz = lcm(fizz,buzz);
for (value = 1; value <= 100; value++) {
    if (value % fizzbuzz == 0) {
        Print("FizzBuzz")
    }
    //etc.
}

Where lcm() is some function that returns the lowest common multiple. At that point we may be overthinking the problem, but it does result in a robust solution.


Don't mix programming language
Try to avoid mixing different languages in one program. You are creating a Frankenstein monster this way, that depends on you having to deal with multiple languages, their interaction with each other, and now your computer needs to have the necessary interpreters and libraries installed for both languages. It is also quite expensive to call os.system(), so performance suffers as well.
For the rest of the review I'm assuming you want to want to continue using Python.
Make sure your script works with Python 3
Python version 2 is obsolete, you should move to Python 3. The most important change in your script though is adding parentheses to the print-statements.
Ensure you implement your program according to the requirements
The requirements you mention say that the directory and number of days should be passed as arguments. That means you should not ask for them while the program is running. The easiest way to parse command line arguments is to use the argparse module. As a bonus, this will also automatically create a help text that will be printed when you specify the --help option on the command line.
The requirements also say you have to sort the output based on modification time. Note that your original shell command did not guarantee that the output was correctly sorted: xargs might call ls multiple times, each time with only part of the input.
Have Python produce a list of files
You can use os.listdir() to get a list of all the elements in a directory. That list might also contain the names of subdirectories, but it will not recurse into them. Use os.stat() on each element to check if it is a file or a directory, and also to get the modification time.
Add a shebang line to the top of your script
Add a shebang line to the top, so you can call your script without having to call the Python interpreter explicitly. This line can look like:
#!/usr/bin/python3

I also recommend you remove the .py extension from your script, as it will be a stand-alone script, and for the user it shouldn't matter if it's writting in Python or any other language. This way, along with the argument parsing, you should be able to call your script like so:
$ ./main . 365
./README.txt                      2019-05-09  17:19:53.193771720  +0200
./README.txt.gpg                  2019-05-09  17:20:21.331833720  +0200
./migratemost-master.zip          2019-05-20  12:52:34.867119547  +0200
./INC177759                       2019-05-23  13:29:47.014557386  +0200

Of course, the name main doesn't really tell what your script does. Give it a better name, like list_recent_files.


Let's assume the following enclosing context for your method, this gives us types to work with (types are very important in scala). Notice I changed back from CorsAction to Action since that shouldn't change anything to the types and I don't have the implementation for CorsAction at hand. Also your code doesn't give enough context to know which execution context you have in scope.

import play.api.cache.Cache
import play.api.mvc.{Action, Controller}

import scala.concurrent.Future
import scala.util.{Try, Success, Failure}

trait ResponseService{
  def create(key:String, channel:String):Try[String]
}

class Temp(responseService:ResponseService) extends Controller  {
  def submitResponse(qkey:String) = Action.async(parse.json){ req =>
    ???
  }
}

I assume you have tests for your code so I can start refactoring right away. The first thing is not going through a thread to produce a future for which we know the result and since we have imports we can use short names:

if(!currentQuestionKey.equals(qkey)){
  scala.concurrent.Future{BadRequest("Inactive or Invalid Key")}
}

should really be

if(!currentQuestionKey.equals(qkey)){
  Future.successful(BadRequest("Inactive or Invalid Key"))
}

the Future.apply will execute asynchronously in a different thread capturing exceptions as needed, here that would mean a useless context switch to assign a static value which can not throw exceptions.

The same more or less holds true for

val futureResponse = scala.concurrent.Future {
  responseService.create(qkey,channel)
}
futureResponse.map{response =>
  response match {
    case Failure(x) => { BadRequest("Duplicate " + qkey)}
    case Success(storedResponse) => { Ok(storedResponse)}
  }
}

Because of the pattern matching which is below  the Future instantiation, it seems that the return type of responseService.create is a Try[T].

futureResponse currently has a Future[Try[T]] type which encodes redondant information (see below). The futureResponse.map call can be simplified as :

futureResponse.map{
  case Failure(x) => BadRequest("Duplicate " + qkey)
  case Success(storedResponse) => Ok(storedResponse)
}

which eliminates a bit of boilerplate. By the way, curly braces are unneeded around case expression's bodies since there is no "fall through" to the next case once a case has been matched.

Try[T] will catch the same exceptions which would be caught by Future (NonFatal exceptions) therefore I will assume that the responseService.create is a very long operation. If it is not the case, then using an asynchronous controller makes no sense. If it is indeed the case and you control the signature of responseService.create, I suggest having it return a Future[T] instead of a Try[T].

Assuming you can't change the signature of responseService.create, there is still a  change (debatable) that can be made.

val futureResponse = Future(responseService.create(qkey,channel).get)
futureResponse.map( storedResponse => Ok(storedResponse) )
              .recover{ case t:Throwable => BadRequest("Duplicate " + qkey) }

I assume the type of the exception in the failure doesn't matter since your pattern matching was ignoring it too.

I have avoided Future.fromTry since that would not execute responseService.create asynchronously.

The complete code in context would look like:

import play.api.cache.Cache
import play.api.mvc.{Action, Controller}

import scala.concurrent.Future
import scala.util.{Try, Success, Failure}

trait ResponseService{
  def create(key:String, channel:String):Try[String]
}

class Temp(responseService:ResponseService) extends Controller  {
  // in scala 2.11, use
  def fromTry[T](t:Try[T]):Future[T] = {
    t.map(Future.successful).recover{case t:Throwable=>Future.failed(t)}.get
  }
  def submitResponse(qkey:String) = Action.async(parse.json){
    req =>
      val json = req.body
      val channel = json.\("section").as[String]

      val currentQuestionKey = Cache.getAs[String](channel).getOrElse("N_A")
      if(!currentQuestionKey.equals(qkey)){
        Future.successful(BadRequest("Inactive or Invalid Key"))
      }
      else {
        val futureResponse = Future(responseService.create(qkey,channel).get)
        futureResponse.map{ storedResponse => Ok(storedResponse) }
                      .recover{ case t:Throwable => BadRequest("Duplicate " + qkey)}
      }

  }
}

Actually there is a bit more which can be improved.

  val json = req.body
  val channel = json.\("section").as[String]

json is never used anywhere else, it can be inlined.

  val channel = req.body.\("section").as[String]

This will throw an exception and return a status 500 if section is not a String.

curl -X POST -H"Content-Type: application/json" -d '{"section":1234}' localhost:9000/temp/ABC

will result in

[error] [play-akka.actor.default-dispatcher-2] play - Cannot invoke the action, eventually got an error: play.api.libs.json.JsResultException: JsResultException(errors:List((,List(ValidationError(error.expected.jsstring,WrappedArray())))))
[error] [play-akka.actor.default-dispatcher-2] application -

! @6l2ocbc00 - Internal server error, for (POST) [/temp/ABC] ->

play.api.Application$$anon$1: Execution exception[[JsResultException: JsResultException(errors:List((,List(ValidationError(error.expected.jsstring,WrappedArray())))))]]
     at play.api.Application$class.handleError(Application.scala:296) ~[play_2.10-2.3.6.jar:2.3.6]
     at play.api.DefaultApplication.handleError(Application.scala:402) [play_2.10-2.3.6.jar:2.3.6]
     at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$3$$anonfun$applyOrElse$4.apply(PlayDefaultUpstreamHandler.scala:320) [play_2.10-2.3.6.jar:2.3.6]
     at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$3$$anonfun$applyOrElse$4.apply(PlayDefaultUpstreamHandler.scala:320) [play_2.10-2.3.6.jar:2.3.6]
     at scala.Option.map(Option.scala:145) [scala-library.jar:na]
    Caused by: play.api.libs.json.JsResultException: JsResultException(errors:List((,List(ValidationError(error.expected.jsstring,WrappedArray())))))
     at play.api.libs.json.JsValue$$anonfun$2.apply(JsValue.scala:67) ~[play-json_2.10-2.3.6.jar:2.3.6]
    at play.api.libs.json.JsValue$$anonfun$2.apply(JsValue.scala:67) ~[play-json_2.10-2.3.6.jar:2.3.6]
    at play.api.libs.json.JsResult$class.fold(JsResult.scala:77) ~[play-json_2.10-2.3.6.jar:2.3.6]
    at play.api.libs.json.JsError.fold(JsResult.scala:13) ~[play-json_2.10-2.3.6.jar:2.3.6]
    at play.api.libs.json.JsValue$class.as(JsValue.scala:65) ~[play-json_2.10-2.3.6.jar:2.3.6]

To avoid that you can use the validation API.

(req.body \ "section").validate[String]

will return a JsResult[String] which is either a JsSuccess(value, path) or a JsError(errors).

You can fold over that or map+getOrElse depending on your tastes. I suggest extracting the successul case to a specific method for improved readability.

The final code looks like :

import play.api.cache.Cache
import play.api.mvc.{Result, Action, Controller}

import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Try, Success, Failure}

class ResponseService{
  def create(key:String, channel:String):Try[String] = Try("x")
}

class Temp(responseService:ResponseService)(implicit app:play.api.Application, executor:ExecutionContext) extends Controller  {
  // in scala 2.11, use
  def fromTry[T](t:Try[T]):Future[T] = {
    t.map(Future.successful).recover{case t:Throwable=>Future.failed(t)}.get
  }
  def submitResponse(qkey:String) = Action.async(parse.json){  req =>
    def respondWithChannel(channel:String): Future[Result] = {
      val currentQuestionKey = Cache.getAs[String](channel).getOrElse("N_A")
      if(!currentQuestionKey.equals(qkey)){
        Future.successful(BadRequest("Inactive or Invalid Key"))
      } else {
        val futureResponse = Future(responseService.create(qkey,channel).get)
        futureResponse.map{ storedResponse => Ok(storedResponse) }
                      .recover{ case t:Throwable => BadRequest("Duplicate " + qkey)}
      }
    }

    (req.body \ "section").validate[String].fold(
      error => Future.successful(BadRequest("section was not a valid JSON string ")),
      respondWithChannel
    )
  }
}

Notice that I chose to use a class, which means you will have to inject the necessary depencies through the constructor. For local testing, I used a static compile time injection through an object instantiation:

object Temp extends Temp(new ResponseService)(play.api.Play.current,
play.api.libs.concurrent.Execution.defaultContext)

The corresponding route being

POST    /temp/:qkey     controllers.Temp.submitResponse(qkey:String)

Also note that by using the parse.json body parser any call which is made to your action without providing a json body will be rejected with a 400 error generated in the framework.


The first thing that surprise me in your code is that your map method are non-static. You would need an instance of your component to create a different instance mapping a document.

I think the method to get Components from a document should be static:

public static DownloadAppComponent of(CmsDocument cmsDocument) {
    return new DownloadAppComponent().map();
}

Now, your map methods can initialize only the attributes specific of the Class and rely on the superclass to initialize the more generics attributes:

// Map method of DownloadAppComponent class
protected DownloadAppComponent map(CmsDocument cmsDocument) {
    super.map(cmsDocument);
    setIosURL(cmsDocument.getText(IOS_URL_PATH));
    setAndroidURL(cmsDocument.getText(ANDROID_URL_PATH));
    setHidden(Boolean.parseBoolean(cmsDocument.getText(HIDE_PATH)));
    setPromoText(cmsDocument.getText(DOWNLOAD_PROMO_TEXT_PATH));
    return this;
}

// Map method of Component class
protected Component map(CmsDocument cmsDocument) {
    super.map(cmsDocument);
    setHidden(Boolean.parseBoolean(cmsDocument.getText(HIDE_PATH)));
    return this;
}

// Map method of BaseDocument class
protected BaseDocument map(CmsDocument cmsDocument) {
    setType(cmsDocument.getType());
    setName(cmsDocument.getName());
    setContentId(cmsDocument.getText(CONTENT_ID_PATH));
    return this;
}

EDIT:

If you want the map functionality in mapper classes, your mapper classes could implement a parallel hierarchy to the Component classes and still use inheritance to only initialize the attribute specific to each mapper:

public class DownloadAppComponentMapper extends ComponentMapper {

    public DownloadAppComponent of(CmsDocument cmsDocument) {
        return map(new DownloadAppComponent(), cmsDocument);
    }

    protected DownloadAppComponent map(DownloadAppComponent downloadAppComponent, CmsDocument cmsDocument) {
        super.map(downloadAppComponent, cmsDocument);
        downloadAppComponent.setIosURL(cmsDocument.getText(IOS_URL_PATH));
        downloadAppComponent.setAndroidURL(cmsDocument.getText(ANDROID_URL_PATH));
        downloadAppComponent.setHidden(Boolean.parseBoolean(cmsDocument.getText(HIDE_PATH)));
        downloadAppComponent.setPromoText(cmsDocument.getText(DOWNLOAD_PROMO_TEXT_PATH));
        return downloadAppComponent;
    }
}

public class ComponentMapper extends BaseDocumentMapper {

    public Component of(CmsDocument cmsDocument) {
        return map(new Component(), cmsDocument);
    }
    protected ComponentMapper map(Component component, CmsDocument cmsDocument) {
        super.map(component, cmsDocument);
        component.setHidden(Boolean.parseBoolean(cmsDocument.getText(HIDE_PATH)));
        return component;
    }
}

public class BaseDocumentMapper {

    public BaseDocument of(CmsDocument cmsDocument) {
        return map(new BaseDocument(), cmsDocument);
    }
    protected BaseDocument map(BaseDocument baseDocument, CmsDocument cmsDocument) {
        baseDocument.setType(cmsDocument.getType());
        baseDocument.setName(cmsDocument.getName());
        baseDocument.setContentId(cmsDocument.getText(CONTENT_ID_PATH));
        return baseDocument;
    }
}


Uploading multiple images to Google Cloud Storage using Node.js

Looks good. A few nits:

You might as well use const where you can, and let when that doesn't work. You can avoid var completely.
Instead of var filePath = 'ImagesToUpload/'-- and then modifying filePath with +=, just set filePath to the correct path immediately, ie. const filePath = 'ImagesToUpload' + file. This is just simpler and easier to read.
A subtler point: The logs are providing you your only reference to the file mapping onto the server. I'm concerned that these async functions won't necessarily run in order. Consider a huge file followed by a small file. Would the loop of files allow bucket.upload calls to be running at the same time? I would assume so. The small one would complete before the large one. If this happens, it's possible that your log console.log(file) will happen out of sequence with the console.log(publicUrl). This can be solved by moving the first console log into the loop right before the publicUrl log.
Unused arguments at the end of the list can be omitted safely in JS, so function( file, index ) can be simply function( file), or even file => if you use the new ES syntax (which you are)


Rock Paper Scissors Beginner Python Game

Welcome to Python!

Choosing Rock/Paper/Scissors/

This

if choice == 'R':
    choice = "Rock"
elif choice == 'P':
    choice = "Paper"
elif choice == 'S':
    choice = "Scissors"

can be

choice = [option for option in options if option.startswith(choice)][0]

Since you're grabbing only the first letter, you can make this comparison, instead of checking each option with its own if statement. This also takes advantage of list comprehension. The array is filled for every value that starts with choice. Since only one value will be in this list, you can simply grab the first value in the list [0].

Utilizing in

This

if choice != 'R' or 'P' or 'S':

can be this

if choice not in "RPS":

This simply checks if the choice is within the string, reducing the need to check each individual character separately.

Unnecessary while

This

while cpu_choice == choice:
    print("You chose", choice + "!")
    print("Computer chooses", cpu_choice + "!")
    break

is basically an if statement, since it's a check and only run once

if cpu_choice == choice:
    print("You chose", choice + "!")
    print("Computer chooses", cpu_choice + "!")

We can make it even neater using string formatting

if cpu_choice == choice:
    print(f"You chose {choice}!")
    print(f"Computer chooses {cpu_choice}!")

Also this

while choice != cpu_choice:

should be this

if choice != cpu_choice:

Imports

Imports should go outside of functions, and at the top of the module

import random

def main():
    ... code ...

Better Input Validation

Right now, you check if the input is valid. If it isn't, you print "Invalid choice!". But you don't stop the program. It keeps running with that choice. You can simplify this by using a while loop here, only breaking if the input is valid:

choice = input("Enter your choice: ")
while choice not in "RPS":
    print("Invalid choice!")
    choice = input("Enter your choice: ")

Unused Variables

This

game_active = True

is never used in your program. You should remove this to avoid confusion, as I initially thought this was the flag that determined if the game was to be run again.


More efficient way to narrow down a range

Worksheets have a CodeName property - View Properties window (F4) and the (Name) field (the one at the top) can be used as the worksheet name. This way you can avoid Sheets("mySheet") and instead just use mySheet. This will eliminate the shtz variable, which isn't telling us anything.

Speaking of variable names, try to give them more meaningful names - it makes it easier to follow what is happening.

Like this snippet

Sheet1.Cells(counter, searchVal))

I can tell searchVal has to be an integer, but if I saw it anywhere else, I'd think it's a string.

Also with your search columns being SchCol1 - I'm sure there's a better way to do that. Maybe productColumn and such.

I have to think your series of If Not Nothing is because you were getting errors. I also have to imagine you're passing all of these values to the above code? All the columns and all the search strings?

So, the easiest way to make this more efficient is to bring it into an array. In my example, I'm returning a string instead of a range, because I assume that's what you're after. Either way, it's an example.

Option Explicit
Sub RichardU()
    Dim lastRow As Long
    Dim lastColumn As Long
    Dim searchValues As Variant
    Dim searchArray As Variant
    Dim foundRange As Range
    Dim startRange As Range

    lastRow = 10
    lastColumn = 4
    Set startRange = Sheet1.Cells(1, 1)

    searchValues = Sheet1.Range(Cells(1, 7), Cells(1, 10))
    searchArray = Sheet1.Range(startRange, Sheet1.Cells(lastRow, lastColumn))

    Set foundRange = FindInArray(searchArray, searchValues(1, 1), searchValues(1, 2), searchValues(1, 3))

End Sub

Function FindInArray(ByVal valueArray As Variant, ByVal firstString As String, ByVal secondString As String, ByVal thirdString As String) As String
    Dim rowIndex As Long
    With valueArray
        For rowIndex = LBound(valueArray) To UBound(valueArray)
            If valueArray(rowIndex, 1) = firstString And valueArray(rowIndex, 2) = secondString And valueArray(rowIndex, 3) = thirdString Then
                FindInArray = valueArray(rowIndex, 4)
                Exit Function
            End If
        Next
    End With
End Function

So what you're doing here is bringing the entire search range into an array, passing that array to your function and matching all of the search strings at once.

You will probably have to build in some error handling. And if you want the range instead of the string, you can still bring it all into the array and return where the range would be as a pair of coordinates

Option Explicit
Sub RichardU()
    Dim lastRow As Long
    Dim lastColumn As Long
    Dim searchValues As Variant
    Dim searchArray As Variant
    Dim foundCoordinates As Variant
    Dim foundRange As Range
    Dim startRange As Range

    lastRow = 10
    lastColumn = 4
    Set startRange = Sheet1.Cells(1, 1)

    searchValues = Sheet1.Range(Cells(1, 7), Cells(1, 10))
    searchArray = Sheet1.Range(startRange, Sheet1.Cells(lastRow, lastColumn))

    foundCoordinates = FindInArray(searchArray, searchValues(1, 1), searchValues(1, 2), searchValues(1, 3))
    Set foundRange = Sheet1.Range(Cells(foundCoordinates(1) + 1), Cells(foundCoordinates(1) + 1, foundCoordinates(2) + 2))

End Sub

Function FindInArray(ByVal valueArray As Variant, ByVal firstString As String, ByVal secondString As String, ByVal thirdString As String) As Variant
    Dim rowIndex As Long
    Dim foundCoordinates() As Long
    ReDim foundCoordinates(1 To 2)
    With valueArray
        For rowIndex = LBound(valueArray) To UBound(valueArray)
            If valueArray(rowIndex, 1) = firstString And valueArray(rowIndex, 2) = secondString And valueArray(rowIndex, 3) = thirdString Then
                foundCoordinates(1) = rowIndex
                foundCoordinates(2) = 4
                FindInArray = foundCoordinates
                Exit Function
            End If
        Next
    End With
End Function

You'd just change the offsets I used to match your sheet layout.

So I was thinking about it, and I think the best way for you to simplify this would be to use a function to get the row index that matches -

Function FindArrayRow(ByVal valueArray As Variant, ByVal searchValues As Variant) As Long
    Dim rowIndex As Long
    With valueArray
        For rowIndex = LBound(valueArray) To UBound(valueArray)
            If valueArray(rowIndex, 1) = searchValues(0) And valueArray(rowIndex, 2) = searchValues(1) And valueArray(rowIndex, 3) = searchValues(2) Then
                FindArrayRow = rowIndex
                Exit Function
            End If
        Next
    End With
End Function

You would just return the row number in the array, adjust it for wherever your array started on the sheet, and use it to get the target column that you were initially looking for.


Operations on files and their locks - code too bulky?

Why not use a class to hold both the file and the lock, so you don`t need to manage two Lists like:

public class SafeDirectory {

    private File directory = null;
    private FileLock lock = null;
    private List<SafeFile> deleteableSafeFiles = new ArrayList<>();

    public SafeDirectory(String directoryPath) {
        directory = new File(directoryPath);
    }

    public boolean CanBeDeleted() {
        boolean canBeDeleted = false;
        if (directory != null && directory.canWrite() && directory.isDirectory()
                && ((lock = getLock(directory)) != null)) {

            canBeDeleted = true;
            for (File file : directory.listFiles()) {
                SafeFile safeFile = new SafeFile(file);

                if (safeFile.CanBeDeleted()) {
                    deleteableSafeFiles.add(safeFile);
                } else {
                    canBeDeleted = false;
                    System.out.println("Currently unable to write to "
                        + file.getName());
                    RelaseLock();
                    break;
                }
            }

        }
        return canBeDeleted;
    }

    public boolean Delete() {
        for (SafeFile safeFile : deleteableSafeFiles) {
            safeFile.Delete();
        }
        directory.delete();

        RelaseLock();
        return true;
    }

    private void RelaseLock() {
        for (SafeFile safeFile : deleteableSafeFiles) {
            releaseLock(safeFile.lock);
        }
        releaseLock(lock);
    }

    private boolean releaseLock(FileLock lock) {
        if (lock != null) {
            try {
                lock.release();
                System.out.println("Released lock on " + lock.toString());
                return true;
            } catch (IOException ex) {
                System.out.println("Cant release lock on " + lock.toString());
                return false;
            }
        }
        return true;

    }

    private static FileLock getLock(File file) {
        try {
            return new RandomAccessFile(file, "rw").getChannel().tryLock();

        } catch (IOException ex) {
            System.out.println(ex.toString());
            return null;
        }
    }

    private class SafeFile {

        private FileLock lock = null;
        private File file = null;

        SafeFile(File file) {
            this.file = file;
        }

        boolean CanBeDeleted() {
            return (file.canWrite() && ((lock = SafeDirectory.getLock(file)) != null));
        }

        boolean Delete() {
            return file.delete();
        }
    }
}


Positioning the left-right arrow buttons for a carousel

Is it not possible to wrap both the 'arrow' and the image inside a relative div then do some absolute position and stuff?

jsfiddle so you can change the height to see it change without javascript: https://jsfiddle.net/3bm2hp5f/1/

Code:

html, body {
  height: 100%;
  width: 100%
}

    &lt;

  <image style="width: 100%; height: 100%;"></image>

 something else


Calculating the Average Minimum Length of Random Numbers From 0 - 1 that Adds up to Greater Than 1

If I rewrite genSequence so that it takes numTrials as an argument, then I get the following timing in CPython:

Python 3.6.4 (default, Dec 21 2017, 20:33:21)
>>> from timeit import timeit
>>> timeit(lambda:genSequence(10**8), number=1)
2.71825759
62.77562193598715

Based on this, it would take about 10 minutes to compute genSequence(10**9). Possibly you just didn't wait long enough.

This kind of loop-heavy numerical code generally runs much faster if you use PyPy, which has a "just-in-time" compiler. I get more than ten times speedup with PyPy:

[PyPy 5.10.0 with GCC 4.2.1 Compatible Apple LLVM 9.0] on darwin
>>>> from timeit import timeit
>>>> timeit(lambda:genSequence(10**8), number=1)
2.71816679
5.389536142349243

On PyPy you should be able to carry out \$10^9\$ trials in under a minute (on my computer it takes 51 seconds).

Some review points:

The number 1000000000 is hard to read — it could easily be confused with 100000000 or 10000000000. I would write 10**9 to make it clear.
There's no need for the variable numberOfAttempts; you could just add one to storenums on each loop.
The name storenums is a bit vague. This is the total length of the random sequences generated so far, so a name like total_length would be clearer.
Similarly, the name genSequence is vague. This calculates the mean length of a random sequence, so a name like mean_sequence_length would be clearer.
The meaning of the constant 1 is not altogether clear. I would give it a name like target_sum.
When a loop variable like x is not used, it's conventional to name it _.
range(0,numTrials) can be written range(numTrials).

Revised code:

import random

def mean_sequence_length(trials, target_sum=1.0):
    """Return mean length of random sequences adding up to at least
    target_sum (carrying out the given number of trials).

    """
    total_length = 0
    for _ in range(trials):
        current_sum = 0.0
        while current_sum < target_sum:
            current_sum += random.random()
            total_length += 1
    return total_length / trials


I'm not sure what you mean by "used too much memory" — if I try submitting a copy of your code now, then LeetCode says:

Memory Usage: 12.3 MB, less than 57.53% of Python online submissions for Trapping Rain Water.

It is impossible to know whether the 12.3 MB is a lot or a little without knowing what this includes and how big the test cases were, neither of which LeetCode tells us.
1. Review

I found it difficult to follow the algorithm because of the proliferation of similarly named variables. There are four variables that contain heights: elevation, bound, left_bound and max_left_bound. How do these variables relate to each other? Is left_bound actually a right bound when iterating over heights in reverse? There are three variables that contain amounts of water: storage, temp_storage and block_capacity. Again, how do these relate to each other?
Finding good names for variables and writing comments to clarify any remaining difficulties, is crucial in writing code that will be maintainable when you come back to it after having forgotten how it works.

The trap function modifies the list heights (by reversing it). It's best if functions don't modify their arguments (unless modifying the arguments is the point). Otherwise callers will be surprised by the side-effects. In this case you could easily use reversed(heights) instead of heights.reverse().

The code considers each vertical slice through the landscape in turn, adding left_bound - elevation (that is, the current water height minus the current land height) to the total trapped water. But in practice left_bound (the current water height) stays the same for several iterations of the loop, so we could wait until it changes and then add the block of water all at once. See §2 below for how to do this.

2. Alternative solution
Consider a typical landscape filled with water:

If we ignore the difference between water and land, and just look at the overall surface level, it should be clear that the filled landscape is made up of rectangles arranged like this:

There is a central "plateau" whose height is the maximum height of the landscape, flanked by staircases that start low at the outside and rise up to the plateau.
If we find the height of the plateau, which is just max(landscape), then we can work inwards from the left and right ends, finding the rectangles in the rising staircases until we reach the plateau height. By summing the rectangles we get the overall area of the filled landscape, and by subtracting the land part, which is just sum(landscape), we get the water part.
def trap2(landscape):
    """Return area of water trapped by landscape (a list of heights)."""
    if not landscape:
        return 0
    plateau_height = max(landscape)
    plateau_width = len(landscape)
    total_area = 0
    for heights in (landscape, reversed(landscape)):
        height_max = i_max = 0  # maximum height so far and its index
        for i, height in enumerate(heights):
            if height > height_max:
                total_area += (i - i_max) * height_max
                if height == plateau_height:
                    plateau_width -= i
                    break
                height_max = height
                i_max = i
    return total_area + plateau_height * plateau_width - sum(landscape)

It is a bit clearer, I hope, how this works, and it is several times faster than the code in the post. The reasons why this is faster are (i) the accumulation total_area += ... is done once per rectangle, not once per vertical slice; and (ii) the subtraction of the land part is done once by calling the built-in function sum, which runs in fast compiled code.
The exact speedup depends on the shape of the landscape, but here's a test case where the revised code was about 8 times faster:
>>> from random import choices
>>> from timeit import timeit
>>> HEIGHTS = choices(range(100), weights=(100,) + (1,) * 99, k=1000000)
>>> timeit(lambda:trap(HEIGHTS), number=1) # code in the post
0.31537632799881976
>>> timeit(lambda:trap2(HEIGHTS), number=1) # revised code
0.04002986599880387

But on LeetCode it runs in much the same time as the code in the post — clearly they are not try big enough test cases to detect the difference.


You should keep 4 variables:

The start index of the longest run
The end index (or length) of the longest run
The start index of the current run
The iterating index

For performance, you'd likely also store the char of the current run in a variable.

When done iterating, return substring of longest run.


Performance

You have implemented Floyd’s Cycle-Finding Algorithm which adheres to \$0(1)\$ storage space. An alternative exists Brent’s Cycle Detection Algorithm which uses the same storage space. Check out this review on Computer Science SE for a comparison. It appears in general, Brent's algorithm is faster.

  According to Brent's paper, the complexity of Floyd's algorithm is between 3max(m,n) and 3(m+n), and that of Brent's is at most
  2max(m,n)+n, which is always better than 3max(m,n).

courtesy of Yuval Filmus' answer at CS

Style Guidelines

use var to declare a variable, specially when the type can be inferred from code
use a separate line for declaring attributes on top of members
use a white space after a method name and the opening parenthesis
use a white space after the while statement
use white space around operators (!=)
remove redundant nested else branches if the if branch always performs a return


Linux background changing daemon in Rust

since it is basically 'sleeping' most of the time

That's not really the most accurate thing...

impl Duration {
    fn new(secs: u64, nanos: u32) -> Duration
}

Duration's second argument is nanoseconds, thus your "long wait" is 750 nanoseconds. That's 0.75 microseconds / 0.00075 milliseconds / 0.00000075 seconds. For reference, a cycle of a 3GHz computer is 0.3333 nanoseconds. If your code takes zero time, you are waking 1 million times per second!

This is the very definition of a busy wait loop.

So how do you fix it? You need to rearchitect. You state:

  and abusing cron jobs to the same effect

Cron jobs have resolution of a minute (8×10^7 bigger!). If you can live with that, sleep for that long.

Another solution is to move to an event-driven system. You make some mention:

  it needs to monitor _NET_CURRENT_DESKTOP which could change at anytime.

If that's the case, you'd have two sources of events: a timer and whatever provides the _NET_CURRENT_DESKTOP event. The current front-runners of this type of code in Rust are futures and mio. I don't know exactly how the X code works, but it's probably event driven (GUI code usually is), and there's probably some mio/futures periodic timer. You "simply" need to configure both of them and then respond whenever either triggers.


Finding word acronyms for telephone numbers

This is pretty nice code.

I have two main concerns. The first one is about handling errors.
You are mixing tree approaches: Maybe, throwing explicit error, throwing implicit error (as in readNumber).
It's better to stick to Maybe or Either — they are explicit and you can handle them in pure code.

The second one is about dividing your program in meaningful functions each having single responsibility. Such functions are simpler and you can more easily compose them.

For example, getMatches checks if dictionary is not empty, adds \b to pattern and matches pattern.
It is better to split error handling from data processing (in this case by lifting dictionary check to main).

Another one is readNumber: it parses string into list of digits and implicitly checks for nondigits (throwing useless 'no parse' error).
You can skip this as you check for invalid symbols in toRegex.

Some other remarks:

the type of toRegex is so general that it almost useless. I think you actually meant Integer -> Maybe String;
in parseList you first scanning list for Nothing and then catMaybes scanning it again to remove Nothings. It is possible to do this in single pass by using sequence.

Here is my take:

{-# LANGUAGE OverloadedStrings #-}

import Text.Regex.TDFA
import qualified Data.ByteString.Char8 as B
import Data.Monoid ((<>))
import Control.Monad (when)
import System.Exit (die)
-- `die` was introduced in the latest base, you can replace it with
-- die err = putStrLn err >> exitFailure

main = do
  dictionary <- B.readFile "words.txt"
  when (dictionary == "") $ die "Your dictionary is empty."

  putStrLn "What is your phone number?"
  phoneNumber <- getLine
  case toPattern phoneNumber of
    Nothing ->
      die "Some input was incorrect. Make sure no letters or numbers with 0 or 1 are being used."
    Just pattern -> case getAllTextMatches $ dictionary =~ pattern of
      []  -> B.putStrLn $ "Sorry. No matches were found."
      res -> B.putStrLn $ "Matching words: \n" <> B.unlines res

toPattern :: String -> Maybe B.ByteString
toPattern str = do
  parts <- sequence $ map toRegex str
  return $ "\\b" <> B.concat parts <> "\\b"

toRegex :: Char -> Maybe B.ByteString
toRegex = flip lookup
  [('2', "(a|b|c)")    ,('3', "(d|e|f)")
  ,('4', "(g|h|i)")    ,('5', "(j|k|l)")
  ,('6', "(m|n|o)")    ,('7', "(p|q|r|s)")
  ,('8', "(t|u|v)")    ,('9', "(w|x|y|z)")
  ]


What is the optimal way to retrieve a list of sorted dates in a list of sorted periods in python?

Your algorithm seems fine, it seems you brought it down in complexity enough. I have thought about it and couldn't think of anything better.

Still, the code can be rewritten to be more Pythonic:

import collections
import sys
import timeit
from datetime import datetime as dt
from typing import List

RatePeriod = collections.namedtuple("RatePeriod", ["start_date", "end_date", "rate"])

periods = [
    RatePeriod(dt(2019, 1, 3), dt(2019, 4, 1), 10.7),
    RatePeriod(dt(2019, 4, 2), dt(2019, 12, 2), 20.5),
    RatePeriod(dt(2019, 12, 3), dt(2020, 1, 2), 37.8),
    RatePeriod(dt(2020, 1, 3), dt(2020, 12, 2), 41.3),
    RatePeriod(dt(2020, 12, 3), dt(2021, 1, 2), 52.7),
]

series = [
    dt(2019, 2, 20),
    dt(2019, 3, 6),
    dt(2020, 1, 5),
    dt(2020, 12, 5),
    # dt(2022, 1, 1),  # error, no period found
]

def get_rates(dates: List[dt]) -> List[float]:
    rates = []
    last_period = 0
    for idx, date in enumerate(dates, 1):
        for idx2 in range(last_period, len(periods)):
            period = periods[idx2]
            last_period = idx2
            if period.start_date <= date <= period.end_date:
                rates.append(period.rate)
                break
        if len(rates) < idx:
            sys.exit("No period found for date: {}".format(date))
    return rates

def get_rates_generator(dates: List[dt]) -> List[float]:
    last_period = 0
    for date in dates:
        for idx_period, period in enumerate(periods[last_period:], start=last_period):
            if period.start_date <= date <= period.end_date:
                last_period = idx_period
                break
        else:
            sys.exit(f"No period found for date: {date}")
        yield period.rate

result = get_rates(series)
result_generator = list(get_rates_generator(series))

setup = "from __main__ import get_rates, get_rates_generator, series"
print("Old:", timeit.timeit("get_rates(series)", setup=setup))
print("New:", timeit.timeit("list(get_rates_generator(series))", setup=setup))

expected = [10.7, 10.7, 41.3, 52.7]

assert result == result_generator == expected

where the printed output will be somewhere in the ballpark of

Old: 2.3620867
New: 2.3765742000000003

aka, the rewritten function is not actually faster.
A couple notes on the new, suggested approach:

imported datetime.datetime as dt for readability; from datetime import datetime is likely confusing and should be avoided
handling the case of not finding an item is nicely handled using for/else. In fact, it is one of the prime uses of for/else. The else block is run if no break was encountered for the entire loop. Since there is already a break in place, it is straightforward to implement the else block. This also gets rid of having to enumerate over dates.
instead of building and returning a list, a generator only yields on request. Having found a match, the loop is broken out of and yield is hit. The function exits and returns to its saved state on the next iteration. As such, list() can be called on the generator object to exhaust it fully and receive a list, as in your code. If no full list is desired, a generator is lighter than a full list.
the enumerate function, together with list slicing, can do what your range code did. This way, the new code is a bit dense on that line; since it is also verbose, I think it's manageable. I find it to be more readable.


Execution flow diagram (call-stack) of recursive count-down

It would be better to add the method arguments in the diagram, for example:

printit(0) -- n=0, prints "0,", returns 0
printit(1) -- n=1, prints "0,", returns 0
printit(2) -- n=2, prints "1,", returns 1
main()

I don't think you need 4 drawings side by side for this, just one like this would be clear enough already.


Freeing shared memory with a signal handler

There are a lot of functions that aren't safe to call in a signal handler. For the few that are allowed, look at the Async-signal-safe functions section of the signal(7) man page.

Your current signal handler is almost okay, but any variable that might be changed from a signal handler needs to be declared volatile. Officially it must also be sig_atomic_t instead of int, though I'm not sure how important that is on real-world platforms.

You should be checking the return value of printf and scanf. They will return EOF (which is usually -1 but could theoretically be any negative number) with errno set to EINTR if the signal has been delivered during the underlying system call. That said, there is nothing to prevent the signal from being delivered before or after the syscall itself (before scanf is the nasty case, and doing the syscall yourself won't help unless the signal is blocked around the call).

If you want to handle signals in any sort of sane way, you need to sigblock them, at least some of the time. Either then unblock them during "safe" runs of code and check the flag periodically or else leave them blocked call sigwait (which will not invoke the handler).

My preference is to then use signalfd so that I can stuff it in a select or poll or epoll set along with any other read- or write- file descriptors.

There is no good reason for you to make 4 separate mmap calls. Most likely a single call for 4 * sizeof(int) would be enough, but even if you have a pressing need for them to be on separate pages, you should still mmap 4 pages in a single call.

You don't need to open "/dev/zero" to get anonymous memory, just pass -1 as the FD and add the MAP_ANONYMOUS flag.

Your child should call _exit, not exit.

PIDs should be stored in a variable of type pid_t.

Any memory that you read/write from multiple processes (or threads) must be protected either by some sort of mutex or by atomic operations with an appropriate memory order. It would not be enough to volatile.

So the following line may be optimized to be an infinite loop:

while (*flag);

Edit: It does indeed happen. Looking at the relevant assembly (at -O3):

# *flag = 1;
  400840:       mov    DWORD PTR [r12],0x1
# child_pid = fork();
  400848:       call   400720 <fork@plt>
  40084d:       mov    esi,0x4009c0
  400852:       mov    r14d,eax
  400855:       mov    edi,0x2
# signal(SIGINT, intHandler); - oh, this should be before the fork!
  40085a:       call   4006c0 <__sysv_signal@plt>
# 3-way branch for child_pid
  40085f:       test   r14d,r14d
  400862:       js     400885 <main+0x155>
  400864:       je     400897 <main+0x167>
# child_pid > 0
  400866:       mov    edx,DWORD PTR [r12]
# if (*flag) - condition only tested once
  40086a:       test   edx,edx
  40086c:       je     400870 <main+0x140>
# infinite loop
  40086e:       jmp    40086e <main+0x13e>
# else
  400870:       mov    esi,DWORD PTR [r13+0x0]
  400874:       mov    edi,0x400af2
  400879:       xor    eax,eax
# printf("The sum is: %d\n", *sum);
  40087b:       call   400680 <printf@plt>
  400880:       jmp    400772 <main+0x42>
# child_pid < 0
  400885:       mov    edi,0x400ae5
# printf("Fork error. \n");
  40088a:       call   400660 <puts@plt>
  40088f:       or     edi,0xffffffff
# exit(-1); - should use 1 or EXIT_FAILURE actually.
  400892:       call   400710 <exit@plt>
# child_pid == 0
  400897:       mov    edi,0x2
  40089c:       mov    esi,0x1
# signal(SIGINT, SIG_IGN); //ignore ctrl+c
  4008a1:       call   4006c0 <__sysv_signal@plt>
  4008a6:       mov    eax,DWORD PTR [rbx]
  4008a8:       add    eax,DWORD PTR [rbp+0x0]
  4008ab:       xor    edi,edi
# *sum = *num1 + *num2;
  4008ad:       mov    DWORD PTR [r13+0x0],eax
# *flag = 0;
  4008b1:       mov    DWORD PTR [r12],0x0
# exit(0);
  4008b9:       call   400710 <exit@plt>


The most Pythonic solution would be to use itertools.islice from the standard library. For example, like this:

from itertools import islice

class Sliceable(object):
    """Sliceable(iterable) is an object that wraps 'iterable' and
    generates items from 'iterable' when subscripted. For example:

        >>> from itertools import count, cycle
        >>> s = Sliceable(count())
        >>> list(s[3:10:2])
        [3, 5, 7, 9]
        >>> list(s[3:6])
        [13, 14, 15]
        >>> next(Sliceable(cycle(range(7)))[11])
        4
        >>> s['string']
        Traceback (most recent call last):
            ...
        KeyError: 'Key must be non-negative integer or slice, not string'

    """
    def __init__(self, iterable):
        self.iterable = iterable

    def __getitem__(self, key):
        if isinstance(key, int) and key >= 0:
            return islice(self.iterable, key, key + 1)
        elif isinstance(key, slice):
            return islice(self.iterable, key.start, key.stop, key.step)
        else:
            raise KeyError("Key must be non-negative integer or slice, not {}"
                           .format(key))

Note that I've given the class a better name, written a docstring, and provided some doctests.


Proceed when prevReading file does not exist?

Your script proceeds to create the file first, and then almost immediately performs the same calculation. In this case, it might be better to just create the file first, exit from the script and then wait for its next invocation to do the comparison.
Performing the same calculation twice

You are repeating the same commands for setting prev and current, so you should put it in a function:

checkDiskUse() {
    df "$monDrive" | awk '/\'"$monDrive"'/{printf "%0.2f",$3/$2*100; exit}'
}

cut -d' ' -f23/24 can be substituted with awk

As illustrated above, awk can 'solve' your weird usage of cut-ting on whitespaces, and then calling bc on them. Your use of cut assumes that the relevant line has your desired values (used / total) exactly 23 whitespaces before them, which may be wrong in the future. Let awk do the whitespace parsing for you instead, and simply extract the third and second values respectively ($3, $2).
Validate file contents

It's good practice to sanity check that the file you are reading from has valid data. A simple way to do so is to check if printf is able to parse it correctly or not:

printf "%0.2f" "$prev" > /dev/null || exit

If the input value $prev is valid, printf returns with a successful exit code. Otherwise, the statement proceeds to the 'or' || part and exit the script as a fail-safe measure.
[ vs [[

As you have discovered, the basic test command [ does not deal with decimal values, but bash's built-in [[ conditional expression happens to handle that well. Compare:

$ [ 0.601 -gt 0.6 ] && echo Y
bash: [: 0.601: integer expression expected
$ [[ 0.601 > 0.6 ]] && echo Y
Y

To sum it up

monDrive=/opt
prevReading=/root/diskcheckreading.txt
percentThreshold=1
emailAlert=alerts@domain.com
checkDiskUse() {
    df "$monDrive" | awk '/\'"$monDrive"'/{printf "%0.2f",$3/$2*100; exit}'
}
[ -f $prevReading ] && prev=$(cat $prevReading) || { checkDiskUse > $prevReading; exit; }
printf "%0.2f" "$prev" > /dev/null || exit
current=$(checkDiskUse)
results=$(bc <<< "$current - $prev")
if [[ $results > $percentThreshold ]]
    then printf "\"$monDrive\" has grown $results%% in the past hour.\n\n$(hostname):$(pwd)/$(basename $0)" | \
        mail -s "Disk Alert - $(hostname):$monDrive" $emailAlert
fi
emailecho $current > $prevReading

Note: $monDrive is assumed to only contain / at the start, since only the first is escaped in the awk statement. Refer to comments for a somewhat hack-y workaround in vim's syntax highlighting (YMMV). Alternatively, I think using END instead of the regex might work too:

df "$monDrive" | awk 'END{printf "%0.2f",$3/$2*100; exit}'


BASH correct usage of single/double quotes when writing variables to file

Instead of embedding sudo in the script, simply require that it be run as root, either by simply failing (using set -e), or with a friendly check such as

die() { echo "$@" >&2; exit 1; }

test $UID = 0 || die "$0: you need to be a superuser!"

That echo can be made much easier to read, and can avoid the non-portable -e option, by using a here-document:

cat <<END >"$MY_FILE"
#!/bin/bash
if [ "\$1" == "$ni" ]; then
    case "\$2" in
        up)
            nmcli radio wifi off
            notify-send "cable network detected, turning WIFI off" --urgency critical --expire-time 6
            ;;
        down)
            nmcli radio wifi on
            notify-send "cable network unplugged, turning WIFI on" --urgency critical --expire-time 6
            ;;
    esac
fi
END

(I'm assuming you meant tee rather than tee -a in your code).


How to avoid duplication in my document writer?

You need to look at what's common to both methods:

StringBuilder builder = new StringBuilder();
using (StringWriter stringWriter = new StringWriter(builder))
{
    using (XmlWriter writer = XmlWriter.Create(stringWriter))
    {
        writer.WriteStartDocument();
        writer.WriteStartElement(/* different in the two methods */);
        WriteTypeHeader(writer, header);
        foreach (TypeDetail typ in TypeDetailList)
        {
            /* different in the two methods */
        }
        writer.WriteEndElement();
        writer.WriteEndDocument();
    }
}

Looks like you could have a base class with a GenerateXml method calling into abstract members that derived types (Type1XmlGenerator, Type2XmlGenerator... whatever Type1 and Type2 means) can override:

public abstract class XmlGenerator
{
    protected abstract void WriteDetails(XmlWriter writer, TypeDetail type);
    protected abstract string XmlRootNode { get; }

    public string GenerateXml(TypeHeader header, IEnumerable<TypeDetail> details)
    {
        StringBuilder builder = new StringBuilder();
        using (StringWriter stringWriter = new StringWriter(builder))
        {
            using (XmlWriter writer = XmlWriter.Create(stringWriter))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement(XmlRootNode);
                WriteTypeHeader(writer, header);
                foreach (TypeDetail detail in details)
                {
                    WriteDetails(writer, detail);
                }
                writer.WriteEndElement();
                writer.WriteEndDocument();
            }
        }
    }
}

Then you can have a class Type1XmlGenerator : XmlGenerator that will override the WriteDetails method with what you currently have in WriteType1Detail, and the XmlRootNode property getter implementation will return xmlElementConfig.CreateType1RootNode.

Now, writing/generating XML is a solved problem, doing that with a StringBuilder is error-prone. You should really look into what LINQ-to-XML (System.Xml.Linq) has in store for you.


Personally, I see no problem doing it either way. I prefer to keep my lines shorter than that but 120ish characters isn't unreasonable.

Another option you have is to store those values in some other variables and use those instead.

let isMaster = branchInfo.name === BRANCHNAMES.MASTER;
let isRelease = branchInfo.name === BRANCHNAMES.RELEASE;
let isHotfix = branchInfo.name === BRANCHNAMES.HOTFIX;
if (isMaster) {
    branchInfo.isMaster = true;
} else if (isRelease || isHotfix) {
    branchInfo.isDev = true;
}

Another way would be to use a switch statement with case fallthrough. Some people refuse to allow fallthrough so it's your call.

switch (branchInfo.name) {
    case BRANCHNAMES.MASTER:
        branchInfo.isMaster = true;
        break;

    case BRANCHNAMES.RELEASE:
    case BRANCHNAMES.HOTFIX:
        branchInfo.isDev = true;
}

Finally, I would consider just assigning directly.

branchInfo.isMaster = branchInfo.name === BRANCHNAMES.MASTER;
branchInfo.isDev = branchInfo.name === BRANCHNAMES.RELEASE ||
                   branchInfo.name === BRANCHNAMES.HOTFIX;

There's also one trick I use if I need to compare against multiple things at once.

let devBranches = [BRANCHNAMES.RELEASE, BRANCHNAMES.HOTFIX];
branchInfo.isMaster = branchInfo.name === BRANCHNAMES.MASTER;
branchInfo.isDev = devBranches.includes(branchInfo.name);

If you don't perform any extra work in either branch of the if statement, I would use the last or second to last option. If you need to perform additional work, I would use the additional variables to make it more readable.


Validating only attributes that are present in a form

You just need to change the method call from skip_validation to strip_validations.

before_validation :strip_validations

    def strip_validations
      ['teacher_number', 'title', 'name', 'gender', 'location', 'dob', 'contact_mobile', 'contact_home', 'street', 'city', 'state', 'zip_code', 'country'].each do |attr|

        errors.add("Teacher", " #{attr} can't be blank") if send(attr.to_sym) && send(attr.to_sym).blank?

      end
    end

for more specific error messages you can use

errors.add("Teacher", {attr => " #{attr} can't be blank"}) if send(attr.to_sym) && send(attr.to_sym).blank?