Removing jQuery event handler from single element bound by delegate

Well, as far as I can tell, there are 3 ways to deal with this; you've mentioned 2 of them already:

Pre-empt the event for a specific element by adding another handler,
Scope the event handler differently to exclude a specific element, or
Do the filtering in the common handler

(Edit: All of this is assuming you really want to keep the document-level, event bubble handler, rather than go with mseancole's straightforward solution)

The 3rd option would look something like:

$(document).on('keyup','input,textarea', function (event) {
  if( event.type === 'sometype' && this === someElement ) {
    return;
  }
  $.debounce(600, editor.handleGlobalChange).call(this, event);
});

... which isn't pretty either. Of course you could make it fancier by maintaining a list of event type/element combos to be ignored, rather than hardcoding it, but... eh, seems like a lot of work.

I'd say go with option 1, but perhaps wrap that bit of logic in a function or plugin. I.e. something that would let you say:

$(document).on('keyup','input,textarea',$.debounce(600, editor.handleGlobalChange));
$('#afield').ignore('keyup');

.ignore() would then set the event handler that kills the event in its tracks. In your case, you can use stopPropagation instead of stopImmediatePropagation. That way, you can still attach other handlers to that specific element, without ignore eating the event.

Edit: Now that I think about it, ignore is a bad name. Too strong a word. dontBubble is accurate, but I'm a stickler for using proper apostrophes, and doNotBubble sounds too aggressive. Maybe popBubble? Too cutesy? Maybe just something like halt? debubble? Yessss, I'm thinking way too much about this :)

Here's a demo. It's in CoffeeScript, because... well, because I like CoffeeScript. The general idea should be clear enough though. Here's the code in case jsfiddle implodes

makeNoise = ->
  $('pre').append "You typed!<br>"

# 4-line jQuery plugin
$.fn.ignore = (eventType) ->
  $(this).each ->
    $(this).on eventType, (event) ->
      event.stopPropagation();

$ ->
  # General event handler for all inputs
  $(document).on 'keyup', 'input', makeNoise

  # Exempt a specific element
  $('#quiet').ignore 'keyup'

  # Handlers added *directly* to the #quiet element
  # are still called, only the bubbling is silenced.
  $('#quiet').on 'keyup', ->
    alert "Shhhh!"

None of this is any different from what you're already doing. It's just wrapped up for convenience.


What should the type signature of these functions be?

I would really separate the IO from data. In addition, I would display data that you already have. I would not have valid_or_not print stuff out. Instead I would have it return a value. But what value?

Furthermore, don't read global variables. valid_or_not and list_tweak should take paramters.

We'll get to printing stuff in the end.

What do you want to do with an invalid credit card number?

You are both throwing an error, and also printing out whether it is a valid card number. I would say there is a couple ways to go, but I prefer this approach:

  Return an enum that ends up being either: VALID, INVALID_CHECKSUM, or INVALID_FORMAT. Instead of doing printing.

Rework the flow of valid_or_not.

Consider reworking valid_or_not to do the following:

Check to see if the format is valid, and return INVALID_FORMAT if it is not.
The run list_tweak, but don't do try-except on it, return either INVALID_CHECKSUM or VALID depending on list_tweak.

Naming.

I am not sure what list_tweak means, but I am assuming only because I've seen this problem show up time and time again that it is the Luhn algorithm. Name it something appropriate like luhn_checksum.

IO

So what should we really be doing for input? First we should have a main function (see the link for more information why. Thus we get:

def main():
    cardnumber = input('Enter your credit card number: ')
    print(valid_or_not(cardnumber))

if __name__ == '__main__':
    main()

See all the data is manipulated in valid_or_not which is then displayed, instead of displaying information withing valid_or_not).


List the combinations that add up to 0 from a vector of numbers

Rust is a statically-compiled language, which means you get warnings and errors at compile time. Don't ignore those:

warning: unnecessary parentheses around `for` head expression
 --> src/main.rs:3:14
  |
3 |     for a in (0..input.len() - 2) {
  |              ^^^^^^^^^^^^^^^^^^^^
  |
  = note: #[warn(unused_parens)] on by default

warning: unnecessary parentheses around `for` head expression
 --> src/main.rs:4:18
  |
4 |         for b in (a+1..input.len() -1) {
  |                  ^^^^^^^^^^^^^^^^^^^^^
  |
  = note: #[warn(unused_parens)] on by default

warning: unnecessary parentheses around `for` head expression
 --> src/main.rs:5:22
  |
5 |             for c in (b+1..input.len()) {
  |                      ^^^^^^^^^^^^^^^^^^
  |
  = note: #[warn(unused_parens)] on by default

warning: unnecessary parentheses around `if` condition
 --> src/main.rs:6:20
  |
6 |                 if (input.get(a).unwrap() + input.get(b).unwrap() + input.get(c).unwrap() == 0) {
  |                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: #[warn(unused_parens)] on by default

Next, run Clippy to get even more automated suggestions. Note that this contains the answer to your question:

warning: this argument is passed by value, but not consumed in the function body
 --> src/main.rs:1:24
  |
1 | pub fn calc_zer(input: Vec<i32>) -> Vec<(i32, i32, i32)> {
  |                        ^^^^^^^^ help: consider changing the type to `&[i32]`
  |
  = note: #[warn(needless_pass_by_value)] on by default
  = help: for further information visit https://github.com/Manishearth/rust-clippy/wiki#needless_pass_by_value

warning: called `.get().unwrap()` on a Vec. Using `[]` is more clear and more concise
 --> src/main.rs:6:20
  |
6 |                 if input.get(a).unwrap() + input.get(b).unwrap() + input.get(c).unwrap() == 0 {
  |                    ^^^^^^^^^^^^^^^^^^^^^ help: try this `&input[a]`
  |
  = note: #[warn(get_unwrap)] on by default
  = help: for further information visit https://github.com/Manishearth/rust-clippy/wiki#get_unwrap

Extract local variables so you don't even have the overhead of accessing the array multiple times.
There's no reason to provide an explicit type for output - it will be inferred from the return value.
Extract a variable for input.len() since that never changes during the iteration.
It's almost always better to iterate over the collection directly instead of indexing it. We can also use Iterator::enumerate to get the index as we go along.

This yields

fn calc_zer(input: &[i32]) -> Vec<(i32, i32, i32)> {
    let mut output = Vec::new();

    let len = input.len();

    for (a_i, &a) in input[0..len - 2].iter().enumerate() {
        for (b_i, &b) in input[a_i + 1..len - 1].iter().enumerate() {
            for &c in &input[a_i + b_i + 2..len] {
                if a + b + c == 0 {
                    output.push((a, b, c));
                }
            }
        }
    }

    output
}

This is a bit ugly, and even worse — I got it wrong originally! See the revision history for details. This was caused because enumerate starts counting from zero, even though we are iterating through an offset into the original vector.

However, Rust has a strong emphasis on reusing code via crates. In this example, I turn to one of my favorites — itertools:

extern crate itertools;

use itertools::Itertools;

fn calc_zer(input: &[i32]) -> Vec<(i32, i32, i32)> {
    input.iter()
        .tuple_combinations()
        .filter(|&(a, b, c)| a + b + c == 0)
        .map(|(&a, &b, &c)| (a, b, c))
        .collect()
}

Much more readable!


Extremely long if-or-or statement just feel wrong

Sure. Put this into a function, eg. "isCompanyName". This function can be easily commented and written in separate lines.

 if (heading.ToLower().Contains("organisation")
     return true;

 if (heading.ToLower().StartsWith("address.") &&
   heading.ToLower().EndsWith(".surname")))
     return true;

And so on. This allows to comment the separate cases and maybe explain what they are doing. It's also easy to modify. You can also put things like heading.ToLower() in a variable to save space.


Project Euler problems are more about math than programming.

You must prove (or at least observe) the following:

An nth triangular number is \$\dfrac{n(n+1)}{2}\$. One of the numerator's factors is obviously even.
The number_of_divisors is a multiplicative function (known as \$\sigma\$), meaning that if \$m\$ and \$n\$ are coprime, then \$\sigma(mn) = \sigma(m)\cdot\sigma(n)\$
\$n\$ and \$n+1\$ are necessarily coprime.
Once you computed \$\sigma(n)\$ and \$\sigma(n+1)\$ on a certain iteration, on the next iteration you'd only need to compute \$\sigma(n+2)\$. Using memoization, you may even avoid this when \$n+2\$ is even.

This should be enough to build an efficient solution.


Find the max. difference between two array elements a[j] and a[i] such that j > i

The algorithm you're using does a bunch of superfluous work. It would be much more efficient to concentrate on tracking the maximum difference that conforms to the specification than where you are in the array.

Setting the maxIndex the first time through your main loop isn't really setting any meaningful limit for you, because you also need to check to see if there are any other number combinations that have a higher difference than just the array maximum. In fact, you don't need to know what the highest value is at all or it's position in the array. The highest difference already assumes both of these, because when you set the greatest difference it is calculated based on the lowest value up to the current point in the array.

The idea of limiting the minimum check to the position of the previous high is well intentioned, but why not just run through the array once and keep track of everything at the same time?

The pseudo-code is much simpler:

Set the first value in the array to your low value.
Loop through the
array.
If the current element minus the low value is higher than the
maximum difference found, update the maximum difference.
If the current element is lower than the previous low, update the previous
low value.
Return the maximum difference when you hit the end of the array.


Factory pattern for image or shape marker

In looking at your code, what I see are a series of effectively global functions that "make" things based on a string.

The object that calls factoryFor must know what the string is in order to know which type of maker to return (after all, if the string is going to be "X", then the object that calls factoryFor has to know not to pass Shape.) Also, the caller of the factory function must know what the factory is making in order to correctly cast the AnyObject that is returned.

This leads me to wonder what the MakerHelper.factoryFor function's responsibility is? I mean, it's job just seems to be to return the make global function that the caller already knows it wants, so why not just have the caller use the make function directly?

It seems to me that you could have written:

import UIKit

func tintedImageViewNamed(name: String) -> UIImageView {
    let image = UIImage(named: name)
    let tintedImage = image?.imageWithRenderingMode(.AlwaysTemplate)
    let imageView = UIImageView(image: tintedImage)
    imageView.tintColor = UIColor.redColor()
    return imageView
}

func make(type: String) -> UIView? /* thanks nhgrif */ {
    switch type {
    case "CIRCLE":
        //return CircleView()
        return UIView()
    case "X":
        return tintedImageViewNamed("close.png")
    default:
        return nil
    }
}

The above accomplishes the same thing your code does, is no less safe and no more testable than what you have and it's a lot less complex (which means less chance of bugs.)

I'd love to suggest a better solution, but to do that, I would have to better understand what problem you are trying to solve...


Works as intended.
But I get a thread priority of 15 rather than the expected 31 for a REALTIME_PRIORITY_CLASS?
See SetThreadPriority.

It seems that the THREAD_PRIORITY_TIME_CRITICAL is defined to THREAD_BASE_PRIORITY_LOWRT - 1, which could be further elevated to 31 if needed.


Is there a specific reason you want to accept a string? You could pass a list and get by with one overload.

type Calculator() =
  member x.Add(nums: int list) = List.sum nums

let calc = Calculator()

calc.Add([0; 0])
calc.Add([1; 2; 3; 4])
calc.Add(List.init 10 id)

EDIT

I'm sorry, I misunderstood the point of the exercise. There are a few changes I would make.

According to the kata, you only need one method taking a string and returning an int.
There's an overload of String.Split accepting a char array, so you can store your delimiters as such and avoid the call to ToCharArray.
You can use the built-in int function instead of Convert.ToInt32.
There's no need to roll your own "sum" function. It's already built into the various collection modules.

The following code satisfies steps 1-3.

type Calculator() =

  let delimiters = [|','; '\n'|]

  member x.Add(nums) =
    match nums with
    | null -> nullArg "nums"
    | "" -> 0
    | _ ->
      nums.Split(delimiters)
      |> Array.map int
      |> Array.sum


Setting combined height and width viewport "breakpoints"

Here is one way to get rid of if chaines (if that is the repition you mean):

var WIDTHS = [
    {name: 'xs', max: 768},
    {name: 'sm', max: 992},
    {name: 'md', max: 1200},
    {name: 'lg'}
];

function getRangeName(value, ranges) {
    for (var i = 0, len = ranges.length; i < len; i++) {
        var range = ranges[i];
        if (typeof range.max === "undefined" || value < range.max) {
            return range.name;
        }
    }
}

function setWidthBreakpoints(windowWidth) {
    return getRangeName(windowWidth, WIDTHS);
}


Checking winning conditions in a Connect Four game

Don't use Hungarian notation in C#.
The existence of x and y seems pointless. This code:

if (i_IsRow)
{
    x = i;
    y = j;
}
else
{
    x = j;
    y = i;
}
signCounterLogic(m_Board[x, y], ref signCounter);

could just as easily be

if (i_IsRow)
{
    signCounterLogic(m_Board[i, j], ref signCounter);
}
else
{
    signCounterLogic(m_Board[j, i], ref signCounter);
}

  Should I take the (i_IsRow) condition to a method? it will have 5 parameters and 2 of them will be out parameters, this is definitely code smell...

Agreed (though only three parameters if you get rid of x and y), I don't think that warrants a method. The fact that a method (signCounterLogic) encapsulating the actual work done is called in the loop is sufficient I think.
Method names should use PascalCase.
I don't like an int return value for a method called checkRowsOrColsForWin. What does an int value mean? If it only checks whether it won or not then it should return a bool. To me with its current name it should return void. If it is actually returning specific information about the win then the name should be changed to reflect what it checks for and returns.
I don't like the double check for signCounter == k_FourInARow. If the first one is true, the loop breaks, and the same condition is immediately tested again in the outer loop. Unfortunately I've had too much to drink to be able to think of a good way around that.
I don't know what signCounterLogic() does with signCounter, but if it only sets the value then I would prefer that the method returns a value rather than having to pass in a variable by ref. Makes for fewer parameters and a more normal looking method.
Assuming the "sign" in signCounterLogic() isn't a verb, this method should definitely be renamed to say what it's doing.


Reading the color on the canvas is not the right way to proceed, for several reasons :

You want the color string (expl : 'red'), not the r,g,b values provided by getImageData
(expl : 255, 0, 0) .
You can't draw the buckets with gradient or color animation with such a method.

Anyway you are the one handling the buckets, so what about keeping them all within a nice Object ?
And what about going Object for the buckets also ? You'll have great flexibility to change anything to your buckets later.

Below I define a BucketGrid class that will handle the buckets, and a Bucket class that holds data relative to a bucket.

http://jsfiddle.net/gamealchemist/ydtkbzoc/6/

BucketGrid Class :

function BucketGrid(columnCount, rowCount, bucketWidth, bucketHeight) {
    var buckets = [];
    this.columnCount = columnCount;
    this.rowCount = rowCount;
    this.bucketWidth = bucketWidth;
    this.bucketHeight = bucketHeight;

    this.getBucket = function (column, row) {
        return buckets[column + row * columnCount];
    }

    this.setBucket = function (column, row, bucket) {
        bucket.column = column;
        bucket.row = row;
        buckets[column + row * columnCount] = bucket;
    }

    this.insertNewBucket = function (column, row, color) {
        this.setBucket(column, row, new Bucket(this, color));
    }

    this.isValidPosition = function (column, row) {
        return ((column >= 0) && (column < this.columnCount) && (row >= 0) && (row < this.rowCount));
    }

    this.draw = function (context) {
        for (var i = 0; i < buckets.length; i++) {
            var thisBucket = buckets[i];
            if (thisBucket) thisBucket.draw(context);
        }
    }

}

Bucket Class :

function Bucket(owner, color) {
    this.owner = owner;
    this.column = 0;
    this.row = 0;
    this.color = color;

    this.draw = function (context) {
        var owner = this.owner,  bw = owner.bucketWidth,  bh = owner.bucketHeight;
        context.fillStyle = this.color;
        context.strokeStyle = '#000';
        context.save();
        context.translate(this.column * bw, this.row * bh);
        context.fillRect(0, 0, bw, bh);
        context.strokeRect(0, 0, bw, bh);
        context.restore();
    }
}

Setup :

var buckets = new BucketGrid(4, 38, 100, 10);

buckets.insertNewBucket(2, 20, 'red');
buckets.insertNewBucket(2, 21, 'magenta');

/*moving grey character*/
var hero = new Bucket(buckets, 'grey');

Handlers :

/*Function to move the grey character from left to right and from top to button*/
function move(e) {
    var keyCode = e.keyCode;
    switch (keyCode) {
        case 37:
            if (buckets.isValidPosition(hero.column - 1, hero.row)) hero.column--;
            break;
        case 39:
            if (buckets.isValidPosition(hero.column + 1, hero.row)) hero.column++;
            break;
        case 40:
            /*down arrow*/
            if (buckets.isValidPosition(hero.column, hero.row + 1)) hero.row++;
            break;
        case 38:
            /*up arrow*/
            if (buckets.isValidPosition(hero.column, hero.row - 1)) hero.row--;
            break;
    }
    var hovered = buckets.getBucket(hero.column, hero.row);
    colorDiv.innerHTML = hovered ? hovered.color : 'none';

    drawScene();
}

function drawScene() {
    context.clearRect(0, 0, context.canvas.width, context.canvas.height);
    buckets.draw(context);
    hero.draw(context);
}

launch the game :

var canvas = document.getElementById("canvas");
var colorDiv = document.getElementById('whichColor');
var context = canvas.getContext("2d");

document.onkeydown = move;
drawScene();


wxpython program to clear the Desktop or restore files to the Desktop

Your class name is misleading; it says "Window" as if you are trying to draw a window for a GUI purpose, but that is not what that class actually performs. So you should rename it to something else meaningful to enhance the readability of your program.
Parameters and arguments constitute a  level of abstraction which is different from that of the function (or class construction) they are injected it. You should minimize them as much as you can, or avoid them totally if that is possible. In your case, the initializer of your class has a parent parameter which is never used (in your main, you assigned None to it), so it is better you get rid of it as it is useless for your case.
Always in the initializer of your class, you used the id parameter only here:

wx.Frame.__init__(self, parent, id, title="no_caption", size=(300,97), style=no_caption)

So for the same reason as mentioned through the second bullet above, I suggest you to get rid of it. Thus, your initializer should become like this:

def __init__(self):
    ...
    ...

The work is not finished with your __init__(). You should clean it by keeping only what is necessary there, otherwise delegate all the remaining tasks for functions to take care of them. I say your __init__() is not clean because you mix widget creation and settings with some configurations and constants that your application needs. So I suggested you to move this:

self.Desktop = "C:/Users/Name/Desktop/" and "C:/Users/Public/Desktop/"
self.Dfiles = "C:/ Desktop_Files/"

into a different function. The only "constant" you need to keep in your class initializer is the parent  parameter, but you do not use it. In case you used it, it would be the only element that deserves to sit and have its own place in the initializer by running this instruction self.parent = parent
For the same reason, I suggest you to create a separate function to save the settings of your application:

def configure_gui(self):
    no_caption = wx.DEFAULT_FRAME_STYLE | wx.STAY_ON_TOP

Please do not create widgets within your class initializer. Delegate that task, again, for a separate function:

def create_widgets(self):
    wx.Frame.__init__(self, parent, id, title="no_caption", size=(300,97), style=no_caption)
    self.panel=wx.Panel(self)
    self.Butt_Clear = wx.Button(self.panel, -1, label="Clear Desktop", pos=(0,0), size=(100,70))
    self.Butt_Clear.Bind(wx.EVT_BUTTON, self.ClearDesk, self.Butt_Clear)
    self.Butt_Undo = wx.Button(self.panel, -1, label="Undo Clear", pos=(185,0), size=(100,70))
    self.Butt_Undo.Bind(wx.EVT_BUTTON, self.UndoClear, self.Butt_Undo)

In Python, we don't like camelCase and CamelCase naming conventions that you probably used in Java, JavaScript or elsewhere. Please follow the naming conventions as described in PEP8.


Algorithm optimisation to get first parent with specific kind of class

I wouldn't care much about performance here, since a view controller
hierarchy does not have hundreds of elements. But some things can
be simplified. First,

if (currentParent is RootViewController) {
    return (currentParent as? RootViewController)!
}

can be simplified to

if let rootVC = currentParent as? RootViewController {
    return rootVC
}

which also has the advantage that no forced unwrapping operator is
needed. Even if we know that it cannot fail here (because the type has
been checked in the if-statement) it is better to write the code
in a way that it becomes obvious that it cannot crash.

Next, the loop itself can be simplified:

var rootViewController: RootViewController? {
    var currentViewController = self
    while case let parentController? = currentViewController.parent,
        parentController != currentViewController {
        if let rootVC = parentController as? RootViewController {
            return rootVC
        }
        currentViewController = parentController
    }
    return nil
}

Here the "optional pattern"

    case let parentController? = currentViewController.parent

is used to check that there is a parent, and the constraint

    parentController != currentViewController

ensures that the parent is different from the current view controller.

But I don't think that a view controller can be its own parent.
If you don't have a special reason to consider this case, the code
can further be simplified using optional binding:

var rootViewController: RootViewController? {
    var currentViewController = self
    while let parentController = currentViewController.parent {
        if let rootVC = parentController as? RootViewController {
            return rootVC
        }
        currentViewController = parentController
    }
    return nil
}

Another suggestion is to make the method generic, so that it can
be used to find a parent view controller of any given class:

func parent<T : UIViewController>(ofType: T.Type) -> T? {
    var currentViewController = self
    while let parentController = currentViewController.parent {
        if let parent = parentController as? T {
            return parent
        }
        currentViewController = parentController
    }
    return nil
}

Finally: You can replace the loop by recursion, using the
flatMap method of Optional and the nil-coalescing operator ??:

func parent<T : UIViewController>(ofClass: T.Type) -> T? {
    return parent.flatMap { ($0 as? T) ?? $0.parent(ofClass: T.self) }
}

Here parent.flatMap { ... } returns nil if parent == nil,
this terminates the recursion eventually. Otherwise $0 is the
(unwrapped) parent. If the conditional cast $0 as? T succeeds
then this will be the return value. Otherwise the method is called
recursively on the parent view controller.

I doubt that this will be faster, and it is more difficult to read
and to debug. So it's up to you which approach you prefer.


Where to define constants (Bundle Keys) used between 2 Activities?

One thing that I find is that it is not necessary to wrap your keys inside their own inner class. Putting them inside SecondActivity directly is enough.

public class SecondActivity extends Activity {
    public static class Key {
        public static final String USER_NAME = "USER_NAME";
        public static final String USER_PHOTO = "USER_PHOTO";
    }
    ...

Becomes:

public static final String USER_NAME = "USER_NAME";
public static final String USER_PHOTO = "USER_PHOTO";

  Every time when I want add new fields or change existing fields, I should also change the arguments list in the method start(). And this way is also not suitable in the case when number of the input parameters will increase significantly.

You are correct about that.

Even though I have to say that I do like your idea of a prepareIntent method.

I do feel that it is more common to do your first version: (but without using the Key inner class).

private void onOkButtonPressed() {
    Intent intent = new Intent(this, SecondActivity.class);
    intent.putExtra(SecondActivity.USER_NAME, userName);
    intent.putExtra(SecondActivity.USER_PHOTO, userPhoto);
    startActivity(intent);
}

One thing I really have to point out is that this method is a bit overkill:

public static void start(Context context, String userName, Uri userPhoto) {
    Intent intent = prepareIntent(context, userName, userPhoto);
    context.startActivity(intent);
}

I would prefer to have the parent activity call prepareIntent, which gives you the possibility of changing or adding some of the extras passed to the intent. I also find it better because you can in a parent activity call startActivity directly without the need for context.startActivity

startActivity(SecondActivity.prepareIntent(userName, userPhoto));

To summarize: (My opinions at least)

Drop the start static method entirely
Drop the Key inner class and put the constants directly into SecondActivity
It seems to be more common to create the intent inside the parent activity

In the end, which way you choose is up to you.


Preview method for multiple types of panels

I don't know your class but it looks like your object can have different subclasses depending on object.panel_type (maybe a single table inheritance?) and every subclass implements it's own preview method.

 class Image < BaseClass
  def preview
      asset_image_path(object.asset)
  end
end

class Slider < BaseClass
  def preview
       if object.options.present? && object.options["slides"].present?
          Slide.find(object.options["slides"][0]).headline
       else
         "Empty"
       end
  end
end


Which name should I choose for private abstract functionality with a public proxy?

I think that it's more a matter of taste. If I were to come along behind you, I wouldn't have any particular problem with fEval and fSimplify.

I'm not sure that I would like concreteEval.

In my own code I tend to use doEval, but I could also imagine using evalImpl or myEval, depending on what it is exactly that is being done by these functions.


Note that using the standard library function std::next_permutation from the header <algorithm>, your code can more or less be reduced to:

#include <algorithm>
#include <iostream>
#include <string>

int main()
{
    std::string s;
    std::cout << "Enter the amino acid string: ";
    std::cin >> s;
    std::cout << "\nThe permutations of the given string:\n";

    std::sort(s.begin(), s.end());
    do
    {
        std::cout << s << '\n';
    } while(std::next_permutation(s.begin(), s.end()));
}

Note that the iterable (the string in our case) needs to be sorted for the call to std::next_permutation to work, hence the call to std::sort beforehand.

That said, solving your problem in a more idiomatic manner might be interesting, but there are some more things you may want to know if you want to write idiomatic C++ in the future:

You don't need to write your own swap function. The standard already provides std::swap to swap any two values.
using namespace std; is often considered bad practice. While it shouldn't matter in your case, using it in a header file will drag every name from the std:: namespace into the global namespace in every file including this header file. Generally speaking, unless you know what you're doing, avoid this construct and fully qualify every name from the standard library with std::.
You could use some additional spacing. Don't hesitate to separate your functions by empty lines and to add some more spaces between your functions parameters. It will make your code easier to read. Also, try to be consistent when you indent stuff; use the same number of spaces for indentation everywhere.


Making an accordion from a multi-level HTML list

It'll be good if you can provide your HTML markup. Without it I can do this:

jQuery(function($) {
    $('.s4-ql li ul').hide();
    $('.s4-ql ul li').hover(function() {
        $(this).find('a:first').next().slideToggle();
    }, function() {
        $(this).find('a:first').next().slideToggle();
    }).find('ul').each(function(index) {
        var $this = $(this);
        $this.parent().find('a:first .menu-item-text').append(['(', $this.children().length, ')'].join(''));
    });;
});


Best way to toggle a property in an array

This could be accomplished via an XOR,  or boolean not equal in other words.

const people = [
  {
    "name": "Olivia",
    "lead": true
  },
  {
    "name": "Gary",
    "lead": false
  },
  {
    "name": "Adam",
    "lead": false
  }
]

const toggleLead = (name) =>
    [...people].map(person =>
        ({
            ...person,
            lead: person.lead !== (person.name===name)
        })
    )

console.log(toggleLead('Gary'))
.as-console-wrapper { max-height: 100% !important; top: 0; }


Both functions checkPolygon1 and checkPolygon2 perform essentially the same actions and only differ in specific polygon instance. That's an appropriate case for Parameterize Function refactoring technique where polygon instance can serve as a factor.

Define a unified function point_in_polygon (don't forget about Python naming conventions):

def point_in_polygon(row, polygon):
    return polygon.contains(Point(row['X'], row['Y']))

Then, assuming that you already have a list or generator of polygons polygons:

for i, polygon in enumerate(polygons, 1):
    datacopy[f'InPolygon{i}'] = datacopy.apply(point_in_polygon, axis=1, polygon=polygon)


Input validation is a critical aspect of any reliable program. Your code is functional, but there are a few things to note.

First up, the RuntimeException is not a good error type to return, use an IllegalArgumentException instead (because it is an illegal argument). Note that IllegalArgumentException extends RuntimeException so it does not need to be explicitly checked/thrown.

Next, you should validate inputs before using the values - using a "Guard Clause". While your code technically does that, the logic looks like the validation is done after the hours are updated.

Finally, error messages should give the user/programmer an indication of what's needed to fix the problem. Your message should be more useful.

So, all things considered, I would do the code as:

private void setHours(int newHours) {
    if (newHours < 0){
         throw new IllegalArgumentException("Input hours must be positive value: " + newHours);
    }
    hours = newHours;
}


I'd unify both functions and only have the bulk/multiple-emails version
because the single case is basically a specialisation of the general
case and the slight bit more work is unlikely to be noticeable (unless I
missed some other technical reason why this isn't feasible).

Btw. the with can be nested on a single line, i.e.:

def send_bulk_async_email(app, emails):
    with app.app_context(), mail.connect() as conn:
        for email in emails:
            conn.send(email)

The default value for the sender on create_email sounds like it
doesn't belong there and should rather be passed in like the rest,
perhaps store it in a configuration file anyway.

For spawning the threads also consider making it a bit more flexible by
allowing an optional parameter for the thread creation, e.g. to use a
thread pool instead of spawning an unlimited number of threads like done
here.


Is this a right and effcient way of checking AND in a for loop

Currently, once you get ready to be false, all other checks after that will fail (as false && condition2 will always be false).

Why not just break out of the inner for loop when ET[k].Arg[z].Valid is false?  If ready is needed, you may keep the assignment line, but break when it's false.


Find number of whole weeks between months in the same year

public int year;
public String m1;
public String m2;

public Solution(int Y, String A, String B) throws ParseException {
    this.year = Y;
    this.m1 = A;
    this.m2 = B;

These fields shouldn't be public. By making them public you've exposed them to the outside world. These are internal details that should be properly encapsulated. Truthfully though, you don't need them at all. I would just work directly with the arguments that you passed in. Rename them though. Your current names don't tell the client what kind of values to expect. What's an "A"? How would another dev know what to pass into this method without looking at the internals? They wouldn't.

public Solution(int year, String startMonth, String endMonth) throws ParseException


Asp.net web API Nlog implementation with UnhandledExceptionHandler

The variable ex is not used anywhere else, so it can be in-lined.

string strLogText = FormatException(context.Exception);

The multiple calls to DateTime.Now will give different time stamps.

Hold on to the timestamp in one variable early in the function and reuse that.

It was already assigned here

 var timeUtc = DateTime.Now;

so use that

//...

ApiError apiError = new ApiError()
{
    Message = strLogText,
    RequestUri = requestedURi,
    RequestMethod = requestMethod,
    TimeUtc = timeUtc
};

//...

Given the variable name, the assumption is that the timestamp was meant to be UTC, which would mean that it should be using DateTime.UtcNow

The SQL error logging (though commented out) can be encapsulated into its own function/concern

private void LogSQL(string message, HttpRequestMessage request, DateTime timestamp) {
    var requestedURi = (string)request.RequestUri.AbsoluteUri;
    var requestMethod = request.Method.ToString();
    SqlErrorLogging sqlErrorLogging = new SqlErrorLogging();
    ApiError apiError = new ApiError() {
        Message = message,
        RequestUri = requestedURi,
        RequestMethod = requestMethod,
        TimeUtc = timestamp
    };
    //sqlErrorLogging.InsertErrorLog(apiError);
}

This can be abstracted out into its own service/concern if so desired

The above and a few minor changes results in a refactoring of

public class UnhandledExceptionLogger : ExceptionLogger {
    private static readonly Logger logger = LogManager.GetCurrentClassLogger();

    public override void Log(ExceptionLoggerContext context) {
        DateTime timestamp = DateTime.UtcNow;
        string strLogText = FormatException(context.Exception);
        //SQL
        SqlLog(strLogText, context.Request, timestamp);
        //NLOG
        NLog(logger, strLogText, timestamp);
    }

    private void NLog(Logger logger, string message, DateTime timestamp) {
        var sb = new StringBuilder();
        sb.AppendLine(message);
        sb.AppendLine(timestamp);
        logger.Error(sb.ToString());
    }

    private void SqlLog(string message, HttpRequestMessage request, DateTime timestamp) {
        var requestedURi = (string)request.RequestUri.AbsoluteUri;
        var requestMethod = request.Method.ToString();
        SqlErrorLogging sqlErrorLogging = new SqlErrorLogging();
        ApiError apiError = new ApiError() {
            Message = message,
            RequestUri = requestedURi,
            RequestMethod = requestMethod,
            TimeUtc = timestamp
        };
        //sqlErrorLogging.InsertErrorLog(apiError);
    }

    private string FormatException(Exception ex, int depth = 0) {
        //... omitted for brevity
    }
}


You've misspelt std::size_t.

Apart from that, the code seems reasonably straightforward if you always need to return a copy.

A two-pass algorithm (reverse the whole string, then reverse each of the individual components) might be faster, because you can operate in-place, without having to create a new string.  Of course, you'll only get the speed benefit if the caller doesn't need to retain the original (pass by value, and use std::move to control copying).


I am not aware of how to improve the code so that it will be shorter. What I would suggest is that this code can be improved in terms of clarity of intent (in this case, the LOCs will increase). This can be achieved by using small functions and good names for the functions (for more information look and Robert C. Martins wonderful book: Clean Code or this for a little introduction).

I refactored your code by extracting some methods and giving more or less meaningful names:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    char[] inputNumbers = extractInputNumbersFromRequest(request);

    NumberBean bean = createNumberBeanForInputNumbers(inputNumbers);
    request.setAttribute("input", bean);

    forwardRequestToCorrectView(request, response, inputNumbers);
}

private char[] extractInputNumbersFromRequest(HttpServletRequest request) {
    return request.getParameter("input").toCharArray();
}

private NumberBean createNumberBeanForInputNumbers(char[] inputNumbers) {
    NumberBean bean = new NumberBean();
    String inputNumbersWithSpaces = combineInputNumbersWithSpaces(inputNumbers);
    bean.setInput(inputNumbersWithSpaces);
    return bean;
}

private String combineInputNumbersWithSpaces(char[] inputNumbers) {
    StringBuilder inputs = new StringBuilder();
    for (char digit: inputNumbers) {
        inputs.append(digit).append(" ");
    }
    return inputs.toString();
}

private void forwardRequestToCorrectView(HttpServletRequest request, HttpServletResponse response, char[] inputNumbers) throws ServletException, IOException {
    if (lastNumberIsOdd(inputNumbers)) {
        handleLastNumberOddCase(request, response, inputNumbers);
    } else {
        handleLastNumberEvenCase(request, response);
    }
}

private void handleLastNumberEvenCase(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.getRequestDispatcher("/WEB-INF/odd.jsp").forward(request, response);
}

private void handleLastNumberOddCase(HttpServletRequest request, HttpServletResponse response, char[] inputNumbers) throws ServletException, IOException {
    request.setAttribute("sum", sumOfInputNumbers(inputNumbers));
    request.getRequestDispatcher("/WEB-INF/even.jsp").forward(request, response);
}

private int sumOfInputNumbers(char[] inputNumbers) {
    int sum = 0;
    for (char digit: inputNumbers) {
        sum += Character.getNumericValue(digit);
    }
    return sum;
}

private boolean lastNumberIsOdd(char[] inputNumbers) {
    return inputNumbers[inputNumbers.length - 1] % 2 == 0;
}

One could argue about the existence about some of the methods like handleLastNumberEvenCase, but I like the idea from Uncle Bob, that a method should not have different levels of abstractions.  As such, I've introduced these alias-like methods, which just give a one liner a name, that is more clear.

In addition, the class numberBean was renamed to NumberBean to use the standard conventions in the Java world. Furthermore, it should be renamed to a more meaningful name, because the word "Number" does not give you a hint on what this class does. The word "Bean" does not give you further information as well, so I would suggest something like WhitespaceNumberRequestor - which is obviously false, because I don't have any hints on what this class does.


const formate = array => array.map(({all, any, not}) => ({all: all.split(","), any: any.split(","), not: not.split(",")}));

With empty arrays:

const formate = array => array.map(({all, any, not}) => ({all: all?all.split(","):[], any: any?any.split(","):[], not: not?not.split(","):[]}));


AGGRCOW on SPOJ – Maximize the minimum distance between aggressive cows

Well, your indentation gives me a headache. I think there might be a pattern in it, but I don't see it, so I'll reformat it for writing my answer.
<bits/stdc++.h> is non-standard and causes longer compile-times. Maybe just include what you need?
Never use using namespace something_humungeous_and_growing_like_std;, because there might be conflicts, and silent changes of semantics.
There are single-character-names which would actually make sense for your variables: The ones used in the spec. If you don't want to use them, put a bit more effort into finding meaningful names.
You never test whether input succeeds. At the very least, add the following to get an exception (though it messes with the input-processing ordinarily used in bigger / more robust programs):

std::cin.exceptions(std::ios_base::failbit);

Avoid flushing streams (use '\n' instead of std::endl) unless you actually need to flush.
Prefer streaming character literals to size-1-strings. It's potentially marginally more efficient.
Decouple iostreams from stdio.
Refrain from copying expensive things. Every single time you pass your vector by value Needs a copy, thus a useless extra-allocation, -deallocation and block-copy.
Also, while it is generally a good idea to minimize the scope of variables, re-using the same vector over multiple iterations allows you to forego extra-allocations and de-allocations.
You are using extremely dumb brute-force in count() by trying minimal distances starting at zero and then counting up.
Consider using binary-search instead, trivial minimum is \$0\$, maximum is \$(maxpos - minpos) / (cows - 1)\$.
Same in CanBeMin(), use binary-search. std::lower_bound() can help.


Finding legal knight moves in a chessboard in APL

Initial impression

Your code is already quite good, using idiomatic APL in short clear lines that each do a single job well. Your variable names are such that you don't really need comments other than the fine description you already have at the top.

Describe your result

You might want to add a third comment describing the result structure:

  ⍝ Returns a vector of 2-element vectors

Remove unnecessary parenthesis

The vector (¯1 1) could be written as ¯1 1

Adopt a naming convension

Consider a naming convention that makes it easier for the reader to distinguish syntactic classes; mainly variables and functions, but maybe even monadic operators and dyadic operators. One such scheme that some people like is:

variables lowerCamelCase
Functions UpperCamelCase
_Monadic _Operators _UnderscoreUpperCamelCase
_Dyadic_ _Operators_ _UnderscoreUpperCamelCaseUnderscore_

Being that you seem to prefer snake_case: An equivalent such scheme could be used too:

variables lower_snake_case
Functions Upper_snake_case
_Monadic _Operators _Underscore_upper_snake_case
_Dyadic_ _Operators_ _Underscore_upper_snake_case_underscore_

Alternatively, the cases could be swapped: My father used lowercase for functions and uppercase for variables according to the German (and previous Danish) orthography that specifies lowercase verbs and uppercase nouns, and this may also look more natural with things like X f Y rather than x F y.

Interestingly, Stack Exchange's syntax colourer seems to make a distinction between uppercase and lowercase identifiers.

Consider naming complex functions

You use two non-trivial trains. Consider giving them meaningful names, which also allows you to remove their parentheses:

  Dirs ← (⊂⌽),⊂
  offsets ← Dirs 2 1

  In_range ← 1∘≤∧≤∘8
  valid ← ^/¨In_range locations

This isn't necessarily required in this case, but could be relevant with more involved code.

Improve performance by keeping arrays flat

To avoid the overhead of pointer chasing, you can implement your function using only flat arrays, and then, as a finalising step, restructure the data as required. Here is a direct translation of your code to flat-array code:

knight_moves_flat←{
⍝ Monadic function, expects a vector with 2 integers
⍝ Given a chessboard position, find the legal knight moves
⍝ Returns a 2-column table
  signs← ,[⍳2] ,⍤1 0⍤0 1⍨ (¯1 1)
  offsets ← (⌽,[1.5]⊢) 2 1
  moves ← ,[⍳2] signs (×⍤1⍤1 2) offsets
  locations ← moves (+⍤1) ⍵
  valid ← ^/(1∘≤∧≤∘8) locations
  ↓valid⌿locations
}

Compare the performance:

      ]runtime -compare knight_moves¨all knight_moves_flat¨all

  knight_moves¨all      → 7.4E¯4 |   0% ⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕
  knight_moves_flat¨all → 5.0E¯4 | -34% ⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕

The price here is that the code becomes somewhat more involved and less clear.

For an alternative algorithm with even better performance, see Roger Hui's blog post 2019 APL Problem Solving Competition: Phase I Problems Sample Solutions.

Ultimate performance through lookups

If you need to call the function many (more than 100) times, you can get the ultimate performance by pre-computing all the results (by any means). This is because the input domain is rather limited. With only 64 valid arguments, you pay a 64-fold setup cost, but after that, the only costs will be looking up an argument in a list of valid arguments and then picking the corresponding result from a list of results. However, in this case, where the argument already is a proper argument for ⊃, you can simply use the argument directly to pick a result from a vector of vectors of results, thus avoiding even the lookup cost:

all ← ⍳ 8 8
results ← ↓knight_moves¨all
knight_moves_pick ← ⊃∘results

Throughput increases with almost two orders of magnitude compared to the flat edition:

      ]runtime -c knight_moves_flat¨all knight_moves_pick¨all

  knight_moves_flat¨all → 4.4E¯4 |   0% ⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕
  knight_moves_pick¨all → 5.2E¯6 | -99%

Since the result-picking is almost free in comparison to actually computing each result, the setup cost is paid off after less than 100 applications, and is certainly negligible in the above comparison where each expression is run well over 10000 (1002) times. Instead, you pay though additional storage space being required:

      (⍪,⎕SIZE)⎕NL 3
knight_moves       2800
knight_moves_flat  3512
knight_moves_pick 19088

The fully expanded text representation of the function is also unreadable:

knight_moves_pick ← ⊃∘(((2 3)(3 2))((3 1)(2 4)(3 3))((2 1)(3 2)(2 5)(3 4))((2 2)(3 3)(2 6)(3 5))((2 3)(3 4)(2 7)(3 6))((2 4)(3 5)(2 8)(3 7))((2 5)(3 6)(3 8))((2 6)(3 7)))(((1 3)(3 3)(4 2))((1 4)(4 1)(3 4)(4 3))((1 1)(1 5)(3 1)(4 2)(3 5)(4 4))((1 2)(1 6)(3 2)(4 3)(3 6)(4 5))((1 3)(1 7)(3 3)(4 4)(3 7)(4 6))((1 4)(1 8)(3 4)(4 5)(3 8)(4 7))((1 5)(3 5)(4 6)(4 8))((1 6)(3 6)(4 7)))(((2 3)(1 2)(4 3)(5 2))((1 1)(2 4)(1 3)(5 1)(4 4)(5 3))((2 1)(1 2)(2 5)(1 4)(4 1)(5 2)(4 5)(5 4))((2 2)(1 3)(2 6)(1 5)(4 2)(5 3)(4 6)(5 5))((2 3)(1 4)(2 7)(1 6)(4 3)(5 4)(4 7)(5 6))((2 4)(1 5)(2 8)(1 7)(4 4)(5 5)(4 8)(5 7))((2 5)(1 6)(1 8)(4 5)(5 6)(5 8))((2 6)(1 7)(4 6)(5 7)))(((3 3)(2 2)(5 3)(6 2))((2 1)(3 4)(2 3)(6 1)(5 4)(6 3))((3 1)(2 2)(3 5)(2 4)(5 1)(6 2)(5 5)(6 4))((3 2)(2 3)(3 6)(2 5)(5 2)(6 3)(5 6)(6 5))((3 3)(2 4)(3 7)(2 6)(5 3)(6 4)(5 7)(6 6))((3 4)(2 5)(3 8)(2 7)(5 4)(6 5)(5 8)(6 7))((3 5)(2 6)(2 8)(5 5)(6 6)(6 8))((3 6)(2 7)(5 6)(6 7)))(((4 3)(3 2)(6 3)(7 2))((3 1)(4 4)(3 3)(7 1)(6 4)(7 3))((4 1)(3 2)(4 5)(3 4)(6 1)(7 2)(6 5)(7 4))((4 2)(3 3)(4 6)(3 5)(6 2)(7 3)(6 6)(7 5))((4 3)(3 4)(4 7)(3 6)(6 3)(7 4)(6 7)(7 6))((4 4)(3 5)(4 8)(3 7)(6 4)(7 5)(6 8)(7 7))((4 5)(3 6)(3 8)(6 5)(7 6)(7 8))((4 6)(3 7)(6 6)(7 7)))(((5 3)(4 2)(7 3)(8 2))((4 1)(5 4)(4 3)(8 1)(7 4)(8 3))((5 1)(4 2)(5 5)(4 4)(7 1)(8 2)(7 5)(8 4))((5 2)(4 3)(5 6)(4 5)(7 2)(8 3)(7 6)(8 5))((5 3)(4 4)(5 7)(4 6)(7 3)(8 4)(7 7)(8 6))((5 4)(4 5)(5 8)(4 7)(7 4)(8 5)(7 8)(8 7))((5 5)(4 6)(4 8)(7 5)(8 6)(8 8))((5 6)(4 7)(7 6)(8 7)))(((6 3)(5 2)(8 3))((5 1)(6 4)(5 3)(8 4))((6 1)(5 2)(6 5)(5 4)(8 1)(8 5))((6 2)(5 3)(6 6)(5 5)(8 2)(8 6))((6 3)(5 4)(6 7)(5 6)(8 3)(8 7))((6 4)(5 5)(6 8)(5 7)(8 4)(8 8))((6 5)(5 6)(5 8)(8 5))((6 6)(5 7)(8 6)))(((7 3)(6 2))((6 1)(7 4)(6 3))((7 1)(6 2)(7 5)(6 4))((7 2)(6 3)(7 6)(6 5))((7 3)(6 4)(7 7)(6 6))((7 4)(6 5)(7 8)(6 7))((7 5)(6 6)(6 8))((7 6)(6 7)))

It is interesting to note that just parsing the giant constant takes about as long as computing it.


I'd rename Numbers to isPrime
num is not needed. maxNumber serves the same purpose.
Termination condition in the elimination loops must be <, not <=. With an unfortunate value of maxNumber, the latter would make an illegal access.
An inner elimination loop can be shortened to

for (int b = a; b*a <= num; ) {
    isPrime[b*a] = false;
    b += 2;
    if (b%3 == 0)
        b+=2;
}

It is worth noticing that i+=6, j+=6 serves the same purpose as if (b%3 == 0) b+=2. Better be unified (it looks like an expensive modulo operator can be avoided). I'd seriously consider splitting each loop into two independent loops with increment 6.
Finally, the implementation is not slow (other than using %), but it is not any faster than a standard sieve.


Polymorphic pointers-to-functions whose parameters are void pointers as arguments in C

This doesn't really answer your question, but when using function pointers it is usually easier to use a typedef:

typedef void (*Action) (void * const);
static Action action[] = { (Action) number, (Action) letter };

Also the calling of the action would be better expressed as

struct Thing {
    Action action;
    void *data;
};
...
const struct Thing things[] = {
    { (Action) letter, (void *)&aah },
    { (Action) number, (void *)&five },
    { (Action) number, (void *)&six }
};
for(t = things; t < things + things_size; t++) {
    t->action(t->data);
}


Few things.

This number:

unsigned long max = std::numeric_limits<unsigned long>::max();

Is

18446744073709551615

If we assume that the average size of a number is half this length (so 10 characters). Then the size of the file is:

   184467440737095516150 bytes.
=> 180143985094819830 Kbytes
=> 175921860444150 MBytes
=> 171798691830 GBytes
=> 167772150 TBytes
=> 163830 PBytes
=> 150 XBytes

Unless you have some sort of massive raid. I don't think you have storage space foe all those numbers.

Even if your system uses a smaller number of bits for an unsigned long than mine (say 32 bit). This is still a large file (though doable on modern systems).

=> 15 GBytes (approx)

But the problem is not the speed of the program. Its is the speed that the OS can copy data to the disk. That will be your limiting factor. If you want to see how fast it could write to an optimal disk then use the special file "/dev/null". You can write to this and it uses no disk space.

12G in 2 min is a write rate of:

107374182 bytes a sec or
104857 K/s
102 M/s

A quick Google reveals that 500 M/s is achievable for SSD drives while normal HD achieve approx 100 M/s. So it looks like your desk top has normal spinning platter hard disk and it was going at the top speed.

Laptops are known to slower. Especially when they get hot. The hardware is designed to physically throttle the system to make sure it does not overheat.

Why not create and open the file in one line?

std::ofstream myFile;
myFile.open( "/home/awesome/Desktop/large_numbers.txt" );

I would do this:

std::ofstream myFile( "/home/awesome/Desktop/large_numbers.txt" );

Simpler to use a for(;;) loop than a while().

for(unsigned long i = 0;i <= max; ++i)
    myFile << i << "\n";               // Note because you opened the file in
                                       // text mode. The '\n' character will
                                       // translated into the platform end of
                                       // of line sequence.
}

No need to flush or close the stream manually.

myFile.flush();
myFile.close();

When the object goes out of scope the destructor is called. This will close the file which will flush the content of the buffers first.

#include <iostream>
#include <limits>
#include <fstream>

int main() {

    unsigned long max = std::numeric_limits<unsigned long>::max();

    std::ofstream myFile( "/home/awesome/Desktop/large_numbers.txt" );
    for(unsigned long i = 0; i < max; ++i) {
        myFile << i << "\n";
    }
}


You can make use of the Array.new, passing in the maximum number of stars you want to show, and defaulting all the stars to empty. Then, you can fill in the number of full stars you need. Then, finally, thanks to Numeric's divmod returning either 0 or 1 for the number of half stars you need, you make one more pass and fill in the number of half stars you need:

module StarHelper
  EMPTY_STAR_ICON = 'star'.freeze
  FULL_STAR_ICON = 'star_fill'.freeze
  HALF_STAR_ICON = 'star_lefthalf_fill'.freeze

  def full_and_half_star_count(rating)
    (rating * 2).round.divmod(2)
  end

  def stars(rating, max_stars: 5)
    full_stars, half_stars = full_and_half_star_count(rating)

    Array.new(max_stars, EMPTY_STAR_ICON).
      fill(FULL_STAR_ICON, 0, full_stars).
      fill(HALF_STAR_ICON, full_stars, half_stars)
  end
end


Simplifying Code for Drop-Down-Box in JQuery and HTML

Your code is very big and messy so this a bit tricky to really see what you are trying to do.  A few obvious things to make the code more readable:

Replace .css("display","block") with .show()
Replace .css("display","none") with .hide()
You repeat the same color changing hover over and over again.  Instead, group all your elements together and specify this function only once:

$("#containo div").hover(function() {
    $(this).css("color","#FF7722");
},function() {
    $(this).css("color","#005BAB");
});
Do not nest hovers inside other hovers.  .hover() creates a new event handler when it is called.  If you nest them then you each time you move your mouse over the parent, the child is assigned a new event handler.  You do not want these duplicates.  Instead assign all of your events in the root level.

This, plus a little refactoring could reduce your code considerably.  Maybe from here the code will be easier to work with so could see how to reduce it further.

$(document).ready(function() {

    function on(selector) {
        $(selector).css("color","#FF7722");
    };
    function off(selector) {
        $(selector).css("color","#005BAB");
    };

    $("#interact,#online,#tablet,#mobile,#dai,#iguide,#tv,.droptv,#vod,.dropvod")
    .hover(function(){
        on(this)
    },function(){
        off(this)
    });

    $("#tv, .droptv").hover(function(){
        $(".droptv").show();
    },function(){
        $(".droptv").hide();
    });

    $("#vod, .dropvod").hover(function(){
        on("#vod");
        $(".dropvod").show();
    },function(){
        off(".dropvod");
        $(".dropvod").hide();
    });

    $(".tab, .drop").hover(function(){
        on(".tab");
        $(".drop").show();
    },function(){
        off(".tab");
        $(".drop").hide();
    });
});


Python script to update an existing column values in a csv from another two tables

Your code as it stands now will open and read file f2 every time you process a line from f1. This is way more work than you need to do.

I suggest you create a dictionary mapping ids to replacement values. You can then read all the lines from table2 one time, and populate the dictionary:

feed_desc = dict()

with open(table2) as tbl2:
    t2csv = csv.reader(tbl2)
    next(t2csv)  # skip headings

    for t2row in t2csv:
        feed_id = t2row[1]
        desc = t2row[2]

        feed_desc[feed_id] = desc

Once that is done, you can simply check if an id is in feed_desc, and if so provide the replacement value:

with ...
    ...
    for t1row in t1csv:
        feed_id = t1row[2]

        if feed_id in feed_desc:
            t1row[2] = feed_desc   # replace id with desc, you said.

        t1writer.writerow(t1row)

You can do a similar thing for t3 into a different dictionary. Just make sure you read both t2 and t3 before you start processing t1.


function loadDoc(UrlString) {
  var xhttp = new XMLHttpRequest();

First, I'd suggest replacing that XHR code with the newer fetch. There's a polyfill for it for older browsers. fetch returns Promises, which should be analogous to monads if I'm not mistaken.

xhttp.onreadystatechange = function() {
  if (xhttp.readyState == 4 && xhttp.status == 200) {
    document.getElementById("storybox").innerHTML = xhttp.responseText;
  }
};

Next would be to pull in the functionality that updates HTML to the caller instead of pushing it out to your AJAX operation. One big problem with your approach is that you're pushing out functionality all over the place. This becomes maintenance headache as the logic is all over the place. Should I want to change storybox to something else, I would have to trace all the way to loadDoc.

For that big switch statement, use an object as a map instead. Have it hold the url values. When a key doesn't exist, it should return undefined which you can easily default using || and a right-hand-side value.

In the end, your code can be as simple as:

var defaultUrl = 'templates/story/pt1/Start.html';

var urls = {
  YesStart: 'templates/story/pt1/YesStart.html',
  Sleep: 'templates/story/pt1/Sleep.html',
  Swindon: 'templates/story/pt1/Swindon.html'
};

function buttonClicked(buttonid){
  fetch(urls[buttonid] || defaultUrl).then(function(response) {
    return response.text()
  }).then(function(body) {
    document.getElementById("storybox").innerHTML = body
  })
}


Printing twin primes less than a given natural number n

The differences between the two pieces of code are piling up.

The ones that I notice right away are the differences in the style or formatting

Let's first format them the same so that we can tell what is actually different.

This is the second piece of code, in which there are still some things I don't like, but we will get to that.

int n, p, q, f;
n = 0;
p = 3;
q = 5;
f = 0;

scanf("%d", &n);

while (q < n)
{
    f = 1;
    for (int i = 2; i <= p / 2; i++)
    {
        if (p%i==0)
        {
            f = 0; break;
        }
    }
    for (int i = 2; i <= q / 2; i++)
    {
        if (q%i == 0)
        {
            f = 0;
            break;
        }
    }
    if (f)
    {
        printf("p = %d, q = %d\n", p, q);
    }
    p++;
    q++;
}

Here you could actually create you f variable inside of the While loop instead of at the top.

Don't one-line if statements so you don't have to use brackets for the For loop. dangerous coding.  Just use brackets (curly braces).

What are all these variables? I don't know what they are or what they do.  Please use more descriptive variable names.

I don't know what the standard for C is, but in C# you wouldn't declare all your Variables in one line, so this looks bad to me.

Sometimes you put spaces in between operators and variables and sometimes you don't, please use spaces.

The first piece of code looked like it was formatted pretty well. The only thing that I did was to break up the variable declarations and space some things out a little bit.

I would still recommend that you create more memorable variable names though.

int n;
int p;
int q;

scanf_s("%d", &n);

p = 1;
q = 2;

char flag = 1;

while (q < n)
{
    flag = 1;
    for (int i = 2; i <= sqrt(q); i++)
    {
        if (q % i == 0)
        {
            flag = 0;
            break;
        }
    }
    if (flag)
    {
        if (q - p == 2)
        printf("%d %d\n", p, q);
        p = q;
    }
    q++;
}

Not assigning the variable n is probably a really bad idea, definitely not a good habit to fall into for sure.

I have been corrected, it is okay to not assign to n but you don't check the value returned by the scanf and that could result in a null reference exception

One thing that I noticed is that you are using either an integer or a char datatype for a flag, why wouldn't you use a boolean type or even a bit instead?

It looks like you could use an #include if you are in C99.

#include <stdbool.h>

but it does appear that the other options are integers except for one which is an Enum

Option 1

typedef int bool;
#define true 1
#define false 0

Option 2

typedef int bool;
enum { false, true };

Option 3

typedef enum { false, true } bool;

Reference: answer to -> Using boolean values in C

So I guess that it would make sense to use an integer.  The char might even make sense since it is an integer type.  But I think it would be less confusing if you defined a data type or at the very least label it flag and not f.


I changed the main part of the script to:

from time import time
start = time()
val = LSMPut(1, 0.06, 0.15, 100, 90, 20, 40_000, 5)
print(f'Done in {time() - start:.3} seconds')
print(val)

The point is that Python will print how long the calculation took to
run. Before modifications, the script takes 3.05 seconds to run on my
computer.

Now I can modify lsmput (I renamed LSMPut and some other functions
and variables because they names shouldn't contain capital letters
according to the Python style guide) and see which changes makes it
run faster.

Here follows the changes that impacted the runtime the most. Changing

z=np.array([np.random.standard_normal() for _ in range(paths)])

to

z = np.random.standard_normal(paths)

brings the runtime down to 2.43 seconds. Changing

ones=[1 for _ in range(len(X))]

to

ones = np.ones(len(X))

reduces the runtime further to 2.21 seconds. Precalculating the powers
of X in basis_funct like this

X2 = X**2
X3 = X**3
X4 = X**4
X5 = X**5
...
A = np.column_stack((ones, 1 - X, 1/2 * (2 - 4*X + X2), ...

saves an additional 100 milliseconds. Changing

itmPaths = [index for index,value in enumerate(K - S) if value > 0]

to

itmPaths = np.nonzero((K - S) > 0)[0]

brings the runtime down to about 1.60 seconds. I think you see the
pattern now; anytime you loop over a numpy array there's a numpy
builtin function to do the job better and faster.

Then in the calculation of rest_paths:

rest_paths = np.setdiff1d(np.arange(0, paths - 1, 1), exPaths)

Is the paths - 1 intentional here? Looks like a bug to me. Assuming
it is a bug, updating P can be done more efficiently, like this:

mask = np.zeros(P.shape, dtype = bool)
...
mask.fill(False)
mask[itmPaths[Pt > C]] = True

P[mask] = Pt[Pt > C]
P[~mask] *= e_r_dt

Final code

The modified code runs in about 420 milliseconds on my computer. Note
that I have removed all branches except for the k == 5 one from the
basis_funct function. It should be straightforward for you to add it
back.

import sys
import numpy as np

# Uncomment this line during development to always get the same random
# numbers.
# np.random.seed(1234)

def lsmput(T, r, sigma, K, S0, TimeSteps, paths, k):
    dt = T/TimeSteps
    t = np.arange(0, T+dt, dt).tolist()

    z = np.random.standard_normal(paths)
    w = (r-sigma**2/2)*T + sigma*np.sqrt(T)*z

    S = S0*np.exp(w)
    P = np.maximum(K - S,0)

    e_r_dt = np.exp(-r * dt)
    mask = np.zeros(P.shape, dtype = bool)
    for i in range(TimeSteps-1, -1, -1):
        z = np.random.standard_normal(paths)
        w = t[i]*w/t[i+1] + sigma*np.sqrt(dt*t[i]/t[i+1])*z

        S = S0 * np.exp(w)
        itmPaths = np.nonzero(K > S)[0]
        itmS = S[itmPaths]
        Pt = K - itmS

        itmDiscP = P[itmPaths] * e_r_dt

        A = basis_funct(itmS, k)
        beta = np.linalg.lstsq(A, itmDiscP)[0]
        C = np.dot(A, beta)

        mask.fill(False)
        mask[itmPaths[Pt > C]] = True

        P[mask] = Pt[Pt > C]
        P[~mask] *= e_r_dt
    return np.mean(P * e_r_dt)

def basis_funct(X, k):
    ones = np.ones(len(X))
    assert k == 5
    X2 = X**2
    X3 = X**3
    X4 = X**4
    X5 = X**5
    A = np.column_stack((ones, 1 - X,
                         1/2 * (2 - 4*X + X2),
                         1/6 * (6 - 18*X + 9*X2 - X3),
                         1/24 * (24 - 96*X + 72*X2 - 16*X3 + X4),
                         1/120 * (120 - 600*X + 600*X2 - 200*X3 + 25*X4 - X5)))
    return A

from time import time
start = time()
val = lsmput(1, 0.06, 0.15, 100, 90, 20, 40_000, 5)
print(f'Done in {time() - start:.3} seconds')
print(val)


I'm not sure if you really desire that output. But I'll do some refactoring to show what your code does.

In your code

def create_game_data():
    columns = {}
    for column in columnNames.keys():
        columnValues = []
        for event in events:
            columnValues.append(columnNames[column]) if column in columnNames.keys() else columnValues.append("NA")
        columns[column] = columnValues
    return columns

there is an if condition always true. if column in columnNames.keys() is always true for your loop for column in columnNames.keys(). So we skip that test

def create_game_data():
    columns = {}
    for column in columnNames.keys():
        columnValues = []
        for event in events:
            columnValues.append(columnNames[column])
        columns[column] = columnValues
    return columns

Next we find that you loop over the events without using them. So we could safely write

def create_game_data():
    columns = {}
    for column in columnNames.keys():
        columnValues = []
        for _ in events:
            columnValues.append(columnNames[column])
        columns[column] = columnValues
    return columns

This is equivalent to

def create_game_data():
    columns = {}
    for column in columnNames.keys():
        columns[column] = [columnNames[column]] * len(events)
    return columns

Now we chose to iterate over the dict in a key-value manner

def create_game_data():
    columns = {}
    for column, name in columnNames.items():
        columns[column] = [name] * len(events)
    return columns

Which is easily written as comprehension

def create_game_data():
    return {k:[v] * len(events) for k, v in columnNames.items()}

Is that really what you want?


Check for the presence of multiple files

You could use zipmap:

(defn all-files-present?
  [file-seq]
  (let [f  #(bit-flip (look-for % "f") 0)]
    (zipmap (map keyword file-seq) (map f file-seq))))

or juxt:

(defn all-files-present?
  [file-seq]
  (let [f  #(bit-flip (look-for % "f") 0)]
    (into {} (map (juxt keyword f) file-seq))))

Note that I use bit-flip instead of the if to flip 1<->0.

It would be nicer if kind-stat would just return a boolen value, so you would simply use

(defn kind-stat
  [filename expected-type]
  (let [f (File. filename)]
      (= expected-type
        (cond
          (.isFile f)       "f"
          (.isDirectory f)  "d"
          (.exists f)       "o"
           :else            "n"))))

(defn all-files-present?
  [file-seq]
  (let [f  #(if (kind-stat % "f") 1 0)]
    (into {} (map (juxt keyword f) file-seq))))

I removed look-for, since it is virtually useless.


Custom CSRF protection in Express / Node

Not a node expert, but it looks like you cover the basics.  CSRF protection via token is standard practice and very reliable.  You are generating your token via a cryptographically secure random number generator.  You are leaving it in the session and making sure it is present on all post requests.  The only way an attacker can break it is via XSS attack, but XSS attacks are able to defeat any CSRF protection, so that isn't your fault (just make sure that you are practicing defense in depth), nor will CSRF vulnerability be your biggest problem if you have an XSS vulnerability.  Your weaknesses are the same as any CSRF implementation:

Failure to actually implement your CSRF protection on all pages.  Most common cause of CSRF vulnerabilities is either people trying non-standard protection methods (which you are not doing), or inadvertently leaving actions out of CSRF protection.
You can accidentally leave action URLs unprotected if you somehow build a URL that doesn't use your CSRF middleware or if you inadvertently allow GET requests to execute actions, in which case the CSRF protection will be explicitly ignored by your code.  So the biggest weakness is the same weakness that everyone has: you have to follow best security practices everywhere else in your code.  Forget it one place and your CSRF protection disappears.  If you have a valuable enough website someone will find the vulnerability.

In terms of improvements, the only reasonable addition would be to change your CSRF token after every request.  Many systems implement this additional layer of security.  It is not clear to me if this additional security step has any practical benefits, but if it isn't difficult to implement it certainly won't hurt to include it.  In my own implementations in the past I've used it for additional UI help: I keep track of past CSRF tokens and if I see a duplicate come in (which is usually caused by the user hitting "submit" twice on a form), I ignore the second request and warn the user of their error.

You could also consider a dual-protection using referrer and origin headers, but those have mixed results due to incomplete browser support.  Most frameworks I have seen stick with a token-only protection.

I don't think your alternate implementation adds anything.  Throwing in a sha256 hash certainly doesn't change anything, because hashing doesn't introduce any additional randomness.  It just makes things look more random.  The host header doesn't inherently add additional security, IMO.  This is very similar to an attempt to add protection via the ORIGIN or REFERRER headers.  In this particular case, I don't think a more complicated algorithm is worth the (dubious) increase in security.  If you did want to also verify such a header then I would ditch the hash: just store it in the session in plain text and check it on the way back up.  However, you probably don't have to store it in the session either: most of the time you should know what the host, origin, or referrer should be.  No need to store it to check it later.


Reading and processing a file using Pandas

Generator expression

I advice using a generator expression instead of map:

map(lambda x: os.path.join(data_folder, x), os.listdir(data_folder))

should become:

(os.path.join(data_folder, x) for x  in os.listdir(data_folder))

Also x should be renamed to something more expressive.

Separation of concerns

You both print and return values, if the printing is for debugging purposes, use logger.log

Specific Exception

If you write:

except Exception, e:

any Exception will be caught, I suggest IOException.


Possible bug

The method isHeap takes an array along with a start and end index. Although the code does try to take into account potential out of bounds by checking 2 * i + 1 <= end and 2 * i <= end, there is no check that end is strictly lower than heap.length. As such, out of bounds array indexes can still occur:

isHeapReview(new int[] { 0 }, 0, 1);

would throw an java.lang.ArrayIndexOutOfBoundsException: 1. There are multiple solutions depending on the intended usage of the method:

You can defend from such a case by re-defining end to be the minimum of the given end and heap.length - 1 with Math.min(end, heap.length - 1).
You can check if end is greater or equal than heap.length and, if true, throw an IllegalArgumentException.

In the same way, there is no check that start is a positive integer. Those checks should be added to it too.

Code style

Watch out your indentation style and braces. The following

if(2 * i + 1 <= END && heap[i] < heap[2 * i + 1])
        return false;
else if(2 * i <= END && heap[i] < heap[2 * i])
        return false;

doesn't use curly braces and is not indented properly. Even if they are redundant, it is best to explicitely add the curly braces, as they prevent future possible issues. Use this style instead:

if (2 * i + 1 <= end && heap[i] < heap[2 * i + 1]) {
    return false;
} else if (2 * i <= end && heap[i] < heap[2 * i]) {
    return false;
}

where the braces were added, indentation is fixed, spaces are added after if; all of this contribute to easier to read code.

Simplification

end / 2 performs integer division and will return an integer, so invoking Math.ceil on it will have no effect. You can remove it; the code already loops from 0 to end / 2 inclusive.

Also, since end is expected to be lower or equal than heap.length - 1, you can remove the 2 * i <= END check in:

if (2 * i <= END && heap[i] < heap[2 * i])

This will always be true since i maximal value is end / 2.

With this change, you can even refactor the if statement to:

if (2 * i + 1 <= END && heap[i] < heap[2 * i + 1] || heap[i] < heap[2 * i]) {
    return false;
}

without the need of an else if statement. It does make the line a tiny bit longer, but it is short enough to typically fit on a screen and is pretty direct.

Namings

Don't write the parameters in upper-case; only use this for constants. START should really be start; in the same way, END should be end.


Euler 12: counting divisors of a triangle number

This is not a review, but an extended comment.

Project Euler problems are about math, not programming. To optimize, you need to do the math homework first:

The \$n\$'th triangular number is \$\dfrac{n (n+1)}{2}\$.
A number of divisors, aka \$\sigma_0\$, is a multiplicative function. The link to divisor function may also be interesting.
\$n\$ and \$n+1\$ are coprime.

That should be enough to get you started with optimization.


Doubling the even digits and subtracting 9 if > 10 would be mod 9 so a really simple, compact algorithm might be:

for (int i = 0; i < nDigits; i++)
{
    int   digit = digitArray [i] - '0';   // Char to number
    if  (i & 1)  // Digit 1, 3, 5 not 0, 2, 4 - "even digits" starting at 1
        if  ((digit <<= 1) >= 10) //  Double it, check >= 10
            digit -= 9;           //  Same as summing the digits
    shuma += digit;
}
int checksum = shuma % 10;


Here's a quick attempt to clean it up:

c.on('ready', function() {
  return Promise.all(config.clientCheckPaths.map(function (lookInPath) {
    console.log('Examining ' + lookInPath);
    // Go get directory contents.
    return listAsync(lookInPath).then(function(files){
      return files.map(function(i){
        i.lookInPath = lookInPath;
        return i;
      });
    })
  }))
  .then(flatten)
  .then(function (files) {
    console.log('Files: ' + files.map(function (i) { return i.name; }));
    // Filter it down to only the files we want.
    return Promise.all(
      files.filter(function (item) {
        return config.isFileWanted(item.name);
      }).map(downloadWantedFiles)
    );
  });
});

function downloadWantedFiles(x) {
  // For each file, go download it.
  var fullPath = x.lookInPath + '/' + x.name;
  console.log("Wanted file: " + x.lookInPath + '/' + x.name + ", " + Object.keys(x));
  return getAsync(fullPath)
    .then(writeLocalFile(fullPath))
    .catch(couldNotDownload(fullPath))
  });
}

function writeLocalFile(fullPath) {
  return function (stream) {
    // With the stream, name it something reasonable on the disk.
    var localFileName = '/tmp/' + fullPath.replace(/[^A-Za-z0-9\.]/g, '_');
    console.log("Writing stream to " + localFileName);
    var write = stream.pipe(fs.createWriteStream(localFileName));
    // Only resolve once the local file has been written to disk
    return new Promise(function(resolve, reject){
      write.on('end', resolve.bind(null, localFileName));
      write.on('error', reject);
    });
  }
}

function couldNotDownload(fullPath) {
  return function (err) {
    var msg = 'Getting file ' + fullPath + ' failed with ' + err;
    console.error(msg);
    return Promise.reject(err);
  }
}

function flatten(arr) {
  return arr.reduce(function (memo, val) {
    var args = Array.isArray(val)
      ? flatten(val)
      : [val];
    memo.push.apply(memo, args);
    return memo;
  }, []);
}


Insertion Sort and Selection Sort Implementation

First tip: use more aggressive warnings, this way you would be warned by the compiler about passing unused parameters into functions, that is you would automatically made:

template<typename Iter>
Iter minIndex(Iter start, Iter end)

Another thing would be, to write your algorithms in similar way as the standard ones. That is avoid passing the reference to the container, but rather pass iterators into it. So your sort functions should look similarly to:

<typename InputIt>
void someSort (InputIt first, InputIt last)

This will e.g. allow you to sort specific parts of your container with no extra effort.


Building a UI to fetch list of features and edit them

Syntax and Compatibility

Most browsers will balk at the redefinition of a function parameter using the let keyword here:

// builds the list of features
function buildFeaturesList(featureList) {
    let featureList = featureList || activeFeatures

Chrome: Uncaught SyntaxError: Identifier 'featureList' has already been declared
Firefox: SyntaxError: redeclaration of formal parameter featureList
IE11: Let/Const redeclaration

This can be corrected by replacing let with var in this instance. Note that the primary difference between let and var is that let is block-scoped, while var is function-scoped. Since the block containing this variable declaration is a function anyway, you don't gain any advantage by using let.

IE11 also does not yet support arrow (=>) syntax for lambda functions, but if you don't have to support such users you can ignore that problem.

Avoid modifying innerHTML directly

Direct modification of an element's innerHTML property should be avoided whenever possible. It has performance drawbacks (forcing the browser to re-evaluate the DOM with each modification) and it can create memory leaks (when code retains references to elements that have been destroyed by overwriting their HTML).

Instead, consider these approaches:

Clearing innerHTML

To clear the innerHTML without creating memory leaks, instead of features.innerHTML = ''; you can use a loop to remove all child nodes:

while(features.childNodes.length > 0){
    features.removeChild(features.childNodes[features.childNodes.length - 1]);
}

A for loop can be more efficient since you can avoid accessing the childNodes.length property multiple times.

for(let i = features.childNodes.length-1; i >= 0; i--){
    features.removeChild(features.childNodes[i]);
}

Appending to innerHTML

To append to innerHTML without forcing the DOM to reload with every change, you can use element.insertAdjacentHTML().

For example, instead of list.innerHTML += stringValue use list.insertAdjacentHTML("beforeend",stringValue):

list.insertAdjacentHTML("beforeend",
    '
 '
    + item.feature + '
'
    + injectVariants(item.variants) + '

'
);

Note that you might also want to consider element.appendChild() which lets you append any HTML element by its reference, such as the reference obtained when you create an element using document.createElement(). That approach is more versatile (you can retain references to the elements in code and attach event handlers to the elements programmatically) but will be slightly slower than element.insertAdjacentHTML().


The following code is similar to your method 2:

def is_unimodal(seq):
    i = 1
    end = len(seq)
    while i < end and seq[i - 1] < seq[i]:
        i += 1
    while i < end and seq[i - 1] == seq[i]:
        i += 1
    while i < end and seq[i - 1] > seq[i]:
        i += 1
    return i == end

This code probably looks more like C than Python, but I expect it to be fast and readable.


Checking password strength while honoring functional requirements

Your flags shouldn't be in the types definition.
types should be a constant, move it out of the function.
It'd be simpler if you used set.__isub__ and set.__and__, and looped through the types array.

It leaves all the unwanted values in the password too. Allowing for possible improvements on point 3.
You can join the sum and the base for loop together, removing the need for a types list.

TYPES = (
    frozenset(string.whitespace),
    frozenset(string.ascii_lowercase),
    frozenset(string.ascii_uppercase),
    frozenset(string.digits),
    frozenset(string.punctuation)
)

def estimate_quality(password):
    if not password:
        return 0

    password_set = set(password)
    space = 0
    for group in TYPES:
        if password_set & group:
            space += len(group)
        password_set -= group

    if password_set:
        return -1

    return math.ceil(math.log2(space) * len(password))


Code for movement controller of the player in Unity

First of all, I didn't like the long method names you used in the script.
like:

void Start ()
{
    initializeNeededForMovementVariables();
}

I mean, why did you need to call it like that? In my opinion this makes the code very messy once you have a lot of code in a script.
I would had call it something like: "InitVariables" or simply "Init"

Again,

float moveHorizontallyValue = Input.GetAxis("Horizontal");

The same point applies here too. You could have just written:

float h = Input.GetAxis("Horizontal");

Another thing: Why are you doing the following block?

private void playAnimationOfHorizontalMovement()
{
    if (currentSpeed == walkingSpeed)
    { playerAnimationController.beingOnlyWalking(); }
    else if(currentSpeed == runningSpeed)
    { playerAnimationController.beingOnlyRunning(); }
}

You have all this code to play animations. I suppose you are using other scripts too, and again, this is my opinion, it makes everything not totally understandable.

Then, Why aren't using an animator?

The code would be A LOT less and also A LOT more understandable, plus WAY EASIER to code!

Now, don't worry if your code isn't perfect now, you'll get better at it. It requires time. I really hope this helps you, Let me know!

Cheers


Some obvious changes that I'd make:

rename all the variables / methods such that they follow the snake_case convention
remove all the obvious comments and rather add a docstrings into each function instead
add only one space before and after any operator (except if we're passing some arguments into a function / class)
after , you should have a space
the acceptedWord list should be defined within the getWords() function (the same goes for the difficulty dictionary). (or better yet, remove its declaration completely and use list comprehension instead)
you should add if __name__ == '__main__'
user_list is already a list so you don't have to specify the exact same thing here: for item in list(user_list).
use string formatting when you print something: this: print(correct_guess, "out of ", len(true_list), "correct.") will become this: print("{} out of {}".format(correct_guess, len(true_list)))
when you use with to open a file in read mode, you can omit r as that's passed by default.

Reviewed code:
import random

def get_words():
    """Docstring goes here"""
    difficulty = {1: [4, 5, 6], 2: [7, 8], 3: [9, 10, 11], 4: [12, 13], 5: [14, 15]}
    while True:
        try:
            level = int(input("What difficulty would you like? (1,2,3,4,5) "))
            break
        except (ValueError, KeyError):
            print("That is not a number")

    num = random.choice(difficulty[level])

    with open('wordbank.txt') as file:
        accepted_word = [x for x in map(str.upper, map(str.strip, file.readlines())) if len(x) == num]

    answers = random.sample(accepted_word, num)
    true_word = answers[random.randint(0, len(answers) - 1)]
    print('\n'.join(answers))
    game(true_word)

def game(true_word):
    """Docstring goes here"""
    for x in range(0, 5):
        print("Guesses Left: {}".format(5 - x))
        user_input = input("Guess: ").upper()

        user_list, true_list = list(user_input),  list(true_word)
        if user_input == true_word:
            print("Well done, you guessed correctly")
            get_words()
        correct_guess = 0
        for item in user_list:
            if item == true_list[user_list.index(item)]:
                correct_guess += 1
        print("{} out of {}".format(correct_guess, len(true_list)))
    print("Bad luck! The answer was: {}".format(true_word))
    get_words()

if __name__ == '__main__':
    get_words()

More, I'd split the get_words() methods into two methods: get_user_level() and get_words():
def get_user_level():
    """Docstring goes here"""
    difficulty = {1: [4, 5, 6], 2: [7, 8], 3: [9, 10, 11], 4: [12, 13], 5: [14, 15]}
    while True:
        try:
            level = int(input("What difficulty would you like? (1,2,3,4,5) "))
            break
        except (ValueError, KeyError):
            print("That is not a number")

    return random.choice(difficulty[level])

def get_words():
    """Docstring goes here"""
    num = get_user_level()

    with open('wordbank.txt') as file:
        accepted_word = [x for x in map(str.upper, map(str.strip, file.readlines())) if len(x) == num]

    answers = random.sample(accepted_word, num)
    true_word = answers[random.randint(0, len(answers) - 1)]
    print('\n'.join(answers))
    game(true_word)


The config looks great. However, a few points:

If your server responds to both the www and non-www version of the site, just leave a wildcard. So server name should read:

server_name    *.my-site.com;

You shouldn't put your configs in /etc/nginx/conf.d. Instead, place them in /etc/nginx/sites-available and then symlink them (ln -s) to /etc/nginx/sites-enabled. So, your /etc/nginx directory should look like:

 /etc/nginx/
     nginx.conf
     sites-available/
     my-site.conf
     my-other-site.conf
     yet-another-site.conf
 sites-enabled/
     my-site.conf -> /etc/nginx/sites-available/my-site.conf
     my-other-site.conf -> /etc/nginx/sites-available/my-other-site.conf
     yet-another-site.conf -> /etc/nginx/sites-available/yet-another-site.conf


Your code doesn’t have great complexity. I think it’s \$\mathcal{O}(2^n)\$, but I’m rusty so maybe somebody can come in with an assist. The thing to remember is that Haskell lists are linked lists and laziness doesn’t get you out of paying the cost of walking them. Each call to everyOther is \$\mathcal{O}(n)\$, and you pay that twice with every recursive call.
There are a bunch of ways we could solve this. If you actually want to process lists like a binary tree for some reason, then I’d recommend just turning the list into a binary tree and processing that if you’re favoring clarity. If you do that you could get the compiler to fuse away the intermediate structure, but it might not happen automatically without some pragmas.
You could also decompose your problem into smaller, easier to solve bits, then reassemble them into your ultimate solution.
-- Do a single pass through a list, summing elements pairwise
sumPairs :: Num a => [a] -> [a]
sumPairs [] = [0]
sumPairs [n] = [n]
sumPairs (m:n:xs) = m + n : sumPairs xs

-- Identify when there's only a single element left in the list
isLengthOne :: [a] -> Bool
isLengthOne [_] = True
isLengthOne _ = False

-- Repeatedly apply sumPairs until you find a one element list and return that value
pairwiseSum :: Num a => [a] -> a
pairwiseSum = head . find isLengthOne . iterate sumPairs

If you’re looking for testing and benchmarking libraries, check out QuickCheck for testing and criterion for benchmarking.
QuickCheck does what’s known as property testing, instead of constructing elaborate unit tests the library helps you to test random inputs to see if some property holds. Usually that’s things like testing that a function to insert an element into a collection increases that collections size by one, or that after a random sequence of inserts the collection contains all of the elements that were inserted. In this case you can use it to prove equivalence between two versions of functions that should have identical results. I.e.—
import Test.QuickCheck

prop_sumsEqual :: [Int] -> Bool
prop_sumsEqual xs = pairwiseSum xs == sum xs

main :: IO ()
main = quickCheck prop_sumsEqual

criterion handles re-running benchmarks for you and gives you all sorts of fancy statistical output. You might use it like—
import Criterion.Main

main :: IO ()
main = defaultMain [bench "pairwiseSum" $ nf pairwiseSum [1 .. 10000]]

You could bench sum by adding another list element there and compare the difference. Or you could take advantage of your benchmarks being values to generate a series, that might help you understand how your execution time grows with input size.
mkBench_pairwiseSum :: Int -> Benchmark
mkBench_pairwiseSum n = bench ("pairwiseSum:" ++ show n) $ nf pairwiseSum [1 .. n]

main :: IO ()
main = defaultMain $ map mkBench_pairwiseSum [10000, 20000 .. 100000]


The ConfigManager needs some clean-up because to my taste it's too tigthly coupled to the Sirius server and thus it's not testable.

First, make the constructor simpler. Constructors should not do any heavy job. Ideally the should only initialize fields or properties.

Move its logic into a new method like LoadFromOrDefault so that you know that it either loads the configuration from the specified file or gives you a default one that we move into a new DefaultSettings method.

The new LoadFromOrDefault not requries you to specify the file-name, a Func to determine whether the file is locked and a logger.

internal sealed class ConfigManager : IEnumerable<KeyValuePair<string, string>>
{
    private readonly Dictionary<string, string> _settings;
    private readonly ILogger _logger;

    public ConfigManager(IDictionary<string, string> settings, ILogger logger)
    {
        _settings = new Dictionary<string, string>(settings);
        _logger = logger;
    }

    public static IDictionary<string, string> DefaultSettings() => new Dictionary<string, string>
    {
        { "database.host", "localhost" },
        // ..
    };

    public static ConfigManager  LoadFlomOrDefault(string fileName, Func<string, bool> isLocked, ILogger logger)
    {
        var stopwatch = Stopwatch.StartNew();

        try
        {
            if (File.Exists(fileName) && isLocked(fileName))
            {
                var settings = File.ReadLines(fileName)
                    .Where(IsConfigurationLine)
                    .Select(line => line.Split('='))
                    .ToDictionary(line => line[0], line => line[1]);
                return new ConfigManager(settings, logger);
            }
            else
            {
                logger.Warn("Using the default configuration.");
                return new ConfigManager(DefaultSettings(), logger);
            }
        }
        catch (Exception exception)
        {
            logger.Error(exception.Message, exception);
            return null;
        }
        finally
        {
            logger.Information("Loaded Config Data [" + stopwatch.ElapsedMilliseconds + "ms]");
            stopwatch.Stop();
        }
    }

    private static bool IsConfigurationLine(string line)
    {
        return !line.StartsWith("#") && line.Contains("=");
    }

    public string GetConfigElement(string key)
    {
        string value;

        if (!_settings.TryGetValue(key, out value))
        {
            _logger.Error("Missing configuration key `" + key + "`");
        }

        return value;
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
    {
        return _settings.GetEnumerator();
    }
}

You can use it like this:

var config = ConfigManager.LoadFromOrDefault(
    "myconfig.ini",
    fileName => Sirius.GetServer().GetUtility().IsFileLocked(new FileInfo(configFile)),
    Sirius.GetServer().GetLogManager()
);

And agian, you can now test it without the Sirius server.

Desclimer: This is just a rough idea and not ready-to-use code so it might contain some small bugs or not entirely satisfy your needs yet.


Slow performance in looping and filling missing data

It looks like you just need VLookup. In column B1 of your active sheet you'll want =VLookup(A1,Feuil1!$A$1:$B$4,2,0). Make sure to edit Feuil1!$A$1:$B$4 to be the entire range you want. If your range is contiguous, no empty cells, Control+Shift+Down followed by Holding Shift+RightArrow ought to get you what you're after.

Edit:
Below you'll find code that does what you're attempting.

The reason why your initial code is so slow is you have a loop For Each ... Next within another loop. Inside this is checking each and every single one. and must go through the both lists. If in your first loop (ActiveSheet) you have 10 entries and your second loop (Feuil1) you have 15 entries you have to compare 150 times. If either list grows it will get slower and slower. By
 refactoring you have the same outcome but achieved by a better, faster, way.

Strive for code that is self documenting. What is occurring should be apparent when you read it. Minimal effort should be needed to understand what is going on.

The code below has a main Sub that sets some variables and calls on functions to provide information to complete the required task.

Public Sub TraiterNoms()
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    Dim actSheet As Worksheet
    Set actSheet = ActiveSheet

    Dim sourceSheet As Worksheet
    Set sourceSheet = ThisWorkbook.Worksheets("Feuil1")

    Dim lastFormulaRow As Long
    lastFormulaRow = actSheet.Cells(Rows.Count, 1).End(xlUp).Row
    Dim formulaRange As Range

    On Error GoTo NoBlankCells
    Set formulaRange = actSheet.Range(actSheet.Cells(1, 2), actSheet.Cells(lastFormulaRow, 2)).SpecialCells(xlCellTypeBlanks)
    On Error GoTo 0

    Dim lookupFormula As String
    lookupFormula = GetLookupFormula(formulaRange, sourceSheet, 2)
    formulaRange.Formula = lookupFormula
    Dim subArea As Range
    For Each subArea In formulaRange.Areas
        subArea.Value2 = subArea.Value2
    Next

CleanExit:
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
    Exit Sub

NoBlankCells:
    Resume CleanExit

End Sub

Private Function GetLookupFormula(ByVal depositRange As Range, ByVal lookupSheet As Worksheet, ByVal lookupColumn As Long) As String
    Dim valueToMatch As String
    valueToMatch = depositRange.Cells(1, 1).Offset(ColumnOffset:=-1).Address(False, False)

    Dim lookupCells As String
    lookupCells = GetLookupCells(lookupSheet, lookupColumn)
    GetLookupFormula = "=Vlookup(" & valueToMatch & "," & lookupCells & "," & lookupColumn & ",0)"
End Function

Private Function GetLookupCells(ByVal sourceSheet As Worksheet, ByVal lookupColumn As Long) As String
    Dim lastRow As Long
    lastRow = sourceSheet.Cells(Rows.Count, "B").End(xlUp).Row

    Dim sourceRange As Range
    Set sourceRange = sourceSheet.Range(sourceSheet.Cells(1, 1), sourceSheet.Cells(lastRow, lookupColumn))

    GetLookupCells = sourceRange.Parent.Name & "!" & sourceRange.Address
End Function


SQL query C++ code (My first C++ application)

I found this code very difficult to understand, and I feel that I won't be alone. I can't refactor it (for the aforementioned reason) nevertheless some advice which you might find instructive:

Please use names which people will make sense of: column_name_list, opt, "F", opterr etc etc - this makes reading code very difficult.
formatting - please use good formatting it all makes a difference.
break things up into methods so that each method is doing only one thing.
Add better comments if things are not self-explanatory.

My two cents.


This script mixes jQuery DOM lookups (e.g. $(".respond")) with native DOM lookups (e.g. document.getElementById('videoElement')). It is best to use only one style to avoid confusion (e.g. for anyone reading your code, including your future self). If you are going to load jQuery on the page then you might as well use it. Otherwise if you don't need it then it could reduce the page load time slightly if it is removed. You might find this article interesting.

Indentation is inconsistent, though maybe that was a mistake during insertion of the code into your post.

The first line in playVid() references videoElement which looks up the element by id attribute implicitly.

function playVid() {
    videoElement.play();

This can also confuse readers of your code. Because myVid points to that same element, that variable could be used instead.

function playVid() {
    myVid.play();