Conditionally display an Action depending on whether or not a player is connected

It always looks a little odd when one has to 'invent' something that seems like it ought to be a common, built-in expression, so I can understand why you ask.

Please interpret any of the following as nothing but my humble attempt to share what I know about Haskell programming. I don't consider myself a Haskell expert, and I don't know if other people would consider any of the following idiomatic...

Simplify maybeWhen

Is it necessary to pass both a predicate and a value (a) when the value itself turns out to be a Boolean value?

Would it make sense to simplify maybeWhen to something like the following?

maybeWhen' :: Bool -> Maybe b -> Maybe b
maybeWhen' b mb =
  if b then mb else Nothing

This would enable you to rewrite displayConnectionAction like this:

displayConnectionAction :: Reader GameState (Maybe Action)
displayConnectionAction = maybeWhen' <$> (not <$> isConnected) <*> action
  where
    action =
      Just . Action "Connect" "/connect" <$> currentPlayerId

    isConnected =
      asks (playerConnected . currentPlayer)

    currentPlayerId =
      asks (playerId . currentPlayer)

All of the function body (from where and down) is the same; only the composition is different.

Notice that it first maps isConnected with not, and the applies the projected value and action to the simplified maybeWhen' function.

maybeWhen' is just a composition

Instead of writing a function like maybeWhen', you can compose it from bool from Data.Bool:

Prelude Data.Bool> :t flip (bool Nothing)
flip (bool Nothing) :: Bool -> Maybe a -> Maybe a

Plugging that into displayConnectionAction means that you can now write it like this:

displayConnectionAction :: Reader GameState (Maybe Action)
displayConnectionAction = flip (bool Nothing) <$> isConnected <*> action
  where
    action =
      Just . Action "Connect" "/connect" <$> currentPlayerId

    isConnected =
      asks (playerConnected . currentPlayer)

    currentPlayerId =
      asks (playerId . currentPlayer)

Again, all code below where is the same. Notice, however, that you no longer need any helper function.

Or, instead of using the flip function, you could just flip the arguments:

displayConnectionAction :: Reader GameState (Maybe Action)
displayConnectionAction = bool Nothing <$> action <*> isConnected
  where
    action =
      Just . Action "Connect" "/connect" <$> currentPlayerId

    isConnected =
      asks (playerConnected . currentPlayer)

    currentPlayerId =
      asks (playerId . currentPlayer)

Notice that in this version, action and isConnected has changed places.

All this, however, relies on the simplification that in this particular example, the a in maybeWhen turns out to be Bool. Perhaps that's not always the case...

Use do-notation

Personally, I think this would be more readable if you rewrite the function using do notation. There are definitely Haskell programmers who consider do notation a crutch that has 'nothing to do with functional programming', but I don't share that sentiment.

Since Reader is a Monad, you could refactor the function to this implementation:

displayConnectionAction :: Reader GameState (Maybe Action)
displayConnectionAction = do
  currentPlayerId <- asks (playerId . currentPlayer)
  let action = Just . Action "Connect" "/connect" $ currentPlayerId
  isConnected <- asks (playerConnected . currentPlayer)
  if not isConnected
    then return action
    else return Nothing

Instead of having various Reader GameState values that you need to figure out how to combine, a variable like currentPlayerId is now simply an Int, and isConnected is simply a Bool.

Ultimately, though, if you often find yourself short-circuiting Bool values to Nothing, you may want to consider using guard, when, and unless with the Maybe monad. In this case, though, this would require you to use a monad transformer so that you can either stack your Reader inside MaybeT, or stack Maybe inside ReaderT.


Searching for combinations of words and numbers

I'm not a fan of the latter because the compact and flatten methods create new arrays.

Here's another variation with two additional style options: use of product to combine the two arrays, and each_with_object:

def generate_fields_3
  words   = ["foo", "bar", "bla"]
  numbers = [1, 2, 3]

  words.product(numbers).each_with_object([]) do |(word, number), fields|
    content = find_content(word, number)
    next if content.nil?

    fields << {
      kind: word,
      value: content
    }
  end
end


Copying one dimensional array bottom to top

OK, so from what I can understand about your problem is that you want to "chunk" up a one-dimensional array into a two-dimensional array with rows rows and columns columns.

I'm going to assume row-major form since that's a little bit more typical (and seems to be what your code does too).

First of all, I don't understand the condition where it has to be written from bottom to up. I don't see any reason for this, but we'll assume we do have to do that for whatever reason.

Your code does not quite work, because you've confused the row variable and the maxrowIndex variable. In the part where you are attempting to calculate the one-dimensional index based on a given row and column you use this maxrowIndex variable which hints at it actually storing the current row index. But you do not use this when indexing your two-dimensional array.

In terms of style, I have to say that I'm not a fan of opening the brace { on the next line, and especially not indenting twice each time you nest.

Here's how I would approach the problem:

Edit: clarification - the data was original written north to south ([0][0] would have been the north west corner) and we need to flip vertically so that the new [0][0] should be the south west corner.

// We ignore the first row of the original array (which is the last row of the new 2d array
for (int row = 0; row < rows - 1; row++) {
    // From first column to second last column (skips last column)
    for (int column = 0; column < columns; columns++) {
        int originalRow = rows - 1 - row;
        twodim[row][column] = onedim[originalRow*columns + column];
    }
}


user is redundant in your code, it's instantiated but never used at all so it should be removed. Another more wasteful redundancy is printing all the time, that actually slows down the code a surprising amount. You should strip them out. At most print once per loop and for exceptional circumstances (like errors).

Instead of checking if the file is empty it would be better test the lines in it and then afterwards write the password to the file. This way you write the password in the same way whether or not the file is empty, as it will just immediately find that the password isn't in the file anyway.

For the main body, you're reading in all the lines, then looping backwards over them by index to test them backwards. Is there a reason you're doing it backwards? I can't tell why you would do that. There's a lot of problems here, I would actually just start from scratch.

So, you need to test whether a password exists in the file, right? I'd make this a function first of all. So the function needs to take the password as an argument.

def exists(password):

Now we need to open the file and read each line in the file. Rather than read all the lines up front, it's much easier to read lines one by one. Python makes this incredibly easy, letting you iterate directly through the file, returning one line at a time.

    with open("MnemPass.txt") as f:
        for line in f:

Now, we can just test if the password is there and return True if it does, as this indicates that the password already exists.

            if password == line.strip():
                return True

I added .strip() to remove whitespace that might mess with the test. And then of course, if the whole file is read without this problem then you eventually reach the end of the function where you return False, indicating that it does not exist.

def exists(password):
    with open("MnemPass.txt") as f:
        for line in f:
            if password == line.strip():
                return True
    return False

Now. when we go back to the original code this makes things immensely tidier:

for mainLoop in range(passnum):
    newpass = generatePassword() # New password generated each iteration of loop
    if exists(newpass): #changed
        with open("Matchpassword.txt", "a") as passMatch:
            passMatch.write(newpass + "\n")
    else:
        with open("MnemPass.txt", "a") as storePass:
            storePass.write(newpass + "\n")

Now, this can be done even faster. If you were to go back to the function, you could use the any operator to lake the for loop and turn it into a generator expression. Generator expressions are basically like for loops condensed into a single expression. And if you pass one into any it can run a test on every element of a loop. It's faster than normal Python loops. So here's how it'd look:

def exists(password):
    with open("MnemPass.txt") as f:
        return any(password == line.strip() for line in f)

This means that if any ever finds a line that equals password then it will return True, but if it finds no such line it will return False.

After this, optimisation really ought to be done with storage. You could sort the passwords alphabetically and then intelligently detect where they should be. Maybe store in multiple files, corresponding to the starting character of the password. There's only so much that the exact code optimisation itself can do.


Case 1
The return here are good if you want to stop the execution of your function here.

Case 2
Meteor.call is asynchronous, so if (error) is not the next element on stack. You have to return false inside your event function, not inside the Meteor.call's callback.

Template.registration.events({
        "submit #register_form": function (event) {
            // This function is called when the registration form is submitted.

            event.preventDefault(); // Correct usage!

            var form_data = {
                username: event.target.username.value,
            };

            if (!Match.test(form_data.username, String)) {
                Session.set("message", "username must be a string");
                return false;  // 1 : Correct if you want to interrupt
            }

            if (form_data.username.length < 6) {
                Session.set("message", "username must be at least 6 characters");
                return false;  // 1 : Correct if you want to interrupt
            }

            Meteor.call("check_username",form_data.username,function(error, result){
                if (error) {
                    Session.set("message", error);
                }
                if (result) {
                    Session.set("message", result);
                }
                //2: Was incorrect
            });
            //2
            return false;
        }
    });

PS: You have to understand that if the submit method doesn't return false, it will send the form to the action URL. So you have to return false before the execution reaches the end of the function.


Better user experience

JavaScript is primarily for web browsers with some exceptions (like node.js). Unless your using node, you won't be able to get user input using the console. Instead of using console.log("New Hand: " + handValue) use:

alert("New Hand: " + handValue);

and to get user input you can use:

var userResponse = prompt("Dealer hits, do you HIT or CALL?");

Check out this JSFiddle to see alert and prompt in action.

You could create a much more interactive user experience using HTML, but since you're quite new to JavaScript, alert and prompt should be fine for now.

Abstracting duplicate code - Create a function to get cards

Currently, you use a randomInt function to hit the dealer and user with a new card. A random int from 1 to 11 sort of works, but it's statistically inaccurate with a deck of cards. As you get better and better at JavaScript you may eventually refactor want to edit your code to more closely models a deck of cards:

// Here is some code that more closely models a deck of cards
var cards = [];
for (var i = 1; i < 11; i++) { // for cards 1-10
  cards = cards.concat([i, i, i, i])
}
cards = cards.concat((new Array(12)).fill(10));

function drawCard() {
  return cards.splice(randInt(0, cards.length), 1);
}

The only problem is that your code is not prepared for such a refactor. You'll need to change all your calls to randInt that are intended to return cards to the new function. To prepare for this refactor, you can abstract the way you get cards into a function:

function drawCard() {
  return randInt(1, 11); // for now
}

// here are your first two cards
handValue += drawCard();
handValue += drawCard();

// here are the Dealers cards
dealerValue += drawCard();
dealerValue += drawCard();

Now any changes to your drawCard function will be changed throughout all your code.

Keeping track of cards given to dealer and user

You could keep track of the cards dealt to players by using arrays. Use one array for each player:

var userCards = [];
var dealerCards = [];

function hit(array) {
  array.push(drawCard());
}

function printHand(message, cards) {
  alert(message + "\n" + cards.join(", ");
}

//usage
hit(userCards);
hit(userCards);
hit(dealerCards);
hit(dealerCards);

printHand("You have:", userCards);
printHand("Dealer has:", dealerCards);

To get the sum of a hand, you can use a for loop:

function getTotal(cards) {
   var sum = 0;

  for (var i = 0; i < cards.length; i++) {
    sum += cards[i];
  }

  return sum;
}


I think data should just be contained in the component state, because it belongs to the TodoList:

getInitialState: function() {
    return {
        todos: [{task: "eat cheese"}, ...],
        text: ""
    };
},

which would simplify submitHandler into

submitHandler: function(event) {
    event.preventDefault();
    var todo = this.state.text;
    this.setState({
        text: "",
        todos: this.state.todos.concat([todo])
    });
},

The jQuery $('#input').val("") call is unnecessary because React should be handling that state for us. Just make the value of the <input> reflect state.text and all will flow:

<input id="input" key={this.state.timestamp} onChange={this.handleChange}
       value={this.state.text} type="text" />

In render(), the declaration of rows and the forEach can be combined into a map:

var rows = this.state.todos.map(function(todo, index) {
    return (
{todo.task}
);
});

--

In general your code is very clear. Right now your app is simple and I don't think there's much need to break it down into smaller parts.

However, as your app inevitably grows and you add more features, separating, say, TodoItem and TodoList into distinct components would be useful. When a function gets long and starts doing five or six conceptually distinct things, you separate it into smaller functions and compose them together. Same thing when classes start representing many things at once.

So some advantages of breaking things down into smaller components are modularity and composability. Your app becomes easier to test and think about.


Encapsulating logging and throwing exceptions into a method. Bad practice?

The second version removes some duplication, so it's better, but usually you should choose one of logging and rethrowing. Frameworks/appservers usually catch and log uncatched exceptions so you will have two (or more) entries for the same exception it the log file which makes debugging hard.

  Log the exception only once!

  One of the common pain points that I have noticed is logging and
  rethrowing an exception. As a result, the log files contains the same
  exceptions several times on several stack levels.

Author: Nayaki


Portable (Linux, Cygwin,...) Makefile for my own Shell OpenSSL file en-/decryption scripts

The check target always succeeds (because the last command in the pipeline is echo).  We'd like it to fail if any of the tests fail, so we should just write them one per line.  Instead of testing for the existence of the files, we should make the check target depend on them:
check: $(script_name_1)  $(script_name_2)
    sha512sum --check SHA512SUMS
    @echo "OK: Files are prepared. You may use make install command now."

BTW, script_name_1 and script_name_2 are completely unhelpful variable names.  How about encrypt and decrypt, for example?

I think the install target should depend on check - we really don't want to install if the check fails:
install: check

I'm not convinced that this is a good thing:
user_id=$(shell whoami)
group_id=$(shell id -gn)

When we install software, we normally make it owned by an appropriate user on the system, not the person doing the installing.  In most cases, programs are owned by root, so that no ordinary user can accidentally overwrite them (or any other harmful action).

Make provides a $(RM) definition to give you a more portable command for deleting files.

It's great that you've thought about install location and about overridability of such parameters.  You probably ought to know the conventional variables that are used for these:

DESTDIR specifies where the root directory is.  This is usually empty, but packaging tools set this to a suitable working directory to build a (partial) filesystem image that can be archived.
PREFIX works somewhat like your DESTDIR or install_path (I'm not sure why you have two names for the same thing).

This is a rare Makefile that doesn't need .DELETE_ON_ERROR: (since it contains no non-PHONY targets).

Modified code
This is what I ended up with:
PREFIX = /usr/local

install_path = $(DESTDIR)$(PREFIX)/bin

encrypt = encrypt-file-aes256
decrypt = decrypt-file-aes256

check: $(encrypt)  $(decrypt)
    sha512sum --check SHA512SUMS
    @echo "OK: Files are prepared. You may use make install command now."

install: check
    install --d -D $(install_path)
    install -m 0755 -t $(install_path) $(encrypt) $(decrypt)

uninstall:
    $(RM) $(install_path)/$(encrypt) $(install_path)/$(decrypt)

.PHONY: check install uninstall

Note that Make variables specified on the command line will override those in the Makefile, so you can write
make install PREFIX="$(HOME)/testing"

to install to your test directory, for example.


The code is very suboptimal. Keep in mind that Project Euler problems are not about brute force.

You only need to count the distinct powers. You don't have to actually calculate them. Instead, you need to realize that

a base \$a\$ may generate a repeat only if it is a perfect power itself.
each base which is not a perfect power contributes the same amount of unique elements (that is, there is 98 powers of 2, 98 powers of 6, etc) and all such sets are fully disjoint.
sets of elements generated by \$a\$, \$a^2\$, ... \$a^{100}\$ and \$b\$, \$b^2\$, ... \$b^{100}\$ are also equipotent and disjoint.

So, to obtain a solution you need to find out

how many numbers below \$b\$ are not perfect powers (linear complexity),
how many elements are in each set (also linear complexity; think of unique numbers in a multiplication table)

and multiply the results.


Random Password Generator based on user input

At the top of the module use triple quotes to document things instead of using comments. At the top level it will also act as a docstring for your module.
Use random.choice on the iterable instead of getting a random int first and then using it get an from iterable.
if answer == "Y" or answer == "y" etc can be replaced with if answer.lower() == "y".
Use better variables names, for example a and b in FunRun(a, b) doesn't make any sense.
Use new style string formatting instead of the old sprintf based syntax. Or better join str.join in your case if you want to merge bunch of items.
Your code has too many PEP 8 issues as per PEP8 online tool. You should check PEP 8 and use extensions like flake8, pylint etc to catch those.


A generic file helper for my future projects

Imports

It's really uncommon to use the as part of the import. The only time I see it is in NumPy, which is a pretty un-Pythonic library.
I recommend to only use import rather than from ... import statements. This is as it's harder to determine what has been imported from where.
When importing datetime I find it best to only use import datetime. Given that one of the classes is called datetime it can lead to situations where it's unknown what datetime is without having to then look at the imports.

Class

I think you're on the right track, but you've added too much into your class. This is commonly referred to as the god-class anti-pattern.

I think it's a good idea, as pathlib implements a lot of the same stuff that you are doing. Whilst I can understand and would possibly encourage some extensions to the class, I don't think all your changes are great additions.

The following functions can all be replaced with pathlib in some form. Note that the entire of the bottom chunk can utilize Path.stat.

self.full_name = Path.name
self.name = Path.stem
self.extension = Path.suffix
self.dir_path = Path.parent
self.dir_name = Path.parent.name

Path.stat:
    datetime:
        self.created = os.path.getctime
        self.last_modified = os.path.getmtime
        self.last_accessed = os.path.getatime
    self.size_in_bytes = os.path.getsize

Datetime

I don't think this should be re-added to your class. If you feel it's of great importance then you should interface with os.stat_result. This means that using legacy and pathlib interfaces work with your changes.

Usage could be as simple as:

stats = DateTimeStat(os.stat(...))

Size Format

This shouldn't be on the class. If you want to format a number that is in bytes then define a function, not a method, to do this for you. This has the benefit of you being able to pass any number from any origin to the function and it will still happily work, DRYing up your code.

There are three common prefixes schemes when denoting binary sizes.

Metric (SI) prefixes - These are base 1000 and are the units you see pretty much everywhere in science. Much like I can have 1km, I have have 1kB. Which means 1000unit.
ISO binary prefix - There are base 1024 and are common when addressing binary data. The kibibyte, KiB, is 1024B.
JEDEC prefixes - These are discouraged by IEEE as they are confusing. It's not immediately apparent if you are using SI or JEDEC prefixes. These are base 1024 and only define the K, M, G prefixes.

I suggest you stick to SI with base 1000 and ISO with base 1024.
An example of all of them, 1Mib is 131.072kB and 128KB.

import functools

def size_format(size, base, units):
    for unit in units:
        if size < base:
            break
        size /= base
    return size, unit

size_bytes_format = functools.partial(
    size_format,
    base=1000,
    units='B kB MB GB TB YB'.split(),
)
size_ibytes_format = functools.partial(
    size_format,
    base=1024,
    units='B KiB MiB GiB TiB YiB'.split(),
)

Duplicating

I can't see this function being that useful. Even if I can't see a use, I wouldn't recommend adding it to the class. This is just a simple for loop. It's reasonable, and probably more readable, to defer this to the client code.

Result

Given all the above I would remove all the operations that act on an opened file. And it would result in the following class.

class Path(pathlib.Path):
    def unzip(self, destination=None):
        if destination is None:
            destination = self.parent
        with zipfile.ZipFile(self, 'r') as target:
            return target.extractall(destination)

    def copy(self, destination):
        return shutil.copy(self, destination)

File interactions

As stated earlier you shouldn't open the file in Path. I don't really see much benefit your class has over just using open. For example, it doesn't allow streaming and is pretty memory intense.

How is your code better than open and how is open better than your code?


Fold large input lines into smaller ones

The length() function can be replaced using strlen() (you'll need to include <string.h>).  Note that strlen() doesn't consider the terminating NUL to be part of the string - but that will help fix the current bug that causes this code to print that NUL.

Don't measure the length repeatedly - instead, save it to a variable early on, and refer to that variable.

Error messages should go to standard error stream, not standard output:

if (argc < 3) {
    fprintf(stderr, "Usage: %s input cols\n", argv[0]);
    return 1;
}

Don't use uppercase names for variables - we reserve those for macros; the "SHOUTING" of the name warns us that they need special care.

Also, don't use atof() for converting integers - use atoi(), or better, strtoul(), which can tell you whether it succeeded:

char *parse_end;
size_t col_bound = strtoul(argv[2], &parse_end, 10);
if (parse_end == argv[2] || *parse_end) {
    fprintf(stderr, "Usage: %s input cols\n", argv[0]);
    return 1;
}

Prefer one declaration per line, and initialise immediately:

size_t startCol = 0;
size_t currentCut = 0;
size_t nextBound = 0;
size_t numOfCuts = 0;

Be careful about off-by-one errors.  This inequality should be <, not <=:

while ((nextBound = startCol + col_bound - 1) < length) {

It's not the only one.

Test more inputs.  I tried a very simple case and got unexpected output:

./194156 'a b c d e f' 3

a b
c
d e
f
Original string split into 4 parts(bound was 3)

Why did it not split into 3 lines?


Sugestion on a better way to code this EF update?

As @dreza mentioned, you might want to move the code around your LINQ-Statements to a method.

public void changeCategoryTo(String newCategory){
   var record = (from n in db.Navigation where n.Category == newCategory
                   && n.SectionId == SectionID select n).First();
   record.Category = newCategory;
}

this greatly reduces duplication.

further points:

Try to stick to either camelCase or MixedCase to have consistent and speaking variable names:

something like var Category, String PrimaryCategory and similar are diffifult to associate to clear roles in your code.
try to refrain from naming your variables after their type only, this leads to greatly increased effort when handling multiple objects of the same type.

Your if-statement for updating the SecondaryCategory is different from the if-statement for updating PrimaryCategory


There's nothing intrinsically time-consuming here code-wise - I think the best approach is to make sure that your database tables are set up correctly with the required indices. Perhaps create a view on the db to push some work onto that rather than select in code?

I am a little puzzled however by your middle_consumption function. The inner loop contents do something like:

get a date, x years ago from present day
get a reading on that date, or 0 on failure
add that reading to the results
go through the results
    if the current item is 0, delete the **first** item

This seems wrong.

What happens on February 29th? It would be better to add 365 days if that's appropriate for your application.
Why add a value only to (presumably want to) delete it again?  Would something like this be better?

try:
    current_value = Reading.objects.get(
        date = date_of_reading,
        meter = self.meter,
        code = self.code
    ).consumption
except Reading.DoesNotExist: # or suitable exception
    current_value = 0
if current_value > 0:
    anniversary_values.append( current_value )


Generating and sending new password to user

Before reviewing the code, the concept itself has some flaws:

It is possible to reset the password of another user by entering their email address or username.
The password is provided directly in the email which is bad practise (not only is this in clear text but it will be retained in the user's inbox which is not a good place to store passwords).

Entering the email or username should display the same message to the website user regardless of whether the user exists or not. This would stop an attacker from enumerating usernames (i.e. finding whether a particular username or email address is registered on your system). In the email itself include either the details of a password reset link or an account not found message as appropriate for that username/email - this way only the email address owner can see whether they have an account on your system.

The password reset link should be include a time limited reset token that will allow the user to change their password to one of their choosing and it should not then email this out anywhere. Make sure the token is securely generated and does not use a predictable sequence (i.e. a cryptographically secure sequence and not one generated using a Random).


The operation you want is called flatMap, SelectMany, or concatMap (I might have missed a few names.)

  Map a function over a collection and flatten the result by one-level

As far as I'm aware, this isn't provided out-of-the-box but I found an implementation here:

Array.prototype.flatMap = function(lambda) {
  return Array.prototype.concat.apply([], this.map(lambda));
};

Then you can just write

var persons = data.fathers.flatMap(function(father) { return father.daughters; });

Or if you can use arrow functions,

var persons = data.fathers.flatMap(father => father.daughters);


Display PHP Menu Stored in an Array and Looped

I'm not sure for optimization but for readability and maintenance I would use a Class and create the menu items as objects instead of multi-dimension arrays.

class MenuItem {

  protected $id;
  protected $name;
  protected $url;
  protected $level;
  protected $seq;
  protected $under;
  protected $target;
  protected $display;

  public function __construct($name, $url, $id, $level, $seq, $under, $target, $display) {
    $this->id = $id;
    $this->name = $name;
    $this->url = $url;
    $this->level = $level;
    $this->seq = $seq;
    $this->under = $under;
    $this->target = $target;
    $this->display = $display;
  }

  public function getId() {
    return $this->id;
  }

  public function getName() {
    return $this->name;
  }

  public function getUrl() {
    return $this->url;
  }

  public function getLevel() {
    return $this->level;
  }

  public function getSeq() {
    return $this->seq;
  }

  public function getUnder() {
    return $this->under;
  }

  public function getTarget() {
    return $this->target;
  }

  public function getDisplay() {
    return $this->display;
  }

}

And so your creation code would become:

$siteURL = "http://www.mysite.org/";

$menu = array
   (
   //"Name","URL",ID,Level,Seq,Under,Target,Display
   //First Menu
   new MenuItem("TOP1",$siteURL."top1.php",1,1,1,0,0,true),
   new MenuItem("SUB1a",$siteURL."sub1a.php",2,2,1,1,0,true),
   new MenuItem("SUB1b",$siteURL."sub1b.php",3,2,2,1,0,true),
   new MenuItem("SUB1c",$siteURL."sub1c.php",4,2,3,1,0,true),
   new MenuItem("SUB1d","http://www.externalsite.org/",5,2,4,1,1,true),
   new MenuItem("SUB1e","http://www.externalsite.org/",6,2,5,1,1,true),
   new MenuItem("SUB1f",$siteURL."sub1f.php",7,2,6,1,0,true),

   //Second Menu
   new MenuItem("TOP2",$siteURL."top2.php",8,1,2,0,0,true),
   new MenuItem("SUB2a","http://www.externalsite.org/",9,2,1,8,1,true),
   new MenuItem("SUB2b",$siteURL."sub2b.php",10,2,2,8,0,true),
   new MenuItem("SUB2c","http://www.externalsite.org/",11,2,3,8,1,true),
   new MenuItem("SUB2d","http://www.externalsite.org/",12,2,4,8,1,true),

   //Third Menu
   new MenuItem("TOP3",$siteURL."top3.php",13,1,3,0,0,true),
   new MenuItem("SUB3a","http://www.externalsite.org/",14,2,1,13,1,true),
   new MenuItem("SUB3b","http://www.externalsite.org/",15,2,2,13,1,true),
   new MenuItem("SUB3c","http://www.externalsite.org/",16,2,3,13,1,true),
   new MenuItem("SUB3d","http://www.externalsite.org/",17,2,4,13,1,true),

   //Fourth Menu
   new MenuItem("TOP4",$siteURL."top4.php",18,1,4,0,0,true),
   new MenuItem("SUB4a",$siteURL."downloads/sub4a.pdf",19,2,1,18,0,true),
   new MenuItem("SUB4b",$siteURL."sub4b.php",20,2,2,18,0,true),

   //Fifth Menu
   new MenuItem("TOP5",$siteURL."top5.php",21,1,5,0,0,true),

   //Sixth Menu
   new MenuItem("TOP6",$siteURL."top6.php",22,1,6,0,0,false),

   //Seventh Menu
   new MenuItem("TOP7",$siteURL."top7.php",23,1,7,0,0,false),

   //Eighth Menu
   new MenuItem("TOP8","http://www.externalsite.org/",24,1,8,0,1,true),

   );

Then you can access values in a more readable way. E.g.

foreach ($menu as $menuItem) {
  if (($menuItem->getLevel() === 1) && ($menuItem->getDisplay() === true)) {
    ...
  }
}


The functions says it "Returns fist index of element if present".  If I give it the numbers 2, 2, 2 and ask it to find 2 it says the 1, but the first index with value 2 is clearly 0.

Some minor comments on the code:

the arr parameter to bin_search should be const.  This tells the compiler and the reader that the array is not changed by the function.  The compiler will then enforce this if you, by mistake, try to modify the array data.  The reader/user knows that her data is unchanged after the call.
the parameter names min_index and max_index could be shortened to min and max.  Giving names an appropriate size is a service to the reader (auto-completion by the IDE is a service to you).  In general, the shorter the names, the less dense the code and the easier it is to read.  This can be taken too far of course, once names become meaningless.
Note that it would be more normal to pass the start of the array and its size instead of the array plus two offsets.
functions could be static.  This is of no significance in a one-file program but becomes important with bigger programs.  Making functions and global variables static restricts their scope to the file which allows extra optimisation and reduces namespace pollution.
the output message needs a trailing \n
there is no prompt for the input values - ok that is trivial. Personally I find this sort of test better with values entered on the command line.
exit status is normally 1 (EXIT_FAILURE) on failure, not -1.  On success it is 0 (EXIT_SUCCESS).  These are UNIX conventions.

EDIT

You questioned the use of const. Its utility when used on parameters passed by
reference - pointers/array passed into functions - is, I think clear.

However, its use with parameters passed by value is not so clear.  It plays no
part in the interface seen by callers of a function, as it can have no
influence on the caller.  You can declare a function prototype in a public
header like this

int bin_search(const int arr[], int min, int max, int element);

and then define the function implementation like this:

int bin_search(const int arr[], const int min, const int max, const int element) {...}

And the compiler will be quite happy with the difference.

So it is purely an implementation issue.  Hence you should definitely not use const on pass-by-value parameters in public prototypes, only in the implementation (if at all).  Used in the implementation, const tells the reader and the compiler
that a parameter is not (and cannot be) changed.  This gives the reader some
extra information and of course the compiler will enforce this read-only
behaviour.

So shouldn't you use it on all parameters that are not changed (and some might say that parameters should never be changed)?  Good question!  I never use const on call parameters but would have no hesitation in adding const to a local variable

int cirle_area(double radius)
{
    const double pi = 3.14;
    return pi * radius * radius;
}

A lot of good programming style concerns consistency, so my inconsistency here
is troubling.  And my previous comment - that if you make the element
parameter const, then you should be consistent and do the same for min and
max uses consistency as an argument!

I'm afraid I can do no better than that.  I've programmed for 20 years in C
and have rarely seen const applied to parameters. But maybe it should be.


Compute binary XOR of all integers in a range, mod 2

Welcome to CR, nice challenge

A few comments about the code

Many unnecessary conversion

Python is a duck typed language, if it talks like a duck, walks like a duck... it must be a duck!

This means that

p ^= int(x)

Here x is already an int, same goes for the str conversion later
Use _ variable names for variable you don't use

  for i in range(int(t)):

Replace the i with _
You could return directly

if p % 2 == 0:
    return "Even"
else:
    return "Odd"

Instead, you could do which uses a ternary operator

return "Even" if p % 2 == 0 else "Odd"

As for the speedup

I've used this SO link to inspire me, which does a way better job of explaining this then I could ever do

In short there is a trick to get the XOR'd product of a certain range

Using the method from the link, I get a massive speedup,

For these timings: range(1, 1000)

Bitmagic:  0.023904799999999997
OP: 2.2717274

Code

# https://stackoverflow.com/questions/10670379/find-xor-of-all-numbers-in-a-given-range
def bit_magic(bound):
    magic = [bound, 1, bound + 1, 0]
    return magic[bound % 4]

def bitwise_check(lower_bound, upper_bound):
    p = bit_magic(upper_bound) ^ bit_magic(lower_bound - 1)
    return "Odd" if p & 1 else "Even"

def main():
    n = int(input("Number of testcases: "))
    for _ in range(n):
        lower_bound, upper_bound = map(int, input().split())
        print(bitwise_check(lower_bound, upper_bound))

if __name__ == '__main__':
    main()


Maximum subarray problem solved with divide and conquer also for the all negative element case

Bugs

Your sum in max_cross_sub() could overflow an int, causing a change in sign.  Therefore, you could either miss the maximum subarray if your sum erroneously became negative, or get the wrong subarray if your sum erroneously became positive.
It seems that you want lower and upper to return the bounds of the maximum subarray.  Otherwise you could just pass those arguments as regular integers instead of pointers.  However, max_sub() doesn't set the correct bounds in the case of cross_sum being the max sum.
In addition to #2, max_cross_sub() doesn't set *lower and *upper to the correct bounds.  The problem is that you don't set max_left and max_right correctly, so you end up leaving the bounds unchanged from whatever was passed in.
This line isn't right:

printf("%d %d\n",max_sub(a, &lower, &upper), max_noncont_sub(a, &lower, &upper));

The problem with it is that the call to max_sub() changes lower and upper, so that the call to max_noncont_sub() has the wrong bounds passed in.  You should use two separate copies of the lower and upper bounds instead.

Better way

Clearly you already knew about Kadane's algorithm, because you mentioned it.  The question is why you didn't use it?  Not only is it faster, it's also only 6 lines of code compared to the roughly 60 lines you used to do it the divide and conquer way.


Map client application's DTO to service-proxy's DataContract

Is it good to map every DTOs into Proxy's DataContract? As my this
  class will grow with more service calls with different DTOs.

Yes, mapping to your own domain improves modularity by decoupling the DTO library from your domain.

  How this class should be architect so that it doesn't violate
  SRP/Design-patterns?

Use either a custom or existing mapping framework to remove the boiler-plate mapping code from your flow. You could create a Mapper class.
Consider using AOP for refactoring boiler-plate try-catch blocks. You could create a LogEntryExitAndErrorAnnotation class.
Your reponse object is not required
Use a using block to dispose the client
Don't use a boolean, when it is always true on success, and hidden when an exception occured.

adapted:

     [LogEntryExitAndErrorAnnotation]
     public void Send()
     {
          var sd = mapper.Map<Proxy.MessageProcessorProxy.SessionDetails>(_sessionDataDTO);

          // see notes below why to use an adapter
          using (var client = new MessageProcessorClientAdapter(
              new Proxy.MessageProcessorProxy.MessageProcessorClient()))
                  client.LogEventDetails(sd);
     }

Note on (4)

As the OP pointed out: Dispose could hide the root exception.

To avoid this, you can use an adapter. I would use T4 templates to generate these for all my clients.

Suppose your client interface is

public interface IMessageProcessorClient : IDisposable {
    void LogEventDetails(object data); // or typed class
}

You can use the code below to have the best possible exception details. If no error occured during the operation, the error of Dispose is thrown, else an aggregate error is thrown.

public class MessageProcessorClientAdapter : IMessageProcessorClient {
    public IMessageProcessorClient Source {get; private set;}
    public Exception Error {get;private set;}
    public MessageProcessorClientAdapter(IMessageProcessorClient source) {
        this.Source = source; // check for null
    }
    public void LogEventDetails(object data) {
        try {
            this.Source.LogEventDetails(data);
        } catch (Exception error) {
            this.Error = error;
        }
    }
    public void Dispose() {
        try {
            this.Source.Dispose();
        } catch (Exception error) {
            if (this.Error == null) {
                this.Error = error;
            } else {
                this.Error = new AggregateException(this.Error, error);
            }
        } finally {
            if (this.Error != null) {
                throw this.Error;
            }
        }
    }


I'm guessing that you call this method frequently.  If so, you might consider memoizing the result.  Something like

private Map<Player, ChatColor> playerChatColors = new HashMap<>();

in the class.  Possibly make this static.  And then at the beginning of the method, replace

    ChatColor color = ChatColor.GRAY;

with

    ChatColor color = playerChatColors.get(p);
    if (color != null) {
        return color;
    }
    color = ChatColor.GRAY;

And then before the return at the end, add something like

    playerChatColors.put(p, color);

I don't know if this is faster or not.  In the typical case, it will just do a single hash access.  If that is fast, then it's faster.  If that's slow, then it might not be.

There's also the problem that if the permissions change, this won't adjust.   I'm assuming that this will be rare enough not to matter.  If that's not so, you might need to find a way to invalidate the caching when permissions change.  Of course, if you invalidate too often, you lose the benefits of caching.  The first call to this method will be slower.  It's the subsequent calls that this might help.


Probably something like this would enable you to extract it. Basically I'd suggest looping through hiding everything then setting the one you want to open, you could be clever and check if the menu selected is already one, but hopefully this will give you the idea:

$("menubar ul").each(function(){
   $("li", this).click({
      $("menubar ul").each(function(){
         $("li ul", this).hide()
      })
      $("ul",this).toggle(...
   })
})


Handling Enum flags for a copy operation

For an aesthetic point of view, you could define some constants:

AllEstimations = Copy.All | Copy.Estimations
SingleEstimations = Copy.Single | Copy.Estimations
etc.

You could then check the value against these constants and create a single level if statement:

if (copyType == SingleEstimationsSubItems)
{}
elseif (copyType == SingleEstimations)
{}
elseif (....

I'm not claiming this will improve performance, but it will make the code more readable.


Dynamic filtering and sorting with Entity Framework

EDIT: I apologize from my earlier sample that didn't quite compile. I've fixed it and added a more complete example.

You could associate each condition with a strategy for changing the query. Each strategy (called SearchFieldMutator in this example) will hold two things:

A way to decide if to apply the strategy.
The strategy itself.

The first part is a delegate (of type Predicate<TSearch>) that returns true or false based on the data in the UserSearchViewModel (or any other type, since it only defines a generic type TSearch). If it return true, the strategy is applied. If it returns false, it's not applied. This is the type of the delegate:

Predicate<TSearch>

(it could also have been written as Func<TSearch, bool>)

The second part is the strategy itself. It is supposed to 'mutate' the query by applying a LINQ operator to it, but really just returns a new query with the added operator, and the caller of it should discard the old query and keep the new one. So it's not really mutation, but it has the same effect. I've created a new delegate type for it, so its usage is clear:

public delegate IQueryable<TItem> QueryMutator<TItem, TSearch>(IQueryable<TItem> items, TSearch search);

  NOTE: I've defined both the item type and the search data as generic types (as TItem and TSearch, respectively) so this code is usable in multiple locations in your code. But if this is confusing, you can remove the generics completely, and replace any TItem with UserListItem and any TSearch with UserSearchViewModel.

Now that we have defined the two types of the strategy, we can create a class that holds them both, and also does the (simulated) mutation:

public class SearchFieldMutator<TItem, TSearch>
{
    public Predicate<TSearch> Condition { get; set; }
    public QueryMutator<TItem, TSearch> Mutator { get; set; }

    public SearchFieldMutator(Predicate<TSearch> condition, QueryMutator<TItem, TSearch> mutator)
    {
        Condition = condition;
        Mutator = mutator;
    }

    public IQueryable<TItem> Apply(TSearch search, IQueryable<TItem> query)
    {
        return Condition(search) ? Mutator(query, search) : query;
    }
}

This class holds both the condition and the strategy itself, and by using the Apply() method, we can easily apply it to a query if the condition is met.

We can now go create out list of strategies. We'll define some place to hold them (on one of your classes), since they only have to be created once (they are stateless after all):

List<SearchFieldMutator<UserListItem, UserSearchViewModel>> SearchFieldMutators { get; set; }

We'll then populate the list:

SearchFieldMutators = new List<SearchFieldMutator<UserListItem, UserSearchViewModel>>
{
    new SearchFieldMutator<UserListItem, UserSearchViewModel>(search => !string.IsNullOrWhiteSpace(search.Name), (users, search) => users.Where(u => u.FirstName.Contains(search.Name) || u.LastName.Contains(search.Name))),
    new SearchFieldMutator<UserListItem, UserSearchViewModel>(search => !string.IsNullOrWhiteSpace(search.Email), (users, search) => users.Where(u => u.Email.Contains(search.Email))),
    new SearchFieldMutator<UserListItem, UserSearchViewModel>(search => search.UsertypeId.HasValue, (users, search) => users.Where(u => u.UsertypeId == search.UsertypeId.Value)),
    new SearchFieldMutator<UserListItem, UserSearchViewModel>(search => search.CurrentSort.ToLower() == "namedesc", (users, search) => users.OrderByDescending(u => u.FirstName).ThenByDescending(u => u.LastName)),
    new SearchFieldMutator<UserListItem, UserSearchViewModel>(search => search.CurrentSort.ToLower() == "emailasc", (users, search) => users.OrderBy(u => u.Email)),
    // etc...
};

We can then try to run it on a query. Instead of an actual Entity Framework query, I'm going to use a simply array of UserListItems and add a .ToQueryable() on to it. It will work the same if you replace it with an actual database query. I'm also going to create a simple search, for the sake of the example:

// This is a mock EF query.
var usersQuery = new[]
{
    new UserListItem { FirstName = "Allon", LastName = "Guralnek", Email = null, UsertypeId = 7 },
    new UserListItem { FirstName = "Kristof", LastName = "Claes", Email = "whoknows@example.com", UsertypeId = null },
    new UserListItem { FirstName = "Tugboat", LastName = "Captain", Email = "tugboat@ahoy.yarr", UsertypeId = 12 },
    new UserListItem { FirstName = "kiev", LastName = null, Email = null, UsertypeId = 7 },
}.AsQueryable();

var searchModel = new UserSearchViewModel { UsertypeId = 7, CurrentSort = "NameDESC" };

The following actually does all the work, it changes query inside the usersQuery variable to the one specified by all the search strategies:

foreach (var searchFieldMutator in SearchFieldMutators)
    usersQuery = searchFieldMutator.Apply(searchModel, usersQuery);

That's it! This is the result of the query:

You can try running it yourself. Here's a LINQPad query for you to play around with:

http://share.linqpad.net/7bud7o.linq


Are there any security issues? Where should I store the secret's key,
  DB or InMemory? What's a good 'JWT' Lifetime? Should I send the 'JWT'
  in Header for every request? What should be done when a 'JWT' Expires?

The contents are merely base64 encoded and thus are simple to decode -- so don't encode your valued customers personal data.

cut and paste your token in here as evidence
https://developers.google.com/wallet/digital/docs/jwtdecoder

the secret key is not a session one so in memory makes no sense. buy an oracle license and then stick it in there. or theres nothing wrong with something nice and simple like this.

    const string algorithm = "HS256";

if you're logging a user onto a site. 1 hour? its possible to copy/paste the token and gain access to data. so it depends on the nature of the data.
yes. its an awesome method to send to a REST server instead of some internal userid that never expires
kick them out of your site. make them relog in and get a new token (with another hour long token)


Using descriptors with instance variables to store a human's age

That looks reasonable; but you should handle the case of when the descriptor is invoked from the class: Human.age.  In that case, __get__ is invoked with None as an argument to instance.  If you've no better use for it; you can just return the descriptor itself:

def __get__(self, instance, owner):
    if instance is None:
        return self
    else:
        return getattr(instance, self.name)

Another thing you can do, which is sometimes preferred, is to make the descriptor figure out its own name by inspecting the class it's attached to;  this is a little more complicated, of course, but has the advantage of allowing you to specify the "name" of the descriptor attribute just one time.

class NumberDescriptor(object):
    def snoop_name(self, owner):
        for attr in dir(owner):
            if getattr(owner, attr) is self:
                return attr
    def __get__(self, instance, owner):
        if instance is None:
            return self
        name = self.snoop_name(self, owner)
        return getattr(instance, '_'+name)
    def __set__(self, instance, value):
        name = self.snoop_name(self, type(instance))
        setattr(instance, '_' + name, int(value))

class Human(object):
    age = NumberDescriptor()

Other variations to get a similar effect (without using dir()) would be to use a metaclass that knows to look for your descriptor and sets its name there.


The Blacklist: Blocking Malicious domains using Bash

We're missing a shebang line.  The question is tagged bash, but that seems overkill, since there's nothing here that's not standard POSIX shell.
#!/bin/sh

We append to the_blacklist.temp.txt, but don't ensure that it starts off empty, or that it's even writeable.  It's best to create temporary files using mktemp:
tmpfile=mktemp || exit $?
trap "rm $tmpfile" EXIT

Also, instead of directing final output to the_blacklist.txt, it would be more flexible to write to standard output, and let the user choose where to send it (perhaps pipe into another filter).
But there seems to be no reason to use a file here - just pipe the for loop directly into awk (or into sort -u - that may be a better choice if you're memory-constrained, as it will perform an external merge-sort if it needs to).
The duplicated sed pipe could be replaced with a single sed program of two commands:
for
    …
done |
    sed -e 's/\r//g' -e 's/^/0.0.0.0 /' | gawk '!a[$0]++'

There's a security issue here:

                    gawk "$rule" | \

We are executing downloaded content in awk.  Because we can't be sure that the adblock.sources URL cannot be replaced with a more harmful version, we should run awk in its constrained "sandbox" mode, and use the -- separator so we don't interpret the script as arguments.
                    gawk --sandbox -- "$rule" | \

These changes give me
#!/bin/sh

set -eu

sources=$(mktemp)
trap 'rm "$sources"' EXIT

curl -s -o "$sources" https://raw.githubusercontent.com/T145/packages/master/net/adblock/files/adblock.sources

for key in $(jq -r 'keys[]' "$sources")
do
    case $key in
        gaming | osid_basic )
        # Ignore these lists
        ;;
        * )
            url=$(jq -r ".$key.url" "$sources")
            rule=$(jq -r ".$key.rule" "$sources")

            curl -s "$url" |
                case $url in
                    *.tar.gz) tar -xOzf - ;;
                    *) cat ;;
                esac |
                gawk --sandbox -- "$rule"
    esac
done |
    sed -e 's/\r//g' -e 's/^/0.0.0.0 /' | sort -u

Somebody more expert with jq could probably avoid the remaining temporary file by making a single pass over the retrieved data.


A practical example of evenly distributing n lists into a single list

One word.... VELOCIRAPTORS.

You seem like a nice guy, I don't want the raptors to get you, so let's take Heslacher's advice and move this code outside of the loop.

    If i = 2 Then
        wsDest.Range("A1:C" & iSource).Value2 = wsSource.Range("A1:C" & iSource).Value2
        wsSource.Range("A1:C" & iSource).Delete (xlShiftUp)
        GoTo NextI
    End If

Since we'll handling the special case of the first row outside the loop, we need to change which row the loop starts on. While we're at it, let's get rid of that magic number and replace it with a variable. Note that I also replaced i with the more meaningful name row.

iSource = wsTotals.Range("B2").Value
wsDest.Range("A1:C" & iSource).Value2 = wsSource.Range("A1:C" & iSource).Value2
wsSource.Range("A1:C" & iSource).Delete (xlShiftUp)

Dim startRow As Long
startRow = 3
For row = startRow To iLast
    iSource = wsTotals.Range("B" & i).Value
    iDest = wsDest.Range("A99999").End(xlUp).Row

Now that the dreaded GoTo has been banished, let's see what else we can clean up.

There's no sense in assigning ThisWorkbook to a variable. There's no need to keep an extra reference to it in memory. Just do this. (Note that although I hate hungarian notation, I find using wb for workbook and ws for worksheet acceptable. The intention is clear to any VBA developer.)

Set wsTotals = ThisWorkbook.Worksheets("Totals")
Set wsSource = ThisWorkbook.Worksheets("Source")
Set wsDest = ThisWorkbook.Worksheets("Dest")

Your method of finding the last row has unpredictable results. Use this instead.

lastRow = wsTotals.Range("A" & wsTotals.Rows.Count).End(xlUp).row

Same deal with finding the destination row.

iDest = wsDest.Range("A" & wsDest.Rows.Count).End(xlUp).row

Applying most of Vogel612's naming suggestions, this is the code up to this point.

Sub WeaveSort()

    Dim wsDest As Worksheet
    Dim wsSource As Worksheet
    Dim wsTotals As Worksheet
    Dim row As Integer
    Dim lastRow As Integer
    Dim destinationRow As Integer
    Dim sourceRow As Integer
    Dim oldRow As Integer
    Dim newRow As Integer
    Dim difference As Double
    Dim differenceSum As Double

    Set wsTotals = ThisWorkbook.Worksheets("Totals")
    Set wsSource = ThisWorkbook.Worksheets("Source")
    Set wsDest = ThisWorkbook.Worksheets("Dest")

    lastRow = wsTotals.Range("A" & wsTotals.Rows.Count).End(xlUp).row - 1

    sourceRow = wsTotals.Range("B2").Value
    wsDest.Range("A1:C" & sourceRow).Value2 = wsSource.Range("A1:C" & sourceRow).Value2
    wsSource.Range("A1:C" & sourceRow).Delete (xlShiftUp)

    Dim startRow As Long
    startRow = 3
    For row = startRow To lastRow
        sourceRow = wsTotals.Range("B" & row).Value
        destinationRow = wsDest.Range("A" & wsDest.Rows.Count).End(xlUp).row

        difference = destinationRow / sourceRow
        differenceSum = 0
        newRow = 0

        For oldRow = 1 To sourceRow
            difference = destinationRow / sourceRow
            differenceSum = differenceSum + difference
            newRow = Round(differenceSum, 0)
            wsSource.Rows(oldRow).Copy
            wsDest.Rows(newRow).Insert xlShiftDown
            destinationRow = destinationRow + 1
        Next oldRow

        wsSource.Range("A1:C" & sourceRow).Delete (xlShiftUp)
    Next row

End Sub

We introduced a little duplication when we got rid of the raptors. Let's introduce a sub to delete the data from the source. To make things easy, we'll declare the different worksheets at the module level.

Option Explicit

Private wsDest As Worksheet
Private wsSource As Worksheet
Private wsTotals As Worksheet

Private Sub DeleteFromSource(ByVal row As Long)
    wsSource.Range("A1:C" & row).Delete (xlShiftUp)
End Sub

Changing WeaveSort to:

Sub WeaveSort()

    Dim row As Integer
    Dim lastRow As Integer
    Dim destinationRow As Integer
    Dim sourceRow As Integer
    Dim oldRow As Integer
    Dim newRow As Integer
    Dim difference As Double
    Dim differenceSum As Double

    Set wsTotals = ThisWorkbook.Worksheets("Totals")
    Set wsSource = ThisWorkbook.Worksheets("Source")
    Set wsDest = ThisWorkbook.Worksheets("Dest")

    lastRow = wsTotals.Range("A" & wsTotals.Rows.Count).End(xlUp).row - 1
    sourceRow = wsTotals.Range("B2").Value

    wsDest.Range("A1:C" & row).Value2 = wsSource.Range("A1:C" & row).Value2
    DeleteFromSource sourceRow

    Dim startRow As Long
    startRow = 3
    For row = startRow To lastRow
        sourceRow = wsTotals.Range("B" & row).Value
        destinationRow = wsDest.Range("A" & wsDest.Rows.Count).End(xlUp).row

        difference = destinationRow / sourceRow
        differenceSum = 0
        newRow = 0

        For oldRow = 1 To sourceRow
            difference = destinationRow / sourceRow
            differenceSum = differenceSum + difference
            newRow = Round(differenceSum, 0)
            wsSource.Rows(oldRow).Copy
            wsDest.Rows(newRow).Insert xlShiftDown
            destinationRow = destinationRow + 1
        Next oldRow

        DeleteFromSource sourceRow
    Next row

End Sub

Ultimately leaving this clever solution unchanged, but much more understandable.


One way would be to wrap it in an object with each method returning self so that methods can be chained.

class DataObject
  def initialize(data)
    @data = data
  end

  def clean
     @data = @data.data.map(&::strip)
     self
  end

  def write(filename)
    File.open(filename, "w") do |f|
      f.write(@data.to_yaml)
    end
    self
  end

end

def read(filename)
  data = YAML.load_file(filename)
  DataObject.new(data)
end

Another way would be to use mixins.

module DataMethods

  def clean
    # need to use the destructive methods to modify self
    map!(&::strip)
    # or each(&:strip!)
    self
  end

  def write(filename)
    File.write(filename, to_yaml)
    self
  end

end

def read(filename)
  YAML.load_file(filename).extend(DataMethods)
end


Count and group rows for six months prior

This is one of those things.... date manipulation in SQL.

For performance reasons, it is a pain to cast to NVarchar, etc. For readability reasons, everything is a pain.....

What I have found works best for me, is the following function:

DateAdd(d, 1 - DatePart(d, actualdate), actualdate)

The above subtracts the number of days needed to bring a date back to the first-of-the-month.

For example today, (the 28th April), would subtract 1 - 28 (or 27) days from the 28th, to get the 1st.

You can do your current month-manipulation to move months around once you are back on to the first-of-the-month, and then you don't have to worry about the month overflow problems..

For readability reasons, I would recommend you use variables, if you can:

declare @thismonth as Date = Convert(DateAdd(d, 1 - DatePart(d, CURRENT_TIMESTAMP), CURRENT_TIMESTAMP) as Date);
declare @firstmonth as Date = DateAdd(m, -6, @thismonth);

SELECT YEAR(Meeting_Date) year,
       MONTH(Meeting_Date) month,
       COUNT(project) meetings
FROM
    meetings
WHERE Meeting_Date BETWEEN @firstmonth AND @thismonth
GROUP BY YEAR(Meeting_Date), MONTH(Meeting_Date)
ORDER BY YEAR(Meeting_Date), MONTH(Meeting_Date)


Improving Speed of VBA Code - Copy/paste two sets of variable, Excel does a calculation, returns a value then copy/paste the output value

As best I can tell, Sub CF_Amb_Pr_NG() sets cells C2 and C3 to formulas that changes with each iteration through the loop, then ends with them set to "=R1539C2".
You then copy cell E2 to each row in column D from 40 to 1539.
Unless there's something going on with the value in C2 and C3 that somehow impact E2, if you really want to stick with the .Select and .PasteSpecial this should do the trick:
Sub test()

  With ThisWorkbook.Worksheets("Sheet1")
    .Range("E2").Select
    Selection.Copy
    .Range("D40:D1539").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    .Range("C2").FormulaR1C1 = "=R1539C2"
    .Range("C3").FormulaR1C1 = "=R1539C3"
  End With

End Sub

Otherwise, I'd suggest this which is even easier:
Sub test()

  With ThisWorkbook.Worksheets("Sheet1")
    .Range("d40:d1539").Value2 = .Range("e2").Value2
    .Range("C2").FormulaR1C1 = "=R1539C2"
    .Range("C3").FormulaR1C1 = "=R1539C3"
  End With

End Sub

It copies E2 to D40 through D1539, then it sets C2 and C3 to the final values they have in your loop.
Make a similar change to Sub CF_RH_NG().

If the value in E2 changes with the values as determined in C2 and C3 for each iteration through the loop, I'd strongly suggest that you add a helper column (out in column Z or LLL or someplace) that calculates E2 for the current row, then simply make the formula in D40 read =LLL40 (manually copy that formula down to D1539 one time), and be done with it - no need for code at all.

These simple assignments should execute in a second or two (Excel is notably slow in copying in my recent experience), but significantly less than the 10 minutes you're currently experiencing.

Based on the update, a loop is required, avoiding .Select will still help performance:
Sub test()

  On Error GoTo CleanExit
'  Application.ScreenUpdating = False
  Dim row As Long
  For row = 40 To 1539
    With Sheet1
      .Range("C2").FormulaR1C1 = "=R" & CStr(row) & "C2"
      .Range("C3").FormulaR1C1 = "=R" & CStr(row) & "C3"
      .Range.Cells.Item(4, row).Value2 = .Range("e2").Value2
    End With
  Next

CleanExit:
  Application.ScreenUpdating = True

End Sub

Note in this case the With Sheet1 - you can use the worksheet's (Name) property as a direct reference to it (you'll have to modify this for your Workbook):

Note that this is not the same as the .Name of the worksheet as displayed on the "tab":
Additionally, I've added Application.ScreenUpdating = False, but left it commented out for now. Make sure your new code is working properly before enabling this. This will prevent Excel from refreshing the screen with each step it takes. Removing all the UI activity reduces the amount of execution time (it's not a panacea, though). Note the addition of the On Error Goto... to ensure that if anything were to go wrong during execution, it will reenable ScreenUpdating. If you don't weird and confusing things happen.


Your default constructor Library() initializes the allBook member variable twice, with the same value in each case.  Probably not what you had in mind.  The immediate fix is to remove the (re) assignment in the default constructor.

Now you have two different constructors that do the right thing two different ways.  To save yourself maintenance headaches, you'd normally prefer to have one code path that does "everything", so it would be good to combine the two.  There are two different ways of doing that, depending on the requirements....

Consider this test.

ArrayList source = new ArrayList();
source.add(book1);
source.add(book2);
source.add(book3);

Library library = new Library(source);
library.add(book4);

At this point, the library should contain four books.  But how many books should the source array contain?

If the answer is four, the the library is supposed to be modifying the array it was passed.  In that case, the easy answer to the constructor problem is to have the default constructor call the other, like so:

Library () {
    this(new ArrayList<Book>);
}

On the other hand, if the source array should still contain three books, then the Library should contain a copy of the ArrayList, rather than holding onto the original.  If that's your requirement, then the good answer is to go the other way around - initialize the allBook member where you declare it, but use copy semantics when you are passed the ArrayList

ArrayList<Book> allBook = new ArrayList<Book> ();

Library () {}

Library (ArrayList<Book> books) {
    allBook.addAll(books);
}

Your code in this version of the puzzle is very confused about Books, titles, and Strings.  Your requirements said

public ArrayList findTitles(String title)

but the signature in your class is

public ArrayList<Book> findTitles(Book title)

The code in a number of places suggests that, once upon a time, you thought all books were just Strings, and then you changed your mind.  Your compiler should be telling you that you aren't being consistent.

The requirements for findTitles says that you should be returning an ArrayList of books with matching titles.  That means you probably need to be creating a new ArrayList, and then add()ing the matching Books to it.  The code you've written returns all of the books, but takes extra time to compare at the books first.  You probably don't want to call Book.compareTo (although you can implement the solution correctly that way), but instead Book.getTitle().equals(otherBook.getTitle())

There are better answers than for loops for visiting all of the elements in an ArrayList.  See Iterable.  Since you've written Book.toString() already, you can start Library.toString() by building a big String out of all of the Book.toString()s.


If you need to account for mixed response types (in your case "unknown errors" or JSON-formatted errors), then you could consider checking the Content-Type of the response. See this StackOverflow answer for reference. This, of course, trusts in the server echoing the correct content type header for a response.
As you mentioned, fetch does not reject on HTTP error status, instead response.ok will be set to false. You can use this to decide if you want to reject or resolve your promise.
/* ... */.then(async response => {
    const contentType = response.headers.get("content-type");
    if (contentType && contentType.indexOf("application/json") !== -1) {
        const json = await response.json();
        return response.ok
            ? Promise.resolve(json)
            : Promise.reject(json);
    } else {
        const text = await response.text();
        return response.ok
            ? Promise.resolve(text)
            : Promise.reject(new Error("Unknown Error!"));
    }
});

You could also (which is what the post linked above suggests aswell) use a try-catch block, if you do not trust the response headers.
/* ... */.then(async response => {
    const text = await response.text();
    try {
        const data = JSON.parse(text);

        // If the line above has not produced an error, the response contained valid JSON.
        // We can either choose to just return the resulting data, or, as in
        // example above, resolve/reject the Promise based on the status code.

        return response.ok
            ? Promise.resolve(data);
            : Promise.reject(data);
    }
    catch(err) {
        // This means that the response probably contained text. As above, you can
        // decide if this means an error has occurred, or if the result will just
        // be handled differently.

        return response.ok
            ? Promise.resolve(text);
            : Promise.reject(new Error("Unknown Error!"));
    }
});

As for your additional question on the difference between:
if (response.ok) {
    const json = await response.json();
    return json;
}
// ... and ...
if (response.ok) {
    return response.json();
}

This essentially boils down to the difference between:
return await response.json();
// ... and ...
return response.json();

The difference lies within the way that JavaScript handles async/await methods. The first line returns a generic T, while the second one returns Promise<T>. What this means is that the first one "delays" the execution of the return statement until the promise returned by response.json() is resolved, while the second one says "I don't care that execution is continued, whoever calls me later will have to wait for my value to be resolved.", which is what happens when you perform .then(...) on a promise.
Note that the first method still ultimately returns a Promise<T> though, since async methods are essentially just fancy wrappers for promise generations.


Positioning text and images on a site grid

a) Don’t use &nbsp &nbsp to separate the navigation links. You could use ul instead (and style it with CSS display:inline; if required):

About Us

Our Cheeses

Contact Us

b) div has no meaning. You should only use div if there is no other appropriate, "narrower" element. If you are quoting something, use blockquote. If you have a navigation menu, use nav. Of course you can use div in addition to those appropriate elements, if needed.

c) This is not an error, but an opinion-based advice: If you don’t have a strong reason, don’t add id attributes just because you need a styling hook. You could use the class attribute even for what some call "unique" elements. Good reasons to use id are: in-page links (fragment identifier) and, sometimes, JavaScript hooks.


Data structure to count occurrences of entries

Make the inner Node class static

You can do this, because this class doesn't use anything in the enclosing class.
A non-static class contains a private reference to the enclosing class,
which is just a waste when you don't really need it.

When you make the class static you will also need to add a template parameter of its own, like this:

private static class Node<T> {
    // ...
}

However, this will also mean that when you use variables of type Node, you will also need to specify the template parameter T, changing all occurrences to Node<T>.

Naming

The getF and addF methods are poorly named. It would be easier to read if you spell them out as getFrequency, and incrementFrequency.
On the other hand, in getFrequencyOf, I find the "Of" redundant,
I think you can just drop that.
Data is not a good variable name in Java,
because the convention is to use camelCase, for example data instead.

Unnecessary operations

In getMaxFrequency,
this part pointlessly compares the first node against itself:

    if (firstNode != null) {
        Node currNode = firstNode;
        Node maxNode = firstNode;
        while (currNode != null) {

Since the first if already ensures that the first node is not null,
this way would be more optimal:

    if (firstNode != null) {
        Node maxNode = firstNode;
        Node currNode = firstNode.next;
        while (currNode != null) {

Simplify using early returns

It can be a good idea to return early when the first node is null,
this way you could reduce one nesting level, which is slightly more readable,
like this:

    if (firstNode == null) {
        return 0;
    }
    Node maxNode = firstNode;
    Node currNode = firstNode.next;
    while (currNode != null) {
        if (currNode.getF() >= maxNode.getF()) {
            maxNode = currNode;
        }
        currNode = currNode.next;
    }
    return maxNode.getF();

You can apply the same logic to the getProbabilityOf method (drop the "Of", return early, iterate from firstNode.next).


Showing a "back-to-top"-button after scrolling a certain amount

Does the longer version have a better performance?

No, the longer version has two different if conditions and you're recalculating the scroll area twice (i.e.: document.body.scrollTop > 100 || document.documentElement.scrollTop > 100 and document.body.scrollTop <= 100 || document.documentElement.scrollTop <= 100)

  Does the browser optimize it itself – i.e. in the short version if the class is already present, it doesn't repaint?

Yes, if the class name already exists it'll simply be ignored.

classList MDN Documentation:

  add( String [, String [, ...]] )

  Adds the specified class values. If these classes already exist in the element's class attribute they are ignored.

Handling the scroll event can be performant heavy if you have a complex handler as the scroll event will be continuously fired during a scroll.

If you wish to optimize your scroll event handler, I would highly recommend using setTimeout. This allows your script to ONLY be called once the scroll has ended and skips doing your "heavy" condition checking for every scroll tick.

let setTimeoutId = null;
window.addEventListener('scroll', event => {
  //clear a previously pending timeout
  clearTimeout(setTimeoutId);
  //create a new timeout that will be launched in 400ms
  setTimeoutId = setTimeout(()=>onScroll(event), 100);
});

function onScroll(event){
  console.log("On scroll called");
}
body {
  height: 2000px;
  background-color: lightblue;
}


Asymptotic complexity of multiple binary search

There are multiple problems in your approach - but they are more at the conceptual level, not in the style of the code, which is just fine. The unit tests are also commendable. But:

The algorithm you have coded is not the binary search algorithm.
The code implements a recursive search algorithm in an unsorted array. It has \$O(n)\$ time complexity and \$O(log(n))\$ space complexity - a clearly suboptimal for this task. The space complexity comes from the recursive function calls and the fact that Python does not optimize tail recursion. While you do demonstrate that solving the problem with recursion is possible, it is not the best option in terms of efficiency.
If you do implement binary search, sort the array first. To find the value I suggest using the functions from bisect module rather than reinventing the wheel, if this is a production code.
The Python in operator does not use binary search, as it has to avoid sorting the string, so binary search would not work; however, it does use some advanced string search algorithms, so is better than a naive version.

In this loop:

    for letter in letters:
        result = result and search(word, letter)

it is clear that the answer will be False as soon as the first search() call fails. Therefore you can if not search(word, letter): return False for better efficiency, and don't need the result variable.

This is an alternative version that:

Has \$O(max(||letters||, ||word||))\$ effective complexity (assuming
\$O(1)\$ for set insertion and lookup) due to the use of counting sort.
Increases the average efficiency by returning False immediately after the first missing character is encountered

def elfish(word, letters):
    present_characters = set()
    for c in word:
        present_characters.add(c)
    for letter in letters:
        if letter not in present_characters:
            return False
    return True


Only thing I can think of is that wrap the condition:

var hasUserLocation = function (hasFunc, noFunc) {
    if ($(".userLocation").size() > 0) {
        hasFunc();
    } else {
        noFunc();
    }
}

then you can call like this:

hasUserLocation(function () {
    alert("has");
}, function () {
    alert("no")
})

jsfiddle


Search for rows in a 2D array that contain a given sequence

I rewrote your SearchSequence function to be as absolutely brain-dead as possible:

#include <iostream>
#include <vector>
#include <algorithm>
#include <chrono>

std::vector<int> SearchSequence(std::vector<std::vector<int>> const &matrix, std::vector<int> const &sequence)
{
    std::vector<int> result;

    for (unsigned int i = 0; i < matrix.size(); i++) {
        auto it = std::search(matrix[i].begin(), matrix[i].end(), sequence.begin(), sequence.end());
        if (it != matrix[i].end()) {
            result.emplace_back(i);
        }
    }
    return result;
}

int main() {

    int m = 25000, n = 25000; // assume `m` and `n` can vary.
    std::vector<std::vector<int >> matrix(m, std::vector<int>(n));

    auto start_time = std::chrono::steady_clock::now();

    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            matrix[i][j] = rand() % 1000;
        }
    }

    std::vector<int> sequence = matrix[9999]; // This is purely for testing purpose, actual input(matrix&sequence) is read from files.

    auto initial_time = std::chrono::steady_clock::now();
    std::cout
        << "Initializing the array with rand() took: "
        << std::chrono::duration_cast<std::chrono::milliseconds>(initial_time - start_time).count() << " ms\n";

    std::vector<int> result = SearchSequence(matrix, sequence); // This is the ONLY function which needs to be optimised.

    auto search_time = std::chrono::steady_clock::now();
    std::cout
        << "Executing the actual search took: "
        << std::chrono::duration_cast<std::chrono::milliseconds>(search_time - initial_time).count() << " ms\n";

    return 0;
}

On my laptop, this prints:

$ clang++ -std=c++14 -O3 ./x.cc
$ ./a.out
Initializing the array with rand() took: 5304 ms
Executing the actual search took: 2 ms

$ clang++ -std=c++14 -O0 ./x.cc
$ ./a.out
Initializing the array with rand() took: 7670 ms
Executing the actual search took: 8 ms

This is single-threaded, with absolutely no cleverness to the search at all — I'm just using the $O(n^2)$ std::search algorithm from the standard library.

I suggest that your business with std::vector<std::future<int>> is completely unnecessary, and that if you're measuring any slowness, it's slowness in initializing the matrix with random numbers.


Some suggestions:

Nested functions are unusual; typically they would be neighbour functions instead. This ensures that all the context that each function needs is passed to it, making it easier to grasp the entire context involved in the processing in each function.
Python 3 supports type annotations, which are a more explicit way of declaring input and output types. You can check that your code is properly annotated using mypy, for example with this rather strict configuration:

[mypy]
check_untyped_defs = true
disallow_untyped_defs = true
ignore_missing_imports = true
no_implicit_optional = true
warn_redundant_casts = true
warn_return_any = true
warn_unused_ignores = true

Longer variable names can make your code more readable. For example, I can't tell what q is without reading most of the code, and even then it might be unclear, especially since it's an "intermediate" variable (neither a parameter nor a return value).
You could use a set of constants to define the directions in a more human readable form such as DIRECTION_WEST = (-1, 0).
Inlining such as if foo: continue is generally frowned upon, since it makes it harder to skim the code vertically.
Your docstring could include a definition of the problem, possibly by simply copying from the LeetCode website.
Python has exceptions, and it's recommended to use them rather than special return values to signal a problem.


Here are some things that may help you improve your code.

Write standard C

The code includes this line:

*out = (stack) {};

However, as my compiler helpfully reminds:

  ISO C forbids empty initializer braces

Fix typos

The struct declares a member variable len but the code refers to a member variable length.  If you're asking for code to be reviewed, it would be good if you invest sufficient time to make it as good as you can get it.

Enhance error checking

Both malloc and realloc can fail, but this code doesn't check for that. If realloc fails, then the following line, will attempt to dereference NULL which will cause a program crash on most systems.

Use calloc if you need the memory zeroed

Rather than calling malloc and then expressly initializing your struct, you can do this in one step by calling calloc instead of malloc.  Doing so reduces stack_new() to a single line:

stack *stack_new() {
    return calloc(1, sizeof(stack));
}

Understand pointers

The major problem with this code is that it seems to confuse the length of a string with the size of a pointer to a string.  When you have a variable declaration such as char **items, it means that you have a pointer to a pointer to char.  So the thing stored in items is a pointer to a string, not a string.  For that reason, it should instead be written like this:

void add(stack *in, char *val) {
    in->items = realloc(in->items, (1+in->len) * sizeof(val));
    if (in->items) {
        in->items[in->len] = val;
        in->len++;
    } else {
        in->len = 0;
    }
}

Note that this only increments len if the reallocation succeeded. If it failed, the stack length is set to zero because the contents have been lost. Also, the allocation is to accomodate sizeof(val) rather than the length of the string because what we're storing is the pointer to the string rather than the string itself.  This also means that there is no copy being made of the string itself -- it's just storing a pointer, so that means that the string must continue to exist for the duration of the stack's lifetime which may not be a good design, depending on your proposed use.

Provide a full sample program for review

It's useful to provide a small but complete program for a code review where practical (and it's certainly practical here).  That would include both header and functions as well as a simple main showing the intended use.  Here is a version of your program that does not leak memory. You and valgrind can become friends again.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct stack {
    char **items;
    int len;
} stack;

stack *stack_new() {
    return calloc(1, sizeof(stack));
}

void stack_free(stack *in) {
    if (in) {
        free(in->items);
        in->len = 0;  // not really needed
        free(in);
    }
}

void add(stack *in, char *val) {
    if (in) {
        in->items = realloc(in->items, (1+in->len) * sizeof(val));
        if (in->items) {
            in->items[in->len] = val;
            in->len++;
        }
    }
}

void print(stack *in) {
    if (in) {
        for (int i=0; i < in->len; ++i) {
            puts(in->items[i]);
        }
    }
}

int main()
{
    stack *words = stack_new();
    add(words, "Avoid");
    add(words, "memory");
    add(words, "leaks");
    print(words);
    stack_free(words);
}


365*60*60*24 should be a constant.
You should really improve your variable naming.

$date2 = date("Y-m-d H:i:s");

date2? Does that say anything? currentTime is more like it. Always describe what variables contain, not what they are.
Isn't $diff already the number of seconds?
Most part of the date/time checking could be rewritten to:

$seconds = time() - strtotime($key);


Shell install.sh for repository (rpi_videoloop)

Set these options at the beginning:

set -eu

so that errors fail early

Don't use sudo in a script, because it can hang when not connected to a terminal.  Possible exception: once at the beginning:

if ! test $UID -eq 0
then
   test -t 0 && exec sudo "$0" "$@"
   # Not a terminal - or exec failed
   echo "Insufficient privileges - try sudo $0 $*" >&2
   exit 1
fi

You probably want to be using the standard install command instead of cp and mkdir.  That lets you specify the permissions as you create the targets.

Consider using a $DESTDIR prefix when specifying the targets.  This makes it easier for package builders (such as debhelper) to re-use your script.  They will need to omit the dependency checks, so make that separable if you can (or at least disable it when $DESTDIR is set).


Your algorithm is way off.... ;-)

Let's consider the solution to a decent number.

For any decent number, the more 5's we put at the front, the better.

So, let's break it down to some maths....:

d => number of digits in the decent number
f => number of fives in the decent number
t => number of threes in the decent number

also

d = f + t
f % 3 == 0
t % 5 == 0

We have:

d = f + t

Algorithm:

// tmp number of five values is the number of digits
ftmp = d
// decrease the number of fives (by the number of threes in a batch)
// until both the rules f % 3 == 0 and t % 5 == 0 are satisfied
while ftmp % 3 != 0 : ftmp -= 5

check the ftmp is a valid value
if ftmp % 3 != 0 : return -1;

f = ftmp;
t = d - f

return "5" x f + "3" x t

Writing it in Java, I have the following:

private static String sherlock(final int target) {
    int threes = 0;
    int fives = 0;
    int digits = target;
    while (digits > 0) {
        if (digits % 3 == 0) {
            fives = digits;
            break;
        }
        digits -= 5;
    }
    threes = target - digits;
    if (digits < 0 || threes % 5 != 0) {
        return "-1";
    }
    StringBuilder sb = new StringBuilder(target);
    while (fives-- > 0) {
        sb.append("5");
    }
    while (threes-- > 0) {
        sb.append("3");
    }
    return sb.toString();
}

For me, on my laptop, this solves the 100000 digit problem in less than 1 millisecond. First I 'warm up' Java with the first 10,000 solutions....

Then I run some big ones....

public static void main(String[] args) {
    int cnt = 0;
    long ms = System.currentTimeMillis();
    for (int i = 0; i < 10000; i++) {
        cnt += sherlock(i).length();
    }
    ms = System.currentTimeMillis() - ms;
    System.out.println("Warmup created " + cnt + " characters in " + ms + " Milliseconds");
    for (int i : new int[] { 1, 3, 5, 11, 19, 100000 }) {
        long nanos = System.nanoTime();
        String val = sherlock(i);
        nanos = System.nanoTime() - nanos;
        System.out.printf("    request digits %d : actual digits %d Value %s in (%.3fms)%n",
                i, val.length(), val.length() > 20 ? "too long" : val, nanos / 1000000.0);
    }
}

This produces the output:

Warmup created 49995011 characters in 703 Milliseconds
request digits 1 : actual digits 5 Value 33333 in (0.004ms)
request digits 3 : actual digits 3 Value 555 in (0.012ms)
request digits 5 : actual digits 5 Value 33333 in (0.003ms)
request digits 11 : actual digits 11 Value 55555533333 in (0.002ms)
request digits 19 : actual digits 19 Value 5555555553333333333 in (0.002ms)
request digits 100000 : actual digits 100000 Value too long in (0.622ms)


Setting output width with ostream_iterator

There are one problem with your approach you make local information global as consequence your FixedWidthDouble class is not thread-safe. There is a simple way to solve the problem by turning width_ into a integral template argument of the class template template<int width> FixedWidthDouble.

In C++11 I'd use range-based for:

std::ostream& Vector::Print(std::ostream& out, int width) const
{
  out << "[" << std::setprecision(1) << std::fixed;
  for (auto& x : *this)
    out << std::setw(width) << x;
  return out << " ]";
}

In the old C++98 it is cleaner to use old for with iterators.  Also you can create a new iterator type that will set the width:

template<typename T, typename CharT = char, typename Traits = std::char_traits<CharT> >
class width_ostream_iterator
  : public std::iterator<std::output_iterator_tag, void, void, void, void>
{
public:
  typedef CharT char_type;
  typedef Traits traits_type;
  typedef std::basic_ostream<CharT, Traits> ostream_type;

private:
  ostream_type* stream;
  const CharT* separator;
  int width;

public:
  explicit width_ostream_iterator(ostream_type& stm, int width, const CharT* separator = 0)
    : stream(&stm), separator(separator), width(width)
  { }

  width_ostream_iterator& operator=(const T& value)
  {
    *stream << std::setw(width) << value;
    if (separator) *stream << separator;
    return *this;
  }

  width_ostream_iterator& operator*()     { return *this; }
  width_ostream_iterator& operator++()    { return *this; }
  width_ostream_iterator& operator++(int) { return *this; }
};

Update: Your proposed solution is valid if the width can only be changed at compile time, if you want to change the width at the runtime (e.g. from configuration file or command line arguments) you have to use plain for loop or the width_ostream_iterator I've provided.  One thing I do not like about the width_ostream_iterator — it is definitely a library entity intended to be used in multiple places but it allows you only to change the width of the field and nothing else.  It is too specific for the library (it does not allow an arbitrary manipulator to a stream before outputting a value) it is too complicated for a single use.

And one more note: the Print function uses only public interface of the vector (I assume that begin and end functions are public), so it does not required to be a member function.  Prefer to make such functions free not member.  Why not use member function for all class operations? You can extend the interface of a class without modifying it, e.g. you can have a Vector class and stream I/O operations defined in separate headers, you can later add another I/O operations (e.g. for QDataStream) in a third header and you will not have to recompile the parts of the program that depend only on the first and second headers.  Your Print function can potentially work with any class which looks and behaves like a standard sequence, just like any algorithm from the standard library.  The class (just a function) must do one thing well, the Vector class stores a number of values of some type and provides constant-time random-access to the elements, it doesn't sort elements (that what std::sort algorithm is for), it does not search for elements (that what std::find and std::find_if algorithms are for), it does nit provide elementwise arithmetic operations (oops, there is no std::zip to combine several sequences into one), etc.


SQL: Search for a keyword in several columns of a table

Something "prettier"? And so many repetitions call for generalization?

SELECT *
FROM   tabela AS t
JOIN   "TabelaPai" tp ON tp."ID" = t."RefTabelaPai"
WHERE  NOT t."Deleted"
AND    tp."RefProject" = 'projectid'
AND    t::text LIKE E'%\\_\\_param1\\_\\_%';

Major points:

You can reference the composite type of any relation in the SELECT list. I quote the manual:

  Whenever you create a table, a composite type is also automatically
  created, with the same name as the table, to represent the table's row type.

You can cast the whole row (the composite type) to its text representation in one fell swoop, which is a very convenient syntactical shorthand. The resulting filter in my query is guaranteed to find every occurrence in the whole row.
The LIKE operator is generally faster than regular expression pattern matching (~). Regular expressions are far more powerful, but whenever LIKE can do the job use it. Its syntax is simpler, too.
Underscores (_) have a special meaning for the LIKE operator, so you need to escape literal _. Default escape character is \, which also has a special meaning in escape string constants, so you have to double them when you use the E'' prefix: E'\\_'.

As of version 9.1, the setting standard_conforming_strings is on by default. With this setting \ has no special meaning in plain string literals (without the E prefix) and you don't need to double them: '\_'.
There is a minor flaw / corner case: If the separator in text representation (, by default, and some values are enclosed in double quotes "), can be part of the search pattern, there can be false positives.

Minor cleanup / simplification:

JOIN is shorthand for INNER JOIN.
It is cleaner to write AND tp."RefProject" = 'projectid' as WHERE clause, as it has no connection to tabela. Else you could put NOT t."Deleted" into the JOIN condition as well. Either way, you get the same result here.
No point for mixed case in Tabela (without double quotes). By default (and without double-quotes), all identifiers are folded to lower case automatically. My standing advice is to use legal. lower case identifiers exclusively in PostgreSQL and avoid avoid double-quoting and possible confusion.


A few observations.

Properties should be PascalCase.

public class Truck
{
    // ...
    public int Wheels { get {return _wheels; } }

    // ...
}

The this keyword is not needed here.  by having the '_' in front of your class variables, you are differentiating them from the local variables.

Now, to answer your question, you could use Automatic Properties, which would change your class to be something like:

public class Truck
{
    public int Wheels { get; private set; }
    public string Color { get; private set; }
    public bool Loaded { get; private set; }

    public Truck(int wheels, string color, bool loaded)
    {
        Wheels = wheels;
        Color = color;
        Loaded = loaded;
    }
}

As for your question of having a better way: the only other way to set them is to make the property's set method public and set them through that.  Personally, I like passing them through the constructor better, it makes it easier to make the the class immutable.


TPL Task tracker which keeps track of tasks

I don't think you want a TaskScheduler and this is a better idea.  Creating a custom TaskScheduler isn't for the faint of heart and the ThreadPoolTaskScheduler does a lot of things and it's better to just let it do it's own thing.

Your code is headed down the correct path but I'd make a couple of changes.  One for the delay I wouldn't use a uint I'd use a TimeSpan.  That easier to understand and can use Factory method like TimeSpan.FromMilliseconds to indicate what is the delay.  I don't like passing in numbers.  Is it milliseconds? seconds?  Also from your code you are not using the delay.

Also why create delegates for the events and not just use the standard EventHandler? Also when sending out the source of the event you are sending our your collection.  This seems like a very bad idea.  What if someone would clear your collection or add to it outside your class?

You have a synclock that you are not using.  Using the SynchronizedCollection wouldn't require a lock. But that being said I would probably ditch the SyncronizedCollection.  That will do a lot more locking than what is required for this application.  I would just use a HashSet and and lock on that since it's going to be internal.

This now becomes the class and the constructor

public class TaskCompletedNotifier
{
    public event EventHandler AllTasksCompleted;
    public event EventHandler TaskStarted;
    private readonly ISet<Task> _tasksCollection = new HashSet<Task>();
    private readonly TimeSpan _delay;

    public TaskCompletedNotifier(TimeSpan delayBeforeRemovingTasks)
    {
        if (delayBeforeRemovingTasks.TotalMilliseconds < 1)
        {
            throw new ArgumentOutOfRangeException(nameof(delayBeforeRemovingTasks));
        }

        _delay = delayBeforeRemovingTasks;
    }

Now when adding a task to the collection we just need to account for the delay and we can do that with the Task.Delay and combo that up with Task.WhenAny.  Also any time there is an async void that is a code smell.  I would just run the remove from the ContinueWith and not get task involved.  I wouldn't think the overhead of the thread switching would be that great for just removing an item from a hashset.

public void Add(Task task)
{
    // short-cut why add a task that is already done?
    if (!task.IsCompleted)
    {
        // Create a task that is done when either the time has passed or when it's completed
        var newTask = Task.WhenAny(task, Task.Delay(_delay));
        var fireEvent = false;
        lock (_tasksCollection)
        {
            if (_tasksCollection.Add(newTask))
            {
                // set if we need to fire event
                fireEvent = (_tasksCollection.Count == 1);
            }
        }

        // fire event outside of locker
        if (fireEvent)
        {
            // Don't pass in the internal collection as we don't want anyone modifying our data outside our self
            TaskStarted?.Invoke(this, EventArgs.Empty);
        }

        // add the continuation to remove it from the collection
        //     after we might have fired the event to ensure the events run in correct order
        newTask.ContinueWith(RemoveTask);
    }
}

private void RemoveTask(Task task)
{
    var fireEvent = false;
    lock (_tasksCollection)
    {
        {
            if (_tasksCollection.Remove(task))
            {
                fireEvent = (_tasksCollection.Count == 0);
            }
        }
    }

    if (fireEvent)
    {
        AllTasksCompleted?.Invoke(this, EventArgs.Empty);
    }
}

It's important to note that you should still await the task that is passed into this class outside of this class to handle any faults.