Calculating quiz score, with weights and partial credit

You don't seem to have any concept of objects or other reusable code in what you have written.  I would take a step back and think about what real-word objects you are trying to model.  At a minimum, I would think you would need three different concepts:

Answer Option: a single answer option that will be related to the question and hold logic on it fractional value as an answer.
Question: which stores a related set of answers and provides logic on calculating score for the question.
Quiz: which represents an ordered collection of questions.

Let me start by modeling the objects noted above:

// let's build a question class
function Question(text, baseScore) {
   this.text = null;
   this.answerOptions = [];
   this.selectedAnswerIndex = null;
   this.baseScore = null;

   this.setText(text);
   this.setBaseScore(baseScore);
}

// add methods to question class
Question.prototype = {
    setText: function(text) {
        this.text = text;

        // return the question object to allow for chaining
        return this;
    },
    setBaseScore: function(score) {
        this.baseScore = score;

        return this;
    },
    addAnswerOption: function(answer) {
        if(!answer instanceof Answer) {
            console.log('Give me an answer object!');
            return null;
        }
        this.answerOptions.push(answer);

        return this;
    }
    setAnswerIndex: function(idx) {
        this.selectedAnswerIndex = idx;

        return this;
    },
    getScore: function() {
        if(this.selectedAnswerIndex === null || this.baseScore === null) {
            return null;
        }
        var ansIdx = this.selectedAnswerIndex;
        var scoreModifier = this.answerOptions[ansIdx].questionScoreModifier;
        if(scoreModifier === null) {
            return null;
        }

        return this.baseScore * scoreModifier;
    }
};

// build answer class
function Answer(text, modifier) {
    this.text = null;
    this.questionScoreModifier = null;

    this.setText(text);
    this.setScoreModifier(modifier);
};

// answer class methods
Answer.prototype = {
    setText: function(text) {
        this.text = text;

        return this;
    },
    setScoreModifier(value) {
        this.questionScoreModifier = value;

        return this;
    }
};

// build quiz class
function Quiz(title) {
    this.title = null;
    this.questions = [];
    this.score = null;

    this.setTitle(title);
}

// quiz class methods
Quiz.prototype = {
    setTitle: function(text) {
        this.title = text;

        return this;
    },
    addQuestion: function(question) {
        if(question instanceof Question) {
            console.log('Give me a Question object!');
            return null;
        }
        this.questions.push(question);

        return this;
    },
    answerQuestion: function(questionIndex, answerIndex) {
        this.questions[questionIndex].setAnswerIndex(answerIndex);

        return this;
    },
    getTotalScore: function() {
        var total = 0;
        for(i=0; i<this.questions.length; i++) {
            var questionScore = this.questions[i].getScore();
            if (questionScore !== null) {
                total +== questionScore;
            }
        }
        this.score = total;

        return total;
    }
}

You now have the basic building blocks to create your quiz. You could include this code anywhere and have a reusable quiz.

Now you need to build the quiz itself.  That may look like this:

// build your quiz
var myQuiz = new Quiz('My cool quiz');

// now let build some questions
var question1 = new Question(
    'This is text of question 1. What is correct answer?',
    50
);

// now attach answers to the question
question1
    .addAnswerOption(new Answer('Answer worth 50%', .5))
    .addAnswerOption(new Answer('Answer worth 100%', 1))
    .addAnswerOption(new Answer('Answer worth 25%', .25));

// add the question to the quiz
myQuiz.addQuestion(question1);

// you could continue code like above to fill out your quiz

Finally, we can start working with the quiz to set answers and get scores.

// now let's set a user answer on a question
// we can assume that we get both the question index
// and the answer index for the question from elsewhere in javascript
// for example from clicking on answer selection
var questionIdx = {some value};
var answerIdx = {some value};

// set the answer
myQuiz.answerQuestion(questionIdx, answerIdx);

// we can also get total quiz score
var totalQuizScore = myQuiz.getTotalScore();

// or we can get scores on individual questions
var question1Score = myQuiz.questions[0].getScore();

Note that the outcome here is very reusable code that could be pretty much dropped anywhere within a larger application to implement your quiz.  In a real application you may also add something like a quiz rendering class to be able to render the quiz using javascript (and to separate display of quiz from core quiz objects).

It also makes it much easier to modify your code in the future. You need to change how questions are scored? - well just change the scoring logic within the answer and question classes as implemented in those class properties and methods.  As long as you keep the contract (i.e method calls) with the quiz, the quiz class itself would likely not need to be modified.


Converting a binary string to an ASCII string, the longer way

int [] mapping = {1,2,4,8,16,32,64,128};

This seems avoidable - array access could be replaced with a bitshift. It'd also clear up what you're doing...

for (int j = 0; j < chars.length; j+=8) {
    int idx = 0;
    int sum = 0;
    for (int i = 7; i>= 0; i--) {
        if (chars[i+j] == '1') {
            sum += 1 << idx;
        }
        idx++;
    }
    System.out.println(sum);//debug
    sb.append(Character.toChars(sum));
}

It's only after making this change that I understand what you're doing! You're splitting the input string into segments that represent a single character (I got that far already), but after that, you start at the back of the represented character, and check for each bit representing character that it is '1'. If it's '1' (and thus not '0'), you add the value that the bit would represent to sum. Once you've gone through a single character representation, you let Character.toChars cast the int-value of the character back to a character. Then you add it to the result buffer, which will form the full string.

Phew.

You need more comments, so that other developers can read and understand directly how this method works.

Specifically, 1 comment to explain what your replaceAll does (regex are not obvious to me and I have to look them up), and 1 comment to say that you're parsing bits in reverse per character.

Maybe like so:

//for each character
for (int j = 0; j < chars.length; j+=8) {
    int idx = 0;
    int sum = 0;
    //for each bit in reverse
    for (int i = 7; i>= 0; i--) {
        if (chars[i+j] == '1') {
            sum += 1 << idx;
        }
        idx++;
    }
    System.out.println(sum);//debug
    sb.append(Character.toChars(sum));
}

Getting rid of all the built-in functions (for fun only)

So you want to do everything yourself?

This is bad style, since everything in java.lang (and in generally, java.util as well) can be relied on without turning this into a puzzle for your fellow programmers, but I'll humor you.

First, you can get rid of the String.split via Thomas Junk's answer, incrementing by 9 each time instead.

public static String convertBinaryStringToString(String string){
    StringBuilder sb = new StringBuilder();
    char[] chars = string.toCharArray();

    //for each character
    for (int j = 0; j < chars.length; j+=9) {
        int idx = 0;
        int sum = 0;
        //for each bit in reverse
        for (int i = 7; i>= 0; i--) {
            if (chars[i+j] == '1') {
                sum += 1 << idx;
            }
            idx++;
        }
        System.out.println(sum);//debug
        sb.append(Character.toChars(sum));
    }
    return sb.toString();
}

Leaves us with this bit of code.

We can get rid of the StringBuilder by writing to a char[]. We can get rid of Character.toChars(sum) with (char) sum. We do have to make a new string out of the character array, though.

public static String convertBinaryStringToString(String string){
    char[] chars = string.toCharArray();
    char[] transcoded = new char[(chars.length / 9)+1];

    //for each character (plus one for spacing)
    for (int j = 0; j < chars.length; j+=9) {
        int idx = 0;
        int sum = 0;

        //for each bit in reverse
        for (int i = 7; i>= 0; i--) {
            if (chars[i+j] == '1') {
                sum += 1 << idx;
            }
            idx++;
        }
        transcoded[j/9] = (char) sum;
    }
    return new String(transcoded);
}

And voila, we're rid of most of the built-ins. There's no way to get the contents of a String without use of built-ins, however, so string.toCharArray or string.charAt is required.


Here is a function I wrote that, with the help of jQuery, will randomize a bunch of properties

Notes

I had a go at converting it to native JavaScript, was fun :P Pretty nifty bit of code. Here are my notes:

I pulled Math.ceil(Math.random() * x)) out into a function randomInt(x), I recommend against extending native JavaScript objects. They tend to be difficult problems to debug, just create a new function instead.
I would probably prefer to have .container outside of .some-elem or programmatically generated. I didn't make this change though. The main issue with having it inside .some-elem next to the text is that when you attempt to fill spots in JS you need to get rid of the .container markup from .innerHTML as it comes out like this:

hello world

Which leads to a bit of ugly code to extract everything before the '<':

var spots = [].splice.call(elem.innerHTML, 0, elem.innerHTML.indexOf('<'));

You can add the speak: none; to .container so screen readers don't read "hello world lakmsdlkaslkadsadfas...".
You can extend jQuery like so:

$.fn.customFunction = function () {
    console.log(this);
}

$('.some-elem').customFunction();

I've used CSS3 transitions in place of $.fadeIn(), browser support isn't quite as good (looking at you IE), but the implementation is worth it in my opinion. Especially when most people wouldn't even notice like this super subtle fade in.
I'm not so sure about adding a number as a class name, I don't think it's legal to have class names start with a number.
Your indentation when you were applying everything to the  was a little ugly :P
Overall it was a pretty decent and clean jQuery implementation.

Code

jsFiddle

HTML

hello world

CSS

body { background: black; font-family: consolas;}

div.content {
    background: white;
    opacity: 0.9;
    min-height: 1000px;
    width: 960px;
    margin: auto;
    color: black;
    padding: 10px;
    list-style: none;
    position: relative;
}

div.content > .some-elem {
    text-shadow: 1px 1px 6px rgba(0, 0, 0, 1), 0px -1px 2px rgba(0, 0, 0, 1);
    border-bottom: 7px solid #41919B;
    border-top: 7px solid #41919B;
    border-right: 1px solid #BDBDBD;
    border-left: 1px solid #BDBDBD;
    padding-bottom: 7px;
    box-shadow: 0px 11px 17px 1px rgba(0, 0, 0, 0.5), inset 0px 0px 0px 1px rgba(0, 0, 0, 0.6);
    border-radius: 5px 5px 5px 5px;
    text-align: center;
    color: black;
    width: 960px;
    overflow: hidden;
    position: relative;
    letter-spacing: 11px;
    line-height: 60px;
    cursor: pointer;
}
div.content > .some-elem:hover {
    color: #fff;
    text-shadow: 1px 1px 6px rgba(0, 0, 0, 1), 0px -1px 2px rgba(0, 0, 0, 1);
}

span.spot {
    position: absolute;
    top: 0px;
    z-index: -1;
    text-shadow: none;
    box-shadow: none;
}

.container {
    opacity:0;
    -webkit-transition:opacity .8s ease;
    -moz-transition:opacity .8s ease;
    transition:opacity .8s ease;
    speak: none;
}

.container.show {
    opacity:1;
}

JS

function twisty(elemClass, containerClass) {
    var elem = document.getElementsByClassName('some-elem')[0];
    var container = elem.getElementsByClassName('container')[0];
    var spots = [].splice.call(elem.innerHTML, 0, elem.innerHTML.indexOf('<'));

    for (var i = 0; i < 300; i++) {
        var span = document.createElement('span');
        var color = 'rgb('+ randomInt(70) + ',' +
            randomInt(70) + ',' +
            randomInt(70) + ')';
        var transform = 'rotate(' + randomInt(360) + 'deg)';

        span.innerHTML = spots[randomInt(spots.length - 1)];
        span.className = 'spot '+ i;
        span.style.fontSize = randomInt(50) + 'px';
        span.style.left = randomInt(1000) + 'px';
        span.style.top = randomInt(30) + 'px';
        span.style.bottom = randomInt(50) + 'px';
        span.style.opacity = Math.random() / 3;
        span.style.color = color;
        span.style.webkitTransform = transform;
        span.style.mozTransform = transform;
        span.style.transform = transform;
        container.appendChild(span);
    }

    container.classList.add('show');
}
twisty();

document.getElementsByClassName('some-elem')[0].onclick = function () {
    var container = document.getElementsByClassName('container')[0];
    container.classList.remove('show');
    while (container.hasChildNodes()) {
        container.removeChild(container.lastChild);
    }
    twisty();
};

function randomInt(max) {
    return Math.ceil(Math.random() * max);
}


Python function to implement an image-processing pipeline

As Reinderien mentions, you can decrease some of the complexity of your code by inverting your if-statements. While I cannot test this because I do not have your whole code, here is how it could be done:

def get_image(width, height, collection_sku, order_id, name, handle):
    """image processing pipeline"""

    # Check-1 image exception should be checked before proceeding further
    # covers both images in exception(currently bookshelves) list and also personal true doors
    #   1. bookshelves need to be cropped
    #   2. personal TD images needs to be added in the required size when it's submitted by the user.
    if not helpers.image_exception(collection_sku):
        return None

    # Step-1 Find image folder
    directory_sizes = helpers.find_directory(width, height)

    if directory_sizes is None:
        return None

    # Step-2 Find the image from the given folder.
    key = helpers.find_image(directory_sizes, collection_sku)

    if key is None:
        return None

    requires_resize = helpers.should_resize(width, height)
    requires_flip = helpers.should_flip(handle) and not helpers.flip_exception(collection_sku)

    # Check-2 check whether image requires resizing or flipping
    if requires_resize or requires_flip:

        # Step-3 Create local directory to store temporary images
        location, is_created = helpers.local_directory(
            order_id)

        if not is_created:
            return None

        # Step-4 Download image
        image = helpers.download_image(key, location, name)

        if image is not None:
            width_px = helpers.cm_to_pixel(width)
            height_px = helpers.cm_to_pixel(height)
            image_modified = False

            # Step-5.1 Resize image
            if requires_resize:
                helpers.resize_image(image, width_px, height_px)
                image_modified = True

            # Step-5.2 Flip image
            if requires_flip:
                helpers.flip_image(image)
                image_modified = True

            # Step-6 Upload image
            if image_modified:
                helpers.upload_image(image, key)

        # Step-3 No local dir created
        # Step-4 Can't download image
        # Step-5.1 Can't resize image
        # Step-5.2 Can't flip image
        # Step-6 Can't upload image

    # Check-2 if no image processing required then copy image over
    helpers.copy_image(key, target = None) # TODO
    return True

    # raise exception in sub job
    #   Check-1 if image door image cannot be processed
    #   Step-1 if directory not available
    #   Step-2 if image not available

This, for me, vastly increases readability -- before, it was hard to figure out which if-statements do what (especially with fragments of code at the ends of them). However, your comments are useful in describing the process as it goes along.

I'm sure it could be flattened more, but this should demonstrate the idea of it. Hope this helps!


Is using java enums to store filepaths good practice

Enum are a good way to do this in my opinion if this is really static.

Might I suggest you do:

public enum Datafile {
    ACTIVITIES("activities.yaml"),
    OPEN_LOOPS("open_loops.yaml");

private String filepath;

private Datafile(String filepath) {
    this.filepath = filepath;
}

public String getFilepath() {
    return filepath;
}

This is a bit more readable than the overriden methods in each declaration, especially with long enums.

If the values of the filepaths are subject to changes from time to time. I suggest using a properties file. These can be reloaded without recompiling you package, meaning non-developers could maintain them. That is useful in some team setups.

EDIT:
For properties, I suggest you read the java properties tutorial: http://download.oracle.com/javase/tutorial/essential/environment/properties.html. There are also a lot of already well written tutorials about them and I could never hope to match their quality here. Also, never having worked on Android, I do not know if google has provided something that is more user friendly.

For small applications, I would go for enums personally, as they are very easy to manage and usually do the job pretty well.


Finding the number of vowels in a string

Outline

In this case, instantiating a new CountVowels() is overkill.  all you need is a function.

As a rule, classes should be named as nouns.  A better name for the class would be VowelCounter.

public class VowelCounter {
    public static int vowelCount(String s) {
        …
    }

    public static void main(String[] args) {
        …
        System.out.println(vowelCount(userInput));
    }
}

Implementation

Your countingVowels() function is fine, but could be simpler.

public static int vowelCount(String s) {
    int count = 0;
    for (char c : s.toLowerCase().toCharArray()) {
        if ("aeiou".indexOf(c) >= 0) {
            count++;
        }
    }
    return count;
}

Specifically, note:

Using an enhanced for loop is less tedious than a counting loop.
Avoid boxed types such as Character, when a primitive char will do.
For such a short array, a binary search is overkill.

Your main() is also OK, but I would write it this way:

public static void main(String[] args) {
    try (Scanner scanner = new Scanner(System.in)) {
        String userInput = scanner.next();
        System.out.println(vowelCount(userInput));
    }
}

In particular:

A Scanner is AutoCloseable, so a try-with-resources block is tidier than calling close() on it manually.
There doesn't seem to be much point in the …1 suffix on your variable names sc1, cv1, and s1.


Haskell Servant - login endpoint with two error states

Since the Handler LoginAttempt from action only ever contains Ok, its result should instead be Handler Text. And then nobody ever sees a LoginAttempt object, so we don't need it.

action :: Config -> JWTSettings -> Credentials -> Handler Text
action config jwt (Credentials email pass) = do
  login <- either authenticationError pure =<<
    runSqlPool (Queries.validateAccount email pass) (getPool config)
  token <- either tokenGenerationError pure =<<
    liftIO (makeJWT login jwt Nothing)
  pure $ decodeUtf8 token -- perhaps: pure $ decode $ object [ "token" .= decodeUtf8 token ]
  where
    autheticationError   _ = throwError $ err401 { errBody = encode $ object [ "error" .= ("Invalid username or password" :: Text) ] }
    tokenGenerationError _ = throwError $ err500 { errBody = encode $ object [ "error" .= ("Error generating token"       :: Text) ] }


Find repeated substrings of length 3 in a string

It's quite fine. The logic is simple and clear.
There might be a more clever solution (I don't know),
but probably it will be less clear.

A few improvements would be good though:

counter is set to 0 at two places, both unnecessary, as the value is overwritten later
It's a good practice to declare variables in the smallest scope where they are used. For example counter and sub would be better to declare inside the loop.
stringLen is not a great name, because it's not really the "length" of anything. Even limit would be better
Instead of the magic number 3, and str.length() - 2, it would be better to make the target length a method parameter.
Instead of calling .containsKey followed by get and put, I prefer to get, check null and then put, whenever possible. This is not always possible, for example when null is a meaningful entry, but that's not the case here.

Based on the above suggestions, the implementation could become a bit simpler:

public Map<String, Integer> findOccurences(String str, int length) {
    Map<String, Integer> map = new HashMap<>();
    int limit = str.length() - length + 1;
    for (int i = 0; i < limit; i++) {
        String sub = str.substring(i, i + length);
        Integer counter = map.get(sub);
        if (counter == null) {
            counter = 0;
        }
        map.put(sub, ++counter);
    }
    return map;
}

And it would be good to add a unit test for it:

@Test
public void test_This_This_() {
    Map<String, Integer> map = new HashMap<>();
    map.put("his", 2);
    map.put("Thi", 2);
    map.put(" Th", 1);
    map.put("s T", 1);
    map.put("is ", 2);
    assertEquals(map, findOccurences("This This ", 3));
}


Converting minutes and seconds in seconds

I'm not familiar with PHP too much but globals are usually considered harmful. I don't know what's the best practice in PHP but passing the $warning argument by reference seems a good idea here.
When a field is not posted you get various PHP notices. I guess it's better to avoid these notices:

PHP Notice:  Undefined index: min in /tmp/x.php on line ...
PHP Notice:  Undefined index: sec in /tmp/x.php on line ...

A robust code should handle these cases.
tmpsec and min_in_sec are not initialized in every code paths, so you can get notices about these too when there is no min key in the $_POST array:

PHP Notice:  Undefined variable: tmpsec in /tmp/x.php on line 24
PHP Notice:  Undefined variable: min_in_sec in /tmp/x.php on line 2

I think it's cleaner to initialize all variables. It also could help debugging since you don't have to ignore lots of PHP notice messages when you are looking for an uninitialized global variable.
tmpsec and min_in_sec could be omitted if you reorganize the code to not count anything until it is sure that there isn't any input error. (See below.)
A small note: The function is a little bit inconsistent: it allows 60 as minute but doesn't as seconds. It would be cleaner and more common to set one hour as hours = 1, minutes = 0 and seconds = 0.

$warning = array();

function val_duration(&$warning, $min, $sec, $required = false) {
    if (empty($min) && empty($sec)) {
        if ($required) {
            $warning['duration'] = "The duration is a required field";
        }
        return NULL;
    }

    if (!ctype_digit($min) || $min > 61) {
        $warning['min'] = 'The minutes must contain a positive numeric value between 1 and 60';
    }
    if (!ctype_digit($sec) || $sec > 59) {
        $warning['sec'] = 'The seconds must contain a positive numeric value between 1 and 59';
    }
    if (!empty($warning)) {
        return NULL;
    }

    return $min * 60 + $sec;
}


(Codewars) Linked Lists-Sorted Insert (2)

To me it seems the purpose of this rewrite is to mitigate the special treatment for replacing the head. Like the previous solution, it also suffers from lack of separation of distinct logical elements. In this example, tmp is used for two purposes: traverse the list, and act as the dummy to check if head was replaced.

This is one step away from a clear dummy node to prefix the list to eliminate the special treatment of the head, and I think this clean separation is simpler and easier to understand:

def sorted_insert(head, data):
    # a dummy node inserted in front of head
    dummy = Node(None)
    dummy.next = head

    # whatever happens in the rest, the new head will be dummy.next

    # loop until the insertion point
    node = dummy
    while node.next:
        if node.next.data > data:
            break
        node = node.next

    # create the new node and insert it
    new_node = Node(data)
    new_node.next = node.next
    node.next = new_node

    # return the head. it may or may not have been replaced
    return dummy.next


Creating an array of strings from a text file

If you are truly coding in C then all variables should be declared at the start of the function. This has traditionally been how the C language worked and what C coders expect.

C has also traditionally not allowed for runtime declarations of array sizes. You should malloc the list variable.

If you initialize a loop variable then just omit it in the for loop definition. In other words don't do this:

for(c; c < foo; c++)

do this:

for( ; c < foo; c++)

A char is already a byte, no need to multiple strlen by sizeof(char).

Personally I would move most of the logic into proper functions and out of main. It is just a good habit to get into.


Rather than using ViewData I might consider using ViewBag (if on MVC 3 and above) or even wrapping Author within a ViewModel.  That what you won't need the cast on the view (if using a viewModel).

Otherwise your MultiSelectList code is only one line.  Don't see you getting much better than that :)

Your viewmodel might look like

public class AuthorViewModel
{
   public Author BookAuthor { get; set; }
   public MultiSelectList BookList { get; set; }
}

[HttpGet]
public ActionResult Edit(int id = 0)
{
    Author author = db.Authors.Find(id);
    if (author == null)
    {
        return HttpNotFound();
    }

    var viewModel = new AuthorViewModel
    {
       BookAuthor = author;
       BookList = new MultiSelectList(db.Books, "Id", "Name", author.Books.Select(x => x.Id).ToArray());
    }

    return View(viewModel);
}

Your view will need to be typed to the view model and you could then write

Html.ListBox("SelectedBooks",Model.BookList);

I'm not 100% sure then if you need to re-bind it back on the post if there is a problem.  If you do, I would consider doing that after the Model.IsValid unless of course your "Index" action usings the ViewData["BookList"] value?

EDIT:
Ok, what about this then.

    internal class BookEqualityComparer : IEqualityComparer<Book>
    {
        public bool Equals(Book x, Book y)
        {
            return x.Id == y.Id;
        }

        public int GetHashCode(Book obj)
        {
            return obj.GetHashCode();
        }
    }

Then your code in the Post will be:

    // Take the values common to both lists based on the EqualityComparer
    edit.Books.Union(author.SelectedBooks, new BookEqualityComparer ());

And I would consider making the Books DbSet lazy loaded.

public class DataContext : DbContext
{
    private DbSet<Book> _books;
    public DbSet<Book> Books
    {
       get { return _books ?? (_book = new DbSet<Book>()); } // TBH not 100% sure you can set DbSet like this but worth a shot
       set { _books = value; }
    }

    public DbSet<Author> Authors { get; set; }
}


Determining if a string is a palindrome of a permutation

I'd change a number of things in this code.

std::string output("");

No need for the empty initializer--it'll be initialized to an empty string by default (i.e., std::string output; is fine).

for(char& c : s)
    if(isalpha(c)){
        c = tolower(c);
        output += c;
    }

I don't see where you gain anything by modifying the input string here, instead of just writing the modified character to the output:

for (char c : s)
    if (isalpha(c))
        output += tolower(c);

Unfortunately, things aren't quite that simple. In most implementations, a plain char is signed, and passing a negative number to isalpha or tolower gives undefined behavior. Anytime you call either, you really need to convert to unsigned char first:

for (unsigned char c : s)
    if (isalpha(c))
       output += tolower(c);

Now when somebody tests with (for example) an accented character, it won't crash and burn.

static const int ascii_sub = 97;

This strikes me as wrong in at least a couple of different ways. First, the name strikes me as poor (ASCII, as such, is mostly obsolete, and even before that, it was unnecessarily narrow). I guess you mean the sub to refer to subtraction (somehow or other) but it's not immediately apparent how the two combine meaningfully.

Worse, it appears that your real intent is to just get the value of a. If you want that, it's almost always better to just use 'a'.

static int counters[26]{0};

Here I'd rather use something like static size_t counters['z'-'a']; Since it's static, it'll be initialized to zeros automatically. Using 'z' - 'a' makes it apparent what that 26 is intended to signify--and as a bonus, even makes it work with systems that use EBCDIC, where the distance from a to z is more than 26.

And, of course, the standard type for counting things where you can't ever have negative values is size_t (though a signed int like you've used will typically be perfectly fine).

Rather than using a static array, I'd probably use a std::vector (not static, and return it by value rather than returning a pointer to it).

Looking at check_chars, I think I'd do things a bit differently.  I'd probably use std::find_if to do the searching, something like this:

auto first = find_if(counts.begin(), counts.end(), [](size_t s) { return s % 2 != 0); });

auto second = find_if(first, counts.end(), [](size_t s) { return s % 2 != 0; });

return second != counts.end();

The first tries to find an odd value. The second tries to find a second odd value between the first, and the end. If the first failed, it'll return counts.end(). The second will try to search between the end and the end, and obviously conclude no such thing exists (very quickly), so it'll return counts.end() as well.

Finally this:

std::cout << (palindromePermutation(input) ? "True" : "False") << std::endl;

...can be simplified a bit as well:

std::cout << std::boolalpha << palindromePermutation(input) << "\n";

std::boolalpha is not only a bit shorter, but also uses the names defined in the locale, so when using (for example) a German locale, it could print out falsch and wahr (and with a Chinese locale, if Google Translate is to be trusted, 假 and 真) for "false" and "true", respectively.


Print all subsets and permutations of a string

Some (most of?) dynamic allocations seem unnecessary. A call to createString can be safely replaced with a local char string[6]; Similarly, a call to genBetween could be reduced essentially to

char generatedSubString[6];
strncpy(generatedSubString, string + counter1, counter2 - counter1);

Testing for numPermuted < 120 looks strange. You should trust your math. If you do not, don't fail the test silently, but rather assert(numPermuted < 120), and if it triggers, revisit your assumptions.
A search for already permuted (in fact, already visited) substring is suboptimal. Consider filling the permuted array in sorted order (to enable binary searching it).


Find all letter Combinations of a Phone Number

whenever you encounter a task where you have to combine or permute things, then backtracking is a possible approach.

True. It is not necessarily the best though (in fact it is rarely the best).

In this particular case, the problem naturally maps to finding the next combination. In turn, it is no more than an increment of a number in some fancy numbering system. In your example, the minimal possible string is ad. Subsequent increments yield ae, then af, then ('f' + 1 is d and a carry bit does carry) bd, etc.

Consider implementing the increment/next method directly. The space complexity will definitely benefit; and it is trivial to convert into a generator. The time complexity is likely to also benefit, depending on the use case.

PS: thank you for posting your train of thoughts.


Another approach is to work with individual columns:

Option Explicit

Public Sub ShuffleColumns()

    Const ROW_OFFSET As Long = 3

    Dim fr As Long, fc As Long, lr As Long, frx As Long, lrx As Long
    Dim res As Variant, arr As Variant, i As Long

    With Sheet1

        fr = .UsedRange.Row
        fc = .UsedRange.Column
        lr = .Cells(fr, fc).End(xlDown).Row

        frx = lr + ROW_OFFSET   'Next first row
        lrx = (frx - fr) + lr   'Next last row

        res = Array(9, 10, 11, 2, 3, 1, 4, 5, 6, 7) 'IN columns mapped to OUT columns

        fc = fc - 1 'Optimized for the loop

        For i = LBound(res) To UBound(res)

            arr = .Range(.Cells(fr, res(i) + fc), .Cells(lr, res(i) + fc))  'IN column

           .Range(.Cells(frx, i + 1 + fc), .Cells(lrx, i + 1 + fc)) = arr   'OUT column

        Next

       .Range(.Cells(frx, fc + 1), .Cells(lrx, fc + 1)).NumberFormat = "yyyy-mm-dd"

    End With
End Sub

.

Note: Public Const OutputColumnsTotal As Long = 10 is global but it is used only in ShuffleArrayColumns() - it's advisable to declare constants and vars as close to their scope as possible

.

Test results with OP code:

Test results with this code:

Performance: for 100,000 rows - 2.167 sec (OP code) vs 1.277 sec (this code)

Edit

Testing with different optimizations for the FOR loop:

Version 2

Public Sub ShuffleColumnsUnoptimizedFC()
    Const ROW_OFFSET As Long = 3

    Dim fr As Long, fc As Long, lr As Long, frx As Long, lrx As Long
    Dim res As Variant, arr As Variant, i As Long, t As Double
    With Sheet1
        t = Timer
        fr = .UsedRange.Row
        fc = .UsedRange.Column
        lr = .Cells(fr, fc).End(xlDown).Row

        frx = lr + ROW_OFFSET
        lrx = (frx - fr) + lr

        res = Array(9, 10, 11, 2, 3, 1, 4, 5, 6, 7)
        For i = LBound(res) To UBound(res)
            arr = .Range(.Cells(fr, res(i) + fc - 1), .Cells(lr, res(i) + fc - 1))
           .Range(.Cells(frx, i + 1 + fc - 1), .Cells(lrx, i + 1 + fc - 1)) = arr
        Next
       .Range(.Cells(frx, fc), .Cells(lrx, fc)).NumberFormat = "yyyy-mm-dd"
        Debug.Print "Rows: " & lr & "; Time: " & Format("0.000", Timer - t) & " sec"
    End With
End Sub

Version 3

Public Sub ShuffleColumnsUnoptimizedLoop()
    Const ROW_OFFSET As Long = 3

    Dim fr As Long, fc As Long, lr As Long, frx As Long, lrx As Long
    Dim res As Variant, arr As Variant, i As Long, t As Double
    With Sheet1
        t = Timer
        fr = .UsedRange.Row
        fc = .UsedRange.Column
        lr = .Cells(fr, fc).End(xlDown).Row

        frx = lr + ROW_OFFSET
        lrx = (frx - fr) + lr

        res = Array(9, 10, 11, 2, 3, 1, 4, 5, 6, 7)
        For i = LBound(res) To UBound(res)
            arr = .Range(.Cells(fr, res(i) + fc - 1), .Cells(lr, res(i) + fc - 1))
           .Range(.Cells(frx, i + 1 + fc - 1), .Cells(lrx, i + 1 + fc - 1)) = arr
            If i = 1 Then
                .Range(.Cells(frx, fc), .Cells(lrx, fc)).NumberFormat = "yyyy-mm-dd"
            End If
        Next
        Debug.Print "Rows: " & lr & "; Time: " & Format("0.000", Timer - t) & " sec"
    End With
End Sub

After 3 tests with 500,000 rows

Rows: 500,000; Time: 7.01171875 sec (v1)
Rows: 500,000; Time: 7.05078125 sec (v2)
Rows: 500,000; Time: 7.08984375 sec (v3)

The idea is to move all unnecessary operations outside the loop - repetition will amplify any minor effort - exponentially if the loops are nested.


You need to #include <time.h> for struct timespec to be defined.

Why are NS_PER_SECOND and MAX_NS enum members?  There's no advantage compared to plain old const long.  I'm not sure why we need two constants anyway; the code that uses MAX_NS is simplified if we use NS_PER_SECOND instead:
long total_ns   = t1.tv_nsec + t2.tv_nsec;
time_t total_s  = t1.tv_sec  + t2.tv_sec;

while (total_ns >= NS_PER_SECOND) {
    total_ns -= NS_PER_SECOND;
    ++total_s;
}

(Note the use of the correct types in this version).

I think this logic is wrong:
if (t.tv_sec > 0 && t.tv_nsec < 0) {
    t.tv_nsec += NS_PER_SECOND;
    t.tv_sec--;
} else if (t.tv_sec < 0 && t.tv_nsec > 0) {
    t.tv_nsec -= NS_PER_SECOND;
    t.tv_sec++;
}

I'm reasonably sure that tv_nsec should always be positive, even when tv_sec is negative.  So we can simplify that to just:
if (t.tv_nsec < 0) {
    t.tv_nsec += NS_PER_SECOND;
    t.tv_sec--;
}

Note that the logic in timespec_add() already assumes positive tv_nsec.

This is highly susceptible to overflow:
unsigned int total_ns = t.tv_nsec + (t.tv_sec * (MAX_NS+1));

The whole reason we have struct timespec is that we might need to represent values outside the range of the integer types.  Probably better to use divmod to divide tv_nsec by n, and add the remainder to nsec before dividing - we need to be very careful here to avoid overflow.  Again, an unsigned type is inconsistent with other code.
Modified code
Here's my version of these functions:
#include <time.h>

const long NS_PER_SECOND = 1000000000L;

struct timespec timespec_sub(const struct timespec t1, const struct timespec t2)
{
    struct timespec t;

    t.tv_nsec = t2.tv_nsec - t1.tv_nsec;
    t.tv_sec  = t2.tv_sec - t1.tv_sec;

    if (t.tv_nsec < 0) {
        t.tv_nsec += NS_PER_SECOND;
        t.tv_sec--;
    }
    return t;
}

struct timespec timespec_add(const struct timespec t1, const struct timespec t2)
{
    struct timespec t = { t1.tv_sec + t2.tv_sec, t1.tv_nsec + t2.tv_nsec };
    if (t.tv_nsec >= NS_PER_SECOND) {
        t.tv_nsec -= NS_PER_SECOND;
        t.tv_sec++;
    }
    return t;
}

struct timespec timespec_divide(struct timespec t, const int n)
{
    time_t remainder_secs = t.tv_sec % n;
    t.tv_sec /= n;
    t.tv_nsec /= n;
    t.tv_nsec +=
        remainder_secs * (NS_PER_SECOND / n) +
        remainder_secs * (NS_PER_SECOND % n) / n;

    while (t.tv_nsec >= NS_PER_SECOND) {
        t.tv_nsec -= NS_PER_SECOND;
        t.tv_sec++;
    }
    return t;
}

And a primitive unit-test:
int main(void)
{
    const struct timespec a = { 1, 905234817 };
    struct timespec a_2 = timespec_add(a, a);
    struct timespec a_4 = timespec_add(a_2, a_2);
    struct timespec a_5 = timespec_add(a_4, a);
    struct timespec z = timespec_sub(a, timespec_divide(a_5, 5));
    return z.tv_sec || z.tv_nsec;
}

You should expand on the testing, to prove correctness for the tricky cases where overflow could happen.

Further simplification
We can separate out the code to normalise out-of-range nanoseconds into its own function:
struct timespec timespec_normalise(struct timespec t)
{
    t.tv_sec += t.tv_nsec / NS_PER_SECOND;
    if ((t.tv_nsec %= NS_PER_SECOND) < 0) {
        /* division rounds towards zero, since C99 */
        t.tv_nsec += NS_PER_SECOND;
        --t.tv_sec;
    }
    return t;
}

Then the functions can use that, to make them shorter and simpler:
struct timespec timespec_sub(const struct timespec t1, const struct timespec t2)
{
    struct timespec t = { t2.tv_nsec - t1.tv_nsec, t2.tv_sec - t1.tv_sec };
    return timespec_normalise(t);
}

struct timespec timespec_add(const struct timespec t1, const struct timespec t2)
{
    struct timespec t = { t1.tv_sec + t2.tv_sec, t1.tv_nsec + t2.tv_nsec };
    return timespec_normalise(t);
}

struct timespec timespec_divide(struct timespec t, const int n)
{
    time_t remainder_secs = t.tv_sec % n;
    t.tv_sec /= n;
    t.tv_nsec /= n;
    t.tv_nsec +=
        remainder_secs * (NS_PER_SECOND / n) +
        remainder_secs * (NS_PER_SECOND % n) / n;
    return timespec_normalise(t);
}

Because we have the unit tests, we have high confidence that we haven't affected the functionality here.


Swapping

def swap(l, i, j):
    temp = l[i]
    l[i] = l[j]
    l[j] = temp

Just do:

l[i], l[j] = l[j], l[i] # (a)

You could abstract this into a swap function like you have done, but I probably wouldn't in this case. Matter of taste. Nevertheless, if you do swap the body definition should consist of (a).

Unnecessary variables.

pivot_ind = left
return pivot_ind

Just return left. Write a comment explaining what left is if you need to.


Seeking a quick and dirty way to populate a list of entities for testing purposes

As far as I can see, most of your data is fairly predictable.  What about:

for (int i = 0; i < 9; ++i)
{
   int scenarioTimeInSeconds = 60*(i/3); // Intentional loss of fractional part
   int bearingInDegrees = (i % 3) * 120; // It's now 0, 120, 240
   int rangeInNauticalMiles = (i % 3 == 0) ? 0 : 1;
   int courseInDegrees = (i == 5) ? 180 : 90;
   yield return new Snapshot
       {
           Id = i + 1,
           ScenarioTimeInSeconds = scenarioTimeInSeconds,
           BearingInDegrees = bearingInDegrees,
           RangeInNauticalMiles = rangeInNauticalMiles,
           CourseInDegrees = courseInDegrees,
           SpeedInKnots = 7,
           XCoordinate = 0,
           YCoordinate = 0,
      };
}

This already seems more readable to me.  Now you can split the logic that makes the values for the various local ints off into separate functions and document each one.  In order to do it this way, you do have to have GetSnapshots return an IEnumerable<Snapshot>, but that makes sense anyway -- and if you really want them as an array, just call ToArray() on it outside the function (i.e. GetSnapshots().ToArray()).

Even if you'd rather not do that, you should still change numbers that are used multiple times (in your case: 60, 90, 120, 180, 220) into named constants, unless they're entirely unrelated.


Populating monthly report with new data each month

Let me start with a number of general guidelines that can make your code more maintainable and more reusable. After that I will give some more specific advise regarding your code.

General Guidelines

Good variable names are one of the best ways to document what your code is doing. If someone else ever reads your code, he will be very grateful in case the variable names actually tell him what the variables are. This might actually also apply to yourself coming back to code after a few month. In the case of FindDate you are already using a good name. However, I have absolutely no idea what PTNUM is.
Try to follow the single responsibility principle. In short it states that a unit of your code, e.g. a procedure, should do one and only one thing. This leads to shorter more focused procedures that are easy to understand. Combined with good naming, this makes nearly all comments unneccesary. Admittedly, often it is rather hard to get this principle really right.
Do not use magical numbers, like e.g. 1 and 11 in your code. Either declare a constants minVerticalOffset and maxVerticalOffset or even pass these as parameters.
Do not hard-code configuration all over the place. Your comments show that you have to adjust the code in several places every year. Instead you should rather extract all but the configuration into a parametrized procedure that you call from Copy_Data.
Explicitely declare the scope of procedures and variables, i.e. declare them as Private, Public or Friend.
Declare you variables close to where you actually use them. I know that this contradicts with old coding conventions for VBA, but having the declaration right before its use makes it clear of what type the variable is without any need of a naming convention.
Rather VBA specific, use Long in favor of Integer if you do not specifically want to limit the range to that of an integer. As explained in the answer to this SO question every Integer is internally converted to a Long anyway on any halfway modern system.

Specific Advice

As I hinted at already above, the variable names in all caps could use some work. E.g. the variable X could be renamed to verticalOffset.
Getting more specific regarding point 4 above, it might be of great use for reusability to extract the body of the procedure into its own (private) procedure with three parameters:  TurnoverSheet As WorkSheet, FindDate As Date, DataSheet As worksheet. The names might need a little work, though. The parameters would then be passed in when calling the procedure from Copy_Data.
Most probably, your code contains a hard to see bug. Inside the with blocks, the Range(AddressString) is not prefixed with a dot. Thus, it refers to the range on the active sheet. This means that this procedure only works when called from the sheet Turnover2017.
Your three With blocks all refer to the same variable. Hence, they can be combined into one and even be pushed outside the For loop.
When using Range.Find you should always consider the possibility that there is no search result. In this case Nothing is returned. This would lead to runtime errors whan trying to call anything on it. So, you might want to test the result range for Is Nothing.
From your code I get the impression that you first only want to search in the first row, then  only in the 18th row and then only in the first column. If this is the case, then you should actually use the appropriate ranges. (This would also make the use of the optioanl parameter SearchOrder obsolete, which contains the very subtle difference between the first and third search.)
The performance could be improved by pushing the searches out of the For loop. Your searches are independent of the value of X. So, at the moment, you are performing the same work for each value of this variable. If you have really large worksheets, this wastefulness can be a problem.
After pushing the searches out of the For loop, you can eliminate the loop alltogether. To do this wyou have to load the three sets of data each into a two dimensional array by assigning the Value property, or better Value2 property, of the the corresponding ranges to a Variant variable. (See this blog post for why to use Value2.) Then the values can be assigned to the target ranges by setting the Value property of the top left cell of the target range to the corresponding array. This is much faster then itterating over the cells because accessing the worksheet is rather slow.


Processing a sequence of additions and deletions

So I made your code a function and then ran it on the example you gave.
I got to the following code:

def shift_indexes(dellist, addlist):
    ii = jj = kk = 0
    plus = minus = 0
    while ii < len(dellist) or jj < len(addlist):
        if jj < len(addlist):
            if addlist[jj] == kk:
                addlist[jj] -= minus
                addlist[jj] += plus
                jj += 1
                plus += 1
        if ii < len(dellist):
            if dellist[ii] == kk:
                dellist[ii] -= minus
                ii += 1
                minus += 1
        kk += 1
    return dellist, addlist

dellist = [4, 5]
addlist = [2, 6]
print('del: {}\nadd: {}'.format(*shift_indexes(dellist, addlist)))

It works fine with the input you gave, but it doesn't when I change addlist to 6, 2 not 2, 6.
And so I'll 'white box' test your code:

if addlist[0] == 0: # 6 == 0 : False
kk += 1             # kk = 1
if addlist[0] == 1: # 6 == 1 : False
kk += 1             # kk = 2
if addlist[0] == 2: # 6 == 2 : False
kk += 1             # kk = 3
if addlist[0] == 3: # 6 == 3 : False
kk += 1             # kk = 4
if addlist[0] == 4: # 6 == 4 : False
kk += 1             # kk = 5
if addlist[0] == 5: # 6 == 5 : False
kk += 1             # kk = 6
if addlist[0] == 6: # 6 == 6 : True
jj += 1             # jj = 1
kk += 1             # kk = 7
if addlist[1] == 7: # 2 == 7 : False
kk += 1             # kk = 8
if addlist[1] == 8: # 2 == 8 : False
...                 # loop for ever

The error is clear!

Ok, so lets change this.
We know that the deletes and the adds are in an order,
and that order is important!
We should be able to guess that inserts and removals should be able to happen anywhere.
We need the algorithm to work with numbers in any order.

And so honestly I'd recommend a new algorithm.

To make all the code easier I'd highly recommend that you change the input,
this input should be a list in the order you want to add and remove.
The items in this list should be (operation, index).

To save you figuring out how to change your current input to this form. You want to:

Make two lists. One of operations, one of indexes.
zip lists together.
Change list to list of list, from list of tuples (Python2) or iterator of tuples (Python3).

And so:

list_ = [list(i) for i in
         zip(['del'] * len(dellist) + ['add'] * len(addlist), dellist + addlist)]

Not too nice to read, but it makes the algorithm much nicer!
Your plus minus method doesn't work, and so I'm not going to talk about modifying it.

And so the simplest method from this is to transform the list_ whilst iterating through it.
When iterating we will want to pass it through enumerate this is to get the index in list_,
we also want the operator and the index that we want to shift relative to.
This results in:

for i, (operation, curr_index) in enumerate(list_):

From this we want to skip any operations that we don't know.
If you later decide to remove the horrible zip list comprehension stuff.
This is a simple if ...: continue:

if operation not in ('add', 'del'):
    continue

And now the main part of the algorithm.
You want to change the indexes after that item by +1 if the operator is add otherwise -1.

change = 1 if operation == 'add' else -1

You then want to add the change to all the items following the current item if the index is greater than the current one.
And so:

i += 1
for j, (_, index) in enumerate(list_[i:], i):
    if index >= curr_index:
        list_[j][1] += change

If we merge this all together, you should get:

def shift_indexes(dellist, addlist):
    # Transform input to better format
    list_ = [list(i) for i in
             zip(['del'] * len(dellist) + ['add'] * len(addlist), dellist + addlist)]
    for i, (operation, curr_index) in enumerate(list_, 1):
        if operation not in ('add', 'del'):
            continue
        change = 1 if operation == 'add' else -1
        for j, (_, index) in enumerate(list_[i:], i):
            if index >= curr_index:
                list_[j][1] += change
    return list_

If you have more than just add and del then you may want to use a dictionary.
The current 'dictionary' we have is:

d = {
    'add': 1,
    'del': -1
}

To use this dictionary you'd change the if and how to get change.
Using dict.get to get the change or None if it's not a valid item then we can use:

change = d.get(operator, None)
if change is None:
    continue

Either way this is much simpler to what you were doing.


I assume you refer to https://cses.fi/problemset/task/1071/ .
Your Algorithm itself is fine as far is i can tell.
The Problem is the large amount of inputs that need to need to be read(Testcases=100000), which Scanner cant provide within the 1s time limit.
A BufferedReader should offer the performance needed for this.(See https://www.geeksforgeeks.org/fast-io-in-java-in-competitive-programming/ for more information).
The same might apply to System.out.println in which case it would be better to use a BufferedWriter


Your initMap function is called by the Google Maps' DOM listener.  I would actually move this to the anonymous window.onload function that you have.

The reason is is more philosophical than practical.  You're trying to use Google maps' api to initialize your maps objects.  It seems un-intuitive that Maps should initialize maps.

If Google ever changed their API for their DOM listener, it could mess up this functionality.

The only other issue I would consider is some protection against the initMap being called twice.  Just a flag at the top or something simple like that:

if (mapsInitialized)
    return;
mapsInitialized = true;


Utility Method to find the Square root of a number

Duplicated logic

Avoid duplicated logic like this:

public static boolean closeEnough(double a, double x, double epsilon) {
    return (Math.abs(x - ((a / x) + x) / 2)) <= epsilon;
}

public static double betterGuess(double a, double x) {
    return ((a / x) + x) / 2;
}

The closeEnough method includes the exact same logic as betterGuess.
Make it a habit to look at duplicated code fragments with suspicion.

If you eliminate the duplication, the code becomes:

public static boolean closeEnough(double a, double x, double epsilon) {
    return (Math.abs(x - betterGuess(a, x))) <= epsilon;
}

public static double betterGuess(double a, double x) {
    return ((a / x) + x) / 2;
}

... but then, does this actually make sense? Calling betterGuess from closeEnough? Not really. How can you check if a candidate square root is close enough? You cannot compare with the real square root, because that's the target unknown. What you can compare with, is the original number, which you should be able to get by squaring:

public static boolean closeEnough(double a, double x, double epsilon) {
    return Math.abs(a - x * x) <= epsilon;
}

This implementation is more logical, and has another positive side effect:
it makes it possible to clean up the squareRoot method with the suspicious 0-check:

public static double squareRoot(final double a, final double epsilon) {
    if (a == 0)
        return a;
    else
        return internalSqrRoot(a, a / 2, epsilon);
}

The method can become simply:

public static double squareRoot(final double a, final double epsilon) {
    return internalSqrRoot(a, a / 2, epsilon);
}

It would seem the 0-check was there to prevent a division by zero problem in Math.abs(x - ((a / x) + x) / 2))

Method visibility

The MathUtil class name suggests it's a utility class,
but the public MathUtil.betterGuess method (to name just one) doesn't seem very useful.
It's an implementation detail that should be hidden, so make it private.
Question the other methods too, and change their visibility as appropriate.

The variable names are quite poor.
For example in closeEnough it's impossible to tell if the target number is a or x.
target and candidate might have been better names.

Input validation

More than just commenting "Function takes a non-negative real number ",
it would be better to enforce that by throwing an IllegalArgumentException.

Poor JavaDoc

This kind of JavaDoc is worse than no JavaDoc at all:

/**
 * Method internalSqrRoot.
 *
 * @param a double
 * @param x double
 * @param epsilon double
 * @return double
 */

It's worse, because tells nothing new about the method,
but since it's there, I've read it, in vain.

Minor things

It's recommended to use braces even with single-line if statements
Redundant parentheses in the expression (Math.abs(x - ((a / x) + x) / 2))
Perhaps instead of internalSqrRoot, squareRootHelper might be a better name. Or, since the method has a different signature than squareRoot, it can just as well be squareRoot (overloading)


You have a wrong assumption here. await never starts a new thread! Strictly speaking even Task.Run might not start a new thread since it uses the thread pool.

See this answer for more details on await: https://stackoverflow.com/questions/16978904/async-programming-control-flow/16980183#16980183


Looks pretty good. I have a few suggestions though:

There should be a way to exit (maybe if you don't type anything when it asks which dictionaries?)
You should probably use urllib.parse.urljoin instead of +.
You should probably use recursion instead of using while True then always breaking or continueing.
You don't need parentheses when returning tuples.
Bare raise statements are for reraising exceptions. Otherwise, it gives you RuntimeError: No active exception to reraise.
Don't use bare except.
I would probably use a list of tuples instead of using zip.
You could pass around the whole list instead of its length.
You can use enumerate(iterable) instead of zip(range(len(iterable)), iterable). What enumerate does is create an iterable that when iterated, yields tuples of increasing numbers starting with 0 and the next item from the iterable (in your case a list) you are enumerating. More info at the Python Docs.
You should handle the logic for * in one place.
Contained the logic for handling numerals within the get_user_data function.
You should probably name your main function main instead of __main__.
Don't combine multiline strings and '\n'.
It might be good to have it display the result directly in the console instead of the web browser, but that would be a whole other project.
You should probably return directly instead of using break.
I might have made a few other minor changes.

Note that some of the changes are just personal preferences.

The result (also available at https://repl.it/@solly_ucko/DictionarySearchCodeReview):

import webbrowser
from urllib.parse import urljoin

class OnlineDictionary:
    """Represents an online dictionary.

    Attributes:
name: str
url: str
    """
    def __init__(self, name, url, sep):
        """Initializes an OnlineDictionary object.

        name: str
        url: str
        sep: str
        """
        self.name = name
        self.url = url
        self.sep = sep

    def search(self, query):
        """Searches the dictionary for a given query.

        url: str
        query: str
        """
        query = self.sep.join(query.split())
        webbrowser.open(urljoin(self.url, query))

def print_instructions(message, instructions, dictionaries):
    """Prints the available dictionaries, their corresponding
    numerals and the instructions.

    message: str
    instructions: str
    names: list
    num_of_dics: int
    """
    print(message)

    for numeral, (name, _, _) in enumerate(dictionaries):
        print(numeral, name)

    print()
    print(instructions)

def get_user_data(dictionaries):
    """Asks the user for which dictionary
    to use and for what to search for.

    num_of_dics: int

    Returns: tuple
    """

    while True:
        to_use = input('Specify which dictionary or dictionaries to use.\n')

        if to_use == '':
            return (), ''
        elif to_use == '*':
            to_use = dictionaries
        else:
            try:
                to_use = to_use.replace(' ', '').split(',')
                numerals = []

                for num in to_use:
                    num = int(num)

                    if num not in range(len(dictionaries)):
                        raise ValueError

                    numerals.append(num)

                to_use = set(map(dictionaries.__getitem__, numerals)) # set is used to get rid of duplicates
                query = input('Type something to search for.\n')
                return to_use, query
            except ValueError:
                continue

def main():
    dictionaries = [
        ('Merriam-Webster Dictionary', 'https://www.merriam-webster.com/dictionary/', '%20'),
        ('Oxford Dictionary', 'https://en.oxforddictionaries.com/definition/', '_'),
        ('Camberidge Dictionary', 'https://dictionary.cambridge.org/dictionary/english/', '-'),
        ('Collins Dictionary', 'https://www.collinsdictionary.com/dictionary/english/', '-'),
        ('Longman Dictionary of Contemporary English', 'https://www.ldoceonline.com/dictionary/', '-'),
        ('The American Heritage Dictionary of the English Language', 'https://ahdictionary.com/word/search.html?q=', '%20')
    ]

    message = 'These are the available dictionaries:\n'

    instructions = """To use a dictionary type its corresponding numeral.
To use more than one dictionary separate the numerals with ",".
To use all of them type "*". Do not type the quotation marks.
"""

    print_instructions(message, instructions, dictionaries)

    while True:
        to_use, query = get_user_data(dictionaries)

        if not to_use or not query:
            break

        print()
        chosen_dictionaries = [OnlineDictionary(name, url, sep) for name, url, sep in to_use]

        for dictionary in chosen_dictionaries:
            print('Searching %s for "%s"...' % (dictionary.name, query))
            dictionary.search(query)

        print('Finished searching. Check your Web browser.\n')

if __name__ == '__main__':
    main()


Create histogram with greater than symbol in x axis in pyplot

Nice work! You might also be interested in Matplotlib histogram with collection bin for high values.

I like the ascii-art explanation :-)

Things I see that could improve the code:

Put the histogram building in a function. This way others can import it / use it / copy-paste it more easily. Then it also becomes clearer what is the required input (data) and what are parameters that could be set by default (K, bins, title).
The name center is misleading. It is a list. And in fact those are the bins. So I would call it bins, overwriting the old value.
Instead of newhist you could call it bin_values or bin_heights.


Reverse Polish Notation shell interpreter with one variable in C

Here are some ideas for improving your program.

Use the correct prototype for main

Many compilers will default to an int return type when the function return type is undeclared, but it's not a good idea to omit it, especially with main.  Instead of this:

main () {

write this:

int main() {

Eliminate global variables where practical

The code declares and uses 5 global variables.  Global variables obfuscate the actual dependencies within code and make maintainance and understanding of the code that much more difficult.  It also makes the code harder to reuse.  For all of these reasons, it's generally far preferable to eliminate global variables and to instead pass pointers to them.  That way the linkage is explicit and may be altered more easily if needed.  In this case, I'd suggest gathering everything together into a structure within main's scope and then passing that structure to each of the functions.  For example, it might be defined like this:

typedef struct stack_s {
    int sp;
    int bufp;
    double x;
    double stack[MAXSTACK];
    char buf[BUFSIZE];
} StackMachine;

And then within main it could be defined like this:

StackMachine sm = { .sp = 0, .bufp = 0 };

Then push could be reimplemented like this:

void push(StackMachine *sm, double f) {
    if (sm->sp < MAXSTACK)
        sm->stack[sm->sp++] = f;
    else
        printf(CRED "ERROR: Stack is full, cannot push %g\n" CRESET, f);
}

Be consistent with the user interface

When the user uses an empty line to see the top of the stack, it reports 0 instead of STACK EMPTY when the stack is empty.  This is inconsistent with the other operations.


Refreshing customer list periodically in the background

You are probably right in not using Task.Factory.StartNew. You should prefer Task.Run instead. Task.Run explicitly uses the default task scheduler which targets the thread pool while StartNew uses whatever the last used scheduler was.
I'm not sure you really need to distinguish the case between "I have to wait before refresh" and "I can run refresh now". The second one is just a special case of the first one with a delay of 0. Yes you may waste a scheduling cycle or two due to calling Delay but will 20ms or so really make a difference?
You have a bug: If your application runs when the system clock gets adjusted for DST the time can go backwards by 1h between one check an the next. The result will be that intervalFromLastRefresh is going to be negative in which case you will wait up to an hour extra before refreshing (we just hit this exact bug in one of our apps recently so the pain is still fresh ...).

With the above in mind you could simplify your implementation to:

private Task RefreshCustomers()
{
    lock (_refreshLock)
    {
        // If there is already a refresh task, just return this one.
        if (_refreshTask != null)
            return _refreshTask;

        // Check if the time between this refresh request and the previous one is too close.
        var intervalFromLastRefresh = DateTime.Now - _lastRefreshTime;

        var delay = MinimumRefreshInterval - intervalFromLastRefresh;
        if (delay < TimeSpan.Zero)
        {
            delay = TimeSpan.Zero;
        }
        else if (delay > MinimumRefreshInterval)
        {
            delay = MinimumRefreshInterval;
        }

        return _refreshTask = Task.Run(async delegate { await Task.Delay(delay); RefreshCustomersInternal(); })
                                  .ContinueWith(t => { lock (_refreshLock)
                                                        {
                                                            _refreshTask = null;
                                                            _lastRefreshTime = DateTime.Now;
                                                        } });
    }
}


Extending UITableViewCell to preserve UIView background color when selecting the cell

This is a very strange approach for quite a few reasons.

First, the fact that this is an extension of UITableViewCell makes absolutely no sense to me.  The method is completely procedural.  It takes in an array of views (any views... from any where).  From these views, it creates an array of colors to preserve the current background color.  Then executes a function, f (which by the way, SwiftLint would never allow a single-letter variable name like this) (and you should definitely be using SwiftLint).  And function f may or may not even change the colors of any of these views.  And then we use parallel arrays, a very procedural approach, to reset these colors.

And would we even notice the color change at all?

Or is the intent here to hide the color change?

As for a more concrete review of some of the code you have, this function:

private func backgroundColors(views: [UIView]) -> [UIColor?] {
    var colors = [UIColor?]()
    for view in views {
        colors.append(view.backgroundColor)
    }
    return colors
}

Could be replaced with a single line of code.

let backgroundColors = views.map { $0.backgroundColor }

But... to make our code less procedural... why don't we build a tuple array:

let viewColorPairs = views.map { ($0, $0.backgroundColor) }

And then when it comes time to reset the background colors:

for (view, color) in viewColorPairs {
    view.backgroundColor = color
}

So now we've eliminated your first two functions, and your preserveBackgroundColors function is simplified into:

func preserveBackgroundColors(views: [UIView], @noescape closure: () -> Void) {
    let viewColorPairs = views.map { ($0, $0.backgroundColor) }
    closure()
    for (view, color) in viewColorPairs {
        view.backgroundColor = color
    }
}


Getting the count of how many times a route has been hit

The Enumerable.group_by method is perfect for situations like this. The method takes the items in the enumerable, evaluates a block on them to yield a key, and inserts them into a hash under that key. Using this the code is very short:

puts(File.open('test.log').entries
    .group_by { |line| line.split(" ")[4] }
    .map { |k, v| "#{k},#{v.count}" })


Implementation of Strategy Pattern (photo gallery example)

I would use dependency injection. Something like

serviceCollection
   .AddTransient<IShareStrategy, ShareOnFacebook>()
   .AddTransient<IShareStrategy, ShareOnTwitter>()
   .AddTransient<IShareStrategyProvider, ShareStrategyProvider>();

public class ShareStrategyProvider : IShareStrategyProvider
{
   private readonly IEnumerable<IShareStrategy> _strategies;
   public ShareStrategyProvider(IEnumerable<IShareStrategy> strategies)
   {
      _strategies = strategies;
   }

   public GetStrategy(ShareStrategy sharingStrategy);
   {
      return _strategies.Single(s => s.SharingStrategy == sharingStrategy);
   }
}

edit: Read up on open/closed principle, its related


Exposing WCF Service with dynamic search operation

Without knowing its intended audience (Intranet / Internet), I'm assuming Intranet.

In my opinion, you are giving a lot of flexibility to this service in one method call, which isn't immediately clear how a user would structure a call to this. The caller has to have knowledge of a "propertyId" which doesn't make too much sense on a glance. I hope your API documentation describes this well, and how the user would retrieve what these IDs are.

So here is my assumption of the coded interface:

public interface ISearchService
{
    List<object> Search(string clientId, IEnumerable<PropertyQuery> propertyQueries);
}

// Element
public class PropertyQuery
{
   // Attribute
   public string PropertyID { get; set; }

   // Array
   public IEnumerable<Value> Values { get; set; }

   // Attribute
   public byte AND { get; set; }

   // Attribute
   public byte OR { get; set; }

   // Element
   public string Operator { get; set; }
}

// Element
public class Value
{
   // Attribute
   public int Id { get; set; }

   // Attribute
   public byte Start { get; set; }

   // Attribute
   public byte End { get; set; }

   // Text
   public string Text { get; set; }
}

To make this a little simpler, I would add a single class that takes all parameters and a class returning the results, following the Request/Response pattern. This means that the interface can change over time, and should not affect backwards compatibility.

public interface ISearchService
{
   // Gets the search criteria for the screen
   SearchCriteriaResponse GetSearchCriterias(SearchCriteriaRequest request);

   // Searches by the search criteria
   SearchResponse SearchBy(SearchRequest searchCriteria);
}

// Base elements for a response
public abstract class ResponseBase
{
   public bool Success { get; set; }
   public string Message { get ; set; }
}

public class SearchCriteriaResponse : ResponseBase
{
   public string[] DocumentTypes { get; set; }
   public string[] BankName { get; set; }
}

public class SearchResponse : ResponseBase
{
   public IEnumerable<SearchResult> Results { get; set; }
}

public class SearchRequest
{
   public string ClientId { get; set; }
   public string[] BankNamesToMatchExactly { get; set; }
   public string[] BankNamesToPartiallyExactly { get; set; }
   public string[] DocumentTypesToMatchExactly { get; set; }
   public string[] DocumentTypesToPartiallyExactly { get; set; }
   public DateTime? StartDate { get; set; }
   public DateTime? EndDate { get;set; }
   public bool CheckBetweenDates { get; set; }
}

This interface is a more clean on its approach. Its slightly larger, but it makes the ORing and ANDing much more obvious. It also makes the code cleaner at the service side as each of these properties have well-named properties and should be easy to implement:

public List<SearchResponse> SearchBy(SearchRequest searchCriteria)
{
   IQueryable dbQuery = DbContext.BankNames;

   foreach(var bankName in searchCriteria.BankNamesToMatchExactly)
   {
      dbQuery = dbQuery.Where(bn => bn.BankName == bankName);
   }

   foreach(var bankName in searchCriteria.BankNamesToMatchPartially)
   {
      dbQuery = dbQuery.Where(bn => bn.BankName.Contains(bankName);
   }

   // etc..
}


Get users that are presidents and compute their name

why do you have a 1:n relation? you can just add a 1:1 or column to your user table which has a type column for example and it holds president or vice-president values and then you can have a function in your model to check if it's a president or vice-president.

You can add a function to your repository to get all user which they are president with a simple query.


Easily registering WordPress custom post types and taxonomies

Of course it's ok. You will have 1 object per post type. GetInstance is called factory method.
I have noticed two strange things in your code:

PostType.php Line 116

Why do you use random here? It will be ok if you leave default priority param.

PostType.php Line 123
You call toSlug function before slug usage but it's better to call it when name was setted up here PostType.php Line 380

This way you will never forgot to call toSlug before slug usage.


Save handler without a nested "deferred antipattern"

You can also leave out reject. Your code would look like:

function save() {
    return confirm().then(function(response) {
        return commit();
    });
};

The promise returned by then() will automatically be rejected if the promise returned by confirm() is rejected.

Combining with @ShaunH's answer you would be left with

function save() {
    return confirm().then(commit);
};


Downloads historical data from a yahoo finance csv and returns a pandas DataFrame

You could be using pandas DataFrame.read_csv method, instead of manually going through csv.reader first (you need to go through StringIO, though...):

try:
    from io import StringIO
except ImportError:
    # python 2.x
    from StringIO import StringIO
...

class Fetcher:
    ...

    def getHistorical(self):
        """Returns a list of historical data from Yahoo Finance"""
        data = requests.get(self.url, cookies={'B':self.cookie})
        content = StringIO(data.content.decode("utf-8"))
        return pd.DataFrame.read_csv(content, sep=',')

If you didn't need the cookie, you could just do the following, alas you can't get around that part...

    def getHistorical(self):
        """Returns a list of historical data from Yahoo Finance"""
        return pd.DataFrame.read_csv(self.url, sep=',')

I would also expect a class called Fetcher to accept an url parameter to determine where it is fetching from (hence I already used self.url above). Since it is some arcane API url here, I would make it at least a class variable that can be modified if needed in a sub-class or on-the-fly:

class Fetcher:
    api_url = "https://query1.finance.yahoo.com/v7/finance/download/%s?period1=%s&period2=%s&interval=1d&events=history&crumb=%s"

    def __init__(self, ticker, start, *args):
        self.ticker = ticker.upper()
        self.cookie, self.crumb = self.init()

        self.start = int(time.mktime(dt.datetime(start[0],start[1],start[2]).timetuple()))

        if args:
            end = args[0]
            self.end = int(time.mktime(dt.datetime(end[0],end[1],end[2]).timetuple()))
        else:
            self.end = int(time.time())
        self.url = self.api_url % (self.ticker, self.start, self.end, self.crumb)

    ...

if __name__ == "__main__":
    fetcher = Fetcher(...)

I also added a section for you to actually call the code, guarded by a if __name__ == "__main__": guard.


It seems you are iterating the sets a lot with the Except method and possibly the ToArray.

Consider iterating the sets at most once:

public static bool SetEqual<T>(this IEnumerable<T> source, IEnumerable<T> other, IEqualityComparer<T> comparer = null)
{
    if (source == null)
        throw new ArgumentNullException("source");

    if (other == null)
        throw new ArgumentNullException("other");

    if (source is ICollection &&
        other is ICollection &&
        ((ICollection)source).Count != ((ICollection)other).Count)
        return false;

    HashSet<T> set;
    if (comparer == null)
        set = new HashSet<T>(source);
    else
        set = new HashSet<T>(source, comparer);

    return set.SetEquals(other);
}

Source IEnumerable implementation.


Returning early makes code not follow the arrow anti-pattern. And makes the flow of the code simpler.
There's otherwise not much to comment on.

class LoginSerializer(serializers.Serializer):
    phone = serializers.CharField()
    password = serializers.CharField()

    def validate(self, data):
        phone = data.get("phone", "")
        password = data.get("password", "")
        # need simplify the structure below
        if not (phone and password):
            raise exceptions.ValidationError('Must provide username and password both.')

        user = authenticate(phone=phone, password=password)
        if not user:
            raise exceptions.ValidationError('Unable to login with given credentials.')

        if not user.is_active:
            raise exceptions.ValidationError('User is deactivated.')

        data['user'] = user
        return data


Your DayOnWeek object is mutable, allowing you to set the .day_number property.  For such a simple object is not a good idea.  An immutable object is better.
There are exactly 7 days of the week.  For a one-of-seven choice, the go-to data-storage structure is an Enum.  For example:
from enum import Enum

class DayOfWeek(Enum):
    Sunday = 1
    Monday = 2
    Tuesday = 3
    Wednesday = 4
    Thursday = 5
    Friday = 6
    Saturday = 7

    @property
    def weekend(self):
        return self in {DayOfWeek.Saturday, DayOfWeek.Sunday}

    @property
    def category(self):
        return 'Weekend' if self.weekend else 'Business day'

    @property
    def number(self):
        return self.value

Borrowing Reideerien's request_day_number() function you'd use the DayOfWeek enum like:
def main():
    day_no = request_day_number()
    day = DayOfWeek(day_no)

    print(f'Day {day.number} is {day.name}')
    print(f'{day.name} is a {day.category} day')

if __name__ == '__main__':
    main()


How would you better organize/code this basic HTML and CSS?

A lot of this type of stuff is just personal style, or if you're working on a team, the layout is defined ahead of the project.

The use of classes vs id's is also personal. I've seen people say that they ALWAYS use classes. I've tried both classes and id's on many pages, and I find that I get into fewer problems with mostly classes, reserving id's for truly individual elements.

I've read that the stuff at the top of your CSS can slow things down quite a bit and may not be necessary in many cases.

I formatted the last two parts of your CSS a bit differently. I do that a lot with PHP, but have seen in recently in CSS, and I think it might work nicely in some situations.

But for fun...

<!DOCTYPE html>

  <title>Alpha Tau Omega | Theta Omega</title>
  <link rel="stylesheet" type="text/css" href="ATOStyle.css" />

Home

Rush

History

Alumni

Calendar

Media

CSS

html, body, div, span, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
abbr, address, cite, code,
del, dfn, em, img, ins, kbd, q, samp,
small, strong, sub, sup, var,
b, i, dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, figure, footer, header,&nbsp;hgroup, menu, nav, section, menu,
time, mark, audio, video {
  margin: 0px;
  padding: 0px;
  border: 0px;
  outline: 0px;
  font-size: 100%;
  vertical-align: baseline;
  background: transparent;
}
#navbar ul {
  list-style-type: none;
  margin: 0px;
  padding: 0px;
}
#navbar ul li a {
  text-decoration: none;
  color: black;
}
#navbar ul li a:hover {
  color: white;
}
#navbar ul li {
  font-family: Arial, Helvetica, sans-serif;
  text-decoration: none;
  color: #000000;
  display: inline-block;
  width: 70px;
  height: 40px;
  margin: 10px;
}
#banner {
  background:url(./pieces/banner.png);
  position: absolute;
  margin-left: 0px;
  min-height: 193px;
  min-width: 183px;
  background-repeat: no-repeat
}

#title {
  position: absolute;
  background: url(./pieces/name.png);
  margin-left: 190px;
  min-height: 75px;
  min-width: 285px;
}
#navbar {
  position: relative;
  top: 80px;
  left: 210px;
  margin-left: inherit;
}
#social ul li{
  display: inline-block;
  width: 35px;
  height: 35px;
  margin: 5px;
}
#social {
  position: absolute;
  float: left;
  right: 180px;
  top: -5px;
}
#social ul {
  list-style-type: none;
}

#innerheader {
  height: 139px;
  width: 750px;
  margin-right: auto;
  margin-left: auto;
  position: relative;
}

#header {
  background:url(./pieces/headerBar.png);
  position: static;
  width:100%;
  height:139px;
  z-index: 10000;
}

#pagecenter {
  position: static;
  margin-right: auto;
  margin-left: auto;
  height: 50px;
  width: 750px;
  min-height: 1000px;
  background: url(./pieces/mainBG.png);
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;
  margin-top: -19px;
  z-index:50
}
body {
  width: 100%;
  margin: 0px 0px 0px 0px;
  background-color: #808080
}
#footer {
  margin-top:   20px;
  padding-top:  30px;
  background:   url(./pieces/footerbar.png);
  height:       77px;
  width:        100%;
  margin-right: auto;
  margin-left:  auto;
  clear:        both;
  bottom:       0px;
  position:     static;
}
#footerbanner {
  background:        url(./pieces/footerbanner.png);
  position:          absolute;
  min-height:        95px;
  min-width:         90px;
  background-repeat: no-repeat;
  margin-top:        -30px;
}


Parse.com simple query: login and display account balance

Promises

Promises are the next big thing in JavaScript. You can read more about them here. Luckily, Parse supports Promises and you should make good use of them.
Essentially, Promises will replace the messy callback pyramid structure you have here

Parse.User.logIn("user", "pass", {
  success: function(user) {
    ...
      success: function(results) {
        ...
          success: function(result) {
            ...
          },
          error: function(result, error) {
            // error
          }
        });
      },
      error: function(error) {
        // error
      }
    });
  },
  error: function(user, error) {
    // error
  }
});

Promises use the then function, which can be given callbacks to be called when the promise is fulfilled or has failed. Promises can also propogate errors, not calling any callbacks until an error handler is encountered. So, your code can be re-written as:

Parse.User.logIn("user", "pass").then(function(user) {
  return query.find();
}).then(function(results) {
  // ...
}).then(function(result) {
  // ...
}, function(error) {
  // error
});

One thing to remember that a successful promise does not imply the Parse Query itself was successful. A successful promise simply means your query was successfully executed, regardless of what value was returned by the query. So, make sure to check the return value from Parse:

.then(function(result)){   // Promise succeeded
  if(!result){             // check if return is not null
    // do something
  }
})

 Duplicated event handling

You have this

$(document).ready(function () {

and then you also have this

$(function () {

Why? Just put all the content inside the .ready function and you are good to go

Beware of Javascript string concatenation

This is one of the most naive mistakes:

document.write("Insufficient funds. Must have " + balance + charge + " balance left");

Let's assume balance=10 and charge=20. You expect it to print :

Insufficient funds. Must have 30 balance left

What it will actually print is:

Insufficient funds. Must have 1020 balance left

String concatenation in javascript is not well-defined when types get mixed. In your case string + int types are getting mixed. What you need to do instead is:

document.write("Insufficient funds. Must have " + (balance + charge) + " balance left");

Notice the parantheses besides the int types.

Mixing logic and view

You are mixing your logic. Look here

document.write(mssg);

Code that is rendering the view such as document.write should be handled in a separate function. It becomes very messy and hard to debug when you combine your logic-side and view-side code in one place. Read up on MVC (Model-View-Controller).

Illusion of binding

Take a look here why dropping brackets and misleading indentation can have unforeseen consequences

if(balance < charge)
  document.write("Insufficient funds. Must have " + b + ch + " balance left");
else if(balance  == charge)
  document.write("Oops!");
  document.write("Sorry, balance cannot reach zero");

At what times do you think "Sorry, balance cannot reach zero" message will be printed? Will it be printed only when balance == charge? Unfortunately, no! It will be printed every single time!

Why? Because your indentation leads to you believe that the 2nd document.write statement is bound to the else clause, when infact it isn't. Dropping brackets might make code look more clean & readable, but make sure you don't let the indentation give you false illusion of binding.

Avoid unnecessary string creation

In Javascript, strings are immutable. When you do something like this

var mssg = "";
for(var i=0; i<arr.length; i++) {
    mssg += arr[i] + " ,";
}

it isn't "modifying" the mssg string, but instead creating a new string on every iteration. For large iterations, say a million, you will definitely have a performance hit. Other languages like C# solve this problem by using a StringBuilder class, but for Javascript you can use the join() method instead

var mssg = arr.join(", ");

Incorrect code

document.write(today - 1 + 1);

Why are you doing this? What is the purpose of -1 + 1?
To me, it seems like you are trying to convert the date to an int. But you wouldn't need to do that if you hadn't done this earlier

var day = '' + d.getDate();

Don't add the empty string to the date in the first place. Just leave it as this

var day = d.getDate();

 Underscore.js

Naive summation operations such as

function sumArray(arr) {
    var S = 0;
    for(var i=0; i<arr.length; a++){
        S += arr[i];
    }
    return S;
}

can be replaced by powerful helper functions provided by the Underscore.js library. Using reduce() function, we can re-write it as follows:

// return sum of all elements of an array
var sum = _.reduce(arr, function(memo, num){ return memo+ num; }, 0);
return sum;

Lacking comments

Please always comment your code.


fread (tmp1, sizeof *tmp1, readsz, fp1);
fread (tmp2, sizeof *tmp2, readsz, fp2);
count += 16;
if(memcmp(tmp1, tmp2, readsz)){
    …
}

You are discarding the return values of the fread() calls, blindly assuming that they both successfully read 16 bytes.

It is unclear what the return value of compare_two_binary_files(…, …) means.  In fact, you sometimes don't return a value at all.  Your compiler should have warned you about that problem.

File I/O should be done a block at a time: 512 bytes, 1024 bytes, or 2048 bytes would be a more reasonable chunk size than 16.

Technically, most of the time is spent waiting for I/O.  cpu_time_taken is a misnomer: what you're measuring is called "wall clock time".


Ways to improve:

simplifying list construction:

*list(x if x != '0' else ' ' for x in board)) --> *[x if x != '0' else ' ' for x in board]
check_diagonal function. The function performs a logical check if the passed row is fully selected/marked with the same mark/code and returns boolean result respectively.Therefore, it's better to give it a more meaningful and unified name, say row_crossed (reflecting boolean purpose):

def row_crossed(row):
    return '0' not in row and len(set(row)) == 1

Besides, renaming it will serve beneficially for the next improvements (see below)
2 consecutive conditions:

if check_diagonal(a.diagonal()):
    return True

# check rl diagonal
if check_diagonal(np.fliplr(a).diagonal()):
    return True

return the same boolean result. That's a sign for Consolidate conditional expression technique.Thus, the flow becomes:

# check lr diagonal
if row_crossed(a.diagonal()) or row_crossed(np.fliplr(a).diagonal()):
    return True

the for loop (in check_for_win function) which iterates through pair of  matrices (initial and transposed one) duplicates the same logical check

 ...
 if '0' not in row and len(set(row)) == 1:

as row_crossed (formerly check_diagonal) function does. Thus, replacing duplicated condition with function call.Eventually, the restructured check_for_win function would look as below:

def check_for_win(board):
    def row_crossed(row):
        return '0' not in row and len(set(row)) == 1

    a = np.array(board).reshape(3, 3)

    # check lr diagonal
    if row_crossed(a.diagonal()) or row_crossed(np.fliplr(a).diagonal()):
        return True

    # check rows & cols
    for matr in (a, a.transpose()):
        for row in matr:
            if row_crossed(row):
                return True

    return False

Actually, the above Consolidation of conditionals can be even more encompassing with applying np.concatenate and builtin any functions, though may seem less readable but quite viable for those who likes concise/compact code:

def check_for_win(board):
    def row_crossed(row):
        return '0' not in row and len(set(row)) == 1

    a = np.array(board).reshape(3, 3)

    if row_crossed(a.diagonal()) \
            or row_crossed(np.fliplr(a).diagonal()) \
            or any(row_crossed(row) for row in np.concatenate([a, a.transpose()])):
        return True

    return False

Minor "refinements":

for matr in (a, a.transpose()) looks a bit more "connected" than for matr in (a, np.transpose(a)):
optionally, to reduce typing misses of codes = ('c1', 'c2', 'c3', 'b1', 'b2', 'b3', 'a1', 'a2', 'a3') - a good alternative is:

codes = tuple(map(''.join, itertools.product('cba', '123')))


Fastest way to change the HSV value of all pixels in a bitmap

Disclaimer: I am NOT familiar with Java, let alone the Android version. This may not compile or may be slower. I have no way to test this!

First of all, You deserve huge congratulations!!! Even I could read and understand what is going on! From the bottom of my heart: Thank you!

But still, there are a few points that scared me.

One of them is this:

int[] rgbs = new int[width * height];

Why rgbs? Sure, you are storing an RGB representation of a pixel in the form of an integer. So, why not just call it pixels?

Other variable that needs rewording is rgbi. Since it is an incrementer, it should be simply i. No need to complicate.

Based on http://developer.android.com/training/articles/perf-tips.html, you could use the for loop with 'cached' length, to try to speed up your code. I'm not sure if it will work.

It would look like this:

int length = pixels.length;
for(int i = 0; i < length; i++)
{
    float[] hsv = new float[3];
    Color.colorToHSV(pixels[i], hsv);
    hsv[2] = newV;
    pixels[i] = Color.HSVToColor(hsv);
}

You may ask: Why aren't you using for-each?

Since you are setting the value of the pixels again, it won't work. Based on https://stackoverflow.com/questions/15844443/why-java-foreach-doesnt-change-element-value, you couldn't write back the new value since it will create a copy. You could try to get a reference instead (possible in PHP), but I'm not sure if it works in Java.

Besides that, the page also says that for performance-critical loops, this is the best choice.

Your biggest bottleneck is this block:

float[] hsv = new float[3];
Color.colorToHSV(pixels[i], hsv);
hsv[2] = newV;
pixels[i] = Color.HSVToColor(hsv);

This is where everything happens! You could try to use memoization techniques to store already-calculated values. This will speed-up for images with less colors, like a photo of the sun/clean sky or a logo or similars. Photos with areas of colors that are equal or similar.

For images with lots of colors, like a photo of a landscape, it may still produce somewhat good results in RAM. Since there are 16777216 colors that can be generated using RGB values, this would be equivalent to storing 4 * 16777216 = 67108864 Bytes = 65536 KBytes = 64MBytes in your worst case scenario. Since your bitmaps are 1920 x 1080 pixels, you have 1920 * 1080 = 2073600 pixels * 4 = 6220800 bytes = 6075 KBytes ~= 5,9326171875 MBytes of information. So, you don't have to worry about your worst case scenario. As long as the newV doesn't change, all this data is re-usable to other images, being it even faster on the next ones.


As you observed, casting within your implementation of setAttribute() is ugly.  Worse than that, returning Object from getAttribute() is horrible — you've given up all type safety.  In a loosely typed language, that would just be business as usual.  However, in Java, the caller would have to cast the result (cumbersome and a potential source of bugs) or just treat it as an opaque Object (spreading the nastiness throughout the program).

Are you sure that you want to represent phone numbers as integers?  You would only get 9 digits reliably.  That's not enough to hold, say, an American phone number including the area code, which would be 10 digits.  Not to mention, you may need country codes, extension numbers, and spaces or punctuation for readability.  A string may be more appropriate after all.

Now, suppose that you just store all three attributes as strings, which eliminates the type safety issue.  What if you want to implement validation within setAttribute()?  You would end up putting in a switch, which would defeat any code savings you have achieved by doing this instead of implementing a separate setter for each attribute.

In summary, this is a bad idea, unless you had a requirement to associate many obscure or arbitrary attributes with a person (e.g. pet, priest, etc.).  In that case, you would implement something more elaborate, such as

public abstract class ModelEntity {
    public String getAttribute(String attrname);
    public void setAttribute(String attrname, String value) throws ValidationException;
    public ModelEntity getRelationship(String relname);
    public void setRelationship(String relname, ModelEntity obj) throws ValidationException;
}

public class Person extends ModelEntity {
    ...
}

public class Pet extends ModelEntity {
    ...
}

… but you would be doing that out of necessity, not out of laziness.  If you really wanted to be sloppy and lazy, you might as well publicly expose the Person's instance variables (not that I'm recommending that at all!).

Returning false to indicate validation failure is poor design.  I would throw an exception to force the caller to deal with it.

Your hashCode() and equals() methods need to be consistent.  If your equals() compares names case insensitively, then your hashCode() should also squash the name to lowercase.


Well there's not much code to review here, but for what's here, I'd say it looks okay. I would only make one suggestion. If all you're going to do in your controller action is return single string wrapped up in a JSON object, why not dispose of the JSON and just return the HTML as content?

Ajax call:

function getPreviewText() {
    $.ajax({
        type: 'POST',
        url: '@Url.Action("PreviewWiki")',
        dataType: 'html',
        data: 'source=' + $('#markItUp').val(),
        success: function (result) {
            $('#previewMode').html(result);
        }
    });
};

Controller action:

[HttpPost]
public ActionResult PreviewWiki(string source) {
    return Content(m_wikiEngine.Render(source, GetRenderers()));
}


Handling Parent-Child Relationship using MVP within a WinForms Application

I'm no expert in design patterns, but I fail to see the benefit in having a completely empty interface.

public interface IParentView { }

Interfaces do two things for us.

They enforce a contract. Anything implementing this interface must have this specific public api. Which allows for...
The ability to code against an expected api, not an implementation.

While you've done a good job of coding against IParentView instead of IChildView, what does the parent view get us? Nothing as far as I can tell. There's no real contract being made here, so there's no reason you couldn't have coded directly against IChildView. (Which, at that point, would not be a good name.)

But don't take just my word for it, 24 people on stack overflow agree that this pattern is a code smell.


class QuackBehavior():

Don't put () after classes, either skip it, or put object in there

    def __init__(self):
        pass

There's no reason to define a constructor if you aren't going to do anything, so just skip  it

    def quack(self):
        pass

You should probably at least raise NotImplementedError(), so that if anyone tries to call this it'll complain. That'll also make it clear what this class is doing.

You don't really need this class at all. The only reason to provide classes like this in python is documentation purposes. Whether or not you think that's useful enough is up to you.

class Quack(QuackBehavior):
    def quack(self):
        print "Quack!"

class QuackNot(QuackBehavior):
    def quack(self):
        print "..."

class Squeack(QuackBehavior):
    def quack(self):
        print "Squeack!"

class FlyBehavior():
    def fly(self):
        pass

class Fly():

If you are going to defined FlyBehavior, you should really inherit from it. It just makes it a litle more clear what you are doing.

    def fly(self):
        print "I'm flying!"

class FlyNot():
    def fly(self):
        print "Can't fly..."

class Duck():

I'd define a constructor taking the quack and fly behavior here.

    def display(self):
        print this.name

    def performQuack(self):
        self.quackBehavior.quack()

    def performFly(self):
        self.flyBehavior.fly()

class MallardDuck(Duck):
    def __init__(self):
        self.quackBehavior = Quack()
        self.flyBehavior = Fly()

There's not really a reason for this to be a class. I'd make a function that sets up the Duck and returns it.

if __name__ == "__main__":
    mallard = MallardDuck()
    mallard.performQuack()
    mallard.performFly()
    mallard.flyBehavior = FlyNot()
    mallard.performFly()


Thread safety

You want to have only one instance of CloseableHttpAsyncClient which is why you use static method and static variable, right ?

Sadly, using only static methods and global states is usually a bad idea (impossible to inject object... and thus you can't mock in your unit test, it also  increases the coupling between your objects)

If you still want to use static methods, the synchronized method for the HttpAsyncClient creation make it safe against thread race and you are guaranteed to have only one HttpAsyncClient instance so you have that guarantee but you should consider using Dependency Injection instead.

Code format

The indentation is good IMO, however...

private static CloseableHttpAsyncClient HTTP_ASYNC_CLIENT = null;
private static HttpPost HTTP_POST = null;
private static HttpContext HTTP_CONTEXT;

private static PropertiesLoader PROP_LOADER = new PropertiesLoader();
private static Properties PROPERTIES = PROP_LOADER.initProp("./config/config.properties");

You should only use SCREAMING_SNAKE_CASE in java when the field is static final and using the object don't have any side-effects. Here it's not only non-final, CloseableHttpAsyncClient and PropertiesLoader are full of side-effects so SCREAMING_SNAKE_CASE is better avoided.


The algorithm looks correct.

Regarding the function signature, I'd make three changes:

You're not modifying elements, so take it by constant reference rather than reference.
You don't need to specify a pointer to Function, Function is already a template parameter, and non-pointers could be valid (ex: a class with a () operator).
"callback" isn't a very useful name for this case.  "predicate" would be better.

While this form is fine, I'd also include a version that takes a start/end iterator instead of a container.

Also, there's no reason to include vector or iostream in any.hpp - only include things that are necessary.

For completeness in the testing method, you should also test with an empty collection, and a collection with no matches.