Correctness and Performance of graph plotting on R

The plot looks about right with the data, and I see no egrerious errors in your code. I do have a few remarks.

In r it's unnecessary to end your lines with a semi-colon, and most styleguides advise against it. The only real purpose it has is allowing multiple statements on a single line, but why would we want that.
With regards to your code where you install packages. There are two ways of loading a library: library(name) and require(name). One big difference is that require returns a FALSE when the package is missing, library throws an error. What you can do is try and load the library, and if it fails install it:

for(libraryName in c("ggplot2", "reshape2")){
  if(!require(libraryName)){
    install.package(libraryName)
    require(libraryName)
  }
}

If your csv files are going to be huge, I recommend using data.table::fread for reading your csv files. In my experience it is the fastest reading large datasets. It also allows for efficient dataframe operations.
If at reading time you specify the correct columnnames, you can prevent having to do the melt operation later: add the argument col.names = c("File.Length", "value"). Add the column FileOutputWithoutBufferMetrics["Time"] <- "Non.Buffered.Time.Taken..ns." to both dataframes, and simply rbind them. This is most likely more efficient than melt, especially on big datasets.
# This line has to be updated on every place, possible. This is generally accounted for using the "working directory" of the R process. If you run the script from commandline, the working directory is the current directory. If you run it from Rstudio you can set it using the setwd(dir) function, or in Session -> Set Working Directory -> To Source File Location in the Rstudio ui. Once that is set, you don't have to add that path to the filename in read.csv.

In summary:

for(libraryName in c("ggplot2", "data.table")){
  if(!require(libraryName)){
    install.package(libraryName)
    require(libraryName)
  }
}

FileOutputWithoutBufferMetrics <- fread("FileOutputWithoutBuffer-Metrics.csv"), col.names = c("File.Length", "value"))
FileOutputWithoutBufferMetrics["Time"] <- "Non.Buffered.Time.Taken..ns."

FileOutputWithBufferMetrics    <- fread("FileOutputWithBuffer-Metrics.csv"), col.names = c("File.Length", "value"))
FileOutputWithBufferMetrics["Time"] <- "Buffered.Time.Taken..ns."

df <- rbind(FileOutputWithoutBufferMetrics, FileOutputWithBufferMetrics)

ggplot(df, aes(File.Length, value)) + geom_line(aes(colour = Time))


No, this code is not secure, as you are using prepared statements wrong. See here for correct usage of mysqli prepared statements (you should not ever have user supplied input in the prepare statement, it is only for SQL syntax; add the user input via bind later on).

For example, your code might look like this:

$sql = $db->prepare('INSERT INTO p_lica (povjerilac, doc_br, dokument_vlasnik) VALUES(?, ?, ?)'); // note that there is no user input in prepare
$sql->bind_param('iss', $key, $dok_broj, $ses_val); // s for string, i for integer. use d for double, b for blob

foreach($povjerilac as $key) { // set values for $key, which is bound to the first ? parameter
    $sql->execute(); // insert new row with current key
}
$sql->close();

(see also here or here)

Misc

formatting: your code is very badly formatted. If this is just a copy-paste error it's ok, but otherwise, you should definitely fix it.
variable names: the standard is to use english names, if you can.
your header call seems wrong. From the documentation: Remember that header() must be called before any actual output is sent. You should also use a complete URL.


Here my thoughts on your solution. But I'm also learning Haskell right now, so I'm not an expert..

You don't need the data type. You can use base 10 logarithm to get the number of digits. Like this:

(floor $ logBase 10 $ fromIntegral n) + 1

I like the fact that digs is tail recursive. It looks simpler without the data type:

digits :: Int -> [Int]
digits = digits_tr []
    where
        digits_tr :: [Int] -> Int -> [Int]
        digits_tr l 0 = l
        digits_tr l n = digits_tr (n `mod` 10 : l) (n `div` 10)

Why does balancedNum give a string? A boolean would be more natural.
If you want to handle errors, why not use Maybe instead of error? Like in balancedNum :: Int -> Maybe Bool. Anyway according to the problem description you wouldn't need it: a negative number is just not balanced, so the function should just give False back.

Here is my solution:

balanced :: Int -> Bool
balanced n
    | n >= 0 = (sum $ take middle $ digits n) == (sum $ take middle $ reverse $ digits n)
    | otherwise = False
    where
        len = (floor $ logBase 10 $ fromIntegral n) + 1
        middle = if len `mod` 2 == 0 then len `div` 2 - 1 else len `div` 2


Twisting words! (boustrophedon formatting)

Looks fine to me. Only thing I'd change is the way the padding is done: You can use ljust instead, which seems a little more appropriate to me. Something like:

.ljust(text.length.fdiv(chunk_size).ceil * chunk_size, " ")

You can also use the with_index modifier on map instead of doing a separate each_with_index, i.e.:

.map.with_index { |chunk, index| index.odd? ? chunk.reverse : chunk }

Of course there are several approaches to this. For instance, you needn't necessarily use chars and then join. For instance:

def twist(text, chunk_size)
  text
    .ljust(text.length.fdiv(chunk_size).ceil * chunk_size, " ")
    .scan(%r/.{#{chunk_size}}/)
    .map.with_index { |chunk, index| index.odd? ? chunk.reverse : chunk }
    .join("\n")
end

I won't say it's a better solution, though. Fewer lines, sure, but the interpolated regex isn't pretty. But again, it's just to show an alternative approach.

You can also move the ljust, to avoid the long'ish bit of arithmetic:

def twist(text, chunk_size)
  text
    .scan(%r/.{1,#{chunk_size}}/)
    .map { |chunk| chunk.ljust(chunk_size, " ") }
    .map.with_index { |chunk, index| index.odd? ? chunk.reverse : chunk }
    .join("\n")
end

It's obviously it's kinda brute-force, since we know that it'd only be the last chunk that could require padding. But again: Just an alternative.


Calculating the last digit of a^b where a and b are very large numbers

Wrong answer

$$ everything^0 = 1 => 0^0 = 1$$

    if ( e == 0 && b == 0 )
        cout<<"0"<<"\n";

Solution

Last digit relay only on last digit and you can not look at digits than goes before last one. As your power is up to \$10^{18}\$ you have to use modular binary power function.

Here is my solution:

#include <iostream>
#include <string>

typedef unsigned long long int ULLI;
typedef unsigned int UI;

UI bin_pow(UI a, ULLI n) {
    UI result = 1;
    while (n) {
        if (n & 1) {
            result = (result * a) % 10;
            n -= 1;
        } else {
            a = (a * a) % 10;
            n >>= 1;
        }
    }
    return result;
}

int main(int argc, char *argv[]) {
    int n;
    std::cin >> n;
    while (n--) {
        std::string a;
        ULLI b;
        std::cin >> a >> b;
        std::cout << bin_pow(a.back() - '0', b) << std::endl;
    }
}

  C++11 std::string

  Since C++11 std::basic_string had method .back() that returns last char in the string.

  To do this with C++98 you can use .rbegin() iterator.

Solution with complexity \$O(1)\$

Previous code can be acceptable solution, but if it will still not be enough, try to set predefined array for length of circle when

$$ a^{length} mod(10) = a | a = [0 \ldots 9]$$

I'd write some Python script, lets take a look at the results:

(2, [2, 4, 8, 6, 2, 4, 8, 6, 2, 4, 8])
(3, [3, 9, 7, 1, 3, 9, 7, 1, 3, 9, 7])
(4, [4, 6, 4, 6, 4, 6, 4, 6, 4, 6, 4])
(5, [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5])
(6, [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6])
(7, [7, 9, 3, 1, 7, 9, 3, 1, 7, 9, 3])
(8, [8, 4, 2, 6, 8, 4, 2, 6, 8, 4, 2])
(9, [9, 1, 9, 1, 9, 1, 9, 1, 9, 1, 9])

What does it means? First number is the digit which was processed. Array is array of lower digits from previous equation. As you can see, there are not too many circles of repetitions.

Lets take a look at digit 2:

with power of 1 we have \$2^1 mod(10)=2\$
with power of 2 we have \$2^2 mod(10)=4\$
with power of 3 we have \$2^3 mod(10)=8\$
with power of 4 we have \$2^4 mod(10)=6\$
with power of 5 we have \$2^5 mod(10)=2\$

that's it, we've got the circle for digit 2.

Also digits may be grouped by number of powers before lower digit will be repeated.

2, 3, 7, 8 repeated after 4 power operations
1, 5, 6 repeated after each power opetation
4, 9 repeated each 2nd power operation

const unsigned int predefined[10][4] = {
    {0},
    {1},
    {2,4,8,6},
    {3,9,7,1},
    {4,6},
    {5},
    {6,4},
    {7,9,3,1},
    {8,4,2,6},
    {9,1}
};

unsigned int bin_pow(const unsigned int& a, unsigned long long int n) {
    if (!n) return 1;

    switch(a) {
        case 0:
        case 1:
        case 5:
            return a;
        case 2:
        case 4:
        case 7:
        case 8:
            return predefined[a][n & 3];
        default:
            return predefined[a][n & 1];
    }
}


Monte Carlo estimation of the Hypergeometric Function

I am the Adams of Adams-Skopek.  I want to point out a couple of things:

You get some truncation error when you sum or multiply a series of values in different orders.  You need to estimate this and account for it.
There is a lower limit on sparsity of the data, you need to address this.
If you can get a copy of the Pagano and Halverson program (cited in Adams and Skopek), it is useful for comparing it's results with your results.   It does the exact hypergeometric test very efficiently.
There is a PC version here. You might need to ask the authors for the code.
The computer department here can probably locate the original Fortran code for the original version of the Adams Skopek program and give you a copy (which I don't have).


When one character is dead, the game is over.

No, it isn't, because in your own example output it says:

  Alice attacks Bob [...] Bob has been defeated

  Bob attacks Alice [...] Alice has been defeated

  The game is over!

Bob is apparently dangerous, even in death.

Anyway, code review:

I'd prefer that the characters weren't responsible for printing anything. Their responsibility should only be to be number generators; let the game handle the encounter.

I'd also advise against using attr_accessor :hit_points, since that means you can set the hit points from anywhere. Using attr_reader would be more fitting, I think.

Lastly, naming you instance variables @alice and @bob is rather too specific; they're both just characters. Besides, you might want more at some point.

Here's how I might do the character class:

class Character
  attr_reader :name, :hit_points, :damage

  def initialize(name, hit_points, damage, hit_chance, block_chance)
    @name = name
    @hit_points = hit_points
    @damage = damage
    @hit_chance = hit_chance
    @block_chance = block_chance
  end

  def dead?
    @hit_points <= 0
  end

  def hits?
    roll(@hit_chance)
  end

  def blocks?
    roll(@block_chance)
  end

  def take_damage(amount)
    @hit_points -= amount
  end

  def block_damage
    @block_damage ||= (damage / 2).round
  end

  private

  def roll(threshold)
    rand(100) > threshold
  end
end

As you can see, it just a data model; it doesn't manipulate anything outside itself.

For the game class, here's a simple implementation that has 3 characters in the mix (everyone gets an attack at each of the others, which isn't too RPG'ish, but it's just for illustration).

class Game
  def initialize
    @characters = []
    @characters << Character.new("Alice", 5, 2, 75, 50)
    @characters << Character.new("Bob", 5, 2, 75, 50)
    @characters << Character.new("Carol", 5, 2, 75, 50)
  end

  def play
    while play_turn
      puts "----------------------------"
      print_status
      puts "----------------------------"
      sleep 1
    end
  end

  def play_turn
    living_characters.permutation(2) do |a, b|
      puts "#{a.name} attacks #{b.name}"

      if a.hits?
        blocked = b.blocks?
        damage = blocked ? a.block_damage : a.damage
        puts "\t#{b.name} blocks" if blocked
        puts "\t#{a.name} inflicts #{damage} points of damage"
        b.take_damage(damage)
        puts "\t#{b.name} has been defeated" if b.dead?
      else
        puts "\t#{a.name} misses"
      end

      if living_characters.size == 1
        puts "Game over, #{a.name} wins"
        return false
      end
    end
    true
  end

  def print_status
    living_characters.each do |player|
      puts "#{player.name}: #{player.hit_points} hit points"
    end
  end

  private

  def living_characters
    @characters.reject(&:dead?)
  end
end

The game class is responsible for printing too, which isn't necessary the nicest way to do things. It conflates the view and controller, even though the model (the character) is now nicely encapsulated. However, I don't know the exact ruleset and UI you're going for, so I'll leave it as-is.

This class also does things a little differently than yours: The game ends the moment there's only one character left alive; recently dead characters do not get a final swing.


Algorithm for computing LCM (least common multiple)

I've included my review comments in the revised code below as program comments,
unmistakable because there weren't any comments in the OP.
Hmm. That's not a good sign. Though, I can't say that I've helped that much. Backward-looking reviewer comments make a poor substitute for useful forward-looking developer comments.

public class LcmAlgorithm {

    /* Making "main" the only public member clearly limits this as a
       stand-alone "toy", and that's OK -- it is what it is.

       Yet, you might want to get in the habit of deciding up front which
       functions are purposely permanently private and which you'd
       consider exposing as public in a "real world" implementation.
       This makes your intent clearer to a reviewer (or your future self).

       On the other hand, arguably, you should only expose something as public
       when/if you have to
       (because you have an actual external caller -- at least a unit test).
       With that in mind, a good short-term compromise might be to comment
       your intent on the private declaration with e.g. '// candidate for public'.
    */

    public static void main(String[] args) {
        long[] input = { 28, 50, 14 };
        // Use the Object, Luke.
        LcmAlgorithm lcmAlgorithm = new LcmAlgorithm(input);
        System.out.println(lcmAlgorithm.lcm());
    }

    // Was named "inputs" but its role is more important than its origin.
    // Note: some people prefer plurals for collection names.
    // Whatever you choose, be consistent
    // -- not "input" here and "inputs" there.
    private final long[] increment;

    // Was "compute" -- don't verb your data names
    // ("sum" sits on the verb/noun fence).
    private long[] sum;

    private LcmAlgorithm(long[] input) { // candidate for public
        assert input.length > 0;
        // Initializing 'increment' here
        // (vs. with an argument to lcm) allows declaration as final
        increment = input.clone();
        // Initializing both 'increment' and initial 'sum' here
        // saves re-computes if lcm is called more than once.
        sum = input.clone();
    }

    // The name LcmAlgorithm.lcm seems a little redundant
    // -- some alternatives are "compute", stressing the action
    // (perhaps too much?) or "result".
    // "result" may be especially apropos since if you call the
    // function a second time on the same object, you get the
    // result again with very little computation.
    private long lcm() { // candidate for public
        while (!allSumsEqual()) {
            int minIx = minSumIndex();
            sum[minIx] += increment[minIx];
        }
        return sum[0];
    }

    // The next two methods have been slightly simplified, including
    // being made instance methods to get implicit
    // access to the array member, and better leveraging
    // the asserted first element.
    private boolean allSumsEqual() {
        final long firstSum = sum[0];
        for (int i = 1; i < sum.length; i++) {
            if (firstSum != sum[i])
                return false;
        }
        return true;
    }

    private int minSumIndex() {
        long min = sum[0];
        int minIx = 0;

        for (int i = 1; i < sum.length; i++) {
            if (sum[i] < min) {
                min = sum[i];
                minIx = i;
            }
        }
        return minIx;
    }
}


Check if string is or can be made into a "valid string"

Your logic is fine. I think that a function of this sort does not necessarily need to be broken down into different functions. This function would still serve a single responsibility and without any wider need of such really specific functions in a wider application context, I see no reason to break it apart like this.

I think what you have can be simplified to something like this:

function isValidString(str) {
    var strArray = str.split('');
    var counter = strArray.reduce(
        (cnt, letter) => { cnt[letter] = (cnt[letter] || 0) + 1; return cnt; }
        ,{}
    );
    var i = 0;
    var compareVal;
    var diffFound = false;
    for (letter in counter) {
        i++;
        if (i === 1) {
            compareVal = counter[letter];
            continue;
        }
        if (counter[letter] === compareVal)
            continue;
        if (diffFound)
            return 'NO';
        diffFound = true;
        if (Math.abs(counter[letter] - compareVal) > 1)
            return 'NO';
        if (counter[letter] < compareVal) {
            if (i === 2) {
                compareVal = counter[letter];
            } else {
                return 'NO';
            }
        }
    }
    return 'YES';
}

Note here we use reduce function to build the letter counter object, eliminating need for separate function. We also slightly optimize the logic to iterate and evaluate the counter, allowing for early exit from that iteration as soon as an invalid condition is encountered.

I probably would not include console logging within the function itself, as I think the function should do only one thing, which is determine if string is valid, not output it as well. Obviously, it is trivial to log the output of this function like

console.log(isValidString(testString));

Be careful in ensuring your function and variables names are meaningful. Your functions are vaguely named and do not specifically convey what caller should expect to happen. 'letterCount' as a variable name would lead me to expect an integer value to be contained therein, not an object with letter counts in it. A simple change to 'letterCounter' would make tremendous difference in conveying meaning of this variable.


I won't comment about your algorithm, as I understand that that's not the focus of this review - suffice it to say that there are better ways of checking winning than comparing against hard-coded winning lines, even in Scala.

Also, Scala has a beautiful and extensive standard library, especially for collections - learn and use it!

In no particular order:

Don't explicitly construct lists - use factory methods

i.e., List.apply(values: T*), a variadic method which can be invoked with syntax sugar as List(value1, value2, ... valueN), as well as similar fill and tabulate.

In fact, fill makes your listOfDuplicates function redundant. There's also a forall method taking a boolean predicate and a list and returning whether all elements of the list satisfy the predicate or not, which makes your allEqual method kind of redundant.
Use appropriate prompts and notification when interacting with the user

For example, when you recurse in playerChoice, you do not let the user know why you're prompting him/her for input again. let him/her know that the position is occupied or invalid before asking him/her again.
Use IndexedSeq for random-access immutable collections

Here I recommend using IndexedSeq instead of Vector specifically to ensure that we type to interfaces - you might want to swap out the implementation for an array later on. This'll also make you update the function signatures.

Why IndexedSeq instead of List? You use updated, a function which accesses elements by index. This is \$O(n)\$ for a List, but amortized \$O(1)\$ for Vector or Array, which follow the IndexedSeq interface.
collect instead of chained filter and map

collect allows you to combine filter and map, essentially allowing you to do pattern-matching in situ. Leads to 1 less intermediate collection (seeing that you aren't using lazy .views) and cleaner code.

Use nested/local functions instead of function literals

In Scala, you can put def within def and so on. This'll allow you to get around the ugly List[Option[Any]] you have for emptyCells and replace it with a proper type parameter. You do this for allEqual already, I don't know why you aren't doing it for everything else (did you copy allEqual` from somewhere else?).
Alias long, frequently used types

Type-alias Player.Value to Player and import it to reduce some visual clutter. Also do the same with List[Option[Player.Value]] by aliasing it to Grid to reduce visual clutter even more.

Use more descriptive variable names

grid for g and value/position for v couldn't hurt.
Proper spacing and indentation

Good enough, but somewhat inconsistent. Put it through an IDE autoformatter, e.g., IntelliJ IDEA's.
Some general ideas for improvement

Incorporate a clean quit mechanism, maybe a q at the prompt?
A help menu where you explain how to play would be nice.
Adding player choice is not that difficult - try it. Just a wee bit of initialization code.

All in all, functional programming is about composing functions together to write programs; immutability and stuff is good to have but it isn't primary. You have some repetition, as in the hasWon check - see if you can get rid of it (Hint - you might want a function which can iterate over the values of the Player enum and check if any of them have won).

Also, this

  def hasWon(p: Player) = winningLines.foldLeft(false)((i, s) => i || allEqual(Some(p), s.map(newGrid(_))))

isn't really ugly. It's a mouthful, yes, but that can be improved with better parameter names (something I'm not doing for you right now - I hope I've indicated how to do it on your own). Don't worry - you'll get used to it. I nowadays find that foldLeft easier to read than a couple nested for loops.

Here's the current code (I might throw in more improvements later):

import scala.annotation.tailrec
import scala.io.StdIn
import scala.util.{Success, Failure, Random,Try}

/**
 * A simple expirement in tic tac toe the idea
 * is to try to have something that contains state
 * without having vars.
 */
object TicTacToe extends App {

  object Player extends Enumeration {
    val X, O = Value
    type Player = Value
  }

  import Player._
  type Grid = Seq[Option[Player]]

  val grid: Grid = IndexedSeq.fill(9)(None)

  val winningLines =
    IndexedSeq(
      IndexedSeq(0, 1, 2),
      IndexedSeq(3, 4, 5),
      IndexedSeq(6, 7, 8),
      IndexedSeq(0, 3, 6),
      IndexedSeq(1, 4, 7),
      IndexedSeq(2, 5, 8),
      IndexedSeq(1, 4, 8),
      IndexedSeq(2, 4, 6))

  @tailrec
  def play(next: Player.Value, grid: Grid): String = {
    def sliceHorizontal(g: Grid) =
      IndexedSeq(
        g.slice(0, 3),
        g.slice(3, 6),
        g.slice(6, 9))

    def playerRepr(p: Option[Player]) = p.map(v => s" $v ").getOrElse("   ")
    def gridRepr(g: Seq[Grid]) = g.map(_.map(playerRepr).mkString("|")).mkString("", "\n---+---+---\n", "\n\n")

    def printGrid(g: Grid) = println(gridRepr(sliceHorizontal(g)))
    printGrid(grid)

    def emptyCells[T](g: Seq[Option[T]]) =
      g.zipWithIndex.collect {
        case (value, index) if value.isEmpty => index
      }

    lazy val randomCell = Random.shuffle(emptyCells(grid)).head

    @tailrec
    def playerChoice(g: Grid): Int = {
      print("Please enter selection: ")
      Try(StdIn.readInt()) match {
        case Success(v) =>
          if (emptyCells(g).contains(v)) v
          else {
          println("Position already occupied, please try a different one")
          playerChoice(g)
        }
        case Failure(_) =>
          println("Invalid Position - try a value between 0 and 8")
          playerChoice(g)
      }
    }

    if (emptyCells(grid).isEmpty) {
      "Draw"
    } else {
      val newGrid = if (next == O) {
        grid.updated(randomCell, Some(O))
      } else {
        grid.updated(playerChoice(grid), Some(X))
      }

      def allEqual[A](first: A, seq: Seq[A]): Boolean = seq.forall(_ == first)

      def hasWon(p: Player) = winningLines.foldLeft(false)((i, s) => i || allEqual(Some(p), s.map(newGrid(_))))

      if (hasWon(X)) {
        printGrid(newGrid)
        "X Wins"
      } else if (hasWon(O)) {
        printGrid(newGrid)
        "O Wins"
      } else {
        play(if (next == O) X else O, newGrid)
      }
    }
  }

  println(play(Player.X, grid))
}


Incrementing time in a discrete-event simulation of a supermarket queue

if (probK <= prob) { // increment k until cumulative probability, prob, reached
             k++;
             prob -= probK;
          } else {
             break;
          }

With this pattern, it's often better to write

          if (probK > prob) {
              break;
          }

          k++;
          prob -= probK;

This saves some indent and makes it clear what is happening.  We check for the end condition and then proceed normally if it was not reached.  The other way, it's not obvious what the end condition is, since it is hidden in an else.

But I would actually rewrite the whole loop.

      int k = 0;
      for (double probabilityOfK = Math.exp(-lambda);
              probabilityOfK <= targetProbability;
              probabilityOfK *= lambda / k) {
          targetProbability -= probabilityOfK;
          k++;
      }

The for loop declaration is on three lines to eliminate side scroll on this site.  It might fit on one line in actual code.

I prefer probabilityOfK to probK as being more readable.  I prefer targetProbablity to prob as being more descriptive.

I stopped using Math.pow as a rather expensive calculation.  It is replaced with a simple multiplication.  And you were multiplying anyway, so that's effectively free.

Now it doesn't use a loop forever pattern with a break.  It just loops normally until the condition fails.

This works because you never use cumulativeProbability outside the loop, but each value relates to the previous one.

The result may change slightly due to double rounding.  It's up to you if that matters.  And if it does matter, if the original was better.

    for (int i = 0; i < lines.length; i++) {

I would do this with a range-based for loop.  Something like

    for (Queue<?> line : lines) {

Then you could replace all the lines[i] with just line.  Replace Queue<?> as necessary.

       while (!lines[i].isEmpty() && k > 0) {

Consider something like

        if (k >= line.size()) {
            line.clear();
            continue;
        }

        while (k > 0) {

Now you don't have to check if line is empty, as you'll run out of k before you run out of line.

You could move that check into the previous loop.  Then if you reach the maximum possible k, you can stop immediately rather than continuing.  That might be more efficient.  Something like

        for (Queue<?> line : lines) {
            if (line.isEmpty()) {
                continue;
            }

            updateLine(line);
        }

and

    public void updateLine(Queue<?> line) {
        int k = 0;
        for (double probabilityOfK = Math.exp(-lambda);
                probabilityOfK <= targetProbability;
                probabilityOfK *= lambda / k) {

            targetProbability -= probabilityOfK;
            k++;

            if (k >= line.size()) {
                line.clear();
                return;
            }
        }

        while (k > 0) {
            line.decrement();
            k--;
        }
    }


Try/catch block inside a method that returns String

If you can process exception inside of your method, process it, otherwise throw it, to let the caller process it or throw further.

Printing stack trace is not exception processing, it is more about logging. And there it is not necessary to return something. Below, there's my approach to handle errors. Please note that it is encouraged to throw more specific Exception class instances rather than Exception or Throwable. For instance: IOException, etc.

public void execute() throws IOException, MyCustomException {
    // Do something
    // if there's an error you can't process, throw a new or this exception
    // otherwise just return nothing.
}


Instead of subtracting the day_in_seconds repeatedly you could divide the total seconds by day_in_seconds and then set seconds equal to (seconds % days_in_seconds).

Something like:

if(seconds/days_in_seconds > 0) {
    days = seconds/days_in_seconds;
    seconds = seconds%days_in_seconds;
}

And so on for the other values..

Hope that helps (Posting from mobile)


A simple brainf*** interpreter in Haskell

Well done. Overall, there are no big flaws, just some minor issues.

Type annotations

While it's great that all top-level functions have proper type signatures, the local bindings inside those functions usually don't. After all, their types should get inferred, e.g.

example :: [Int] -> [Int]
example = map inc
  where
    inc x = 1 + x

doesn't need a type signature since x's type is already fixed to Int. It makes refactoring also a lot easier if we change the type later. If we started with

example :: [Int] -> [Int]
example = map inc
  where
    inc :: Int -> Int
    inc x = 1 + x

and later want to generalize, we might forget the second type signature and end up with an error message:

example :: Num a => [a] -> [a]
example = map inc
  where
    inc :: Int -> Int -- whoops, GHC will yell about that
    inc x = 1 + x

Therefore, type signatures for local functions are usually not written out. There are some instances where they're necessary, but that's usually with RankNTypes or other extensions.

The tape

The tape works well, and is pretty much how you would expect it.

Infinite tapes and debugging

That being said, an infinite tape has the slight inconvenience that you can never inspect it for debugging purposes.

Also, if you ever create a module from your code, you must not export the Tape data constructor, as it would enable Tape [] 0 [] and therefore break assertions.

A finite tape circumvents those issues, but needs slightly more effort in the movements.

Working on the current value

In runBf we can find several spots where we advance the program after we worked on the current value, e.g.:

        Increment -> advance prog (Tape ls (x+1) rs)
        Decrement -> advance prog (Tape ls (x-1) rs)

That's now a possible source of errors, since we could have used

        Increment -> advance prog (Tape ls (x+1) ls)
        Decrement -> advance prog (Tape ls (x-1) ls)

by accident. A small helper can prevent that issue:

onCurrent :: (a -> a) -> Tape a -> Tape a
onCurrent f (Tape ls x rs) = Tape ls (f x) rs

current   :: Tape a -> a
current (Tape _ x _ ) = x

Then we end up with

        MovLeft   -> advance prog (moveLeft tape)
        MovRight  -> advance prog (moveRight tape)
        Increment -> advance prog (onCurrent (+1) tape)
        Decrement -> advance prog (onCurrent (subtract 1) tape)
        Input     -> do
            char <- getChar
            advance prog (onCurrent (const (fromEnum char)) tape)

Naming and scope

As neither advance nor getLoop use any of the bindings in their scope, they're candidates for top-level functions.

runBf' can be called go or another short name. Calling the inner worker just go is really common and won't alienate other readers.

Make interfaces hard to use wrong

getLoop uses an Int as first argument that's not properly documented. Types only go so far as documentation, and we could accidentally use getLoop 0 in BeginLoop.

Instead, we should make it impossible to misuse getLoop:

getLoop :: BfProgram -> BfProgram
getLoop = go 1
  where
    go _ [] = error "Mismatched brackets in BF program"
    go 1 (EndLoop:ps) = []
    go n (p:ps) = p:case p of
        BeginLoop -> go (n + 1) ps
        EndLoop   -> go (n - 1) ps
        _         -> go n ps

Similarly, runBf should probably take a BfProgram, not an arbitrary String, as this doesn't decrease the strength of your program, we can recreate the previous behaviour with

runBf . parseBf

However, speaking of parsing…

Loop validation

A drawback with our current BfProgram is that we might end up with mismatched brackets, e.g.

parseBf "]["

parses fine and leads to a runtime error. However, we could easily detect that during parsing. Our parseBf needs a way to report errors:

type ParserError = String

parseBf :: String -> Either ParserError BfProgram
parseBf = go
  where
    go []     = Right []
    go (x:xs) = case x of
        '<' -> MovLeft <$:> go xs
        '>' -> MovRight <$:> go xs
        '+' -> Increment <$:> go xs
        '-' -> Decrement <$:> go xs
        ',' -> Input <$:> go xs
        '.' -> Output <$:> go xs
        '[' -> -- exercise ; use `getLoop`-like function
        ']' -> -- exercise ; easier if previous one done correctly.
        x   -> go xs
   x <$:> xs = fmap (x:) xs

but afterwards, we can be sure that parseBf only returns BfPrograms with valid brackets.

Unfortunately, we still need to use getLoop, as BeginLoop and EndLoop are still in our instruction set. If we change the instruction set, we can get rid of that too:

data BfInstruction
    = MovLeft
    | MovRight
    | Increment
    | Decrement
    | Output
    | Input
    | Loop BfProgram
    deriving (Show, Eq)

I go into more details in some of my previous Bf reviews, feel free to read them if you get stuck on Loop.

Final remarks

Other than the usual re-evaluation of loops (which is a common scenario in Haskell Bf interpreters), your code was fine, so all the issues are really minor. Again: well done.


Overall, this is pretty straightforward, easy-to-read code. Nicely done.

As @Loufylouf mentioned in the comments, there is a function in OpenCV that calculates a histogram already - the calcHist function. You'd be better off using that. But it doesn't hurt to try to do it yourself just to see how it's done.

You're calculating the histogram of an image with 8-bit per channel RGB pixels. You only need 256 bins, not 257. You're allocating an extra int for each histogram. That's not a huge problem, but you don't need it. (Unlike C strings, arrays do not need a terminating value or anything like that.)

Also, there's a lot of magic numbers in the code. Instead of:

int HistR[256] = { 0 };

You could tell a potential future reader of your code what the 256 (or 257) is. Something like:

const int MAX_BINS = 256;
...
int HistR[MAX_BINS] = { 0 };

Or, since the reason you have 256 bins is because the values you're analyzing are unsigned 8-bit characters, you could use the predefined UINT8_MAX constant. (It's in stdint.h.) Just remember to add 1 to it.

If it were my code, I might even define constants for red, green, and blue you use with the Vec3b type:

const int RED_CHAN = 0;
const int GREEN_CHAN = 1;
const int BLUE_CHAN = 2;

and then:

        int Red = intensity.val[RED_CHAN];
        int Green = intensity.val[GREEN_CHAN];
        int Blue = intensity.val[BLUE_CHAN];

It just clarifies what you're pulling out of the array.

Or, since this is C++, you could subclass Vec3b to add a red(), green() and blue() method and then just write:

int Red = intensity.red();

And I'd also make a constant to use instead of the 500 you have for the width of the histogram images.

I'd break this up into 3 functions - calculateHistogram(), drawHistogram(), and showImage(). calculateHistogram() would have the double loop where you add up values in the different bins. drawHistogram() would generate the HistPlot* images, and showImage() would create the windows and show the images.

Lastly, I'd add some white space! A blank line here or there to group together related lines helps me mentally organize what's going on.


Pascal Triangle implementation in javascript

Minor style points and an alternative solution.

With these types of problems the first port of call is always Wikipedia to get as much info as you can before you start on creating a solution.

Two things stand out about the solution.

The rows are symmetrical, the right side is a mirror of the left.
There is a formula that lets you calculate a row which can help reduce the complexity.

Your code

There is nothing majorly wrong with the code, the following are just general style points

Do the output outside the function.
Use const for variables that do not change.
Declare variables with var at the top of the function or use let to declare variables in the block they are to be used.
In nested loops try to avoid double indexing by creating a reference to the inner array outside the inner loops.
The function is not complete, as it does not return the correct results for pascalTriangle(0) and pascalTriangle(1) a simple if statement can take care of that.
Don't duplicate variables for no reason. The variable i (out loop iteration counter) is immediately copied to a variable curr and neither are changed inside the loop.
When writing we put a space after a comma, this make it easier to read then without,thus illustrated. The same with code, put spaces after commas so that it does not all blend together. Same for operators where the convention is a space either side. eg data[curr+1] should be data[curr + 1] and data = [[1],[1,1]]; should be data = [[1], [1, 1]];
(minor point as the problem is simple and solution sort) You could use some better names for some of the variables.

Rewrite

Rewriting your function using the above points.

function pascalTriangle1(rowCount) {
    if (rowCount === 0) { return [] }
    if (rowCount === 1) { return [[1]] }
    const rows = [[1], [1, 1]];
    var prevRow = rows[1];
    for (let n = 1; n < rowCount - 1; n += 1) {
        const row = [1];
        let val = prevRow[0];
        for (let k = 0; k < prevRow.length - 1; k += 1) {
            row.push(val + (val = prevRow[k + 1]));
        }
        row.push(1);
        rows.push(row);
        prevRow = row;
    }
    return rows;
}

Alternative solution

The following reduces the number of calculations to about half by exploiting the symmetry of each row.

Further improvements can be made by using Float64Array and pre-calculating the triangle size, then indexing directly into the array, avoiding the expensive array creation left and right and concatenation for each row. But that would only show any real benefit for very large triangles, where he need to hold all the rows would be questionable.

const pascalTriangle = rowCount => {
    const createRow = rowIndex => {
        var k = 1, val = 1;
        const n = rowIndex + 1;
        const left = [val];
        const right = [val];
        while (k < n / 2) {  // only do half the row
            val = val * (n - k) / k++;
            left.push(val);
            right.unshift(val);
        }
        if (n % 2) { right.shift() }  // when n is odd remove first right item
        return [...left, ...right];
    }
    const rows = [];
    if (rowCount > 0) {
        let i = 1;
        rows.push([1]);
        while (i < rowCount) {  rows.push(createRow(i++)) }
    }
    return rows;
}


In general you should try and avoid floating point operations for any cryptographically specific code. Floating points have issues with regards to precision, and even I don't see any issue for this specific code, they always require special attention, e.g. during reviewing of the code.

Similarly, using recursive code is strongly discouraged for cryptographic algorithms. If your code can be coded using loops and only local variables you should really do so. I imagine that goes against the idea of Rust (and is thus up for debate), but crypto code generally requires special attention. If you keep to recursive calls make sure you document them as such, both inline and in the function description.

Although you nicely implemented the Drop destructor it makes more sense to create either a class with just a keyInputMaterial (now called data I presume) or simply keep all the data in parameters / local variables. The idea of just keeping the keyInputMaterial is that you may reuse the object to derive other keys using the function but with different salt / info. In that case you obviously need to retrain the Drop to clear the input key material.

Note that the internal key handling (padding, initial hashing) of HMAC is always the same. So a sneaky speed up is to perform pre-calculation on the salt which acts as the HMAC key (mainly useful if there is a lot of output expected, this speedup matters more for e.g. PBKDF2).

Your constant time function looks very much run-of-the-mill constant time, which in this case is great :) I don't think HKDF warrants a function where HMAC(k, x) and HMAC(k, y) are compared using a random key - but now you know about that neat little trick.

Note that you may want to make sure that you document that the comparison needs to be done in constant time or include it in a verify function (beware of truncated values - you did this in your code, but you need to consider it in the calling code as well!).

Note that I'm not a Rust expert, so I won't comment on the vector handling / slicing etc.


SQL query that flattens many-to-one relationships

Don't LEFT JOIN unless you really need to
In a comment I asked:

Is there a specific reason you are using LEFT JOIN so much? Do you expect products to not have references in those tables a lot? LEFT JOIN are quite expensive and should be used only when needed – Phrancis

To which you responded:

I don't expect it to happen a lot, but I do expect it to happen. In particular, there are products with no options. But there aren't any products with no categories. – 4castle

That being said, you probably ought to build into your script some checks for that. In plain English, something like this might make sense. You can use if/else blocks to make it work.

Check with only a left join on your options. This should cover a large amount of cases, based on your response.

Should that return no rows for an existing product, then try with more left joins to see if something else might be missing.

Should that still return no rows, or invalid data, throw an error.

Aliases
There are a few points from your code that I think can be improved. For instance FROM product p is not a good alias (consider the other aliases as well), as aliases should at least give a hint as to what they are referring to, and p really doesn't. FROM product AS prod would be better in this case.
Also notice the addition of AS keyword which is good practice. It's less of a big deal with table aliases, but it can cause issues in particular with column aliases if it is missing, so it's really best to just include it.


Integral implemented using a trapezoidal Riemann sum

Embrace even more static analysis tools, such as clippy. It provides warnings like:

warning: `if _ { .. } else { .. }` is an expression
  --> src/main.rs:12:5
   |
12 |       let mut sign = 1.0;
   |  _____^ starting here...
13 | |
14 | |     if a > b {
15 | |         mem::swap(&mut a, &mut b);
16 | |         sign = -1.0;
17 | |     }
   | |_____^ ...ending here
   |

You don't need to rebind a variable to make it mutable. you can just add mut in the argument list.
When a where clause is used, the { moves to the next line.
Why is abs used?  Isn't it guaranteed that b > a?
"side" vs "size" seems likely to cause confusion. Either make them the same or distinct.
Using map and sum avoids needing to make result mutable.
Consider removing all mutability; either by reassigning all the variables at once:

let (a, b, sign) = if a > b {
    (b, a, -1.0)
} else {
    (a, b, 1.0)
};

Or by adding a small shim that reverses the order and applies the negation; I like the latter solution  because it ties the argument reversal and final negation closer together.

/// calculates the signed area between the function f and the x axis from
/// x = a to b using a trapezoidal Riemann sum. precision is the number of
/// trapezoids to calculate
pub fn integral<F>(a: f64, b: f64, f: F, precision: u32) -> f64
    where F: Fn(f64) -> f64
{
    fn core<F>(a: f64, b: f64, f: F, precision: u32) -> f64
        where F: Fn(f64) -> f64
    {
        let delta = (b - a) / precision as f64;

        (0..precision).map(|trapezoid| {
            let left_side = a + (delta * trapezoid as f64);
            let right_size = left_side + delta;

            0.5 * (f(left_side) + f(right_size)) * delta
        }).sum()
    }

    if a > b {
        -core(b, a, f, precision)
    } else {
        core(a, b, f, precision)
    }
}


Method for Access to a Resource with 'Retry' Logic

I agree that having to throw that exception to appease the compiler is ugly. There's also another bit of unpleasantness which isn't quite so egregious, but helps point to what's actually wrong here:

Your while loop condition is

while(currentDbAttempt <= MAX_DB_ATTEMPTS)

But inside the same loop, you do

if (currentDbAttempt == MAX_DB_ATTEMPTS)

So what's happening, causing both these problems, is that you're trying to do something inside the loop which is actually meant to happen when the loop is finished. That should happen outside the loop. Fortunately in this case it's a simple fix- just move your failure exception outside the loop:

static Int32? GetDbValue()
    {
        currentDbAttempt = 1;
        Exception lastException;
        while(currentDbAttempt <= MAX_DB_ATTEMPTS)
        {
            try
            {
                Int32? nextId = [some DB work]
                return nextId.Value;
            }
            catch (Exception ex)
            {
                lastException = ex;
                _log.WarnFormat("Error in [method name]: {0}. Try count {1}",
                    ex.Message, currentDbAttempt++);
            }
        }

        throw new Exception(string.Format("Error in [method name]. Tried {0} times",
                        MAX_DB_ATTEMPTS), lastException);

    }

Doing the above uncovered something else: you swallow the exceptions most of the time, but somewhat arbitrarily expose the last one as an inner exception if you fail. This does make sense on the assumption that the exceptions will always occur for the same reason (e.g. timeout), but you might consider using an AggregateException or similar to expose all of them.

Either the method should have an int return value, or you should be returning nextId instead of nextId.Value. Either you have a potential InvalidOperationException waiting to happen if nextId can truly not have a value, or you're needlessly giving your caller extra work having to do its own HasValue check.

You're doing a worrying amount with statics. Not only are you holding state in currentDbAttempt, you're also accessing what I can only assume is some dependency in _log. While you say multi-threading isn't an issue, over-reliance on statics also sacrifices your ability to take full advantage of OO features like polymorphism.

The currentDbAttempt variable is fixible easily enough by just moving it inside the method, where it should be anyway. But I think more generally you should make sure you're not making things static over-eagerly.

The way you increment currentDbAttempt is a good example of being "too clever". It's much less clear than if you just had an extra currentDbAttempt++ statement outside the WarnFormat line, and that would also be far less prone to accidentally introducing bugs if you later come back to maintain this method.

Even better, why not pick an idiomatic option and use a for loop?


Create CSV file of domain groups and their users

Some notes:

Comments: A lot (if not all) of the comments are pretty much repeating what the code already says. I'd remove them.
server = # enter server name here. Create functions with configurable elements as arguments instead of global variables.
with open('groups_members_output.txt', 'wb') as blank_file. Try to give more meaningful names to variables, be declarative. blank_file says hardly anything useful about the variable.
grps/usrs: Just for saving one or two characters now variables are harder to read.
Put spaces after commas.
Use (functional) list-comprehensions expressions instead of (imperative) for-loop statements whenever possible.
Use always "\n" for line endings (read and write), Python takes care of portability in all platforms.

I'd write:

import win32net

def write_group_members(server, input_groups, output_groups):
    with open(input_groups) as input_groups_fd:
        groups = [line.rstrip() for line in input_groups_fd]

    with open(output_groups, "w") as output_groups_fd:
        for group in groups:
            users = win32net.NetGroupGetUsers(server, group, 0)[0]
            for user in users:
                contents = "{0},{1}\n".format(group, user["name"])
                output_groups_fd.write(contents)

write_group_members("someserver.org", "groups.txt", "groups_members_output.txt")


You're just looping on the rows, but not on the cells:

 for row in all_tables[table].find_all("tr"):

Rather than using multiple find_next("td") one after the other, add another loop using row.find_all('td') and append each row and cell to a 2D array.

Manipulating a 2D array is much easier and will make your code look much cleaner than row.find("td").find_next("td").find_next("td").

Good luck!

Those questions contain some answers that might interest you:

How to convert an HTML table to an array in python
python BeautifulSoup parsing table

To be more specific, this code snippet from @shaktimaan:

data = []
table = soup.find('table', attrs={'class':'lineItemsTable'})
table_body = table.find('tbody')

rows = table_body.find_all('tr')
for row in rows:
    cols = row.find_all('td')
    cols = [ele.text.strip() for ele in cols]
    data.append([ele for ele in cols if ele])


(setq letters (get-letters s))

You are setting the same letters variable from different functions; in Emacs Lisp, that sets a global variable which is bad style: (1) that pollutes the global namespace, (2) that could overwrite an existing variable, and (3) the functions are not reentrant and could lead to bad suprises with side-effects. Better introduce variables with let.

Instead of doing (remhash "" letters), you can pass T for OMIT-NULLS in split-string.

Another approach is to transform the input text so as to downcase all letters, remove spaces, remove duplicate letters and check if it corresponds to the expected alphabet. For example:

(equalp (delete-duplicates
         (sort (coerce
                (downcase
                 (remove ?\s "The quick brown fox jumps over the lazy dog"))
                'list)
               '<))
        (coerce "abcdefghijklmnopqrstuvwxyz" 'list))


Create an instance (view) given its dependency (view model)

A ViewModel should not be convertible to a View, it should be bound to it. The View should have a ViewModel property. You should not have child Views for child ViewModels. Instead, you should have one view that knows how to access the children of your top ViewModel (and there is only one of those).

The code seems way overcomplicated. Unless a Visual is a UI element like a page or control, it is probably a superfluous layer. MVVM where Views are POCO objects is usually a bad idea--it can't present to the screen, which is the most important job of a View. If I am understanding your code correctly, you could probably accomplish your goals by removing your Visual layer and converting your Bundle into a top-level ViewModel, directly binding it to your UI/View. Your child overlays should be child ViewModels of your existing ViewModels, of which there shold only be one per View, and the View knows how to access the children property of the parent ViewModel.


Updating messages from a list of messages

Not sure if it's "optimized", but here's something of a simplification:

    protected void grdMessage_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        string messageIdString = Request["MessageID"];
        int messageId = messageIdString == null ? 0 : Convert.ToInt16(messageIdString);

        using (DataSet mdsRedirect = new DataSet())
        {
            DataTable table = mdsRedirect.Tables[0];
            string updateMessageText = ((TextBox)grdMessage.Rows[e.RowIndex].FindControl("txtupdMessage")).Text;

            mdsRedirect.ReadXml(st);
            table.DefaultView.RowFilter = messageId == 0 ? table.DefaultView.RowFilter : "MessageID=" + messageId;
            if ((messageId != 0) && (table.DefaultView.Count > 0))
            {
                // Find specific item from XML and set updated value
                table.DefaultView[0]["MessageText"] = updateMessageText;
                table.DefaultView.RowFilter = string.Empty;
            }
            else
            {
                table.Rows[e.RowIndex]["MessageText"] = updateMessageText;
            }

            grdMessage.EditIndex = -1;
            mdsRedirect.WriteXml(st);
        }

        getxml(); // read XML file and bind it
    }


One thing that I see right off the bat, is the clean() method.  Why are you escaping things arbitrarily?

public function clean($input) {
    $clean = Array();
    foreach ($input as $field => $data) {
        $clean[$field] = mysql_real_escape_string($data);
    }
    return $clean;
}

All you're doing is making it harder to trace code, and harder to prove if your code is secure or not.  Not to mention that's a major breach of the Single Responsibility Principle.

It's a huge side-effect and should be removed.

Always escape or quote as close as possible to where you're putting it.


Your solution seems pretty optimal - for breadth-first traversal (see below)

MaxDepth() could/should be static.  The containing class too.
The LeetCode question does not require breadth-first traversal.
Depth first would not require an(y) additional data structure (no queue, but would implicitly use the stack)
which might be optimised away by tail-recursion (if C# is smart enough).

The following is therefore not criticism but a suggested alternative.
- I would not expect (much of) a performance difference
- Space-advantage, if significant (due to tail-recursion optimisation, compiler-and/or run-time environment dependent) would have to be measured
- So the main consideration in (not) choosing depth-first traversal would be a (probably) religious argument about brevity/readability of code

public static int MaxDepth2(IEnumerator<Node> nodeEnum = null, int depth = 0)
{
  //  No current node
  if (nodeEnum == null || !nodeEnum.MoveNext()) return depth;

  //  The greater of current and maximum of siblings
  using (var nodeEnumInner = nodeEnum.Current?.children?.GetEnumerator())
    return Math.Max(MaxDepth2(nodeEnumInner, depth + 1), MaxDepth2(nodeEnum, depth));
}

:
:
using (var nodeEnum = new List<Node> { root }.GetEnumerator())
  depth2 = MaximumDepthOfN_aryTree.MaxDepth2(nodeEnum);


static int[] mergeSort(int[] arr) {

If you want to call it array, please go ahead and write out the name.

Personally, I'd prefer data or numbers as names, but that may just be me.

    int[] left, right;

    left = Arrays.copyOfRange(arr, 0, arr.length / 2);
    right = Arrays.copyOfRange(arr, arr.length / 2, arr.length);

While this will work, consider

    int[] left = Arrays.copyOfRange(arr, 0, arr.length / 2);
    int[] right = Arrays.copyOfRange(arr, arr.length / 2, arr.length);

It's actually slightly shorter in this case, as int[] is shorter than left, right;.  But even if it were longer, it is easier to follow with the declaration and initialization on the same line.

    int midpoint = arr.length / 2;

This could make it clearer why you are passing around arr.length / 2 if you replace occurrences with midpoint.

    int i = 0, j = 0, z = 0;

I would find this easier to read as either

    int i = 0,
        j = 0,
        z = 0;

or

    int i = 0;
    int j = 0;
    int z = 0;

One initialization per line.

    printArr(result);

This looks like debugging code to me.  If so, it should have been removed before review.

I don't have any real comments on the algorithm itself beyond what people said in the comments.  You might be able to bring down the memory usage if you tried hard enough, but it shouldn't generally matter.  This is a more elegant version and less susceptible to bugs if you aren't memory bound.

You may be doing this just as an exercise (you can use the reinventing-the-wheel tag to indicate this) or for some other reason.  In practice, the standard Arrays.sort implementation is good enough for most needs.  You wouldn't normally need to roll your own.


How to handle multiple return statements

I'm no expert in JavaScript, but it seems to me if you changed the scope of token so that it is defined at the beginning of the function and then just modify the value as necessary that you can have only one return statement after all the if statements.


You dont need the sorting. The vector contains numbers 1 to (n + 1) with one number omitted. If it wasnt omitted it would sum up to (n+ 1)*(n+ 2)/ 2. Sum the vector, subtract it from the full sum And what Is left over Is the number that was omitted.


Write a function to extract a given number of randomly selected elements from a list

Your solution looks good to me, no reason to discourage using let as far as I know.

Tip: if you make the type randomFromList :: Int -> [a] -> StdGen -> ([a], StdGen), then you can call it like this: main = getStdGen >>= print . randomFromList 7 ['A'..'Z']

Also, if the requirement is interpreted as selecting randomly without replacement, your version only needs slight modification (this also uses randomR rather than mod):

dropAt :: Int -> [a] -> [a]
dropAt k xs = take k xs ++ drop (k+1) xs

randomFromList :: Int -> [a] -> StdGen -> ([a], StdGen)
randomFromList 0 _ generator = ([], generator)
randomFromList _ [] generator = ([], generator)
randomFromList toDo xs generator =
  let (index, generator') = randomR (0, length xs - 1) generator
      (otherNumbers, generator'') = randomFromList  (toDo -1) (dropAt index xs) generator'
  in  ((xs !! index) : otherNumbers, generator'')

See also this shuffle implementation for some attempt at optimisation.  (You could potentially solve the random selection by something like take n . shuffle.)


I think your proposed change is an improvement for two reasons.  First, it breaks up one long function into multiple smaller ones which is better for human comprehension.  Second, it also allows for reuse of the functions which may also improve efficiency, reduce code size, etc.
There are, however, a couple of things that might be considered for further improvements.
Exceptions
With a long and complex constructor like this, and especially one which involves I/O, things can go wrong.  Carefully considering what might go wrong and using C++ exceptions has the possibility of making your code more durable.
Named variables vs. object collection
Although you're using a constructor, the code looks very procedural. Instead of populating a number of named variables, consider each of those variables itself to be an object.  You could store the name (e.g. "path1"), type, and any required value checks encapsulated within individual objects, making the code easier to read, understand and maintain.  I'd be inclined to use a static data structure to store and associate those things rather than burying all of those details in code.  A std::map might be appropriate.
Example code
To flesh out that latter suggestion a bit, consider that you might have a string, and an unsigned int as configuration items.  To refer to them, you could use just the variable names, or you could create a map:
std::map<std::string, std::unique_ptr<ConfigItem> > config;

Here ConfigItem would be a base class for all configuration items.  You would specialize that class for each different kind of configuration item, such as a plain string, a string that represents a filename, a floating point number, etc.  Using the items would then use the std::string as a key to look up and retrieve the corresponding object.  The std::unique_ptr is just to make sure that the contained objects are deleted when config is deleted.
Here's an example base class:
class ConfigItem
{
public:
    friend std::ostream &operator<<(std::ostream &out, const ConfigItem &ci) {
        return ci.printTo(out);
    }
    virtual operator int() const { return 0; }
    virtual operator std::string () const { return std::string(); }
    virtual ~ConfigItem() {};
protected:
    virtual std::ostream &printTo(std::ostream &out) const {
        return out;
    }
};

Note that the member functions are all virtual.  Here's a specialization for a string:
class ConfigString : public ConfigItem
{
public:
    ConfigString(std::string value) : mValue(value) {}
    std::ostream &printTo(std::ostream &out) const {
        return out << mValue;
    }
    operator std::string () const { return std::string(mValue); }
private:
    std::string mValue;
};

Here's a specialization for an int:
class ConfigInt : public ConfigItem
{
public:
    ConfigInt(int value = 0) : mValue(value) {}
    std::ostream &printTo(std::ostream &out) const {
        return out << mValue;
    }
    operator int() const { return mValue; }
private:
    int mValue;
};

If you look at those two classes carefully, I'm sure it will be pretty easy to spot that they could have been written as a template instead.
Here's a test driver:
#include <iostream>
#include <iterator>
#include <memory>
#include <string>
#include <map>
#include "ConfigItem.h"

int main()
{
    std::map<std::string, std::unique_ptr<ConfigItem> > config;
    config.emplace("inputFilename",
                   make_unique<ConfigString>("/var/log/messages"));
    config.emplace("maxMessages",
                   make_unique<ConfigInt>(200));

    for (const auto &it : config)
        std::cout << it.first << " = " << *it.second << '\n';

    int count = *config["maxMessages"];
    std::cout << "count = " << count << '\n';

    std::string filename = *config["inputFilename"];
    std::cout << "file name = \"" << filename << "\"\n";
}

Also note that if you're only using C++11 and don't have access to a C++14 compiler (one that contains a definition for make_unique() yet), you can use this:
template<typename T, typename ...Args>
std::unique_ptr<T> make_unique( Args&& ...args )
{
    return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) );
}

Sorry that's so long, but I wanted to show a clear, complete and correct example.


You can do:

changeText = () => {
    firstDay.textContent = weekday[(day + 1) % 7]
    secondDay.textContent = weekday[(day + 2) % 7]
    thirdDay.textContent = weekday[(day + 3) % 7]
    fourthDay.textContent = weekday[(day + 4) % 7]
    fifthDay.textContent = weekday[(day + 5) % 7]
}

Also I'd recommend passing day as a parameter. Just so that it's more clear.


Class to share data between two threads implemented as FIFO with std::queue

This is more of a stackoverflow question but whatever.

There is no guarantee that std::queue is thread safe and methods empty()/front()/push() will properly interact in a multi-threaded environment. They most certainly cause data races. For this reason you need to use std::mutex to ensure that std::queue isn't accessed simultaneously from multiple threads ensuring that the data is read/written correctly.

What are you going to do when the queue is empty? What if you want to wait for next element? Will you put sleep(10ms) periodically? What if it isn't responsive enough and has too big of a lag? The proper method is to utilize std::condition_variable which has proper wait/notify methods.

It isn't worth to create a shared pointer to view some 100 bytes. You'd better transfer 100 bytes of data by copying it.

This isn't a C++ approach to transfer data by simply copying chunks of bytes. What you should do instead is to template your thread-safe queue over some class T so it moves T's instances from sender to receiver in a safe way.


Crawling through a YouTube channel via the YouTube API

Global variables are almost never needed.  You should pass playlistIds as a parameter.  Well, actually, just don't make getPlaylistId() modify the list; make it return the list.  Even better, make it a generator function that yields each id and title.  That's better because you aren't storing the id's and titles in memory.

Your naming is not in accordance with PEP 8, the Python style guide:

  Function names should be lowercase, with words separated by underscores as necessary to improve readability.

  mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility.

and for Method Names and Instance Variables:

  Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.

You seem to have some magic values such as '50', 'UCtESv1e7ntJaLJYKIO1FoYw', etc.  How did you come up with those values?  I would suggest making constants at the beginning of the file for your defaults.  Then, use sys.argv or, if you want to be fancier, argparse to get the values from the user.

Instead of creating a dictionary (data) and then setting all of the values, why not just create a dictionary with the right values in the first place?  That is, data = {'maxResults': '50', 'channelId': 'UctESv1e7ntJaLJYKIO1FoYw', ...}

Instead of defining items just to iterate, why not for item in json.loads(string)['items']:?

Your indentation in download() is odd.  You use four spaces everywhere else, but here you use eight.  Be consistent at the least.

os.chdir("./" + title)

Don't make it a habit to put the dots and the slashes in yourself.  Use os.path.join(os.curdir, title).  os.chdir("..") also would change to os.chdir(os.pardir).

Let's say I want to use your program in mine, but I have a different list of id's to get and a different list of titles.  This is my program:

from downloader import download

def get_ids_and_titles():
    ...
download(get_ids_and_titles())

After the first line, your program just did its thing.  It downloaded everything.  I didn't want to run your program; I wanted to use one of its functions.  You can find out if your program is being run as a module or as a program like this:

if __name__ == '__main__':
    download(getPlaylistId())

If your program is run as a program, __name__ is __main__, but if it is a module, it will be the name of the module.


Four issues with private static boolean checkMatch(String word, String candidate):

checkMatch is not as descriptive as a name could be.  I think private static boolean isAnagram(String a, String b) would be better.  I would also rename the parameters to acknowledge that they are symmetrical: it doesn't matter which is the original word, and which is the candidate.
You don't need to end with an if-else.  You can just say return Arrays.equals(wordArray, candidateArray);
You would be re-sorting the characters of the original word each time you test a candidate.  That's OK, I suppose, if you prefer clean code over efficiency.
Why not start with

private static boolean isAnagram(String a, String b) {
    if (a.length() != b.length()) {
        return false;
    }

    // Continue with a thorough comparison...
    ...
}

Then the code in readAnagramsFromFile() can read very smoothly:

if (isAnagram(word, candidate)) {
    anagrams.add(candidate);
}

Note that the return type of readAnagramsFromFile() should be List<String>, not just a generic List.


Am I sufficiently cleaning incoming $_GET parameters, especially in the array?

My 2 cents:

$int = abs( intval( $int ) ); // positive number

Silently fixing input values is evil, perhaps required, but still evil.

function gfahp_sanitize_array( $array ) {
     $array = array_walk_recursive( $array, "gfahp_sanitize_string" );
     return $array;
}

You assign and then return, I would just return immediately

function gfahp_sanitize_array( $array )
{
     return array_walk_recursive( $array, "gfahp_sanitize_string" );
}

Also, what is up with gfahp ? Hungarian notation of functions with acronyms is a slappable offence.

As for

function val4_strip($val_4){
// strip down val4
    if (!empty($val4){
        switch ($val4) {
            case 'foo':
                $val4 = 'foo';
            break;
            case 'bar':
                $val4 = 'bar';
            break;
            case 'fudge':
                $val4 = 'fudge';
            break;
            default:
            $val4 = (unset) $val4
            break;
        }
    }

}

You should probably go for a generic function that can look up a value in a set and assign it if found, otherwise return blank. ( Also that function does not return anything? ) (Also you are unsetting var4 in places ). Something like

$val4_set = array( "foo" , "bar" , "fudge" );

( isset( $_GET["val4"] ) ? (string) $val4 = sanitize_string_from_set($_GET["val4"], $val4_set)  : (unset) $val4 );

function sanitize_string_from_set( $string , $set )
{
  return array_key_exists( $string, $set )?$string:"";
}


The ListenHear Game - Listen and type the word

Your game() calls c=setInterval(…), which is balanced by clearInterval(c) in check().  However, giveup() does not call clearInterval(c).  As a result, if you just start the game but do nothing, then it gets ridiculously faster and faster.


Scrape google apps page and store application details in database

This is being ported over to python 3.x from python 2.x

Docstrings: You should include a docstring at the beginning of every method/class/module you write. This will allow documentation to identify what your code is supposed to do. PEP-8 Docstring Conventions.
Variable / Operator Spacing: When not in default parameters, you should put spaces between variables, the =, and the content it's being assigned. Also, there should be spaces between variables that are being passed to methods. PEP-8 Whitespace Conventions.
Import Ordering: Standard library imports should be put first, then related third party imports, then local libraries/files, all grouped and separated by a blank line. PEP-8 Import Conventions.
String Formatting: Your __str__ in your App class is a bit messy. If you see this behavior, something is afoot. This is a red flag to me. I use f"" to directly include variables into my strings, instead of having to type cast them or, in your case, having to use multiple + to concatenate the variables and the strings.
Unnecessary return statements: Your return in your crawl method is unnecessary. Python automatically returns at the end of functions, so having that return isn't needed.

Updated Code

"""
Module Docstring:
A description of your program goes here
"""

import requests
import MySQLdb

from lxml import html

class AppCrawler:
    """
    Class for crawling a link, and gathering information about an app
    """
    def __init__(self, starting_url, depth):
        """
        AppCrawler Class Init Method

        :param starting_url: The starting url for the crawler
        :param depth: How deep the app crawler should go

        """
        self.starting_url = starting_url
        self.depth = depth
        self.current_dept = 0
        self.depth_links = []
        self.apps = []

    def crawl(self):
        """
        Crawls to find links connected to apps
        """
        app = self.get_app_from_link(self.starting_url)
        self.apps.append(app)
        self.depth_links.append(app.links)

        while self.current_depth < self.depth: #0 < 0
            current_links = []
            for link in self.depth_links[self.current_depth]:
                current_app = self.get_app_from_link(link)
                current_links.extend(current_app.links)
                self.apps.append(current_app)
            self.current_depth += 1
            self.depth_links.append(current_links)

    def get_app_from_link(self, link):
        """
        Gets the app from the passed `link`

        :param link: Link to the app

        """
        start_page = requests.get(link)

        tree = html.fromstring(start_page.text)

        name = tree.xpath('//div[@class="id-app-title"]/text()')[0]

        temp_addr = tree.xpath('//a[contains(@href,"mailto") and @class="dev-link"]/@href')[0]
        developer = temp_addr.split(':')

        price = tree.xpath('//button[@class="price buy id-track-click id-track-impression"]/span[2]/text()')
        temp_price = price[0].split()
        price = str(temp_price[0].lstrip('$'))
        if price == "Install":
            price = "0"
        templinks = tree.xpath("//a[@class='title']/@href")

        links = []
        length = len(templinks)
        domain = "https://play.google.com"
        for i in templinks:
            i = f"https://play.google.com{i}"
            links.append(i)
        app = App(name, developer[1], price, links)
        return app

class App:
    """
    Class to represent each app getting crawled
    """
    def __init__(self, name, developer, price, links):
        """
        App Class Init Method

        :param name: Name of the app
        :param developer: Developer of the app
        :param price: Price of the app
        :param links: list of links to the app

        """
        self.name = name
        self.developer = developer
        self.price = price
        self.links = links

    def __str__(self):
        """
        Returns a string representation of the app
        """
        return f"{self.name.encode('UTF-8')}|{self.developer.encode('UTF-8')}|{self.price.encode('UTF-8')}"

if __name__ == '__main__':

    conn = MySQLdb.connect("localhost","root","pA$$W0rd","app_database")
    cursor = conn.cursor()

    crawler = AppCrawler('https://play.google.com/store/apps/details?id=com.mojang.minecraftpe', 0)
    crawler.crawl()

    query = "INSERT INTO app_table (name,developer,price) values('%s','%s','%d ')"
    for app in crawler.apps:
        data = str(app).split('|', 2)
        price = float(data[2])
        try:
            cursor.execute(query % (data[0], data[1], price))
            print("OK")
            conn.commit()
        except:
            print("Failed")
            conn.rollback()
        print(data[0], data[1], price)


Basic password authentication system app

Try using std::vector instead of arrays. As a result, you'll not be required to keep track of the array_size in a separate variable like n in your case.

Something like this:

std::vector<std::string> username;
username.push_back("admin");
//other entries go here
std::vector<std::string> password;
password.push_back("root");
//other entries go here

Then, the size of the std::vector is given by size().
Try to use proper names as variables. Avoid wrong spellings or short-names. Exact variable names make the code easy to understand, as the name represents the actual concept the variable is referring to.
Also, in registerUser() the variable answer can just be a char. This will help in saving a little memory.
Like:

char answer;
std::cin>>answer;
if(answer=='y' || answer=='Y')
{
    //code goes here
}

In your code, the method commandC() is defined to return an int. But it doesn't do so. Make the return type void instead.

void CommandC()
{
    //code goes here
}

Also, the main() method is defined to return an int too. It is a good practice to declare it like that, but make sure to return an integer. 0 (zero) is preferred as it refers to successful completion of main().

int main()
{
    //code goes here
    return 0; //indicates successful termination
}


Format seconds into the two biggest units of time

In general I think your code is pretty good.  It is a simple function, and it does not need to get fancy.

I do think one bit could be a bit cleaner.  I believe this format string:

format_str = lambda v1, v2, p: f"{v1:0>2}{p[0]}{v2:0>2}{p[1]}"
format_str(d, h, ("d","h"))

would be simpler and therefore clearer as:

format_str = "{:0>2}{}{:0>2}{}"
format_str.format(d, 'd', h, 'h')

I think the lambda here is not helping readability.

More Pythonic?

For this simple case I don't think you really need anything more Pythonic.  But let's have some fun and illustrate using some Python libraries.

datetime library

First thing to consider is maybe using standard Python lib for doing some of the date and time math. The library could build those values for you like so:

import datetime as dt

# build a datetime from the number of seconds passed in
a_time = dt.datetime.utcfromtimestamp(seconds)

# get d, h, m, s
d, h, m, s = dt.timedelta(seconds=seconds).days, a_time.hour, a_time.minute, a_time.second

Stacked ifs

You asked specifically about the stacked ifs. In this case the ifs are not stacked very deep, so what follows is rather severe overkill :-)

Here is a general way to get the elements following the first non-zero element.

# get values fllowing first non zero value and their labels
non_zero = tuple(it.dropwhile(lambda x: not x[0], zip(values, 'dhms')))

Yikes, this is that an eyesore! But is does show how to get the elements following the first non-zero element in a general way, IE: No stacked ifs needed.

How does that work?

Let's break it down a bit.  Starting from the inside:

zip(values, 'dhms')

This will produce a sequence of tuples looking something like:

[(0, 'd'), (1, 'h'), (1, 'm'), (5, 's')]

Note how the use of zip() allows the labels to be associated with their elements.  This allows the next step to keep the labels with their values.

Then:

it.dropwhile(lambda x: not x[0], zip(values, 'dhms')))

uses itertools.dropwhile() to drop the leading tuples which start with 0. Finally:

non_zero = tuple(it.dropwhile(lambda x: not x[0], zip(values, 'dhms')))

will produce a tuple so that we can get the number of elements to help produce the format string:

# a format string
format_str = "{:0>2}{}{:0>2}{}" if len(non_zero) > 1 else " {:0>2}sec"

And then bring it all together with:

# format the string
return format_str.format(*it.chain.from_iterable(non_zero or ((0, 0),)))

itertools.chain.from_iterable() flattens the non_zero tuple, to make the format() a little easier:

Complete recast function

import datetime as dt
import itertools as it

def pprint_time2(seconds):

    # build a datetime from the number of seconds passed in
    a_time = dt.datetime.utcfromtimestamp(seconds)

    # get d, h, m, s
    values = dt.timedelta(seconds=seconds).days, a_time.hour, a_time.minute, a_time.second

    # get values following first non zero value and their labels
    non_zero = tuple(it.dropwhile(lambda x: not x[0], zip(values, 'dhms')))

    # a format string
    format_str = "{:0>2}{}{:0>2}{}" if len(non_zero) > 1 else " {:0>2}sec"

    # format the string
    return format_str.format(*it.chain.from_iterable(non_zero or ((0, 0),)))


Cryptographic range based random number generator class 2.0

First of all somehing trivial:

When max < min or max == min you correctly throw ArgumentException but then for min < 0you should throw ArgumentOufOfRangeException however...ulong cannot be less than zero then this check is meaningless.
There is a needless cast in the other overloads of Next(): return value is already an int.
If you cast int to ulong (signed to unsigned) you may want to do it in a checked environment to, at least, have a run-time error instead of wrong but undetected values (I assume that you do not want to penalize distribution simply discarding ms bits).
You may replace new byte[8] with new byte[sizeof(ulong)].

Now more serious things...

Using double for such big range you effectively break the distribution of your random numbers (because above a threshold even integer numbers cannot be represented correctly in floating point). I understand that you're doing that to keep an apparent upper limit equal to UInt64.MaxValue but you're sacrificing randomness. It may be an issue or not, in your case, but be aware of it.

As you already know RNGCryptoServiceProvider generates random bytes and Convert.ToUInt64() is not enough to have a true randomly generated number (because each byte, not their composition, is supposed to be randomly distributed). There is a technique you're somehow applying to compensate this issue and it's described by Stephen Toub and Shawn Farkas in Tales from the CryptoRandom. I suggest to pick their code and to use it as-is until you completely understand their implementation (and the implication of any change). Not that this will  introduce any big bias in your calculations but unless you statistically validate your algorithm I think you should stick to well-known and reviewed implementations.

As Adam already noted in his answer you should not have a static class and RNGCryptoServiceProvider should be a class member. Let the caller decide how your random number generator should be used to have a better distribution. Don't forget to implement IDisposable also for your class. Also consider to accept ctor parameter of type RandomNumberGenerator (which can be mocked in your tests), you may want to test your code with a well-known set of inputs, not with random ones:

public sealed class CryptoRandom : IDisposable
{
    public CryptoRandom(RandomNumberGenerator generator)
    {
        _generator = generator ?? throw new ArgumentNullException(nameof(generator));
    }

    public CryptoRandom()
        : this(new RNGCryptoServiceProvider())
    {
    }

    // ...

    private readonly RandomNumberGenerator _generator;
}

There is, finally, an even more serious problem. If you initialize RNGCryptoServiceProvider without a seed then it will use Environment.TickCount and its resolution is limited to the system timer resolution (typically 10 ms), this alone will practically vanish most of your effort.


Find-grep-sed for project-wide search & replace

Not bad so far!

You seem to like ${name} instead of $name. That's fine, but it's not needed anywhere in the posted code. Usually it's needed in situations like ${name}_suffix, where without the ${...} the "_suffix" would become part of the variable name.

In general, the best way to find files and do something to them is using the -exec flag of find, for example:

find . -name "$file_pattern" -exec grep -rwl "$search_pattern" {} \;
# or end with + to run on a single line
#find . -name "$file_pattern" -exec grep -rwl "$search_pattern" {} +

The second best way is to pipe to xargs -0, and use -print0, for example:

find . -name "$file_pattern" -print0 | xargs -0 grep -rwl "$search_pattern"

Your case has an added twist: you also want to pipe the matched filenames from grep, and like find, the proper way is to use NUL character as the filename separator. In GNU grep the flag to achieve this is -Z. Putting the above together, the safest way to write your chained command:

find . -name "${file_pattern}" -exec grep -Zrwl "${search_pattern}" \; |
xargs -0 sed -i '' "s/[[:<:]]${search_pattern}[[:>:]]/${replacement}/g"

As for [[:<:]], I don't know another way on OSX. In any case, the sed -i '' filaname usage won't work with GNU sed, so this script is not portable.
It would be good to add comments near the top of the file to highlight this fact to whoever will inherit this script from you at some point in the future.
(Uhm, or in any case, for the "future you" ;-)

Lastly, I'm wondering if the -r flag for grep is intentional.
It's for recursive search in sub-directories, not only files.
If that's not intended, then drop that flag.


It's a little difficult to do a good review because there are so many pieces missing, but I've guessed at a number of things and I believe I can help.

Specifically, it looks like your Map is a rectangular grid of Blocks and that all x and y coordinates are integers.  If so, then your shot routine is really doing the equivalent of drawing a line from the entity location to the passed x1,y1 coordinates and one very efficient way to do that is to use Bresenham's line-drawing algorithm.  Using a slight modification of that algorithm, since your shot routine seems to want to go until it either hits something or goes off the Map, we get a very efficient and very small routine:

void shoot(Map *map, Entity *entity, int x1, int y1)
{
    int sx = entity->x1 < x1 ? 1 : -1;
    int sy = entity->y1 < y1 ? 1 : -1;
    int dx = abs(x1 - entity->x1);
    int dy = abs(y1 - entity->y1);
    int err = (dx>dy ? dx : -dy)/2;
    int e2;

    x1 = entity->x1;
    y1 = entity->y1;
    Block *block;
    while (inbounds(map,x1,y1)) {
        e2 = err;
        if (e2 > -dx) {
            err -= dy;
            x1 += sx;
        }
        if (e2 < dy) {
            err += dx;
            y1 += sy;
        }
        if((block = map_block_at(map, x1, y1))->type != EMPTY){
            block_cause_damage(block, entity->hand_item->weapon.damage);
            return;
        }
    }
}

I've assumed that you have or can easily write an inbounds routine that returns true if the passed coordinates are within the Map.


I started reading at play. At first, I thought you had posted non-working code, because your code couldn't possibly work. Then I got up to the definition of Branch and realized that yes, it could work. But it violates so many principles that I don't know what the "real" type of a Branch is.

Let me suggest a slightly different model:

You have an outer loop. The loop ends when the narrative ends. You could express this as either an iteration stop, or as a boolean condition. I'm going to call each step in the narrative a step. You might prefer page or part or section, whatever helps you tell this story:

# Iteration stop:
for step in narrative:
    pass

# Boolean condition:
while not narrative.has_ended:
    step = narrative.current_step

Once you have a step, you can display the narrative text, and then present the user with a collection of options to choose from. Because users are users, there probably needs to be an inner loop that keeps asking for a valid option until one is entered. I would make a function for that:

    # Display the narrative text
    print(step.text)

    # Present the user with options, force a choice:
    choice = get_user_choice(step.options)

Finally, you have interacted with the user and received a choice, so update the narrative. Maybe your iterator has a .select method, or maybe your narrative does:

        step.select(choice)

        # or maybe

        narrative.branch(choice)

After looking at it, I personally prefer the idea of invoking methods on the Narrative. It shows more clearly that the narrative is an object, maintaining and updating its state. However, I would make the menu selection a "simple" cough! enhanced generator (see PEP-342):

from os import PathLike
from typing import Generator, Iterable, None, TextIO

def tell_a_story(datafile: PathLike, output: TextIO,
                 chooser: Generator[str, Iterable[str], None]):
    """
    Tell a branched-narrative story. Configure the narrative using
    "datafile", write the result on "output," interact with "chooser"
    (an enhanced generator) to select branches to follow.

    """
    narrative = Narrative(datafile)

    while not narrative.has_ended():
        step = narrative.current_step
        output.write(step.text)

        # send options to the generator, get a choice back
        choice = chooser.send(step.options)

        narrative.branch(choice)

I chose to use a Writable and an Extended Generator to help with automated testing. You should be able to supply a StringIO and a generator that ignores the options in favor of just iterating over a list of choices, and compare the generated text against what you predict for your test case.

If there is an epilog, you'll want to handle it specially. In particular, your generator should deal with an options parameter that is None. Then you could print the epilog, give the user no options, probably get None back from the generator, select None as your branch, and mark the narrative as ended.

Alternatively, you could create Narrative with some sort of .introduction text, print that outside the loop, and then loop in a different order:

output.write(narrative.introduction)

while not narrative.has_ended():
    choice = chooser(narrative.options)
    narrative.branch(choice)
    output.write(narrative.new_text)

This may tend to make your last loop iteration cleaner, and impose fewer constraints on your generator.

How Enhanced Generators Work

Generators are functions in Python that make use of the yield or yield from statements. We'll focus on yield because that's all we need.

You can create a generator like this:

def g():
    yield 1
    yield 2

You know it's a generator because you see yield. Twice!

Generators don't return a value when you "call" them. Instead, they return a generator object. It's like an iterator - it's an object that you can call next() on and it might return multiple values:

for x in g():
    print(x)

This does what you might expect: it prints

1
2

So you can see that the yield keyword is used to pass data out of a generator, and suspend execution. When the caller invokes next(generator_object) or generator_object.__next__(), execution resumes where it left off - at the yield statement, and more code is executed.

In a first attempt at supporting coroutines, python added generator.send() methods. This allows the caller to push data into the generator, and it works like this:

def eg():
    x = 0
    while True:
        x = yield x + 1

egen = eg()
p = egen.send(None)

for _ in range(5):
    print("P is:", p)
    p = egen.send(p + 3)

The output looks like:

P is: 1
P is: 5
P is: 9
P is: 13
P is: 17

As you can see, this lets you send data into the generator, then pull data back out. You just have to start off by sending a None to "prime the generator".

This is relevant to you because you need to have a 2-way conversation. You want to send out some options, and get back a selection. You could do it like this:

def get_selection(choices):
    print("\n".join(choices))
    return input("What will it be?")

But then how would you test? You'd have to use global variables or something, and where's the fun in that?

But if you built a generator, you could ignore the options and just pre-program a path through the data:

def test_selections(test_data):
    for choice in test_data:
        options = yield choice

chooser = test_selections(["a", "b", "a", "b", "a", "c"])
outfile = io.StringIO()
datafile = "story.txt"

tell_a_story(datafile, outfile, chooser)

Or, you could talk to the user:

def user_selections():
    choice = None
    while True:
        options = yield choice
        print("\n".join(options))
        choice = input("What will it be?")

Depending on whether you want to test or really use it, you just pass a different generator.

Edit (responding to changes in the original question):

First, note that etiquette on CodeReview is to append your updates, not edit them in-place. When you make in-place changes, that invalidates the answers people posted and makes other readers confused.

That said, this version looks considerably better. My main suggestion would be to remove the enumerate from getoptions (let the display code handle the enumeration), and move getoptions into Branch as a method rather than a free function. When you do that, of course, you realize that you could just let the caller access Branch.options directly, which is fine. ;-)

One other suggestion is to make the story an incoming parameter for play(), like:

if __name__ == '__main__':
    play(Story_main)


Initializing local variable to generic interface

This is as safe as your Set implementation for result. For example, swapping for a TreeSet gave the following error:

Exception in thread "main" java.lang.ClassCastException:
            java.lang.Integer cannot be cast to java.lang.Double
    at java.lang.Double.compareTo(Double.java:49)
    at java.util.TreeMap.put(TreeMap.java:568)
    at java.util.TreeSet.add(TreeSet.java:255)
    at java.util.AbstractCollection.addAll(AbstractCollection.java:344)
    at java.util.TreeSet.addAll(TreeSet.java:312)

This is understandable since TreeSet imposes an ordering, which in turns calls the to-be-added Collection-type's compareTo() with the existing entries. This has nothing to do with type incompatibility at compile-time (the code compiles), rather it's a limitation/feature of the TreeSet implementation.

In your linked question @rolfl suggested giving a Supplier to the method, which I will advocate here too:

public class TypeInference {

    public static <E> Set<E> union (Set<? extends E> s1, Set<? extends E> s2,
            Supplier<Set<E>> supplier) {
        Set<E> result = supplier.get();
        result.addAll(s1);
        result.addAll(s2);
        return result;
    }

    public static <E> Set<E> union (Set<? extends E> s1, Set<? extends E> s2) {
        return union(s1, s2, () -> new TreeSet<>(Comparator.comparing(Object::toString)));
    }

    public static void main(String[] args) {
        Set<Integer> ints = new TreeSet<>(Arrays.asList(1, 2, 3, 4, 5));
        Set<Double> doubles = new TreeSet<>(Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0));
        System.out.println(union(ints, doubles));
        System.out.println(union(ints, doubles,
                () -> new TreeSet<>(Comparator.comparing(Number::doubleValue))));
    }
}

The two-argument union() uses a TreeSet that compares by the entries' toString(), which lets us store both Integer and Double values together in the Set. Alternatively, calling union() with a TreeSet supplier that compares by Number.doubleValue() gives us only 5 distinct elements:

[1, 1.0, 2, 2.0, 3, 3.0, 4, 4.0, 5, 5.0]
[1, 2, 3, 4, 5]

Rounding back to your question, I suppose HashSet() is a reasonably safe bet, since it doesn't do anything fanciful other than the usual hashCode()/equals() checks. And as you correctly inferred, since the method return type is just a Set, callers of union() should not have any other expectations - the Set interface simply says "this is how I am intended to be used.".