Building XML by enumerating through array & hashes

Here's a nice recursive solution, that creates <key>value</key> from 'key'=>'value' entries in your hash. If the value is an array, it instead recurses, using the key name as a wrapper element.

require 'nokogiri'

def process_array(label,array,xml)
  array.each do |hash|
    xml.send(label) do                 # Create an element named for the label
      hash.each do |key,value|
        if value.is_a?(Array)
          process_array(key,value,xml) # Recurse
        else
          xml.send(key,value)          # Create <key>value</key> (using variables)
        end
      end
    end
  end
end

builder = Nokogiri::XML::Builder.new do |xml|
  xml.root do                           # Wrap everything in one element.
    process_array('category',data,xml)  # Start the recursion with a custom name.
  end
end

puts builder.to_xml

When used with this data…

data = [
  { 'name' => 'category1',
    'subCategory' => [
      { 'name' => 'subCategory1',
        'product' => [
          { 'name' => 'productName1',
            'desc' => 'desc1' },
          { 'name' => 'productName2',
            'desc' => 'desc2' } ]
      } ]
  },
  { 'name' => 'category2',
    'subCategory' => [
      { 'name' => 'subCategory2.1',
        'product' => [
          { 'name' => 'productName2.1.1',
            'desc' => 'desc1' },
          { 'name' => 'productName2.1.2',
            'desc' => 'desc2' } ]
      } ]
  },
]

…you get this result:

<?xml version="1.0"?>
<root>
  <category>
    <name>category1</name>
    <subCategory>
      <name>subCategory1</name>
      <product>
        <name>productName1</name>
        <desc>desc1</desc>
      </product>
      <product>
        <name>productName2</name>
        <desc>desc2</desc>
      </product>
    </subCategory>
  </category>
  <category>
    <name>category2</name>
    <subCategory>
      <name>subCategory2.1</name>
      <product>
        <name>productName2.1.1</name>
        <desc>desc1</desc>
      </product>
      <product>
        <name>productName2.1.2</name>
        <desc>desc2</desc>
      </product>
    </subCategory>
  </category>
</root>

However, if I had control over the XML schema, I'd do this instead:

require 'nokogiri'

def process_array(label,array,xml)
  array.each do |hash|
    kids,attrs = hash.partition{ |k,v| v.is_a?(Array) }
    xml.send(label,Hash[attrs]) do
      kids.each{ |k,v| process_array(k,v,xml) }
    end
  end
end

builder = Nokogiri::XML::Builder.new do |xml|
  xml.root{ process_array('category',data,xml) }
end

puts builder.to_xml

<?xml version="1.0"?>
<root>
  <category name="category1">
    <subCategory name="subCategory1">
      <product name="productName1" desc="desc1"/>
      <product name="productName2" desc="desc2"/>
    </subCategory>
  </category>
  <category name="category2">
    <subCategory name="subCategory2.1">
      <product name="productName2.1.1" desc="desc1"/>
      <product name="productName2.1.2" desc="desc2"/>
    </subCategory>
  </category>
</root>

…but perhaps you're dealing with some terrible XML schema like PList.


Two things jump out at me.

Decouple from the HTML elements.

var inputRgb = document.getElementById("rgb"),
    inputHex = document.getElementById("hex"),

I would do something like:

function RGB2Hex (inputRgb, inputHex){
    var converter = {
        toHex: ...
        toRGB: ...
    };

    inputRgb.addEventListener("input", converter.toHex, false);
    inputHex.addEventListener("input", converter.toRgb, false);

    return converter;
}

// Usage:
var mainHexConversion = new RGB2Hex(document.getElementById("rgb"), document.getElementById("hex"));
var secondHexConversion = new RGB2Hex(document.getElementById("mini-rgb"), document.getElementById("mini-hex"));

keep the background colour changing code outside the converter.

function RGB2Hex (inputRgb, inputHex, onColourChange)
{
   var converter = {
        toHex: ...
        toRGB: ...
        colourChanged: function(colourValue){
            if(typeof onColourChanged == "function")
            {
                onColourChange(colourValue);
            }
        }
    };
}

// Usage:
var mainHexConversion = new RGB2Hex(
    document.getElementById("rgb")
    , document.getElementById("hex")
    , function(color)
    {
      document.body.style.backgroundColor = color;
    }
);


Input and validation

Using a Scanner is a good idea, and using a try-with-resources block is the right thing to do.

You don't need to close the Scanner or the underlying System.in.  The whole point of the try-with-resources block is that resources will be automatically closed for you.

Note that neither the Scanner(Readable) constructor nor Scanner.nextInt() will ever throw an IOException.  The only exception you need to catch (but didn't) is NoSuchElementException.  (Well, also InputMismatchException, but that is just a subclass of NoSuchElementException.)  Your program will crash with a NoSuchElementException if you send it an EOF at the prompt.

The error messages aren't quite right.  The first message should read: "Input should be exactly 5 digits."  The second message is unhelpful: you should tell the user what would be considered valid input.

The validation is not quite strict enough: a negative four-digit integer will also be accepted.

Output

Strictly speaking, the output is not quite right, in that you also append three spaces after the fifth digit.  On screen, the output will look the same, but if you pipe the output to a program that examines the bytes, you'll see the trailing spaces.

You don't need to call String.trim().

newString is not a good name: it's not a string, and there is no oldString.  If I had to pick a name, I'd call it digits.

Suggested solution

With Java 8, the simplest solution is to use String.join().

public static void main(String[] args) {
    try (Scanner input = new Scanner(System.in)) {
        int n = input.nextInt();
        if (!(1e5 <= n && n < 1e6)) {
            System.out.println("Input should be exactly 5 digits.");
            return;
        }
        System.out.println(String.join("   ", String.valueOf(n).split("")));
    } catch (NoSuchElementException e) {
        System.out.println("Error: No integer was given.");
    }
}


Deadbeef : finding all words made of hexadecimal digits

It is customary to put helper functions first and main() last, to avoid having to write forward declarations like int process_file(FILE* file);.

process_file() is a very generic name.  I suggest renaming it to print_hex_words().

The process_file() function returns an error code.  Therefore, the responsibility for printing any error message for I/O errors should lie with main().

You assume that words are delimited by whitespace, and have neglected to deal with punctuation.

Your algorithm is very tedious.  Instead of using getc() to read a byte at a time, use fscanf() to read a whitespace-delimited word at a time.  To skip to the end of a sequence consisting solely of A-F characters, use strspn(…, "ABCDEFabcdef").

#define xstr(s) str(s)
#define str(s) #s

int print_hex_words(FILE* file) {
    char word_buf[MAX_LEN + 1];
    while (1 == fscanf(file, "%" xstr(MAX_LEN) "s", word_buf)) {
        char *word, *end, *trail_punct;

        /* Skip leading punctuation */
        for (word = word_buf; ispunct(*word); word++);

        end = word + strspn(word, "ABCDEFabcdef");

        /* Skip trailing punctuation */
        for (trail_punct = end; ispunct(*trail_punct); trail_punct++);

        if (word != end && *trail_punct == '\0') {
            /* NUL-terminate the word and convert it to lowercase */
            *end = '\0';
            for (end = word; (*end = tolower(*end)); end++);

            printf("%s\n", word);
        }
    }
    return ferror(file);
}

Instead of … | sort | uniq, you can use … | sort -u.


1. Simplified winner() method

You could merge the checks for 'X' and 'O' by returning one of the chars in a match of three in a row:

char winner() {
  for (int i = 0; i < 3; i++) {
    if (table[0][i] == table[1][i] && table[1][i] == table[2][i]) {
      return table[0][i]; // 'X' if all are 'X' and 'O' if all are 'O'
    }
  }

  for (int i = 0; i < 3; i++) {
    if (table[i][0] == table[i][1] && table[i][1] == table[i][2]) {
      return table[i][0];
    }
  }

  if (table[0][0] == table[1][1] && table[1][1] == table[2][2]) {
    return table[1][1];
  }

  if (table[0][2] == table[1][1] && table[1][1] == table[2][0]) { // *
    return table[1][1];
  }

  return '\0';
}

*Note that your code is missing the forward slash diagonal

2. Consider eliminating your global variables

I know this is just a practice project, and your code is fine as it is. However, if you wanted to scale your code, then you've created some unnecessary problems for yourself in the future.

All of your functions depend on your two global variables, which limits you to one game and gets in the way of other features by polluting the global namespace. You could eliminate the globals by taking an object oriented approach or a more functional programming styled approach.

The Object Oriented way

The OO way would involve creating a TicTacToeGame class and making the global variables member variables members of your class.

class TicTacToeGame() {
private:
  char table[3][3];
  int turn;

public:
  TicTacToeGame() {
    for (int i=0;i<3;i++)
      for (int j=0;j<3;j++)
        table[i][j]='*';

    turn = 1;
  }

  char winner() {}

  void input() {
    // ...
    turn++;
  }

  void print() {}

  int getTurn() {
    return turn;
  }
}

int main() {

  TicTacToeGame game = TicTacToeGame();
  game.print();

  while (game.getTurn() <= 9 && game.winner() == '\0')
  {
    game.input();
    game.print();
    game.winner();
  }

  if(game.winner() != '\0')
    std::cout<<std::endl<<"winner:"<<winner();
  else
    std::cout<<"Draw.";
}

Creating a class comes with a few other benefits. Particularly that you can encapsulate how a Tic-tac-toe game is played which helps with code scalability.

A more functional approach

For the functional approach you can just pass the globals as parameters instead (be sure to pass by reference):

char[][] create_table() {
  // ...
  return table;
}

void input (int turn, char[][] &table) {
  // ...
}

char winner(char[][] &table) {
  // ...
}

int main() {

  int turn = 1;
  char[][] table = create_table();
  print_table(table);

  while (turn <= 9 && winner(table) == '\0') {
    input(turn, table);
    print_table(table);
    winner(table);
    turn++;
  }

  if(winner(table) != '\0')
    std::cout<<std::endl<<"winner:"<<winner(table);
  else
    std::cout<<"Draw.";
}

This way gives you a lot more control over when and where turn and board get declared. You can more easily create multiple games to be played simultaneously. The biggest benefit is that your functions have their dependencies explicitly defined; there are no hidden parameters.

Nice job overall! My second suggestion is mostly just to help with a few concepts with software development, and it isn't really applicable if you intend to keep your Tic-tac-toe game as simple as it is. Keep up the good work.


There is nothing special to say. This is a big bunch of procedural code. You can maybe improve it by keeping references to items or navigating in them instead of re-reading them from the root :

String userLink = body.getElementById("watch7-user-header").getElementsByAttributeValue("class", "yt-user-photo yt-uix-sessionlink      spf-link").attr("href");
String userPhoto = body.getElementById("watch7-user-header").getElementsByTag("img").attr("data-thumb");

// Can be
Element user = body.getElementById("watch7-user-header");
String userLink = user.getElementsByAttributeValue("class", "yt-user-photo yt-uix-sessionlink      spf-link").attr("href");
String userPhoto = user.getElementsByTag("img").attr("data-thumb");

If you want to change the way you parse that, you can introduce a parsing object. (https://www.javacodegeeks.com/2018/03/dont-parse-use-parsing-objects.html)


Return the first word with the greatest number of repeated letters

This approach seems a bit overly-complicated - there are multiple loops over the word just to remove duplicates, count the letters, etc. I would suggest a simple loop over each word to count the number of repeated numbers, maintaining the max count so far, and then using a simple object mapping (or a Set could be used) to look up the max counts for each word. See the rewritten code below for an example of this.
Additionally, the indentation could be greatly improved. Perhaps the first level inside whichWord in your code was lost because of pasting it into the question. However, most JavaScript code is indented by 2 or 4 spaces inside each block.
I noticed that arrow functions are being used (e.g. letters.map((innerArr, i) => innerArr.map((letter, ii).... This is a feature of ecmascript-6 and thus other features from that standard could be used, such as const for any variable that is never re-assigned and let for any variable that needs to be reassigned (e.g. iterator variables, cumulative counts, etc.), as well as the spread syntax instead of using function.apply().
Rewritten code
Below is my first take at simplifying the code. It can be compared for performance in this jsPerf.

function maxMode(word) {
  if (word.length == 1) {
    return 0;
  }
  const counts = {};
  for (const letter of word) {
    counts[letter] = (counts[letter] ?? 0) + 1;
  }
  return Math.max(...Object.values(counts));
}
const whichWord = str => {
  const arr = str.split(' ');
  const mappings = arr.reduce((mapping, word) => {
    mapping[word] = maxMode(word);
    return mapping;
  }, {});
  const mappingCounts = Object.values(mappings);
  const highestNumber = Math.max(...mappingCounts);
  const indexToReturn = mappingCounts.findIndex(c => c == highestNumber);
  return Object.keys(mappings)[indexToReturn];
};
const strings = ['Hello a apple pie yellow', 'axaya zza'];
for (const string of strings) {
  console.log('whichWord('+string+'):', whichWord(string));
}

1https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Character_access
2https://stackoverflow.com/a/4051431/1575353


Old-way of asynchronous programming in ASP.NET MVC 3

There is a lot of code repetition. I would create a custom class that inherits from Task and make it generic enough so you can have an array of your custom class and just loop through that array to do what you need to do.

class TaskController<T> : Task<T>
{
    public TaskController(AsyncManager asyncManager, string asyncManagerParameter, Func<T> callback) : base(callback)
    {
        this.ContinueWith(t =>
        {
            //just for demonstration
            Console.WriteLine(t.Result);

            // Do some work with your asyncManager
            asyncManager.Parameters[asyncManagerParameter] = t.Result.ToString();
        });
    }
}

I would also have GetResponse take a string uri as parameter instead of making a new GetResponse for each url that you want to use.

public static string GetResponse(string uri)
{
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
    req.Method = "HEAD";

    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

    return resp.Headers.ToString(); // just changed this for demonstration purposes
}

and finally I would use it like this

AsyncManager asyncManager = new AsyncManager();

TaskController<string>[] taskControllers = {
    new TaskController<string>(asyncManager, "header1", () => GetResponse("http://google.com")),
    new TaskController<string>(asyncManager, "header3", () => GetResponse("http://www.twitter.com"))
};

foreach (TaskController<string> tc in taskControllers)
{
    tc.Start();
}

It is much less code, you can reuse it later, you can very easily add a new TaskController if you want to work with another URL, and it's a lot more readable.

To use this you will need to just edit this.ContinueWith inside TaskController and have it do whatever you want (decrement, etc)


Nested template variable access in Meteor

I've been looking at your code for a few weeks now, the problem is both that there is not a lot to review and there's nothing wrong with it.

Do consider using lowerCamelCasing which is the standard in JS, so bucket_name -> bucketName.

The code seems elegant enough to me.


Unit testing code that verifies order of method execution

I think your colleagues are correct in that your test looks like it is testing code written as part of your test.  Meaning code that looks similar to the production code, but isn't.  But there are things of value here to test.

You mentioned that your builder has tests around it.  I would think that these "do things execute in order" questions are best answered by testing your builder in different configurations.  the question is simply, "can the builder build things that execute in order".

Secondly, the validation service is a concrete implementation with and interface (abstraction).  You'll likely want to test the concrete implementation because it will probably (unless configured dynamically) have a very fixed set of validation rules that are set for your business needs.  Those tests become, "is my validation service catching all of the currently considered scenarios".


Checking form input data on submit with pure PHP

It's incredibly repetitive.  Repetitive code is hard to maintain because you have to apply the same change in many places.  It's also hard to see at a glance where the similarities and differences lie.

Here is how it could be rewritten:

<?php
    $params = array('name', 'address', 'email');

    session_start();
    $_SESSION['first_page'] = true;

    foreach ($params as $p) {
        $$p = $_SESSION[$p] = '';
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            if (empty($_POST[$p])) {
                $errorVarName = "${p}Error";
                $$errorVarName = 'Missing';
            } else {
                $$p = $_SESSION[$p] = $_POST[$p];
            }
        }
        if ($_SESSION[$p] == '') {
            $_SESSION['first_page'] = false;
        }
    }
    if ($_SESSION['first_page'])) {
        # None of the expected params is an empty string
        header('Location: http://localhost/formProcessing2.php');
    }
?>

To go one step further, I would suggest using $val[$p] and $err[$p] instead of $$p and $$errorVarName, respectively.  That's because variably named variable names are icky, and smell vaguely of the stink associated with register_globals.  An additional benefit of using an associative array is that you can pass all of the processed parameter values as a single argument to a function, which you can't do if they are individual variables.  The template would need to be modified to say

Name <input type="text" name="name" value="<?php echo htmlspecialchars($val['name']);?>">
<?php echo $err['name'];?>


A simple data class based on an existing collection (Scala)

Your code, as posted, doesn't compile because there is no definition for the Address type. However, given the code for nextFreeAddress in the alloc() method, it's pretty obvious that Address can only be type Int, so that's easy to fix.

Also, HeapImpl is private to ... what? A surrounding object I assume, but that's also missing from the posted code so it's a bit unclear. You say you "would like to hide implementation details," which is a good thing, but I don't know that a private implementation class is significantly more hidden than having private members of a public class. Is the implementation class separate because you envision multiple different implementations available to the end user?

It's a bit unusual to have a factory method that takes no parameters except for a type parameter. It wouldn't be difficult to enhance the "constructor" to take optional initial values.

object Heap {
  def apply[T](ts:T*): Heap[T] = HeapImpl(ts.indices.map(x => x -> ts(x)).toMap)
}

Then you can have it both ways:

Heap[Char]()           //res0: Heap[Char] = HeapImpl(Map())
Heap(3L, 5L, 12L, 2L)  //res1: Heap[Long] = HeapImpl(Map(0 -> 3, 1 -> 5, 2 -> 12, 3 -> 2))

(Notice that the REPL has leaked a bit of your implementation detail.)

At first I was confused by the term Heap. Then I re-read the posting and realized that this isn't a heap data structure but is, instead, a chunk of memory for dynamic allocation and requiring memory management.

But your code doesn't actually do any of the things that makes a real heap challenging/interesting: dynamic allocation for heterogeneous data, handle fragmentation, etc. It sort of pretends to be a heap, but not very convincingly (your alloc() doesn't really act like malloc(), calloc(), or realloc()). It's just a thin wrapper around a highly restricted associative array.

So, while I find little to fault in the code, I can't see where it serves much purpose.


Finding the rod pieces in the rod cut issue

I don't get this part of the code:

            if prices[i - j] != 0:
                s[i] = [j, i - j]  # Indices of prices such that price[j] + price[i - j] = max_revenue of i
            else:
                s[i] = [j]

Why not just use have s just store the best size, e.g.:

            s[i] = j

To get the list of parts for a certain size rod, just use:

def best_rod_parts(s, n):
  parts = []
  while n > 0:
    parts.append( s[n] )
    n = n - s[n]
  return parts

where s is the array returned from your solving procedure.

Here is how I would write it:

def solve(prices, n):
    revenue = [0] * (n+1)  # can assume price >= 0
    size = [0] * (n+1)     # best length to cut

    for i in range(1,n+1):
      bestRev, bestSize = 0, 0  # best solution so far

      for j in range(1,i+1):
        rev = price[j] + revenue[i-j]
        if rev > bestRev:
          bestRev = rev
          bestSize = j
      revenue[i] = bestRev
      size[i] = bestSize

If you want s to contain the list of pieces, then you should modify the code this way:

def solve(prices, n):
  revenue = [0] * (n+1)
  sizes = [ [] ] * (n+1)

  for i in range(1,n+1):
    bestRev, bestSize = 0,0
    for j in range (1,i+1):
      rev = prices[j] + revenue[i-j]
      if rev > bestRev:
        bestRev = rev
        bestSize = j
    sizes[i] = sizes[i-bestSize] + [bestSize]
  return revenue, sizes


You can avoid the nested for loops by adding the entire array at the same time. (I'm also using Janos' suggestion here)

function duplicate(arr, n) {
  let result = [];
  for(let i=0; i<n; i++) {
    result.push(...arr);
  }
  return(result);
}

We need the original array unmodified, so we can keep adding it, so I'm using a new result array. This has a few benefits. Firstly it's more common to leave the input array unmodified and return a new array, and secondly it returns an empty array when n=0, which I think makes more sense.

This uses the ES6 spread syntax. If you don't want to use ES6 you can replace

result.push(...arr);

with

result = result.concat(arr);


A few things I see:

The subtraction(-) operator would make more sense to return a Date object instead of an int.  This would also fit in with standard practice.  If such a function is needed, I would suggest naming a specific function for that,DiffDays perhaps.  This has the advantage being more intuitive for the user.

Instead of requiring each instance of the Date object to require the user calling Set, it would be more intuitive to overload the constructor.

It seems to me that returning a string instead of a char* would be more in fitting with a c++ program.


About your primary question: I'd definitely go with Answer... whenever I have the possibility to do so. As you can pass on an array to a varargs parameter, but not varargs to an array parameter, varargs is the better option IMO.

Other comments

Naming

private boolean isCorrect;

It is convention to not prefix boolean fields with is. The name of the method should be is + variable name with upper case starting letter, so:

public boolean isCorrect() {
    return correct;
}

final keyword

It is good practice to mark all possible fields with final, this applies in your case to:

private final String answer;
private final boolean correct; // note the name change

and in the Question class:

private final String question;
private final Answer[] answers;

Mutability

This code might seem harmless to you:

public Question(String question, Answer... answers) {
    this.question = question;
    this.answers = answers;
}

public Answer[] getAnswers() {
    return answers;
}

But the fact is, this is slightly dangerous. Although your Answer class is immutable, this is not. Imagine the following code:

Question questionA = new Question("Do chickens fly?",
     new Answer("Yes", true),
     new Answer("No", false));
questionA.getAnswers()[0] = null;
questionA.getAnswers()[1] = new Answer("Always right", true);

Whoops, now we've cleared one answer and changed the other!

Solution: Make array copies using Arrays.copyOf:

public Question(String question, Answer... answers) {
    this.question = question;
    this.answers = Arrays.copyOf(answers, answers.length);
}

public Answer[] getAnswers() {
    return Arrays.copyOf(answers, answers.length);
}

Possible extension: Make it a score

Your classes supports multiple answers to be correct, that is nicely done. But what if one answer is still "better" than the other? My suggestion is that you use a int or a float for score instead of a boolean correct.

Java 8

If you have Java 8 available, your isCorrect(String answer) method can be improved:

public boolean isCorrect(String answer) {
    return Arrays.stream(answers).anyMatch(a -> a.getAnswer().equals(answer));
}

The same can of course be applied to your isCorrectIgnoreCase method:

public boolean isCorrect(String answer) {
    return Arrays.stream(answers).anyMatch(a -> a.getAnswer().equalsIgnoreCase(answer));
}


Not much to say here, it looks pretty good. I've moved to only using .on for attaching events as I think it encourages better practices. Remember it's better to save selectors as variables if you are going to reuse them.

Instead of catching the click on .qam-account-items you can just fire the event on everything but those classes;

$(document).on('click', '*:not(.qam-account-items)', function() {
    $('#qam-account-toggle.account-active').removeClass('account-active');
    $('.qam-account-items:visible').hide();
});


Lightweight localization for a Cordova app

AFAIK, accessing local files using XMLHttpRequest won't be a problem once you have your page up on a web server.

Anyway, if you decide to go with the solution above, here are some general tips:

getString() method:

Use this.translation rather than window['locale']['translation']. There no point traversing to window and back again when you can use the this pointer.
Try to be more descriptive when naming variables and methods. For example, the required argument. If a third party user is using your API, how would they pssobile know what to pass? A string? An object?

translation object:

Your language objects have some indentical values. To be less repetitive, create a default object and merge with each new language. I will use jQuery.extend() in my example.

Misc:

Create an object that keeps track of your constants and reuse it throughout your module.

The code could look something like this:

var locale = {

    constants: {
        language: {
            localStorageKey: 'language',
            default: 'nl'
        }
    },

    getTranslationByLanguage:function(languageProperty){

        if(!languageProperty)
            throw new ReferenceError('languageProperty not defined');

        var language = localStorage.getItem(this.constants.language.localStorageKey)
                       || this.constants.language.default;

        var translation = this.translation.getTranslationByLanguageKey(language);

        return translation[languageProperty];
    },

    translation: {

        defaults: {
            faq: 'FAQ',
            highscore: 'highscore'
        },

        en: {
            play:'Play',
            gameStart:'Game starting in '
        },

        nl: {
            play:'Speel',
            gameStart:'Spel start in '
        },

        getTranslationByLanguageKey: function(languageKey){
            return $.extend({}, this.defaults, this[languageKey] || {});
        }

    }
};


Get minimum of each group based on hour criteria using pandas

leave the original data intact

Since df is the original data, adding columns to it can have a strange side effect in another part of the calculation. Best is not to touch the original data, and do all the calculations etc in separate series or copied DataFrames

pd.grouper

You can use pd.Grouper to group per day and hour

You can group the date per subject and hour with:

df.groupby(["subject_id", pd.Grouper(key="time_1", freq="h"), "val"])

Then you don't need all those extra columns "hr", "date" and "day" anymore.
There is no reason for the column "t_d" either. since timedelta's can be counted, summed etc as well.

aggregation function

Apart from that,  you can design a specific function to get the requested minimum from one such group.

If you supply it data grouped per subject and date, dropping rows with the same val and checking whether more than 1hr has passed is a lot easier

def day_grouper(group):
    """
    Returns the minimum in `val` that lasted more than 1 hour
    """
    # drop consecutive same values.
    # The first value is retained because it becomes NaN and `NaN != 0`
    group = group.loc[group["val"].diff() != 0]
    # drop those that take less than 1hr
    more_than_1h = group["time_1"].diff().shift(-1) > pd.Timedelta("1h")
    # Check whether the last value started before 23:00
    more_than_1h.iloc[-1] = group["time_1"].iloc[-1].time() < datetime.time(23)
    return group.loc[more_than_1h, "val"].min()

This can then be called like this:

(
    df.groupby(["subject_id", pd.Grouper(key="time_1", freq="d")])
    .apply(day_grouper)
    .rename("val")
    .reset_index()
)

The 2 last rows are to get the format you want

code formatting

Try to follow Pep-8.

£some of your lines are really long, and convention is a space after a comma.

I use black to format my source code, so I don't have to worry about long lines, spaces, etc any more


Efficiently consolidating an array of objects

I'm afraid I'm not familiar with Actionscript but I can give you some general advice with regards to how your code is structured:

Separate the requests into different arrays for each title instead of keeping them in a single array. Admittedly this is a violation of the DRY principle (don't-repeat-yourself) but it will force you to apply specific handling rules for each rather than a general rule that you bend that you do at the moment. This is clear from the degree of nesting of if-statements in your code.
You seem to JSON.parse(...) twice, can you not keep the result from the original call?
You seem to check the uniqueness of the sender id twice requests[i].from.id and consilidated[j].from.id. I think you only need to do this once?
Try to rely on array lengths rather than counters that you implement yourself. I know you've commented on it but consider building and modifying separate arrays.
Don't nest your if-statements but create separate boolean variables.

var idIsEqual:Boolean = consolidated[j].from.id == consolidated[k].from.id;
var titleIsEqual:Boolean = dataObjectJ.title == dataObjectK.title;
var typeIsEqual:Boolean = dataObjectJ.type == dataObjectK.type;
if (idIsEqual && titleIsEqual && typeIsEqual) {
    ...
}

It might be a little overkill but consider creating an associative array keyed by id_title_type (e.g. "12_myTitle_gift"). That would make searching a little easier.
Don't create variables named temp. This is a real bugbear of mine and I see it all the time. By the looks of it, it should probably be named unreadMessageCount. For someone who doesn't know you code, the penny doesn't really drop on what your code is trying to achieve until the last line is read, and suddenly everything becomes clear.


Generally if you want a more in depth review you should provide more code and a potential specifics you want to improve on; your code is very thin, and so it's a little difficult to help you expand on it, however, I would say that there's a few different things you can do to this to improve or follow a different direction forward.

Your use of pure components is good for BuildingUpdateBoxHeader and BuildingUpdateBoxBody as using primitive props is better for performance. However, using a content object inside your props for BuildingUpdateBox means React cannot shallow compare your props and is unable to determine when not to rerender the component, causing potentially wasted rerenders.

I would recommend trying JSS (css in js) to embed your styles directly in your application for an alternate solution to specifying className manually. This couples your css with its implementation rather than needing to update both the css & js when you modify them.


I agree with Heslacher, should be fairly easy to do with NAudio.

var output = new MemoryStream();
using (var reader = new Mp3FileReader(mp3File))
using (var writer = new WaveFileWriter(output, reader.WaveFormat))
{
    //read from reader, write to writer, like you would do with regular streams
    //header is appended automatically to output stream in WaveFileWriter constructor
}

You should also consider encapsulating your resource loading logic to separate class (or classes: one class per resource type). Handling textures and sound in single method looks messy. Single resposibility.

EDIT: If you have to stick to the library of your choosing, then you should just use single output stream.

var output = new MemoryStream();
using (var input = new MP3Sharp.MP3Stream(yourMp3FileStream))
using (var writer = new BinaryWriter(output, Encoding.UTF8, true))
{
    var headerSize = 44; //or w/e it is for RIFF, I might have forgotten
    output.Position = headerSize;
    input.CopyTo(output);
    output.Position = 0;
    //wtite your header
    writer.Write("RIFF".ToCharArray());
    ...
}

Also notice, that you can stack usings on top of each other without adding extra braces.


Convert string array to object with true/false flags

Code looks great to me. Here is a Rubocop-clean version with one change:

def fopt
  filter = (params[:filter] || '').split(',')
  OpenStruct.new(Hash[
    %w(complete inwork cancelled ycancelled).map do |fo|
      [fo.to_sym, filter.include?(fo)]
    end
  ])
end

Note the Rubocop rule to avoid rescue in its modifier form.


Before addressing the main question, I would like to compare two of the primary methods: register and get. The register method is written well in terms of returning early.

  public static function register($name, $class) {
        $reflection = new ReflectionClass($class);
        if (!$reflection->isInstantiable()) {
            throw new Exception('The provided class is not instantiable: ' . $class);
        }
        if (!in_array($name, self::$classes)) {
            self::$classes[$name] = $class;
        }
        self::$lastRegistered = $name;
        return __CLASS__;
    }

With this method the indentation is kept to a single level. Because of this it is simple to read.
The get method could be re-worked to decrease indentation levels.

  public static function get($name = NULL)   {
          $name = (!$name) ? self::$lastRegistered : $name;
          if (self::$classes[$name]) {
              if (self::$instances[$name]) {
                  return self::$instances[$name];
              } else {
                  self::$instances[$name] = new self::$classes[$name];
                  return self::$instances[$name];
              }
          } else {
              throw new Exception('The following class name could not be found: ' . $name);
          }
      }

The ternary operator with null check can be simplified using a null coalescing operator:
 $name = $name ?? self::$lastRegistered;

And with PHP 7.4+ the null coalescing assignment operator is available:
  $name ??= self::$lastRegistered;

By returning early there is need for else - this can decrease indentation levels, which can result in ones that aren’t as long, as well as make the method shorter over-all:
public static function get($name = NULL) {
    $name = $name ?? self::$lastRegistered;
    if (!self::$classes[$name]) {
        throw new Exception('The following class name could not be found: ' . $name);
    }
    if (self::$instances[$name]) {
        return self::$instances[$name];
    }
    self::$instances[$name] = new self::$classes[$name];
    return self::$instances[$name];
}

In addition to requiring fewer lines of code, there is also no need for the else keyword.

How is this called ? Singleton ? Container ? Dependency injection ?

This appears to be a variation of the Singleton pattern. Typically a singleton class would have a private constructor and a static method like getInstance() that would return a static property after conditionally assigning that property to a newly instantiated object if it hadn’t been set.


Monitoring and re-establishing a PostgreSQL connection

What follows is just my subjective opinion; you can disagree.

Robust code is maintainable.  You need to be able to change this code if you find a bug in it, or if the requirements change. It might even be that someone else may need to maintain this code.  So you should probably use a regular indenting pattern (2 spaces is normal for Ruby). That would make it a lot easier to see what was going on.
Likewise, your code would be cleaner if it was split into separate functions. Making the contents of the thread.new block a separate function would be a good place to start, but you could (and maybe should) go further than that.
It seems to me that the sleep ... retry at the end of the first rescue block are redundant, since you are going to loop around again anyway. YMMV.


Trying to convert an extended Array.prototype to a function

My advice is to use a known shuffle algorithm for this.

This stackoverflow answer describes the Fisher-Yates shuffle and provides a function for you to use.

https://stackoverflow.com/a/2450976/423413

Bottom line use that function and replace your Array.prototype.shuffle function and call it something like shuffleArray

var shuffleArray = function(arr) {
    ...
}

Then replace the line that says randIndex.shuffle() with a call to the new function.

shuffleArray(randIndex);


Some suggestions:

In calcator, I would use a ternary expression: return 1. if n is None else n/100.
calcator can be made even more efficient by having iterate_mandelbrot return 100. if the loop finished.  Then you just divide the result of that by 100.  This will result in 1. if the loop exits, avoiding the if test entirely.
I would only do run self.mandelbrot in your loop, and store the result of that function to a 2D numpy array.  Then you can vectorize the rest of the calculation, since it is all just basic math.  This should substantially increase performance.  You can even move the n/100 outside the for loop to further improve performance.
If the previous suggestion does not increase performance enough, you might be able use multiprocessing.Pool.imap to further increase the performance of the loop.
For an even more extreme vectorization, you can do all your calculations on all pixels at once.
Rather than having a griditor function, just use itertools.product.
Follow pep8
I would put the current contents of the if __name__ == "__main__": block in a main function and just call that function inside the if __name__ == "__main__": block.
In render I would allow the code to pass a string (which defaults to mandelbrot, and use getattr to dynamically call method with that name.
I would rename iterate_mandelbrot to iterate_pixel.
I would put in mandelbrot an argument for z that lets the user change z.  Similarly, I would put an argument in julia that lets the user change (0.3, 0.6) to something else.
render should accept *args, **kwargs that are then passed directly to the mandelbrot or julia method.
I would move the julia and mandelbrot lambdas into their own methods.  Or better yet, I would refactor so you just pass the c and z argument.
In render, I would let the user set the scale with an argument.  The scale argument would default to None. If it is None, it would be computed automatically as is done now.
In render, you only ever work with integers.  So I would use n//100 in calcator to make sure it returns an integer.  This allows you to avoid the later integer conversions.

So here is my version of Fractal

import numpy as np

class Fractal:
    def mandelbrot(self, pixels, scale, center=(2.2, 1.5), z=0.):
        return self.calcolor(pixels, scale, center, zs=z)

    def julia(self, pixels, scale, center=(1.5, 1.5), c=(0.3, 0.6)):
        if not hasattr(c, 'imag'):
            c = complex(*c)
        return self.calcolor(pixels, scale, center, cs=c)

    def calcolor(self, pixels, scale, center, cs=None, zs=None):
        pixels = pixels.asarray(pixels)

        xpixels = np.arange(pixels.shape[0])[None, :]
        ypixels = np.arange(pixels.shape[1])[:, None]

        val = (xpixels+ypixels*1j)*scale-complex(*center)
        if cs is None and zs is None:
           raise ValueError('Either cs or zs must be specified')
        if cs is None:
           cs = val
        if zs is None:
           zs = val
        ns = np.full_like(val, 100, dtype='int16')

        for n in range(256):
            zs = zs**2 +cs
            ns[ns>0 & np.abs(zs)>2.0] = n
        return ns

    def calc_pixels(self, cs, zs):

    def render(self, pixels, scale=None, method='mandelbrot', *args, **kwargs):
        if scale is None:
            scale = 1.0/(len(pixels[0])/3)

        try:
            func = getattr(self, method)
        except AttributeError:
            raise ValueError('Unknown method %s' % method)
        i = func(pixels, scale, *args, **kwargs)*256

        r = i%16 * 16
        g = i*8 * 32
        b = i%4 * 63

        return np.dstack([r, g, b])


This is not a complete review, just a few things that jumped out to me:

getID()

Looks more like "easier to write" than "easier to read". From current function name "getID", most people reading the code will assume that the function will return an ID.

If you would like to use jQuery as you can simply write $("#hour") instead of getID("hour"). The core idea of jQuery is to let you select (or query) DOM elements.

alarmSwitch()

If you use simple if/else instead of the switch/case, the code will be much simpler.

if(aSwitch.On){
...
} else {
...
}

Variable Naming

Simply naming the variable tomorrow instead of tomo would have been better for read

var tomo = false;// tomorrow.

If/else blocks for single line

Consistently using if/else blocks, even for single line statements helps avoid hard to find bugs

if( aSwitch.On )
{
    aOff.style.display = "block";
    sound.play();
}
else
    alert("error..");


It is weird to put an object field right next to the method that uses it.  It's more common to put all the object fields together.  Of course, you don't show the rest of the class definition, so perhaps this is something you did just for this.

Consider writing instead

List<Integer> preorderedList = new ArrayList<Integer>();

It won't make much difference here, but using the interface as the type makes it easier to change implementations later.

You can simplify the null handling by changing

public void preorder(TreeNode root) {

   if(root == null){
       return;
   }
    preorderedList.add(root.data);
    if(root.left != null){
        preorder(root.left);
    }
     if(root.right != null){
        preorder(root.right);
    }

}

to

public void preorder(TreeNode root) {
    if (root == null) {
        return;
    }

    preorderedList.add(root.data);
    preorder(root.left);
    preorder(root.right);
}

This way it does the check for null after the recursive call rather than before making it.  Slightly less efficient, but easier to read.  Alternately, if that efficiency is important, note that this makes an extra check.  Consider breaking it into two methods.  This could be something like

private void _preorder(TreeNode root) {
    preorderedList.add(root.data);

    if (root.left != null) {
        _preorder(root.left);
    }

    if (root.right != null) {
        _preorder(root.right);
    }
}

public void preorder(TreeNode root) {
    if (root == null) {
        return;
    }

    _preorder(root);
}

This only checks if root is null the first time.  On the recursive calls, this isn't necessary.  It makes one extra method call (which may be inlined) rather than an extra call per leaf.  And it only checks for null once for each node rather than twice.

Benchmark, as you may find that the compiler already does this for you.


AJAX Done Callback to prevent requests from interrupting each other

To be sure that nothing happens before the AJAX request is achieved, you can simply add the async: false property to your $.ajax({...}).

As pointed by @Tom Stickel, doing so fires a warning about future deprecation of async: false.

I agree, and this is already known from times but, as stated in paragraph 4.5.1 of the page he cited:

  This is a long process that takes many years

It's why I suggest this solution (and also am using it somewhat frequently), but:

only in the case of this kind of situation, where the "detrimental effects to the end user's experience" is clearly not involved (at the opposite, here, it's precisely what is expected)
only for now, considering it's worth applying a so simple solution as long as it works, and change it only when deprecation will effectively happen (note that the involved piece of code might be obsolete first!)


Best way to retrieve music metadata from audio files?

It appears music-metadata is the Node.js/desktop flavor of music-metadata-browser (intended for browsers).  The author doesn't explain the differences between the two, but maybe the desktop variant will be faster for you.

Synchronous anything is a mistake for an inherently parallel task like this.   Use fs.lstat instead of the fs.lstatSync.  If createLibraryEntry or dispatch touch the disk they should be replaced with async versions as well.

Worker threads are a thing but you probably don't need them, because disk access is what's slowing you down and async disk access doesn't require threads.

If you have disk I/O that can't be asynchronized (if that's a word) by conventional callback functions, or if you've made everything async and it's still too slow, that is the time to consider using workers.


It's ok.  A bit hard to follow however since you're taking steps that really aren't necessary.

It is not necessary to give the StringBuilder a starting capacity.  Just let it do its business and you do yours, it will just work.

However if you really wanted to do this, then that's not a problem.  You can clean it up a bit.  Rather than aggregating over the items when adding up all the lengths, just use Sum() instead.

var totalNamesLength = items.Sum(s => s.Length);

Don't really have much of a comment on the rest of your code.  I'd be careful of using ==/!= comparisons in a loop that goes over consecutive values, if the loop variable were to ever change in the body of the loop, you'll have a hell of a time trying to debug any problems you have with that.  I'd stick to using < (or appropriate operator) there exclusively.

for (int idx = 1; idx < loopCount; ++idx)
    // ...

I'd write this differently however as this is much more readable to me and compact.

internal static string GetEnumerated(this string[] items)
{
    if (items == null)
        return "";

    if (items.Length <= 1)
        // concatenates all the (0 or 1) items into a single string
        return String.Concat(items);

    // place all but the last in a comma-separated string
    var commaSeparated = String.Join(", ", items.Take(items.Length - 1));
    // include the last item
    return commaSeparated + ", and " + items.Last();
}

Since we know we are dealing with arrays, you won't be paying for much in terms of performance in the LINQ calls.  If that bothers you, it is simple to write the equivalent without using LINQ.

internal static string GetEnumerated(this string[] items)
{
    // I'd leave these in separate conditions
    // to make it clear they are separate cases
    if (items == null)
        return "";
    if (items.Length <= 1)
        return String.Concat(items);

    var commaSeparated = String.Join(", ", items, 0, items.Length - 1);
    return commaSeparated + ", and " + items[items.Length - 1];
}


Project Euler+ #35 - Summing circular primes less than N

Replace the list of all numbers up to n with a dictionary of primes only

As it stands, N holds mainly False values, which are never used. It would be more idiomatic to use a dictionary, plus Python's in operator, which tells you whether a particular key exists in the dictionary. As the proportion of primes below a given number n is approximated by \$n /\mathcal{ln}(n)\$, a dictionary containing only primes as keys would be smaller than your list by a factor of about \$n/\mathcal{log}(n)\$, while look-up would be just as fast.

Your prime sieve would look like this:

def prime_sieve(n):
    '''Your docstring here.
    '''
    sieve = dict.fromkeys([i for i in range(n)])   # make a dict of all numbers up to n
    for i in range(2, ceil(sqrt(n))):
        if i in sieve:
            for j in range(i**2, n, i):
                del sieve[j]                       # remove composites from dict
    return sieve

(Note: even with this modification, the sieve still begins at size n, and takes on the order of \$\mathcal{O}(n^2)\$ operations to generate. This is a fundamental property of the Sieve of Erasosthenes. A faster implementation might forgo the sieve, generate candidate circular primes, and test them individually, e.g. using Miller-Rabin primality test.)

Follow your own pseudocode

They say in programming that good code should read like prose. Which means it should read as close to a natural sentence as possible. Writing out your program as pseudocode is a great way to prioritize readability. The pseudocode already gives you the most readable version of your code as a place to start. The task is then to rewrite it according to the syntax and idioms of the language you choose.

Based on your own pseudocode, we need:

(1) A simple way to invoke the sieve. You have that already with your prime_sieve function.

Here, your variable large should be something more descriptive. Taking cues from your pseudocode, we can call it max_rotation.

max_rotation = 10**len(str(n))
primes = prime_sieve(max_rotation)

(Note: I changed the name of the output of prime_sieve to primes, as the new dict implementation contains only primes.)

(2) A loop header that makes it clear that we are getting all rotations of each prime less than n.

Translated into Python, the second line of your pseudocode becomes:

for rotations in [get_rotations(i) for i in range(n)]:

This implies that operations such as conversion of the integer i to a string, removal of duplicates, and accumulation into a list, should all be handled by the function rotations, rather than clogging up the main body of your generate_circular_primes function.

Such a function would look like this:

def get_rotations(num)
    '''Your docstring here.
    '''
    def rotate(s, i):
        return s[i:] + s[:i]
    s = str(num)
    return set([int(rotate(s, i)) for i in range(len(s))])

(Note: using set() makes sure all rotations returned are unique.)

(3) Check if all the resulting rotations are prime.

Here, it's clearest and most idiomatic to use the all() built-in expression.

    if all(r in primes for r in rotations):

(4) And finally, we must yield only those circular primes that are less than the original n.

The final code looks like this:

from math import sqrt, ceil

def prime_sieve(n):
    '''Your docstring here.
    '''
    sieve = dict.fromkeys([i for i in range(n)])
    for i in range(2, ceil(sqrt(n))):
        if i in sieve:
            for j in range(i**2, n, i):
                if j in sieve:
                    del sieve[j]
    return sieve

def get_rotations(num):
    '''Your docstring here.
    '''
    def rotate(s, i):
        return s[i:] + s[:i]
    s = str(num)
    return set([int(rotate(s, i)) for i in range(len(s))])

def get_circular_primes(n):
    '''Your docstring here.
    '''
    circular = set()
    max_rotation = 10**len(str(n))

    primes = prime_sieve(max_rotation)
    for rotations in [get_rotations(i) for i in range(n)]:
        if all((r in primes) for r in rotations):
            circular.update(rotations)
    yield [c for c in circular if c < n]

Notice that the last five lines closely match your pseudocode (with the exception of updating the set circular).

[Below is a summary of edits suggested by enedil.]

You use int() unnecessarily here:

    for i in range(2, int(ceil(sqrt(n)))):

Because ceil() already returns an integer, wrapping it in int() is redundant.

The following line can be improved to skip multiples of primes that have already been identified:

        for j in range(i*2, n, i):

As you have it, j increments through multiples of all integers between i and 2, in addition to the integers we are interested in, those greater than i. As multiples of all integers below i have already been removed from the prime list, they can be skipped in subsequent rounds. So, j should be initiated at i**2, the first composite that has not been seen before. The improved loop looks like this:

        for j in range(i**2, n, i):


Returning IQueryable from my repository in Repository pattern design pattern

IQueryable is a leaky abstraction(you don't wan't to know anything about sql in the service layer).
It is also very difficult to test.

I would recommend not returning IQueryable.
I would return IEnumerable or ICollection and make my queries run in the repository(ToList on the repository).

I would create queries in my repositories to handle the joins.
You can test your queries separately for correctness and performance.


Change the inner loop to use old Pyrex syntax:

        for ind from prime + reduced_prime <= ind < top by prime:
            pos[ind] = False

Apparently Cython still does not optimize range loops to pure C when step size is a variable: ticket #546.


Taking student scores from a file, calculating averages, and printing

Declaring that main() throws IOException is probably the right thing to do for a simple program like this.  A lot of beginners try to catch an exception that they don't have any idea how to handle properly.

That's a lot of code to be stuffed into a single main() function.  Ideally, you should develop classes such that main() contains just a minimal amount of code, like this:

public static void main(String[] args) throws IOException {
    try (Scanner input = args.length > 0 ? new Scanner(new File(args[0])) :
                                           new Scanner(System.in)) {
        GradeBook book = new GradeBook(input);
        System.out.println(book);
        System.out.printf("Overall Average: %s\n",
                          FMT.format(book.average()));
    }
}

Hard-coding an input filename makes it hard to reuse your code.  I've modified it to read from either a filename specified on the command line or from System.in.

You should be able to avoid having to explicitly specify the dimensions of the data in the file.

Using Java 8 streams removes a lot of tedious looping from the implementation.  Here is the rest of my suggested implementation:

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.IntStream;

public class GradeBook {
    private List<double[]> students;
    private static final DecimalFormat FMT = new DecimalFormat("#.#");

    public GradeBook(Scanner input) {
        this.students = new ArrayList<double[]>();
        while (input.hasNextLine()) {
            double[] student = Arrays.stream(input.nextLine().trim().split("\\s+"))
                  .mapToDouble(Double::parseDouble)
                  .toArray();
            students.add(student);
        }
    }

    public double getScore(int student, int assignment) {
        return this.students.get(student)[assignment];
    }

    public double averageForStudent(int student) {
        return Arrays.stream(this.students.get(student))
                     .average()
                     .getAsDouble();
    }

    public double averageForAssignment(int assignment) {
        return this.students.stream()
                   .mapToDouble((assignments) -> assignments[assignment])
                   .average()
                   .getAsDouble();
    }

    public double average() {
        return IntStream.range(0, this.students.size())
                        .mapToDouble((s) -> this.averageForStudent(s))
                        .average()
                        .getAsDouble();
    }

    public String toString() {
        StringBuilder out = new StringBuilder();
        int numAssignments = this.students.stream()
                                 .mapToInt((assignments) -> assignments.length)
                                 .max()
                                 .getAsInt();

        // Header
        out.append("\t\t\t\tAssignment #:\n\t\t");
        for (int a = 0; a < numAssignments; a++) {
           out.append(a + 1).append('\t');
        }
        out.append("Avg\n");

        // Body
        for (int s = 0; s < this.students.size(); s++) {
            out.append("Student #").append(s + 1).append(":\t");
            for (int a = 0; a < numAssignments; a++) {
                out.append(FMT.format(this.getScore(s, a))).append('\t');
            }
            out.append(FMT.format(this.averageForStudent(s))).append('\n');
        }

        // Footer
        out.append("Average\t\t");
        for (int a = 0; a < numAssignments; a++) {
            out.append(FMT.format(this.averageForAssignment(a))).append('\t');
        }
        out.append('\n');

        return out.toString();
    }

    public static void main(String[] args) throws IOException {
        try (Scanner input = args.length > 0 ? new Scanner(new File(args[0])) :
                                               new Scanner(System.in)) {
            GradeBook book = new GradeBook(input);
            System.out.println(book);
            System.out.printf("Overall Average: %s\n",
                              FMT.format(book.average()));
        }
    }
}


List iteration, creation, or comprehension

def make_pose(pt):
    pose = Pose2D()
    pose.theta = 0
    pose.x, pose.y = pt
    return pose

poses = [make_pose(pt) for pt in get_points(spline)]

Alternatively, you could subclass Pose2D to give it an appropriate constructor.


You have inconsistent spacing around your operators:

if(item==null)

vs

if (_items == null)

I generally prefer to see the second version (as I think is fairly standard in C#).

As you're using Expression Bodied Members. I know you're using C#6. Did you know about the nameof operator?

throw new ArgumentException("item");

Becomes

throw new ArgumentException(nameof(item));

That gives you compile time checking on the name of your parameter.

You should throw the most specific exception type available. If the argument is null and that isn't allowed. throw new ArgumentNullException(nameof(item)).

A list DynamicArray that doesn't allow null values is really odd. There is no reason why you should disallow null. You wouldn't stop me adding 0 to a list of integers.

You resize the array on every Add. That's O(n) and unnecessary. You should be creating an array larger than your current limit and then making it bigger (by some factor) when you reach the limit.

Also, under the covers, an Array.Resize simply creates a new array and copies everything over.

You have a bunch of things like this:

public bool Contains(T item)
{
    if (_items == null)
        return false;
    return _items.Contains(item);
}

Which could be written more simply as:

return _items != null && _items.Contains(item);

You could also use the ?. null propagation operator:

return _items?.Contains(item) == true;

But it's a bit ugly because you have to do something to go from Nullable<bool> to a bool. I achieved that with a simple == true to force an implicit conversion.

Your Remove is incorrect. It should only remove the first occurrence of the item. See msdn.

All your class is doing is keeping an array as a field and replacing it every time you modify the collection. It's not a very efficient way of doing it. As I said, you should be keeping an array with spare capacity that you resize when you need.

That's everything off the top of my head. I'll come back later when I have more time.


Am I organising my PHP code effectively?

Iterating through the whole user table could be ineffective:

foreach ($db->query("SELECT username FROM usertable") as $row) {

You could use a WHERE username LIKE :username condition here. (And you might need a database index for the attribute as well)
The code does not check the password. I guess you should do that.
You should hash your passwords.
Calling a table usertable is a little bit redundant. I'd use simply users.
The following is hard to read because it needs horizontal scanning:

$user->execute(array(":username" => $_POST["username"], ":password" => $_POST["password"]));

I would introduce an explanatory variable and some line breaks:

$newuser_parameters  = array(
    ":username" => $_POST["username"],
    ":password" => $_POST["password"]
);
$user->execute($newuser_parameters);

From Code Complete, 2nd Edition, p761:

  Use only one data declaration per line

  [...]

  It’s easier to find specific variables because you can scan a single
  column rather than reading each line. It’s easier to find and fix
  syntax errors because the line number the compiler gives you has
  only one declaration on it.

See also: Chapter 6. Composing Methods, Introduce Explaining Variable in Refactoring: Improving the Design of Existing Code by Martin Fowler; Clean Code by Robert C. Martin, G19: Use Explanatory Variables.
I would validate at least the maximum length of the username.
This probably isn't too useful for your clients:

echo $e -> getMessage();

See #3 in my former answer.


CodeChef Fusing Weapons in a circular list

Looking at your merge_data() function, you'll notice that as soon as it finds 2 matching values, it combines them and recurses. What happens during and after the recursion? Let's take a look.

Suppose we have this set:

3,8,4,2,2,7,14

We first get 3. Next we start walking the rest of the list. We compare against 8. No match. We compare against 4. No match. We do this until we run out of things to compare. Then we increment i. We check the rest of the array. Etc. Eventually we come to the 2. We compare to the next value and there is a match! We combine them and recurse. What happens now? We start by comparing 3 to 8, which we've already done. Then again with 4, which we've also already done. So we're doing a bunch of work over and over again.

Then, eventually we return from our recursion. Now we go on to process the rest of the array. There's 2 problems here: 1) At this point, the recursion we're returning from has already processed the rest of the array, and 2) the array is no longer the same size, but we're going to process to the end of the original array anyway!

I haven't worked out a full solution, but hopefully the above is enough to help you see what's wrong with your current solution.


Code to calculate minimum number of pushes required to put the whole dominoes set down

Alternate algorithm
I would suggest the following:

After reading the list of domino dependencies, you should be able to compute a set of "root" dominos.  A "root" domino is simply a domino that is not pushed by any other domino.
Each root domino must be pushed, since there is no other domino to push it.  So for each root domino, push it, and do a dfs to mark all dominos knocked down by it.
After step #2, there may be dominos left standing.  These dominos must either be part of a cycle, or hanging off of a cycle.
For each remaining domino, do a dfs on it, looking for a cycle.
If the domino did not cycle, then do not increment the push count, but mark all the dominos in the dfs as knocked over.  This was a domino hanging off a cycle, and you know that this domino's parent(s) will eventually get knocked over by some other push.
If the domino did cycle, then keep a list of each domino that was part of its cycle (note that there could be more than one cycle through the same domino).  After doing the dfs and marking all dominos as knocked down, go through the list of dominos that were part of its cycle.  If any of them have a parent that is still standing, then do not increment the push count.  The reason is that the still standing parent will get pushed by some other domino, and it will knock down this whole cycle.  In other words, if a cycle of dominos has an external parent, then it can be ignored because the push from another cycle that triggers the external parent will knock down this cycle.

I haven't actually written a program to test this algorithm, so there could be a flaw in my logic dealing with cycles.  But I think it should work, and it should be fast because you never process a node more than once.


Transpose of a very large matrix with fewer than 1021 rows with Python

The golden rule of I/O performance is never read a block twice.  You're reading each block thousands of times.

I made a thousand-row test file with records of about 2MB each:

tr -dc '[:alnum:]' < /dev/urandom  | fold -w2000000 | head -1000 > test.txt

And modified the fps-building portion of your code thusly:

#!/usr/bin/env python
from prettyprinter import pprint
import sys
import os
import re

try:
  in_fn = sys.argv[1]
except ValueError as ve:
  sys.exit(-1)

sz = os.path.getsize(in_fn)
fps = [ open(in_fn, 'r') ]
bufsz = 100 * 2**20 # MB

with open(in_fn, 'r') as f:
  offset = 0
  buf = f.read(bufsz)
  while len(buf)>0:
    for p in [m.start() for m in re.finditer(r'\n', buf)]:
      new_pos = offset+p+1
      if new_pos < sz:
        new_fp = open(in_fn, 'r')
        new_fp.seek(new_pos, 0)
        fps.append(new_fp)

    offset = f.tell()
    buf = f.read(bufsz)

pprint( list( map( lambda f: f.tell(), fps ) ) )

This runs 65 times faster than the bytewise version on my machine.

The actual transposition will benefit similarly from this treatment.   Keep a buffer for each row and append to it with a read when it's empty.

If you want to keep the logic simpler, you can compromise (with a performance penalty) by reading a few kilobytes at a time and rewind-seeking  the filehandle back to the first tab character.  This would remove the need to keep an array of buffers.


Moving window with complete boundary in Python


Simple random number guessing game with various difficulties

1) Avoid using var if you want your code to be more readable.

2) Both CompareNum() and PlayGame() methods should be defined within the Game class as they rely on a game (which means they don't need to have a game as argument anymore)

3) In the CompareNum() method

Console.WriteLine("User num is too Low try again");
Console.WriteLine();

can become

Console.WriteLine("User num is too Low try again\n");

4) In the GenerateComNum() method you can shorten

var comNum = rnd.Next(1, 101);
return comNum;

to

return rnd.Next(1, 101);

and you should avoid creating a new Random() every time you have to generate a random number because it could create unexpected results. You should make a static Random rnd = new Random(); and only use rnd.Next(x, y) whenever you need a random number.

5) In the PlayGame() method you shouldn't have a do ... while loop because if the user chooses to have 0 attempts then he should lose instantly and that's not what will happen with a do ... while loop

6) The usual order for accessors is get then set, you did the opposite : public int attemp { set; get; } = 0; it'll work in both orders, it's just to make things more readable.

7) It's realy unlikely to happen but if the user would win during realy long time, your application could have a System.StackOverflowException because you are calling PlayGame() while it is already running when the user wins which will cause the current one running to wait for the new one to finish and those will stack up and take more and more memory, this is recursion, sorry and check internet if my explanations aren't clear.

To increase the range of possible numbers being generated, you can use a variable to determine what the max generated number is and put this variable as second argument instead of 101 when you do rnd.Next(1, 101);


ASP.NET HTML code generation, two approaches

Second approach is better, according to the rule: do not repeat the code!

Don't use '+=' to join string, in your case better to use StringBuilder:

var sb = new StringBuilder();
sb.Append();
...
sb.Appden();
...
return sb.ToString();

I think this is better way, StringBuilder is made for this.
You can refactor this code better little more :-)


Quickfire review

I see no reason to make this a generic class. You're effectively using the generic type as a name. While having intellisense is nice, keep in mind that the compiler will generate an optimized class for every type you use in your code. E.g. if TClass can either be Foo, Bar or Baz in your codebase; then the compiler created three different ConsoleLogger classes in order to optimize the assembly (actually it creates four, but the point still stands)

Since you're going to cast your generic type to a Type object anyway, it's better to just pass the Type object via the constructor. Functionally equivalent, minor difference in syntax which is ultimately negligible, lessened impact on the compiled assembly.
Personally, I would store the string name (of the type) directly instead of the Type itself, but that's a matter of style.

It seems needlessly repetitive to specify a writeToFile boolean for every message that is logged. I suggest making it a public property or adding it to the constructor so you only have to set it once.
Use Path.Combine(folder, file) instead of folder + file. This has some extra logic to make sure that the appropriate slashes are present and not duplicated. Note that you can use more than two parameters: Path.Combine(folder, subfolder, anotherSubFolder, file)
$"Occurred at [{DateTime.Now:MM/dd HH:mm:ss}] in [{_className.FullName}]: " + message You use interpolation for the first two values (good), but then concatenate the third value. You should interpolate that one as well $"Occurred at [{DateTime.Now:MM/dd HH:mm:ss}] in [{_className.FullName}]: {message}"
In the comments, you mention that it's supposed to be threadsafe, but I see no actual implementation of thread safety in any of the posted code. Are you using separate loggers per thread? (that's different from wanting multple threads to use the same logger).

The rest will be addressed in separate chapters.

Conflated logic

switch (color)
{
    case ConsoleColor.Yellow:
        logFile = "error.log";
        break;
    case ConsoleColor.Cyan:
        logFile = "debug.log";
        break;
    case ConsoleColor.Red:
        logFile = "error.log";
        break;
    default:
        logFile = "trace.log";
        break;
    }

This is not great. What you're doing here is determining the file to write to based on the color you want the log to be written in.

Imagine if Word automatically saved your document to a different location when you change the text color. No one would like that feature.

What you've done here is merged two separate design decisions:

Where do I want to make my log?
What do I want my log to look like?

These questions have nothing to do with each other, but you've merged them. That being said, you're of course going to have to map both behaviors, but not like this.

Create a new enum:

public enum LogType { Success, Warn, Error, Debug }

Change your method call:

public void Warn(string message, bool logToFile = false)
{
    Log(message, LogType.Warn, logToFile);
}

Create separate mappings. There are a few ways to do this. For simple mappings, you can use dictionaries; but a method with a switch gives you more direct control if you need to apply some custom logic in certain cases.

public Dictionary<LogType, string> FilenameForLogType = new Dictionary<LogType, string>() {
    {LogType.Success , "trace.log"},
    {LogType.Warn ,    "error.log"},
    {LogType.Error ,   "error.log"},
    {LogType.Debug ,   "debug.log"},
};

public Dictionary<LogType, ConsoleColor> ColorForLogType = new Dictionary<LogType, ConsoleColor>() {
    {LogType.Success , ConsoleColor.Green},
    {LogType.Warn ,    ConsoleColor.Yellow},
    {LogType.Error ,   ConsoleColor.Red},
    {LogType.Debug ,   ConsoleColor.Cyan},
};

And then your Log() method can use these dictionaries based on the LogType you've passed in:

private void Log(string message, LogType logType, bool logToFile = false)
{
    // ...

    Console.ForegroundColor = ColorForLogType[logType];

    // ...

    if (logToFile)
    {
        LogToFile(FilenameForLogType[logType],  /* ... */);
    }
}

The main benefit here is that if you ever decide to change any of the colors or file names; then you won't need to actually care about the file names or colors (respectively).

Writing to file

private static void LogToFile(string file, string content)
{
    try
    {
        using (var fileWriter = new StreamWriter(FilePath + file, true))
        {
            fileWriter.WriteLine(content);
            fileWriter.Close();
        }
    }
    catch (DirectoryNotFoundException)
    {
        Directory.CreateDirectory(FilePath);
    }
    catch (FileNotFoundException)
    {
        File.Create(file);
    }
}

There are a few things to remark here.

Handling exceptions.

It doesn't make sense for you to create the directory/file after you've tried to write to it.

Suppose you do this:

for(int i = 0; i < 10; i++)
    myLogger.Trace(i.ToString(), true);

The console will show:

  0
  1
  2
  3
  4
  5
  6
  7
  8
  9

But the file will show:

  1
  2
  3
  4
  5
  6
  7
  8
  9

You've swallowed the first log message (only when writing to disk!), because the file did not exist, you did not create it, and then you didn't try to write it again.

A better approach is to first check if the file/directory exists, create it if it doesn't, and then log the file.

private static void LogToFile(string file, string content)
{
    string fullPath = Path.Combine(FilePath, file);

    if(!Directory.Exists(FilePath))
         Directory.CreateDirectory(FilePath);

    if(!File.Exists(fullPath))
         File.Create(fullPath);

    using (var fileWriter = new StreamWriter(fullPath, true))
    {
        fileWriter.WriteLine(content);
        fileWriter.Close();
    }
}

However, this point may be moot if you read the following suggestion. But it's important to understand that your approach had a bug in it.

Streams COULD be your friend.

If you're going to use a stream to write to file, then you should leverage the benefits of using a stream.

Currently, you are opening a new stream every time you write a message to a log file. Streams make more sense when you repeatedly write data to the same stream, and only close it once you're done with it.

Note that this can be dependent on what you're logging.

A log that catches an exception now and then will not receive much use, and keeping the stream open may be more harmful than beneficial.
A log that catches all the trace messages of a particular processing job is going to receive a high volume of messages in a short time. Streams make sense here.

There are many ways to solve this, without resorting to opening a stream for every message:

A ConsoleLogger opens a stream when the first message is written, but then holds on to that stream until it is manually told to close it, or the logger gets disposed himself.
An intermediary StreamHandler is created. A ConsoleLogger simply requests a stream from StreamHandler, which is able to decide (by itself) when it wants to cache stream and when it should create a new one. This allows you to e.g. not keep an error log stream open, but keep a trace log stream open for an extended time.
You can create your own StreamWriter (or use a StreamHandler) to implement a timeout feature, where streams are automatically closed when they haven't received a message in the last X seconds. This is nice, but not easy to implement.

You can make this as complex as you want it to be. I'll suggest the simplest improvement (the first option).

First, make a cache for your streams:

private Dictionary<string, StreamWriter> _streams = new Dictionary<string, StreamWriter>();

When writing to a file, check if you already have a streamwriter for the file, otherwise create it:

private static void LogToFile(string file, string content)
{
    string fullPath = Path.Combine(FilePath, file);

    //...

    if (!_streams.ContainsKey(file))
    {
        _streams.Add(file, new StreamWriter(fullPath , true));
    }

    _streams[file].WriteLine(content);
}

Don't stop yet. We still need to handle closing the stream! I prefer giving two options to consumers:

Manually close the streams. Should they write another message afterwards, then it will automatically open a new stream.
Automatically close the streams if the logger is disposed of.

Manually closing them can be done as follows:

public void CloseStreams()
{
     //close all streams
     foreach(var kvp in _streams)
         kvp.Value.Close();

     //empty the cache
     _streams.Clear();
}

Automatically closing them can rely on the same method; but it gets triggered by the IDisposable interface:

public class ConsoleLogger <TClass> : ILogger, IDisposable
{
    public void Dispose()
    {
       CloseStreams();
    }
}

Note that this allows you to use the using statement with your logger class:

using(var logger = new ConsoleLogger<Foo>());
{
     logger.Debug("Let's go!");
     MethodWhichAlsoLogsThings(logger);
     logger.Debug("Done! Streams will be closed automatically!");
}

//At this point, the streams are closed.


There is no need to comment your code. It is totally broken. Very first thing you need to do is to calculate your complexity. ACM is not about code quality, it is not about language. It is about algorithms. You can write the ugliest code ever but can it be executed? Not a problem if you have satisfying algorithm complexity.

You can not just write different code without thinking about the algorithm and how your changes influence complexity. Moreover, you have to write code that will follow your algorithm.

General strategies for optimizing code for programming challenges? What? If there where such strategies no one would be challenging anymore. That is why it is so difficult and those competitions exist even now.

There are classes of problems that can be solved effectively with specific algorithm\approach. Competition task itself never describes what class or problems it is and what algorithm to use, you have to find it out by yourself. Determine the class of the problem you are trying to solve and then choose an algorithm that will satisfy the problem's memory/time requirements.

First of all. The problem you are trying to solve can be recognized as "implementation" when it didn't relate to any specific class directly. You have to do what it says. Implementation class requires you to be flexible minded, especially in this case because you have time requirements that brute-force didn't meet.

Algorithm

We have a set of digits with their costs. How to construct the largest possible number from it? We have to research the relation between numbers order and digits they have.

$$
A > B =
\begin{cases}
  true  & \text{if } dc(A) > dc(B) & \text{(1)}
  \\
  true  & \text{if } dc(A) = dc(B) \text{ and } \\
        & \text{if } h(A) > h(B) \text{ or } h(A) = h(B) \text{ and } t(A) > t(B) & \text{(2)}
  \\
  false & \text{else}
\end{cases}
$$

, where
\$ X = \left( x_1, x_2, \dots, x_n \right) \$ - number or vector of \$ n \$ digits
\$ dc(X) = |X| = n \$ - is number of digits in number (digits count)
\$ h(X) = x_1 \$ - returns digit of the highest order (head), e.g. \$ h(123) = 1 \$
\$ t(X) = X' = \left( x_2, \dots, x_n \right) \$ - returns number without the highest order digit (tail), e.g. \$ t(123) = 23 \$

Let's look at those rules and figure out rules that will give us the biggest possible number using the given set of digits.

\$ \text{(1)} \$ consequence: more digits you have - better.  That means we have to be greedy and take as much as possible digits with the lowest price.

\$ \text{(2)} \$ consequence: is it obvious that some times we will have enough amount of paint to replace digit with the bigger one but not enough to add another one. Now we know that we have to replace digits starting from the number's head.

Now let's take a look at how much digits we will have in the worst case. It is around \$ 10^6 \$.

With such a number of characters to output, we can not output by a single character at a time because input\output operations took too much time. I hope there is no need to prove that IO takes a long time.

Let's consider using python's big numbers. We will not look at their implementation, just pretend that we have \$ 10^6 \$ digits to write and we know exactly what is it.

start = time.time()
num = 1;
for _ in range(10**5):
    num = num * 10 + 1
finish = time.time()
print (finish - start)

Takes 4 seconds to complete and it is still \$ 10^5 \$. No, we can not use python's big integers.

We can not build a string because it is an immutable object and we will copy it every time on change, same as with big integers.

More or less acceptable will be to make a list with the required amount of digits in it and then use str.join(). Let's stick with this approach for a while and continue research.

So, first, we will find the highest digit with the lowest price \$ d \$, determine the length of the resulting number \$ n = \lfloor \frac{v}{\text{lowest cost}} \rfloor \$ and make a resulting list of \$ d \$ repeated \$ n \$ times.

Now, while we have some paint to spare, we will loop through digits from the highest to lowest and try to replace as many head digits as possible.

But yeah, now when we spell it, you can see that you do not actually need that list at all. You need to know how much digits to write and who it will be starting from the head of the result.

One can say: "hey, this is greedy problem class, not implementation" - yeah we are all smart now.

Implementation

Here is my implementation of described algorithm:

from copy import deepcopy

class Digit(object):
    def __init__(self, _cost, _value):
        self.cost = _cost
        self.value = _value

def main():
    v = int(input())
    a = list(map(int, input().split()))
    a = tuple(Digit(cost, digit+1) for digit, cost in enumerate(a))
    low_digit = deepcopy(min(a, key=lambda digit: digit.cost*10 - digit.value))

    if low_digit.cost > v:
        print(-1)
        return

    digits = v // low_digit.cost
    v -= digits * low_digit.cost
    for i in range(9):
        a[i].cost -= low_digit.cost
    low_digit.cost = 0

    for better in reversed(a):
        if better.cost > 0 and better.value > low_digit.value:
            count = v // better.cost
            v -= count * better.cost
            digits -= count
            print(str(better.value) * count, end='')
    print(str(low_digit.value) * digits)

if __name__ == "__main__":
    main()


Is there a more elegant way to catch a generic exception than using try-catch block?

@HristoYank is correct, you shouldn't catch exceptions that you can't handle. What you are doing is basically just ignoring the error, which will make it difficult to trace bugs.

If I call a method called ParseNumberOutOfString, I will expect to get a number back. If the function can't return a number, I need to know that, so that I can react appropriately.

Depending on the situation, I may want to use a default value, ask the user for new input, or abort with an appropriate error message.

If the function just swallows the error and logs it somewhere, I will continue processing with invalid data (null in this case), which will result in all sorts of bugs down the line. As only a generic error message and no stracktrace is logged, debugging will also be rather difficult.

Misc

match doesn't actually throw an exception, so you will never get into the catch.
don't uppercase your variable names.


void parse_arguments(int count, char * arguments[]){//probably add file pointer here  to pass to load, change return type when an API is decided.
    int currentArg, paramIndex;

    for(currentArg = 1; currentArg <= count; currentArg++){

Why are you counting from zero? In C arrays start from zero, but you are starting from 1. As it stands it looks like you skip the first argument and then read one past the end

        if(arguments[currentArg][0] == '-'){
            for(paramIndex = 0; paramIndex < PARAMMAX; paramIndex++){
                if(strcmp(arguments[currentArg][1], arglist[paramIndex]) == 0){

Isn't arguments[currentArg][1] a char? How are you passing it to strcmp?

                    switch(paramIndex){
                        case 0:
                            //load(currentArg + 1);
                            currentArg++;

I recommend against manipulating loop counters inside your loop. It makes it harder to follow whats going on.

                            break;
                        default:
                            break;
                    }
                    break;
                }
            }
        }
    }
}

So much indentation suggests that you should break this down into smaller functions. I'd also suggest that you store the results of the arguments into a struct.

A general sketch of how I'd do this:

struct options
{
    char * filename;
    int numberOfRabbits;
};

struct parameter
{
    char * name; // 'x' for option '-x'
    bool requiresOption; // whether or not we should have an option
    void (*handler)(struct options * options, char * argument);
};

void parse_arguments(int count, char * arguments[], struct options * options)
{
    char * argument;
    int position = 0;
    while(position < count)
    {
         struct parameter * param = determine_parameter(arguments[position++]);
         if(!parameter)
         {
              panic(); // don't know this parameter
         }
         if(param.requiresOption)
         {
               argument = arguments[position++];
         }else{
               argument = NULL;
         }
         param.handler(options, argument);
    }
}


How to reorganize event listeners in javascript

You could simply declare the functions inline, like:

element.addEventListener("mousedown", function (e){
  dragging = true;
  startX = e.pageX;
  startY = e.pageY;
  element.style.opacity = 0.5;
}, false);

And likewise for the other 2 functions.

But that can get messy in a hurry. Especially because startX, startY and dragging would still be outside.

So instead you could put the handler in an object literal, just to keep them separated:

var dragEvents, element = document.getElementById("whatever"),

dragEvents = (function () {
  var dragging = false, startX, startY;
  return {
    start: function (e){
      dragging = true;
      startX = e.pageX;
      startY = e.pageY;
      element.style.opacity = 0.5;
    },

    move: function (e){
      if (!dragging) return;
      var deltaX = startX - e.pageX;
      var deltaY = startY - e.pageY;
      //apply to element
    },

    end: function(e){
      dragging = false;
      element.style.opacity = 1;
    }
  };
}());

element.addEventListener("mousedown", dragEvents.start, false);
document.addEventListener("mousemove", dragEvents.move, false);
document.addEventListener("mouseup", dragEvents.end, false);

I've wrapped it in an immediately invoked function so the dragging-related vars can be kept in there too.

However, might as well go the extra step and put everything in a function, instead of relying on element being a closure:

function makeDraggable(elementId) {
  var startX,
      startY,
      dragging = false,
      element = document.getElementById(elementId);

  function start(e){
    dragging = true;
    startX = e.pageX;
    startY = e.pageY;
    element.style.opacity = 0.5;
  }

  function move(e){
    if (!dragging) return;
    var deltaX = startX - e.pageX;
    var deltaY = startY - e.pageY;
    //apply to element
  }

  function end(e){
    dragging = false;
    element.style.opacity = 1;
  }
  element.addEventListener("mousedown", start, false);
  document.addEventListener("mousemove", move, false);
  document.addEventListener("mouseup", end, false);
}

The last suggestion I'd make would be to skip the dragging variable in favor of simply adding the move and end handlers on mouse down, and removing them on mouse up, like so:

function makeDraggable(elementId) {
  var startX,
      startY,
      element = document.getElementById(elementId);

  function move(e){
    var deltaX = startX - e.pageX;
    var deltaY = startY - e.pageY;
    //apply to element
  }

  function end(e){
    element.style.opacity = 1;
    element.removeEventListener("mousedown", move, false);
    element.removeEventListener("mousedown", end, false);
  }

  element.addEventListener("mousedown", function (e){
    startX = e.pageX;
    startY = e.pageY;
    element.style.opacity = 0.5;
    document.addEventListener("mousemove", move, false);
    document.addEventListener("mouseup", end, false);
  }, false);
}


Why so complicated?

One possible approach is:

var f = new Form();
if (f.Controls.OfType<TextBox>().Any(x => string.IsNullOrWhiteSpace(x.Text)))
{
    /*your stuff*/
}

A second approach is:

var TextBox1 = new TextBox();
var TextBox2 = new TextBox();

var textboxes = new[] { TextBox1, TextBox2 };
if (textboxes.Any(x => string.IsNullOrWhiteSpace(x.Text)))
{
    /*your stuff*/
}


Surely version two.

It makes no use of control structures such as for or if, it has very low Kolmogorov complexity because of that, and it is good, as it is directly related to difficulty in understanding.
It lets you see in a single glance what the output will look like.


I'd recommend separating the logic of getting the user input from the logic of building and sorting the nested list.
Your code doesn't build a nested list in a way that's useful for solving the problem; I think what you want is a list of lists of names, where each list of names corresponds to a grade.
Any time you want to group things into buckets (e.g. all the names that go with a grade), it's a good time to use a dictionary!
Using list comprehensions is frequently a good way to express a loop in a shorter way.
Type annotations make it easier to keep track of what your code is doing (and they let you use mypy to catch bugs).

Here's my solution that uses a separate function to build the nested list, using a dictionary as an intermediate step to collect all the names for a given grade.  Note that the type annotations tell you exactly where the names (strings) and grades (floats) are going at each step!

from collections import defaultdict
from typing import Dict, List, Tuple

def build_grade_lists(grades: List[Tuple[str, float]]) -> List[List[str]]:
    """
    Given a list of (name, grade) tuples, return a list of names for each grade.
    Each list is sorted, i.e.:
        the top level list is sorted from lowest to highest grade
        each list of names is sorted alphabetically
    """
    grade_lists: Dict[float, List[str]] = defaultdict(list)
    for name, grade in grades:
        grade_lists[grade].append(name)
    return [sorted(grade_lists[grade]) for grade in sorted(list(grade_lists.keys()))]

if __name__ == '__main__':
    scorecard = [(input(), float(input())) for _ in range(int(input()))]
    for name in build_grade_lists(scorecard)[1]:
        print(name)


Failing fast by raising an exception with a custom message

Instead of handling just "Division Failed" you should extend your function to handle any possible error, plus it's better if you pass the exception object along with the message to the decorator as well, by doing this you'll know exactly which error you're going to handle because a except Exception will handle any Exception not just what we actually intended it to.
Second there's no need to use flag variables here, we can simply return the return value from the try-block and in case of exception we re-raise the exception after it is caught.

Code:

from functools import wraps

def on_fail(exception, message):
    def on_fail_dec(func):
        @wraps(func)
        def on_fail_wrapper(*args, **kw):
            message_addon = ""
            try:
                # do something before
                ret = func(*args, **kw)
                # do something after
                return ret
            except exception as e:
               message_addon = str(e)
            raise exception("{0}\nBecause: {1}".format(message, message_addon))
        return on_fail_wrapper
    return on_fail_dec

@on_fail(ZeroDivisionError, "Division Failed")
def divide(a, b):
    return a / b

test_cases = [(1, 2), (20, 5), (3, 0)]

for a, b in test_cases:
    print("Trying to divide {0} from {1}".format(a, b))
    print(divide(a, b))

Note that in above code I didn't use something simple like:

except exception as e:
    raise exception("{0}\nBecause: {1}".format(message, e))

That's because Python 3 introduced something called exception chaining, which means if an exception occurs while handling another exception then the previous exception still remains available to us(Read PEP 3134 - PEP 3134 -- Exception Chaining and Embedded Tracebacks), but this is not useful here as it will end up raising something like:

Trying to divide 3 from 0
Traceback (most recent call last):
  File "/home/ashwini/py/so.py", line 10, in on_fail_wrapper
    ret = func(*args, **kw)
  File "/home/ashwini/py/so.py", line 20, in divide
    return a / b
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/ashwini/py/so.py", line 26, in <module>
    print(divide(a, b))
  File "/home/ashwini/py/so.py", line 13, in on_fail_wrapper
    raise exception("{0}\nBecause: {1}".format(message, e))
ZeroDivisionError: Division Failed
Because: division by zero


The purpose of your class is to perform a single computation: given filename, determine winner. That's a task for a function; there is no need for a class. You can turn each method to an independent function that takes one or two arguments and returns one or two values instead of accessing instance attributes, and provide this function to orchestrate the whole computation:

def concordet_winner(filename):
    voters = _get_data_from_file(filename)
    candidates, scores = _build_dict(voters)
    results = _matches_candidates(candidates, scores)
    return _elect_winner(candidates, results)

Now, reading this code gives a clear picture how the data flows through the computation.

For the purpose of learning OOP, you could consider a slightly different exercise: instead of having all votes in a file, create a class with a vote method that takes in an individual voter's vote, and a winner property that updates automatically after every vote.


Assuming that setT5RadioGroup only sets a variable within the fragment:

In your fragment, use RadioGroup[] radioGroups = new RadioGroup[10];

setTRadioGroup(int number, RadioGroup grp) {
   this.radioGroups[number] = grp;
}

In your activity, or whatever it is:

for (int i = 0; i < rowids.length; i++) { // assuming rowids.length is 10
    RadioGroup grp = (RadioGroup)fragView.findViewById(rowids[i]).findViewById(R.id.t1_radiogroup);
    fragment.setTRadioGroup(i, grp);
}

Whenever you find yourself using multiple numbered methods that does very similar things, think: Array!! (or possibly List<ElementType> if you want to be able to add/remove dynamically)


Is there a better way of defining custom calendars?

If you need to check for holidays repeatedly, I would go for Set and flatten pattern matching blocks for readability:

let holidays = set [ 1, 3; 1, 4; 1, 5; 1, 6; 1, 7; 1, 10 // month, day
                     2, 23
                     3, 7; 3, 8
                     5, 2; 5, 9
                     6, 13
                     11, 4
                    ]

let private isHoliday2011 (dt: DateTime) =
  match dt.DayOfWeek, dt.Month, dt.Day with
  | DayOfWeek.Saturday, m, d | DayOfWeek.Sunday, m, d -> m <> 3 || d <> 5
  | _, m, d -> Set.contains (m, d) holidays


Optimizing Perl script which looks for world-writable files

here are my suggestions:

Your hash %excludes would use less memory, if you would set the value to  undef instead of 1.

You could set $File::Find::prune=1 in those cases where the whole directory is to be excluded. This shortcuts the search for this directory.

You could also use the cached data of stat() afterwards like this -f _.

The regex should use anchors (faster and more robust).

Here is the revised wanted subroutine (untested).

sub wanted {
  my @dirStats = stat($File::Find::name);

  # Is it excluded from the report...
  if (exists $excludes{$File::Find::name}) {
    $File::Find::prune=1 if (-d _);
    return;
  }

  # ...in a basic directory, ...
  if ($File::Find::name =~ /^\bsys\b|\bproc\b|\bdev\b$/) {
    $File::Find::prune=1 if (-d _);
    return;
  }

  # ... not a regular file, ...
  return unless -f _;

  # ...local, ...
  return if (exists $devNums{$dirStats[0]});

  # ...and world writable?
  my $protection = $dirStats[2];
  my $writemask = (S_IWUSR | S_IWGRP | S_IWOTH);
  return unless $writemask == $protection & $writemask;

  # If so, add the file to the list of world writable files
  print(WWFILE "$File::Find::name\n");

}


The problem here isn't in the details of the code, but in the algorithm. For every tile, you check all tiles, so for n tiles, your code has to perform n^2 checks, which is a lot. The only way to significantly reduce the running time of your code, is to make the search smarter. If you can make your use case a bit more visual, we might be able to come up with something.


Returning all possible player moves on a board

Your function suffer from the retained structure (tuples of tuples). Tuples were not thought to be searched in or to be examined using recursion.

By converting it to a List on the fly, you may work with recursion and all the functions working on Lists (map, fold, etc.).

Here’s an example:

import Data.Maybe (catMaybes)

boardToList :: Board -> [Field]
boardToList ((a,b,c), (d,e,f), (g,h,i)) = [a,b,c,d,e,f,g,h,i]

ListToBoard :: [Field] -> Board
ListToBoard [a,b,c,d,e,f,g,h,i] = ((a,b,c), (d,e,f), (g,h,i))
ListToBoard _ = undefined

moves :: Player -> Board -> [Board]
moves player board = map ListToBoard $ catMaybes [boardSet i | i <- [0..8]]
    where (new, lboard) = (symbol player, boardToList board)
          boardSet i = case splitAt i lboard of
                            (start, B:end) -> Just (start ++ [new] ++ end)
                            _              -> Nothing