Append multiple children to a node at once

First the code

Some changes to improve the function.

Node.prototype.appendChildren = function() {
  let children = [...arguments];  // old school

ES6 way

 Node.prototype.appendChildren = function(...children) {

The following is too complicated

  if (
    children.length == 1 &&
    Object.prototype.toString.call(children[0]) === "[object Array]"
  ) {
    children = children[0];
  }

To check for an array

if(Array.isArray(children[0])){...

But you are better of doing that in the loop, then you can handle arrays of arrays

  const documentFragment = document.createDocumentFragment();
  children.forEach(c => documentFragment.appendChild(c));

becomes

  const documentFragment = document.createDocumentFragment();
  children.forEach(child => {
      if (Array.isArray(child)) {
          child.forEach(child => documentFragment.appendChild(child))
      } else {
          documentFragment.appendChild(child);
      }
  });
  this.appendChild(documentFragment);

  // will handle
  foo.appendChildren(bar, [bar1, bar2, bar3]);

The design.

There are some that will argue that adding to a built in prototype is inviting disaster, others will argue its a great way to extend the functionality of the API.

As I see it there are two types of environments.

You share the page with a variety of 3rd party scripts, adverts and what not.
The page is yours alone and no other code, but yours, will ever see that page.

Case 1

For case 1 you should avoid adding to the prototype, as you can not trust it. Someone else may have already added that name to the prototype and you clobber their code, or they may run after you and they clobber yours.

If you must do it, first check

if(typeof Node.prototype.appendChildren === "undefined"){

}else{
     // someone already has added something with that name
}

And if you add it lock it so it can not be over written

Object.defineProperty(Node.prototype, 'appendChildren ', {
     writable : false,    // dont let them over write it
     enumerable : true,   // dont hide it
     configurable : false,   // dont let them change the config so that they
                             // can over write it
     value : function(...children) {... the rest of the function
});

That with the other check ensures you don't step on toes, and your code is safe as well. Though what to do if that function is already taken is an issue that is best solved by not adding to the prototype and just creating a function

function appendChildrenToNode(node, ...children){
  const documentFragment = document.createDocumentFragment();
  children.forEach(child => {
      if (Array.isArray(child)) {
          child.forEach(child => documentFragment.appendChild(child))
      } else {
          documentFragment.appendChild(child);
      }
  });
  node.appendChild(documentFragment);
}

Case 2

For case 2. Do what you want its safe, but be sure you dont forget about it and use it on a public page. In other words do the first case setup to be safe.


Assuming that you load the data into your DataTable instances from database, it's better to issue a direct DELETE FROM ... query over database rather than iterate on a client.

As a side note - it is an awful practice to compare dates by comparing strings. If your table has a DateTime column it's much better to cast the value to DateTime and compare typed dates like that:

DateTime dateFromRange = ((DateTime)rw[0]).Date;
....

    DateTime getDate = ((DateTime)row[0]).Date;
    if (dateFromRange == getDate)
....


A few things straight away:

You have a class called India which really just holds a collection of States. I would suggest not using that class at all, instead creating a List<State> States instead.

Info as a suffix is fairly meaningless, particularly when the object is a collection.

You also do not need to put obj in front of objects you create. In C#, everything is an object, so that means absolutely nothing.

In addition, the names you've chosen for parameters are particularly bad. Asia might be a good value, but continent is a far better variable name.

Last of all, you may want to use object initializers:

public class Country
{
    public string Name { get; set; }
    public string Continent { get; set; }
    public string Zone { get; set; }
    public List<State> Country { get; set; }
}

public void PopulateCountry(string name, string continent, string timeZone, string stateCode, string stateName)
{
    var state = new State
    {
        StateCode = stateCode,
        StateName = stateName
    }
    var country = new Country
    {
        Continent = continent,
        Name = name,
        Zone = timeZone,
        Country = new List<State> { state }
    }
}

This isn't everything you can do. It may make more sense to make a Country class if you plan on adding other things to it. This at the very least makes your code simpler, though.

Alternatively, you could assign a country like this, anywhere:

var country = new Country
{
    Continent = continent,
    Name = name,
    Zone = timeZone,
    Country = new List<State>
    {
       new State
       {
           Name = stateName1,
           Code = stateCode1
       },
       new State
       {
           Name = stateName2,
           Code = stateCode2
       },
    }
}

Or even:

var country = new Country
{
    Continent = continent,
    Name = name,
    Zone = timeZone
}
country.Country = names.Zip(codes, (x, y) => new State { Name = x, Code = y };

Or something close to it, assuming the two are in the correct order. You have many options.


Writing and reading code from a text file

eof inside a loop condition

See why is eof inside a loop condition considered wrong? You do not want to do:

while (!myCourseSummary.eof())
{
    myCourseSummary >> word;
    count++;
}

You do want to do:

while (myCourseSummary >> word)
{
    count++;
}

Arbitrary length course names

You are reading coureses into a char[20]. What if I have a 25-character course name? What about 50? What if it has a space in it? You need to handle all of these conditions, so you should prefer to std::getline a std::string.

Actually solve the problem

The problem statement is:

  read an external text file (“myCourse.txt”) which contains all the course name and numbers you are taking this semester

But you are prompting the user for course names and writing them to a file. You should read the file directly.

Also:

  generate an analysis (total number of courses) into an external file (“myCourseSummay.txt”)

You are currently writing into "myCourse.txt" and reading from "myCouresSummary.txt". The question asks you to read from the first, and write a number into the latter. That is:

std::ifstream myCourse("myCourse.txt");
// do some reading
// come up with what count is

std::ofstream myCourseSummary("myCourseSummary.txt");
myCourseSummary >> count;

You should be able to handle any number of courses. Just read from the file until it's done.


Tell, Don't Ask when dealing with displaying model attributes or a null replacement

Definitely, this does not belong in the model. The orthodox way is to create a helper. Note how you can use the pattern Object#presence:

module ApplicationHelper
  def show_field(field, value)
    value.presence || "#{field}: unknown"
  end
end

And use it in the views:

<%= show_field("Name", user.full_name) %>

You can go a step further and use OOP view presenters if you like the idea (personally I don't use them).


"Need at least two file arguments: Destination Source {Source {Source {...}}}"

I think an easier way of documenting that, at least for *nix, is:

"Need at least two file arguments: DESTINATION [SOURCE]..."

You can also turn the Paths in your main() method into a Stream too:

public class Linemerge {
    // ...

    // suggestion note: had to wrap IOException -> UncheckedIOException too
    private static void merge(Path source, Set<String> seen, BufferedWriter writer) {
        try (Stream<String> words = Files.lines(source)) {
            words.filter(seen::add).forEach(word -> writeWord(writer, word));
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    private static final Predicate<Path> FILTER =
            f -> Files.isRegularFile(f) && Files.isReadable(f);

    private static void checkPath(Path path) {
        System.out.println((FILTER.test(path) ? "Merging"
                : "Unable to read (and ignoring)") + " " + path);
    }

    public static void main(String[] args) {
        if (args.length < 2) {
            throw new IllegalArgumentException(
                    "Need at least two file arguments: DESTINATION [SOURCE]...");
        }
        try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(args[0]))) {
            Set<String> seen = new HashSet<>();
            Stream.of(args).skip(1).map(Paths::get).peek(Linemerge::checkPath)
                    .filter(FILTER).forEach(f -> merge(f, seen, writer));
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}


The most problem in "@Html.HiddenFor" is that users may change this value by means of a browser developer window or CSRF, for avoiding last one you can use

@Html.AntiForgeryToken()

You can protect your application from adverse changes if you will reread all hidden properties such as LocalizeId, Key and Type from your data source before applying user's changes.


Get closest Entity from the Player on a 2D battlefield

First of all, this function would be more idiomatic using a foreach loop:

Entity closest = null;
int distance = int.MaxValue;

for (var other in entities)
{
    int d = Math.Abs((other.X + other.Y) - (player.X + player.Y));
    if(d < distance)
    {
        closest = other;
    }
}
return closest;

  When the Entity number starts growing, the game seems to get a little slow, with FPS drop. I was thinking of maintaining the Entities list ordered, so I would help the branch predictor, I don't know...

If you can keep entities sorted by their e.X + e.Y value,
then you could significantly speed up the search using binary search:
you will be able to find the position of the player in the list,
and check only its two neighbors to find the closest.

However, keeping the entities sorted might be costly as well.
I don't know if that's the case here,
it depends on the rest of your application that you did not include in the post.
My guess is that it's going to be so costly that you will not gain any benefit at all.

On the other hand,
if you need to find the closest entity for not only one player,
but multiple entities,
and if you perform that step for all entities at once,
then you will benefit from performing the sort right before you look for the closest neighbors.
This is different from keeping the entities sorted at all times.
You would only sort right before it's needed.


Sorting linked list with comparator in Java

If you're using Java Collections in any Java version later than 5, you should be using generic typing.  It's an easy way to provide type safety without dealing with casting, multiple class-specific implementations of collections, or the other hassles that have long since been forgotten.  And with the latest Java versions, you don't even need to specify the generic type of the assigned object due to type inheritance, so adding generics support is as simple as:

LinkedList<String> lList = new LinkedList<>();

and:

private static <E> ListIterator<E> midpointIterator(LinkedList<E> lList) {
    return lList.listIterator( lList.size() / 2 );
}

Which brings me to another point: use descriptive method and object names!  Looking at the name of the getIterator method made me wonder why the objects weren't being inserted at the beginning when I ran the code.  midpointIterator (or something similar) lets me know that the ListIterator I'm getting back starts at the midpoint.

Likewise with the comparator:

class StringLengthComparator implements Comparator<String>{
    public int compare(String s1, String s2) {
        return s1.length() - s2.length();
    }
}

Now I know that it compares the length of the Strings passed to it.

On the topic of Strings: are you sure you want to use them?  Because it looks like you're trying to sort a list of numbers, in which case you should use a LinkedList<Integer> and a Comparator<Integer>, although Collections.sort(List)'s default comparator will do the job fine.  Right now you're calling Collections.sort(List), which sorts in character order, and Collections.sort(List, Comparator) using your String length comparator, which sorts by length.  This puts them in numerical order:

LinkedList before sort:     [75, 2, 0, 1, 10, 25, 60, 40, 70, 2, 3, 4, 5, 6, 10, 15]
LinkedList default sort:    [0, 1, 10, 10, 15, 2, 2, 25, 3, 4, 40, 5, 6, 60, 70, 75]
LinkedList comparator sort: [0, 1, 2, 2, 3, 4, 5, 6, 10, 10, 15, 25, 40, 60, 70, 75]

I think what you're really looking to do is something like this:

import java.util.Collections;
import java.util.LinkedList;
import java.util.ListIterator;

public class LinkedListSort {
    public static void main(String[] args) {
        LinkedList<Integer> linkedList = new LinkedList<>();
        linkedList.add(1);
        linkedList.add(2);
        linkedList.add(3);
        linkedList.add(4);
        linkedList.add(5);
        linkedList.addFirst(0);
        linkedList.add(6);
        linkedList.addFirst(2);
        linkedList.add(3, 10);
        linkedList.add(4,25);
        midpointIterator( linkedList ).add( 60 );
        linkedList.add(10);
        linkedList.add(15);
        linkedList.add(6,40);
        midpointIterator( linkedList ).add(70);
        linkedList.addFirst(75);

        System.out.println("LinkedList before sort:  " + linkedList);
        Collections.sort(linkedList);
        System.out.println("LinkedList default sort: " + linkedList);
    }

    private static <E> ListIterator<E> midpointIterator(LinkedList<E> lList) {
        return lList.listIterator( lList.size() / 2 );
    }
}


There is a problem in your code. Assuming that input is [3, 2, 1], the program will work like this.

Set first and second as 3.
Iterate through elements noticing that nothing is larger than 3.
Claim that 3 is the second number.

To fix this, you can do something like this.

if (arr[0] < arr[1]) {
    second = arr[0];
    first = arr[1];
}
else {
    second = arr[1];
    first = arr[0];
}

for (i = 2; i < elems; i++) {
    /* Your code */
}

Also, your program doesn't work well when NaN is involved in first position. This probably doesn't really matter (currently this handles integers, not double floating point numbers), but this may be still relevant for you, as it would require some special code to handle NaN.


Creating formatted "[time] [unit] ago" messages from a seconds value

First, here is my recommended replacement for your script (inspired by this SO post) and some test cases:
Code: (Demo)
function secondsToTime($seconds) {
    $dtF = new DateTime('@0');
    $dtT = new DateTime("@$seconds");
    $diff = $dtF->diff($dtT);
    $units = [
        'y' => 'year',
        'm' => 'month',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second'
    ];
    foreach ($units as $char => $unit) {
        if ($diff->$char) {
            if ($char === 'd' && $diff->$char >= 7) {
                $diff->$char = floor($diff->$char / 7);
                $unit = 'week';
            }
            return sprintf(
                '%d %s%s ago',
                $diff->$char,
                $unit,
                $diff->$char !== 1 ? 's' : ''
            );
        }
    }
}

$tests = [
    53 =>  53,           // y=0, m=0, d=0,  h=0, i=0,  s=53
    365 => 365,          // y=0, m=0, d=0,  h=0, i=6,  s=5
    7200 => 7200,        // y=0, m=0, d=0,  h=2, i=0,  s=0
    176455 => 176455,    // y=0, m=0, d=2,  h=1, i=0,  s=55
    2002000 => 2002000,  // y=0, m=0, d=23, h=4, i=6,  s=40
    4592000 => 4592000,  // y=0, m=1, d=22, h=3, i=33, s=20
    66536000 => 66536000 // y=2, m=1, d=9,  h=2, i=13, s=20
];

var_export(
    array_map('secondsToTime', $tests)
);

Output:
array (
  53 => '53 seconds ago',
  365 => '6 minutes ago',
  7200 => '2 hours ago',
  176455 => '2 days ago',
  2002000 => '3 weeks ago',
  4592000 => '1 month ago',
  66536000 => '2 years ago',
)

By leveraging the beauty of a PHP DateTime object, you can pick out the largest non-zero unit from the diff() evaluation and do a quick return from the loop/function.  As a bonus, you won't need to worry about daylight savings or leap years or anything -- trust the diff() method.
If you call var_export($diff), you will see that there are additional properties populated, but you only need 6 of them.
I don't think I'd bother with the overhead of a pluralizing function, just write the condition as an inline condition (ternary).
If you want to make $unit a constant, okay, because it won't be mutated.
The only special handling that is necessary is the week calculation because that is not an instantly available property in the object.  Do the simple arithmetic and change the unit to be presented and proceed with returning the desired string.

As for critiquing your code:

$ans is always returned but it is not always declared; I assuming this is a typo that you overlooked.
Your is_plural() condition block is missing its curly braces.
else if as two words in php is a violation of PSR-12 coding standards.  You should form one word as elseif.
I hope that your -1 return is never reached, but if it does then that would suggest that you need to validate your incoming seconds value.


Small Markov chain Monte Carlo implementation

def mcmc(prior_dist, size=100000, burn=1000, thin=10, Z=3, N=10):
    import random
    from scipy.stats import binom

Don't import inside functions. It goes against python convention and is inefficient

    #Make Markov chain (Monte Carlo)
    mc = [0] #Initialize markov chain
    while len(mc) < thin*size + burn:
        cand = random.gauss(mc[-1], 1) #Propose candidate
        ratio = (binom.pmf(Z, N, cand)*prior_dist(cand, size)) / (binom.pmf(Z, N, mc[-1])*prior_dist(mc[-1], size))
        if ratio > random.random(): #Acceptence criteria
            mc.append(cand)
    else:
        mc.append(mc[-1])

Why is this in else clause? It only make sense to use else clauses if you are using break.

    #Take sample
    sample = []
    for i in range(len(mc)):
        if i >= burn and (i-burn)%thin == 0:
            sample.append(mc[i])

Actually something like sample = mc[burn::thin] will have the same effect as this loop

    sample = sorted(sample)
    #Estimate posterior probability
    post = []
    for p in sample:
        post.append(binom.pmf(Z, N, p) * prior_dist(p, size))

I'd suggest post = [binom.pmf(Z, N, p) * prior_dist(p, size) for p in sample]

    return sample, post, mc

def uniform_prior_distribution(p, size):
    prior = 1.0/size
    return prior


Another Brainfuck interpreter in Haskell

I find this very difficult to read without any logical line breaks or function types given. I.e., you should leave a blank line between definitions for different functions, and every top-level definition should be given a type signature.

fromList :: [a] -> ZL a
fromList []     = EM
fromList (x:xs) = ZL [] x xs

zprv :: ZL a -> ZL a
zprv EM               = EM
zprv (ZL []     x rs) = EM
zprv (ZL (l:ls) x rs) = ZL ls l (x:rs)

-- &c...

zmap is a partial function, and it isn't acting much like a mapping as it only modifies the current element in your given definition. Maybe zapp is a better name? (Or poke, or prod, or...)

zapp :: (a -> a) -> ZL a -> ZL a
zapp _ EM           = EM             -- Or, raise a descriptive `error`
zapp f (ZL ls x rs) = ZL ls (f x) rs

The definition of run is extremely long and not very semantic, rewrite it to be the composition of smaller, more compositional, more meaningful functions.

zinc :: (Num a) => ZL a -> ZL a
zinc = zapp (+1)

zdec :: (Num a) => ZL a -> ZL a
zdec = zapp (subtract 1)

zjmp :: (ZL a -> ZL a) -> Int -> ZL a -> ZL a
zjmp _   1  i@(ZL _ ']' _) = znxt i
zjmp _ (-1) i@(ZL _ '[' _) = znxt i
zjmp d   n  i@(ZL l '[' r) = zjmp d (n+1) (d i)
zjmp d   n  i@(ZL l ']' r) = zjmp d (n-1) (d i)
zjmp d   n  i@(ZL l   _ r) = zjmp d n     (d i)

interpret :: ZL Int -> ZL Char -> IO ()
interpret _                 EM          = return ()
interpret m              i@(ZL _ '>' _) = interpret (znxt m) (znxt i)
interpret m              i@(ZL _ '<' _) = interpret (zprv m) (znxt i)
interpret m              i@(ZL _ '+' _) = interpret (zinc m) (znxt i)
interpret m              i@(ZL _ '-' _) = interpret (zdec m) (znxt i)
interpret m@(ZL _  x _ ) i@(ZL _ '[' _) = interpret m (if x /= 0 then znxt i else zjmp znxt 0 i)
interpret m@(ZL _  x _ ) i@(ZL _ ']' _) = interpret m (if x == 0 then znxt i else zjmp zprv 0 i)
interpret m@(ZL _  x _ ) i@(ZL _ '.' _) = putChar (toEnum x) >> interpret m (znxt i)
interpret m@(ZL ml _ mr) i@(ZL _ ',' _) = getChar >>= \x -> interpret (ZL ml (fromEnum x) mr) (znxt i)
interpret m              i@(ZL _ _   _) = interpret m (znxt i) -- Comment `Char`

run :: String -> IO ()
run program = interpret tape (fromList program)
    where
        tape :: ZL Int
        tape = fromList (repeat 0)

Your usage of do is redundant in main. You can either just drop the word do, or write it more idiomatically as—

main :: IO ()
main = do
          args <- getArgs
          case args of
              [x] -> do
                        program <- readFile x
                        run program
              _   -> usage
    where
        usage = putStrLn "Usage: bf FILE"


You can remove result = false;, as result is already false.

And to get rid of the nested statements, you could use early returns:

if (userName == null && password == null) {
    return false;
}

if (userName.length <= 0 && password.length <= 0) {
    State.xx.isSaved = false;
    return false;
}
State.xx.isSaved = true;
State.xx.userName = userName;
State.xx.password = password;
return true;

Is it correct that when username is null, isSaved = false should not be set? Because if not, then you could just combine the two if statements, either in my example, or in yours.


URLify a given String - replace spaces with %20

Review
Welcome to Code Review. There are some suggestions as follows.
Consider to use replaceAll
The operation you performed is what String.replaceAll do, you can use replaceAll directly instead of String.toCharArray(), whitespace comparison, and sb.append things.
Create a method URLify
In order to improve usability, it is better to create a method URLify to perform this specific operation.
Summary
Combine all the things:
public class URLify {

    public static String URLify(String input){
        return input.stripTrailing().replaceAll(" ","%20");
    }

    public static void main(String[] args) {
        String str = "Mr John Smith  ";
        System.out.println(URLify(str));
    }
}


Firstly, I would advise you to look at how blaze-html implements their monads for HTML templating. They are doing something very similar to what you want to do.

You can simplify your definitions a bit by removing the second field from the LeftList constructor:

data LeftList a r = LeftList [a]

Then every place where you use the constructor LeftList you can omit the (now) extraneous (), e.g. the >> definition simplifies to:

  (LeftList xs) >> (LeftList ys) = LeftList (xs ++ ys)

You should also make group, describe, and toTests more general by using a type variable instead of ():

group :: String -> LeftList H.Test r -> LeftList H.Test r

This makes these functions valid for any return type r - not just ().
Of course, you don't care what the return type is anyway. But GHC cares - and allowing a general return type might help with type checking.

It actually is possible to define bind for the LeftList monad -- just pass in undefined or error "...":

  (>>=) (LeftList xs) f = let LeftList ys = f (error "LeftList does not support binding")
                          in LeftList (xs++ys)

An error will occur only if the parameter to f is actually evaluated.

For instance, this will not throw an error:

"foo" ... do
   x <- "with even numbers" ~:
           4 ~=? foo 4
   "with odd numbers" ~:
     0 ~=? foo 5

because the value x is never evaluated.

Finally, with GHC 7.10 you will also have to define Functor and Applicative instances for your monad:

instance Functor (LeftList a) where
  fmap f left = left

instance Applicative (LeftList a) where
  pure _ = LeftList []  -- should be same as return
  (<*>)  = undefined


Angular component to render currency or date values

The syntax of both the pipes:

Currency Pipe

{{ value_expression | currency [ : currencyCode [ : display [ : digitsInfo [ : locale ] ] ] ] }}

and Date Pipe

{{ value_expression | date [ : format [ : timezone [ : locale ] ] ] }}

In my understanding, we must use pipes to integrate directly into the "templates" and avoid writing excess code in the component.
In your approach, passing the pipe names and the other parameters appears to me as a redundant step.

My approach would be:

<app-custom-label value="{{10000 | currency:'EUR':true:null:'de-DE'}}" title="My Title for a Currency render"></app-custom-label>
<app-custom-label value="{{'01.10.1980' | date:'dd MMMM':null:'de-DE'}}" title="My Title for a Date render">


Project Euler #58: Primes along the diagonals of a square spiral

A bit of math

It is interesting to see that the corners of a square of size \$s\$ have values: \$s^2-3s+3\$, \$s^2-2s+2\$, \$s^2-s+1\$, \$s^2\$. (Also \$s^2\$ is not a prime ;-))

To be continued later.


If you have repeating values I think the second if(arr[mid]==temp) can fail.

Separate the create the test from the program (method).  Return a value from method and print it in the test.

The first if (arr[mid] == key) that is the least likely condition so put it last and  it can just be an else as you should test for < and > so = is all that is left.

You repeatedly reference arr[mid] when you already have it temp = arr[mid];

You have max = n - 1; but you don't use it in the create test loop

Put assignments on separate lines
This still has problems - this is just cleaning up existing code

static void Main(string[] args)
{
    int n = int.Parse(Console.ReadLine());
    int key = int.Parse(Console.ReadLine());
    int[] arr = new int[n];
    int min = 0;
    int max = n - 1;
    int mid = min + (max - min) / 2;
    int temp;
    for (int i = 0; i <= max; i++)
    {
        arr[i] = i * 5;
    }
    while (true)
    {
        temp = arr[mid];
        if (temp < key)
        {
            min = mid;  // this seems backwards but that is what you have
        }
        else if (temp > key)
        {
            max = mid;
        }
        else
        {
            Console.WriteLine("Position is: " + mid);
            break;
        }
        mid = min + (max - min) / 2;
        if (arr[mid] == temp)  // this still has problems
        {
            Console.WriteLine("Not Found");
            break;
        }
    }
}


You could do something like:

for x in ["type", "typeTwo"] {
    if let type = object[x] where !type.isEmpty,
        let name = object["name"],
        defenseChart = pokemonTypeDefenseChart[type] { /* ... */ }
}

Also, to simplify the rest of your code, you could extend Dictionary like this:

extension Dictionary {
    subscript(key: Key, fallback fallback: Value) -> Value {
        get { return self[key] ?? fallback }
        set { self[key] = newValue }
    }
}

This allows you to replace this:

for weakness in defenseChart {
    if pokemonWeaknessChart[weakness] == nil {
        pokemonWeaknessChart[weakness] = []
    }
    pokemonWeaknessChart[weakness]?.append(name)
}

by this:

for weakness in defenseChart {
    pokemonWeaknessChart[weakness, fallback: []].append(name)
}


Reduce code complexity by applying ternary operator

Before deciding to use more ternary operators in your code, let's understand what if/else is about:

When the expression in the if clause is resolved to true, the block right after it is executed. If that expression is resolved to false, and there is an else block indicated, that block is executed.

An else if clause is needed if when the first condition is false there is still more than one execution option, based on a second(different) condition.

In your code you keep checking one condition, and then the opposite one, although this is totally redundant. if (x==false) is true then (x==true) is always false, and vice versa. Asking the same question and then the opposite is not only redundant, but also a maintenance risk, since you need to change the condition, you need to remember also changing the opposite one.

Also you should try to make all your conditions positive conditions - refrain from asking if(!string.IsNullOrEmpty(eventStatus.cancelDate)) - it is far better to switch the if and else blocks and ask if(string.IsNullOrEmpty(eventStatus.cancelDate)) - the ! operator ("not") is easy to miss, and may cause confusion. Of course, if only one block is implemented - no else block is better than no if block - leave the condition as it is.

To sum the above, a better code would look like this:

if (!string.IsNullOrEmpty(SessionValues.AccessToken))
{
    eventstatuscode = "logged";
    EventStatus eventStatus = rb.GetEventStatus();
    if (eventStatus != null)
    {
        if (string.IsNullOrEmpty(eventStatus.cancelDate))
        {
            eventstatuscode = eventStatus.onWaitingList ? "waitinglist" : "accepted";
        } else {
            eventstatuscode = DateTime.Parse(eventDetails.signUpDeadline) < DateTime.Now ? "expired": eventstatuscode;
        }
    }
    else
    {
        eventstatuscode = DateTime.Parse(eventDetails.signUpDeadline) < DateTime.Now ? "expired" : eventstatuscode;
    }
}

Now it is easier to see that the same line is indicated twice - the "expired" line. By combining the two if clauses - we can reduce that to only once (this is called being DRY):

if (!string.IsNullOrEmpty(SessionValues.AccessToken))
{
    eventstatuscode = null;
    EventStatus eventStatus = rb.GetEventStatus();
    if (eventStatus != null && string.IsNullOrEmpty(eventStatus.cancelDate))
    {
        eventstatuscode = eventStatus.onWaitingList ? "waitinglist" : "accepted";
    }
    else
    {
        eventstatuscode = DateTime.Parse(eventDetails.signUpDeadline) < DateTime.Now ? "expired" : "logged";
    }
}


I can't be very detailed here because I haven't worked in C lately. But basically, yes, you should move more of the code out of the if statements into the breakout functions.
Specifically, each break-out function should have the same signature (type/arity). Based on the examples you've given so far, these appear to be quite open-ended effectful subroutines, each comparable to a mini main, so they might as well have signature ()->int. Or maybe there'll be enough structure to their behavior that you can be more specific than that, IDK.
If you're going to print out the fancy headers, abstract that away into a helper function.
Anyway, you might consider even getting rid of the if itself, in favor of a lookup-table of functions. Exactly how to implement that will depend a bit on the context; it's not something I've ever done in C.


First of all, I think that your variable names are quite good.

  Should I be returning False? Or 0?

I would recommend None

Don't repeat yourself

As you can see, the two branches of your if else are very similar.

Instead you could do a

if path is None:
    fullpath = file_pattern
else:
    fullpath = path + '/' + file_pattern

But joining paths like this is not very pythonic (and might cause problems on windows).

Instead, fullpath = os.path.join(path, file_pattern) is what you are looking for.

About the arguments

You can take inspiration of the os.path.join even further and change the order of your arguments (and completely remove the branching):

def get_latest_file(path, *paths):
    fullpath = os.path.join(path, paths)
    ...
get_latest_file('example', 'files','randomtext011.*.txt')

Use docstrings

And then you might think that the way to call it is not trivial and want to document it: let's use a docstring !

def get_latest_file(path, *paths):
    """Returns the name of the latest (most recent) file
    of the joined path(s)"""
    fullpath = os.path.join(path, *paths)

Miscellaneous

If you use Python 3, you can use iglob instead.

For the os.path.split, I prefer using it like this (instead of the 1 index):

folder, filename = os.path.split(latest_file)

The import datetime is not used.

Instead of if len(list_of_files)> 0:, you can simply do if list_of_files:

Revised code

def get_latest_file(path, *paths):
    """Returns the name of the latest (most recent) file
    of the joined path(s)"""
    fullpath = os.path.join(path, *paths)
    list_of_files = glob.glob(fullpath)  # You may use iglob in Python3
    if not list_of_files:                # I prefer using the negation
        return None                      # because it behaves like a shortcut
    latest_file = max(list_of_files, key=os.path.getctime)
    _, filename = os.path.split(latest_file)
    return filename


In my Hangman game, one of my functions is correct but messy

Because we always return from the inside of the while, we'll never perform the loop more than once. Thus, your while actually acts like an if. Thus the value of place is not really used and you can get rid of it : if place < chars becomes if 0 < chars which is if chars which is if len(secretWord) which is really if secretWord because of the way Python considers the empty string as a false value.
Thus, you code could be :

def isWordGuessed(secretWord, lettersGuessed):
    if secretWord:
        if secretWord[0] in lettersGuessed:
            return isWordGuessed(secretWord[1:], lettersGuessed)
        else:
            return False
    return True

Which can be re-written as :

def isWordGuessed(secretWord, lettersGuessed):
    if secretWord:
        return secretWord[0] in lettersGuessed and isWordGuessed(secretWord[1:], lettersGuessed)
    return True

which is then nothing but :

def isWordGuessed(secretWord, lettersGuessed):
    return not secretWord or secretWord[0] in lettersGuessed and isWordGuessed(secretWord[1:], lettersGuessed)

Now, if I was to write the same function, because it is so easy to iterate on strings in Python, I'd probably avoid the recursion and so something like :

def isWordGuessed(secretWord, lettersGuessed):
    for letter in secretWord:
        if letter not in lettersGuessed:
            return False
    return True

Then, there might be a way to make this a one-liner but I find this to be pretty easy to understand and pretty efficient.


Code to sort based on quantities of a data member occuring

int index = 0;
  for (int i = 0; i < 10; ++index, ++i) {
    counts.emplace_back(index, 0);
  }

Not sure why you use index here which is same as i ?

[](auto a, auto b) { return a.second > b.second; }
for (auto i : sort_by) {

a and b, i can be marked const.

 std::vector<int> sort_by(10);
  for (int i = 0; i < 10; ++i) {
    sort_by[i] = counts[i].first;
  }

Not sure that there's a big improvement, but here's a change anyway.
  std::vector<int> sort_by;
  sort_by.reserve(10);
  std::for_each(counts.begin(), counts.end(), [&sort_by](const auto &i) {
    sort_by.push_back(i.first);
  });

for (auto it = devices.begin(); it != devices.end(); ++it) {
  if (it->fizz == i) {
    std::iter_swap(walker, it);
    ++walker;
  }
}

Can be made a bit simpler by using range based for loop & address instead of iterator. Note the reference in &it.
for (auto &it : devices) {
  if (it.fizz == i) {
    std::iter_swap(walker, &it);
    ++walker;
  }
}


Most of this depends on what exactly do you want to achieve. For example, @articles will be a list of references to the same articles that are also referenced in $self->_get_or_create_cache('articles'). Depending on what you want, you might want to clone these values, instead of just pushing them to @articles.

The other thing is a regex for dates. Are you certain that your dates will be, for example, 23/08/2013, and not 23/8/2013? If not, this might be better:

my $date  = defined($month)
    ? qr/^\d{1,2}\/$month\/$year\s\d{1,2}:\d{1,2}:\d{1,2}$/
    : qr/^\d{1,2}\/\d{1,2}\/$year\s\d{1,2}:\d{1,2}:\d{1,2}$/;

The same goes for the times, of course.

Depending on how clean your input is, you might want to replace $month and $year with \Q$month\E and \Q$year\E to avoid matching special characters in those variables (i.e., that . is matched as a dot and not as any character).

If it may be possible for the input to have extra spaces, you might want to add \s* after ^ and before $, while also replacing \s behind $year with \s+.

Day of month can be more precisely matched as (0?[1-9]|[1-2]\d|3[01]) (similar for months, hours, minutes, and seconds), but this makes regexes quite comples, so see if you need this.


Loop Vue2 tag with keyup + modifier and click

No.

Or well, maybe you could but I absolutely do not see any reason to do so.

What each <span> has in common:

The same class
They all have a click event and a keyup event

What each <span> has different:

They all have different handlers for what to do on the click/keyup event
They all have listen for different keyup events.

I don't see any benefit in creating a loop from this.

Some things you might want to consider though is:

Have a method that is performed for both click and the keyup event, to not copy-paste code between the different handlers.
Create a component for <span class="calc-button-control">

If you have plenty of more of these <span> elements, creating a component would be the way to go. Then you could have a component to handle the following:

It is a <span> element and applies the calc-button-control class.
It has a method for what to do when clicked or keyup event triggers.

I am not sure how flexible you can make the keyup listener, I don't think you can for example pass :keypress="enter" or similar to have it listen to @keyup.enter so I am not sure if creating a component for all of this does more harm than good.


Implementation of many-to-many relation Tag Table

Your Insert method has a bug - if a tag exists in a database, you won't add it to your model.Tags collection. Interesting enough, your Update method doesn't have that problem. After you fix that bug, you're left with almost identical part of the code that could also be reused by BlogPost logic.

Because it should be reused, it would be best to place it in your TagService and, after a few improvements, it would look like this:

public void AddTagsToList(ICollection<Tag> tagList, string[] tagNames)
{
  var listOfActualTags = GetTagsByName(tagNames);

  foreach (var tagName in tagNames)
  {
    var tag = listOfActualTags.FirstOrDefault(t => t.Name == tagName);

    if (tag == null)
    {
      tag = new Tag { Name = tagName };
      Insert(tag);
    }

    tagList.Add(tag);
  }
}

Your Insert method would become:

public void Insert(AddNewsItemViewModel newsItemViewModel)
{
  if (newsItemViewModel == null)
    throw new ArgumentNullException("newsItem");

  var model = Mapper.Map<NewsItem>(newsItemViewModel);

  if(newsItemViewModel.Tags.Any())
  {
    _tagService.AddTagsToList(model.Tags, newsItemViewModel.Tags);

    model.MetaKeywords = string.Join(",", newsItemViewModel.Tags);
  }

  _uow.MarkAsAdded(model);
}

And Update method would become:

public void Update(EditNewsItemViewModel newsItemViewModel)
{
  if (newsItemViewModel == null)
      throw new ArgumentNullException("newsItem");
  var model = GetById(newsItemViewModel.Id);
  model = Mapper.Map(newsItemViewModel, model);
  if (model.Tags != null && model.Tags.Any())
    model.Tags.Clear();

  if(newsItemViewModel.Tags.Any())
  {
    _tagService.AddTagsToList(model.Tags, newsItemViewModel.Tags);

    model.MetaKeywords = string.Join(",", newsItemViewModel.Tags);
  }

  _uow.MarkAsChanged(model);
}

As I said, you can reuse _tagService.AddTagsToList method for BlogPost as well by providing the Tags property as a first parameter and a list of tag names as a second parameter.


Revert knockout model original state back on update cancel?

From a KISS perspective, I would simply load the model again, then you would not need any of this code.

Other than that the code is clean and maintainable, some nitpicking though:

You declare var key twice in copy, that is not required
You are not using hasOwnProperty(key) when you delete all the functions in copy
You could have merged source.hasOwnProperty(key) and key === "__ko_mapping__" with a &&
You access source[key] a lot, you could have considered a var value = source[key] and then work with value


Get every information about the Reservation

I hope I have understood this now.

Instead of iterating over all the Duct items and adding each iteration the related Curve to curves you should create another class like

public class DuctCurev
{
    public Duct TheDuct {get; private set; }
    public Curve TheCurve {get; private set; }
    public DuctCurve(Duct duct, Curve curve)
    {
        TheDuct = duct;
        TheCurve = curve;
    }
}

now we iterate once over all of the Duct's and find the related Curve which we will add to a List<DuctCurve> like so

List<DuctCurve> ductCurves = new List<DuctCurve>();
foreach (Duct d in ducts)
{
    ductCurves.Add(d, FindDuctCurve(d));
}

then we need to adjust the remaining code to use the ductCurves and use the ! operator instead of using containsItemX == false like so

foreach (Wall w in walls)
{
    wallFaces = FindWallFace(w);
    foreach (DuctCurve dc in ductCurves)
    {
        foreach (Face f in wallFaces)
        {
            foreach (KeyValuePair<XYZ, Wall> pair in FindInterWalls(dc.Curve, f, walls))
            {
                Reservation.Res res = new Reservation.Res();
                res.RoundCenter = new XYZ(Math.Round(pair.Key.X), Math.Round(pair.Key.Y), Math.Round(pair.Key.Z));
                res.WallWidth = pair.Value.Width;
                bool containsItemX = resList.Any(itemX => itemX.RoundCenter.DistanceTo(res.RoundCenter) < res.WallWidth + 1);

                if (!containsItemX)
                {
                    res.AssociatedWall = pair.Value;
                    res.Radius = 1;
                    res.AssociatedDuct = dc.Duct;

                    res.Center = pair.Key;
                    resList.Add(res);
                    model.Reservations.Add(new Reservation { ResList = resList });
                }
            }
        }
    }
}


Performance

The main cost of your implementation is in two areas, the sorting and the set memebership test.

When you do check for parents, it is generally advisable to update each of the parent of each of the ones you looked at, such that they would only be one step away from their parent the next time. Here is how it could look:

  def shortcut(self, vertex, parent):
    while self.parents[vertex] != -1:
      next = self.parents[vertex]
      self.parents[vertex] = parent
      vertex = next

  def getparent(self, vertex):
    start = vertex
    while self.parents[vertex] != -1:
      vertex = self.parents[vertex]

    self.shortcut(start, vertex)
    return vertex

It can be shown that this assymtotically reduces the cost of the set membership test in this kind of union based data-structure.

You can also cut these comparisons short when you have found the full minimal spanning tree, which would save you all the extra parent lookups for all the edges following in the sorted sequence. You can do this by checking whether you are done after adding an edge with len(mst) == len(self.graph) - 1, and then do a break or return the result, so the code (the loop in the kruskal function) would look like this:

    for edge in self.edges:
        vertex, neighbour, weight_edge = edge
        x_par = self.getparent(vertex)
        y_par = self.getparent(neighbour)
        if x_par != y_par:
          self.union(x_par, y_par)
          mst.append(edge)
          total += weight_edge
          if len(mst) == len(self.graph) - 1:
            break

For sorting you have two problems:

You specify a key function manually, which means the algorithm will have to call that key function.
You sort more of the problem than you really need to.

The first part comes from that sort may be implemented in a faster language (it looks to be so in my installation), which means that it generally runs faster if it never have to enter python code, which the manual key function breaks. If you however changes the order of attributes in how you store your edges, such that the weight is first, then you can use the default comparison, which will do lexiographic ordering, which in turn means you get it sorted primarily on the edge weights.

For the second part, the main problem is that you only need to search until you get the n-1 edges needed to finish the minimum spanning tree, so you only need this amount sorted. It would therefore be advisable to use a sorting scheme, such as heapsort, where you can stop half-way through and only need to effectively pay in performance for the amount you needed. The downside is that the heapq python module looks to be mainly implemented in python, which means its actual performance might be slower unless you really only need a very small subset (this would typically depend on the graph).

Convenience

There are a few areas in the code, which with some improvement would be more convinient/better future-proofed.

The main one here is the need for a simpler way to add several edges to a graph, or even construct a graph with edges already in it. Here is how I would do it:

  def __init__(self, edges=None):

    self.graph = []
    self.edges = []
    self.parents = {}
    self.size = {}
    self.add_edges(edges)

  def add_edges(self, edges=None):
    if edges is not None:
      for edge in edges:
        self.add_node(*edge)

The construction of your graph would then be this simple:

  g = Graph([
    (0, 1, 10)
    (0, 2, 6)
    (0, 3, 5)
    (1, 3, 15)
    (2, 3, 4) ])

In the union fuction, we could parameterize the if statement as follows:

    child, parent = (x_par, y_par) if self.size[x_par] <= self.size[y_par] else (y_par, x_par)
    self.parents[child] = parent
    self.size[parent] += self.size[child]

This would also seperate the orthogonal parts of the logic, which would make it easier to maintain.

Lastly it would be a good idea to have the kruskal method just return mts, total and then print outside, as this would allow actual use of the class in code outside of problems where this is the final solution.


Using a string column is not a very ideal solution. How would you for example query for rows where the price range is within or below 70.00$?

What if you want to do calculations in the database based on the values?

Instead you should use two columns:

create_table "prices", force: :cascade do |t|
  t.decimal   "price_min"
  t.decimal   "price_max"
  t.integer  "percentile"
  t.datetime "created_at",  null: false
  t.datetime "updated_at",  null: false
end

Note that when dealing with money you should use an integer in the lowest unit of currency (cents) or a decimal. See: why not use Double or Float to represent currency?

You can even write a methods in your model to get/set price_range with a range:

class Price
  def price_range
    (price_min..price_max)
  end

  def price_range=(range)
    self[:price_min], self[:price_max] = range.begin, range.end
  end
end

If you are using Postgres you can use the native range database type.

create_table :events do |t|
  t.numrange :price_range
  t.integer  "percentile"
  t.datetime "created_at",  null: false
  t.datetime "updated_at",  null: false
end

You can write a helper method to format it nicely

module PriceHelper
  def price_range_human( range )
    "$%s to $%s" % [range.begin, range.end].map(:number_to_currency)
  end
end

See ActionView::Helpers::NumberHelper


Your code should work ok. However, I would have used a list to store the intermediate results, and then string.Join to create the result. (Also perhaps Linq to filter the data, but then someone not familiar with Linq will have trouble maintaining the code.) Something like

string[] columnN = AnotherString.Split(',');
string[] stringList = new string[columnN.Length];

for (int i = 0; i < columnN.Length; i++)
{
    string cN = columnN[i];
    string resource = Res.ResourceManager.GetString(cN.ToLower().Trim()));
    stringList[i] = resource ?? cN;
}

AnotherString = string.Join(",", stringList);


There are many ways to improve this code. but the two most basic ones would be

To create a simple helper function in order to avoid the repetitive code when running a query.
To separate the database interaction from the presentation logic, making the application more flexible, maintainable and clean-looking.

And one way of improvement I would advise against of: a function that would automate the HTML table creation. Although for the most primitive cases it would do, in reality there are no primitive cases, and you'll end up with a monster that takes more code to configure than to write just plain HTML, and it would completely unreadable compared with a straightforward HTML template.

A function.

function sqlsrv($conn, $sql, $params)
    $result = sqlsrv_query($conn, $sql, $params);
    $return = [];
    while ($row = sqlsrv_fetch_array($result)) {
        $return = $row;
    }
}

this function accepts a connection, an arbitrary query and an array of parameters, and returns a simple array with returned rows.

You can put this function's definition into the same file where your connection is made.

Code separation

This one is simple. Always split your scripts into two parts: data manipulation (AKA business logic) and a template (aka presentation logic). So you can refactor your code like this

$data = sqlsrv($conn, "{call p_rpt_str310Web (?,?,?)}",[$PlanPkID,$bycatID,$ByDateVal]);
?>

    <? php foreqach ($data as $row): ?>

      <?= $count ?>
      <?= $row['CusName'] ?>
      <?= $row['CusCount'] ?>
      <?= $row['WorkTime'] ?>

    <?php endforeach ?>


public static unsafe void UnsafeMethod(byte[] array, int pos, short value)
{
    fixed (byte* numRef = &(array[pos]))
    {
        *((short*)numRef) = value;
    }
}

is not

public static void UnsafeMethod(byte[] array, int pos, short value)
{
    array[pos] = value;
}

Explanation:
&(array[pos]) gets the address of the memory of the "pos"th element of the array and byte* numRef = &(array[pos]) makes that the pointer numRef points to these address.
if you do *numRef = value you write value into the address numRef is pointing -- which is the "pos"th element of the array.
But you lose precision, because value is short (2 Byte) but you write into a byte (1 Byte) address.

if you cast numRef -- which is a pointer to a byte (= ONE byte) -- into a short (= TWO byte) then the pointer points to the same address BUT the pointer is 2 Byte "wide".
What i mean with "wide" is that if numRef points to 0x0 and you do numRef++ then numRef will point to 0x2 because it is short and short is 2 Byte big.

We have this short* numRef and you want to do *numRef = value then you will write in the memory of the "pos"th element of the array AND in the "pos + 1"th element of the array. so this method is not:

array[pos] = value

it is something like (i can't say that exactly because i am not the compiler):

array[pos] = upperByte(value)
array[pos + 1] = lowerByte(value)

Grafical Explanation:

May this be your array:

Address in RAM| 0x02 | 0x03 | 0x04 | 0x05 | 0x06 | 0x07 | 0x08 | 0x09 |
Array Indexer | [0]  | [1]  | [2]  | [3]  | [4]  | [5]  | [6]  | [7]  |
Content       | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 |

and pos is 2.
and value is this: value = 0x1234

so the pointer numRef points to 0x04:

print(numRef); // Ouptup will be 0x04

and looks like this:

Pointer byte* numRef      -->      <--
Address in RAM| 0x02 | 0x03 | 0x04 | 0x05 | 0x06 | 0x07 | 0x08 | 0x09 |
Array Indexer | [0]  | [1]  | [2]  | [3]  | [4]  | [5]  | [6]  | [7]  |
Content       | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 |

and after *numRef = value the array looks like this:

Pointer byte* numRef      -->      <--
Address in RAM| 0x02 | 0x03 | 0x04 | 0x05 | 0x06 | 0x07 | 0x08 | 0x09 |
Array Indexer | [0]  | [1]  | [2]  | [3]  | [4]  | [5]  | [6]  | [7]  |
Content       | 0x00 | 0x00 | 0x34 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 |

if you cast it to short then you have this:

Pointer short* numRef     -->             <--
Address in RAM| 0x02 | 0x03 | 0x04 | 0x05 | 0x06 | 0x07 | 0x08 | 0x09 |
Array Indexer | [0]  | [1]  | [2]  | [3]  | [4]  | [5]  | [6]  | [7]  |
Content       | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 |

and after *numRef = value the array looks like this:

Pointer short* numRef     -->             <--
Address in RAM| 0x02 | 0x03 | 0x04 | 0x05 | 0x06 | 0x07 | 0x08 | 0x09 |
Array Indexer | [0]  | [1]  | [2]  | [3]  | [4]  | [5]  | [6]  | [7]  |
Content       | 0x00 | 0x00 | 0x12 | 0x34 | 0x00 | 0x00 | 0x00 | 0x00 |

How it could be implemented (not recommended):

  if you use this methods PLEASE test it. with different system (32 / 64
  bit).

for the public static unsafe void UnsafeMethod(byte[] array, int pos, short value):

public static void SafeMethod(byte[] array, int pos, short value)
{
    array[pos] = value >> 8;
    array[pos + 1] = value & 0xFF;
}

and for the same method with int (and here is the problem - is this int 64 or 32 bit?!) it could look like this:

// For 64 bit integer
public static void SafeMethod(byte[] array, int pos, int value)
{
    array[pos    ] = (value >> 24) & 0xFF;
    array[pos + 1] = (value >> 16) & 0xFF;
    array[pos + 2] = (value >> 8) & 0xFF;
    array[pos + 3] = value & 0xFF;
}

Legend:

value >> x <=> shift the bits of value x times right
value << x <=> shift the bits of value x times left
value & 0xFF <=> value & 0b11111111 <=> logical bitwise and


Linq query performs poor according to performance analyzer in VS2012

I think the crux of your problem here is you are using the wrong tool for the job. The purpose of a dictionary is usually for direct retrieval i.e. give me the value associated with X key. I'm not sure how optimized they are for O(n) queries.

To rule out the ConcurrentDictionary<TKey, TValue> being the bottleneck, you could try switching it out for something like a ConcurrentBag<T>.


A function that checks if a word is similar to another word and returns a boolean

Your 2nd approach is better that 1st as it adds length comparison, but

it has redundant else: branch. The 1st if condition, if positive, has unambiguous statement return False terminating function call
my_word.count(my_word[i]), other_word.count(my_word[i] calls will traverse sequence of chars (word) on each loop iteration for equal characters (trying to "run ahead")

Consider the following approach with builtin any function (returns True if any element of the iterable is true):

def match_with_gaps(my_word, full_word):
    '''
    my_word: string with _ characters, current guess of secret word
    full_word: string, regular English word
    returns: boolean, True if all the actual letters of my_word match the
        corresponding letters of full_word, or the letter is the special symbol
        _ , and my_word and full_word are of the same length;
        False otherwise
    '''
    my_word = my_word.replace(' ', '')

    # check for length OR respective characters mismatch
    if len(my_word) != len(full_word) \
            or any(c1 != '_' and c1 != c2 for c1, c2 in zip(my_word, full_word)):
        return False

    return True

print(match_with_gaps('a p p _ e', 'apple'))   # True
print(match_with_gaps('a p p _ c', 'apple'))   # False
print(match_with_gaps('a _ _ _ _', 'apple'))   # True


Evaluation function for minimax/alphabeta algorithm for Tic Tac Toe AI

I'm going to sidestep the complexities of machine learning itself, it is after all a code review.

Unclear method names and unused parameters

private int h(int[][] field, int depth, int player) //final score of the node

h is a really bad method name. What doest this method do? h isn't particularly explanatory. calculateHeuristics would be considerably better.

I have a lot to say on int[][] field which I will address at a later stage in detail.

Both depth and player are part of the method parameters, but they are never used. You should remove them from the parameter list.

Code readability

if (win(field, 1)) //if human won

if (win(field, 0)) //if computer won

0 and 1 are not particularly readably values for "human" and "computer". Use an enum instead. The good thing is that enums can automatically translate to an int, which means that the odds of encountering breaking changes is minimized.

public enum Player
{
    Computer = 0,
    Human = 1
}

And then your code becomes much easier to read, you wouldn't even need the comments anymore:

if (win(field, Player.Human))

if (win(field, Player.Computer))

Secondly, I would rename field to board. "Field" makes it ambiguous as to whether you're referring to the board (similar to "the football field") or a cell on the board (similar to "a form field").

Thirdly, win is not a good name for a method. I suggest renaming it to IsVictoryFor (or any similarly descriptive name). If you then also create a custom class for your board (instead of using int[][] - I will elaborate on this later in the answer), you can move that method to that custom class. This would give you a massive boost in readability:

if(board.IsVictoryFor(Player.Human))

Encapsulation and SRP

int[][] field

I strongly suggest wrapping your int[][] in a custom class. This allows to you use class methods, which help you categorize your methods.

In your current code, you severely lack any application of Single Responsibility Principle (SRP). Especially in topics such as machine learning, you'll find that the complexity of the code increases exponentially, and you should be prepared for this by properly separating your responsibilities before things get out of hand.

As the adage goes, failure to plan is planning to fail. To that end, I suggest improving your code to make future changes/extensions as seamless as possible.

Don't use ints as placeholder values

You have on several occasions used ints to store your data (players, tokens on board cells). Every time you do that, you inherently require whoever reads your code to be aware of the mapping between the used int value and its particular meaning. This is hugely detracting from your code readability.

As a simple fix, you should use enums.

public enum Player { Computer = 0, Human = 1 }
public enum CellValue { Empty = 0, X = 1, O = 2 }

This dramatically increased the readability of your code, as you no longer will need to use hardcoded magical numbers (0 and 1) and can instead rely on human-readable values (Token.X, Player.Human, ...)

Note: You are cleverly relying on the player int matching with the cell int. I would advise against this. If you equate the two, you're effectively hardcoding which player goes first, and it'll be nigh impossible to reuse your code to have the players switch places (or when you want the compluter to play against itself, which you are inevitably going to have to do if you want to run bulk simulations).
Separating the two does come with the disadvantage that you need to perform some additional checking logic, but the reusability of the code makes it worth it.

Magic numbers

Other than the values I already suggested to encapsulate in enums, you also use other literal values throughout your code:

return -1000;

return 1000;

While you luckily didn't spread this throughout your codebase, the principle still applies; you should use const values.

public readonly const int HEURISTIC_POINTS_VICTORY = 1000;
public readonly const int HEURISTIC_POINTS_LOSS = -1000;

This also makes it a lot easier if you want to tweak the numbers in the future, because you only have to adjust them in one location.

Reusability

Currently, you're using powers of 10 to calculate the score (1,10,100). You have used this calculation in multiple locations:

sum += (int)Math.Pow(10, counter - 1);

sum += (int)Math.Pow(10, counter - 1);

sum += (int)Math.Pow(10, counterD - 1);

sum += (int)Math.Pow(10, counterD - 1);

This is not good. If you decide to change your scoring algorithm tomorrow, you're liable to only update some of the code and potentially forget other instances of the same calculation logic. This is a breeding ground for bugs and unexpected behavior.

You can abstract this to a separate method:

public int CalculateScore(int numberOfTokensInLine)
{
    return Math.Pow(10, numberOfTokensInLine);
}

Should you in the future decide to change your score calculation, you only have to adjust this one method; and then you can be certain that you've changed all of the score calculation logic across the codebase.

Note that you could also convert 10 to a constant, but I don't think it's a requirement here, as there's no reason to assume that you want to reuse this particular value in other locations.
However, if you want to be able to tweak the configuration of your learning algorithm in the future, it may be interesting to abstract this into a const or config parameter, so you have quick access to all values from a single location.

Reusability - Part 2

When you look at the individualScore method body, it should become apparent to you that it is quite repetitive. In many different ways, you are always "checking a line of three cells".

Instead of copy/pasting your approach and slightly tweaking it for every use case, you'd be better off making this reusable. I think it's beneficial for me to explain how/why I do things, so I'll deconstruct (and later reconstruct) the algorithm instead of simply presenting you the end result.

Deconstructing/reconstructing is an invaluable tool for writing clean code.

First, some pseudocode to showcase the general pattern of your logic:

1    FOR a particular line
2        IF I am able to win here (= no opponent token in line)
3            CALCULATE score
4            ADD score to total score
5    RETURN total score

This is the most generic pattern that applies to your logic, without duplicating anything. Now, we simply need to fill in the unknowns.

4 and 5 are not difficult, you've already done these.

3 is effectively the CalculateScore method I already mentioned in the earlier chapter.

2 isn't all that hard. Simply check if the particular line contains the opponent's token in any of the fields.

The big issue is in 1, how do we iteratively check all lines?

Step one - Convert the board to a single array

I'm going to assume you already applies my earlier tips, especially implementing the Board class. This enables you to change your underlying data type. To minimize the breaking changes, I'm going to add a conversion from your old data type:

public class Board
{
    //Your old data type, but now it's using the enum
    public Token[][] Fields;

    //Converted to a single (9 cell) array
    public Token[] FieldArray => Fields.SelectMany(row => row);
}

FieldArray is going to be an array with 9 cells, with indexes ranging from 0 to 8.

Step two - Hardcode all index combinations that define a line.

I know that good code often avoids hardcoding, but I'm willing to make an exception here. There are eight possible lines on a tic tac toe board, and that's a mathematical inevitability.
It it possible to calculate these lines at runtime, and e.g. apply the same logic if you suddently decide to play on a board of variable size (4x4, 5x5, ...) but that's beyond the current scope.

public List<List<int>> AllPossibleLines = new List<List<int>>()
{
    { 0, 1, 2 }, //Top row                    |   |
    { 3, 4, 5 }, //Middle row               0 | 1 | 2
    { 6, 7, 8 }, //Bottom row              ___|___|___
                                              |   |
    { 0, 3, 6 }, //Left column              3 | 4 | 5
    { 1, 4, 7 }, //Middle column           ___|___|___
    { 2, 5, 8 }, //Right column               |   |
                                            6 | 7 | 8
    { 0, 4, 8 }, //Diagonal \                 |   |
    { 2, 4, 6 }, //Diagonal /
};

Every "possible line" is a list of three indexes, which refer to the fields of the board. Therefore, if we iterate over AllPossibleLines, we are iterating over all possible lines on the board (all horizontals + all verticals + all diagonals).

Converting the pseudocode to actual code, with what we now know:

private int individualScore(Board currentBoard, Token currentPlayerToken)
{
    int totalScore = 0;

    //Iterate over all possible victory lines
    foreach(var line in AllPossibleLines)
    {
        //Convert the indexes to actual field values
        List<Token> tokens = line.Select(index => currentBoard.FieldArray[index]).ToList();

        //If the line contains an opponent's token, stop processing this line
        if(tokens.Any(token => token != currentPlayerToken && token != Token.Empty))
            continue;

        //Count how many player tokens are on the line
        int playerTokensOnLine = tokens.Count(token => token == currentPlayerToken);

        //Calculate the score and add it to the total
        totalScore += CalculateScore(playerTokensOnLine);
    }

   return totalScore;
}

And this has dramatically simplified your code and enhanced the readability.

Note that I did use LINQ here instead of simple for/foreach loops, specifically because I find that LINQ enhances code readability.
If you're not experienced with LINQ, I highly suggest you look up a tutorial on the basics as LINQ dramatically helps with code readability and not being bogged down by having to manually iterate over collections.

Footnote Remember your win method? You didn't post the content of that method, but you can also rework this using the AllPossibleLines approach:

public bool win(Board board, Token currentPlayerToken)
{
    return AllPossibleLines
               .Any(line =>
                         line.All(index =>
                              board.FieldArray[index] == currentPlayerToken
                         )
                      );
}

The method effectively checks "is there any line in which all of its tokens equal the current player token?".


Write a recursive function that takes a positive integer n and plots an N-by-N Hadamard pattern where N = 2^n

Class names in Java should start with a capital letter.
Avoid initializing two variables in the same line.
The filledSquare call is the same in the two if branches, it could be moved out of the if.  Now the two if branches only change in the argument to the setPenColor call, and you could replace it by
Color theColor = color ? WHITE : BLACK;

Now it seems like you could drop the boolean argument altogether (boolean arguments suck) and pass a Color; all you need is a function that inverts the color.
This criticism has nothing to do with recursion; I have no idea if this works correctly or not :)


Convert sorted linkedlist into balanced binary search tree

I'm going to post a simpler review than I would if I fully understood this class, but hopefully if you clarify some things, I (or others) can come back and review it more in-depth.

My main problem with this code, is that I don't know what it is trying to do. The class is called SortedLinkedListToBalancedBST, which makes me think that it is some kind of converter utility class. However, the class itself has a private member of TreeNode<T> and doesn't have any public methods which are static or return some kind of BST, so that makes me think that it is just a BST implementation which happens to know how to create a BST from a Linked List. But the class doesn't even have all the functionality of a BST!

You need to decide what this class is going to be and then name it appropriately. Is it a class which knows how to convert from a Linked List to a BST and vice-versa, or is it a BST which knows how to create a BST from a Linked List? (The current name isn't even really all encompassing since the class can get the Linked List from the BST as well.)

Without a better understanding of the purpose of this class, I can't comment on the functionality and implementation, but I can talk about the style:

Give your variables better names. ll, lb, and hb are not good names. linkedList is a better name for ll, and for the others, I honestly have no clue what they even are supposed to represent.
Give different methods different names. Your two inorder() methods do two completely different things. One adds items to a List. The other gets a tree from an ordered list.
convert() seems like it might be more appropriate as a constructor.


I recommend you be more consistent in not combining if followed by a statement sequence ending in return with an else (I left out the comments):

def separate(p,l):
    if len(l) == 0:
        return ([],[])
    (true_list, false_list) = separate(p,l[1:])
    if p(l[0]):
        return ([l[0]] + true_list, false_list)
    return (true_list, [l[0]] + false_list)

as you do e.g. in compare().

In compare() I would nest the conditions (arbitrarily based on a):

def compare(a,b):
    if a == '':
        if b == '':
            return '='
        return '<'
    if a != '':
        if b == '':
            return '>'
    if a[0] > b[0]:
        return '>'
    if a[0] < b[0]:
        return '<'
    return compare(a[1:],b[1:])

That way it is more clear to me that compare() never ends without a return value.

Your comments should at least use triple double quotes (PEP8) and you should try to conform to PEP 257 (docstring conventions).


Monadic list for a more functional approach to C#

Just a few points that I've noticed:

Readonly property can be declared directly like this:

private List<T> Items { get; }

It is not clear if this class is intended to be immutable. The Items is not exposed directly, and its backing field is marked with readonly. However, the indexer is exposed. In case it is, you should use ReadOnlyCollection<T> as the container. If not, an T[] would allow you to mutate its element, but prevents you from adding/removing item.
ctor argument value should pluralized.
An overload of ctor that takes params T[] values would be a nice addition, enabling this type of code: new ListMonad<int>(1, 2, 3)
Another ctor overload that support IEnumerable<T> would be great too, which will allow you to write this:

// this likely defeats the purpose of this class?
public ListMonad<TO> Map<TO>(Func<T, TO> func) => new ListMonad<TO>(this.Select(func));
public ListMonad<TO> Bind<TO>(Func<T, ListMonad<TO>> func) => new ListMonad<TO>(this.SelectMany(func));

In the Bind method, you can use AddRange to avoid creating a nested list:

public ListMonad<TO> Bind<TO>(Func<T, ListMonad<TO>> func)
{
    var results = new List<TO>();
    foreach (var element in this)
        results.AddRange(func(element));

    return new ListMonad<TO>(results);
}

The argument order of Compose method seems weird, although it may just be my personal preferences. I would suggest to put the inner-most selector first, and moving toward outside, since this is how we normally solves equations:

public static Func<TInput, TResult> Compose<TInput, T2, TResult>(Func<TInput, T2> func1, Func<T2, TResult> func2)
{
    return x => func2(func1(x));
}

Compose can also be placed in a generic-ally typed static class to avoid having to explicitly mentioning the generic type multiple times:

public static class FuncHelper<T>
{
    // usage: FuncHelper<int>.Compose(x => x * 2, x => x * x)
    public static Func<T, TResult> Compose<T2, TResult>(Func<T, T2> func1, Func<T2, TResult> func2)
    {
        return x => func2(func1(x));
    }
    // and, you can chain even more function
    public static Func<T, TResult> Compose<T2, T3, TResult>(Func<T, T2> func1, Func<T2, T3> func2, Func<T3, TResult> func3)
    {
        return x => func3(func2(func1(x)));
    }
    // and, so on ...

    // or, you can chain as long as you want, if the input, intermediate and result types are all the same
    // usage: FuncHelper<int>.Compose(x => x + 1, x => x * 2, x => x + 3, x => x * 4, ...)
    public static Func<T, T> Compose(params Func<T, T>[] funcs)
    {
        return x => funcs.Aggregate(x, (y, f) => f(y));
    }
}


For a query over multiple databases, is it faster to do GROUP BY first or UNION first?

The Second is Faster

Having just tested a slightly simpler version of this, using only 1 column to be aggregated, I found that the second version is faster. I would also argue that the second is much easier to read.

Here is the code I used to test it:

CREATE TABLE TEST1 (id INT, a INT)

INSERT INTO TEST1
SELECT 1,23 UNION ALL
SELECT 1,26 UNION ALL
SELECT 1,47 UNION ALL
SELECT 2,13 UNION ALL
SELECT 2,31

CREATE TABLE TEST2 (id INT, a INT)

INSERT INTO TEST2
SELECT 1,18 UNION ALL
SELECT 1,45 UNION ALL
SELECT 2,24 UNION ALL
SELECT 2,42 UNION ALL
SELECT 2,64

/*
    Single Group
*/
SELECT
    id,
    MIN(a) AS minA
FROM
(
    SELECT id,a
    FROM TEST1

    UNION ALL

    SELECT id,a
    FROM TEST2
)Data
GROUP BY id

/*
    Multiple Groups
*/
SELECT
    id,
    MIN(a) AS minA
FROM
(
    SELECT id,MIN(a) AS a
    FROM TEST1
    GROUP BY id

    UNION ALL

    SELECT id,MIN(a) AS a
    FROM TEST2
    GROUP BY id
)Data
GROUP BY id

DROP TABLE TEST1
DROP TABLE TEST2

General Feedback

You've consistently capitalised your keywords and your indentation is also consistent. Both of these help readability.

I recommend using the second query, it doesn't require any modification as far as I can see. You've got a pretty nice query there.


Naming conventions

Classnames start with a capital letter. So it should be public class Clavier.

Consistent English or Frensh. Mixing makes things weird:
ligne => line
Clavier => Keyboard

Give variables meaningful names:
m1 => soundMenu
m2 => restartMenu
m3 => helpMenu
b1 => playButton
b2 => stopButton
button => keyboardButtons / letterButtons
key => keyboardLetters

I'd also rename ligne to row to fit better with the column.

Responsibility

What exactly is a Clavier in your program?
Is it a window with some content?
Is it a main screen that you put inside a window?
Is it just the keyboard, or is it a panel that contains a keyboard?

Right now, it's all of those things.

Let's remove all the Frame parts from this class. Some other class will be responsible of putting the keyboard into a frame to show it.
Let's also turn the keyboard into a JPanel instead of letting it reference a panel (parent). That way we can just put the Keyboard directly into a frame.

The biggest problem we'll get with this change is that we don't have a frame anymore to ade the menuBar to. So let's also create the new class that creates the frame, adds the main menu bar and a keyboard.

Our 2 new classes look like this:

public class Application {
    private JMenuBar menuBar = new JMenuBar();
    private JMenu soundMenu = new JMenu("Affecter les sons");
    private JMenu restartMenu = new JMenu("Relancer");
    private JMenu helpMenu = new JMenu("Aide");

    public Application() {
        this.menuBar.add(soundMenu);
        this.menuBar.add(restartMenu);
        this.menuBar.add(helpMenu);
    }

    public void run(){
        JFrame frame = new JFrame("Clavier");
        frame.setJMenuBar(menuBar);
        frame.add(new Keyboard());
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) throws Exception {
        new Application().run();
    }
}

public class Keyboard extends JPanel {

    private JPanel[] keyboardPanel;
    private JButton[][] keyboardButtons;
    private static final String[][] keyboardLetters = {
            {"A", "Z", "E", "R", "T", "Y", "U", "I",
                    "O", "P"}, {
            "Q", "S", "D", "F", "G", "H", "J", "K", "L", "M"}, {"W", "X", "C", "V", "B",
            "N"},
    };

    private JButton playButton = new JButton("Play");
    private JButton stopButton = new JButton("Stop");

    public Keyboard() {
        super(new GridLayout(0, 1));
        keyboardPanel = new JPanel[6];
        for (int row = 0; row < keyboardLetters.length; row++) {
            keyboardPanel[row] = new JPanel();
            keyboardButtons = new JButton[20][20];
            for (int column = 0; column < keyboardLetters[row].length; column++) {
                keyboardButtons[row][column] = new JButton(keyboardLetters[row][column]);
                keyboardPanel[row].add(keyboardButtons[row][column]);
            }
            this.add(keyboardPanel[row]);
        }
        this.add(playButton);
        this.add(stopButton);
        this.setVisible(true);
    }
}

The next steps from here are adding the required listeners to all the buttons and menu items. This is actually the hard part. When doing those you also want to ask yourself: which class is responsible for what?
I'd say the keyboard is responsible for deciding what button is pressed. And then to pass it on to some class that knows what to do depending on which button was pressed.


Comparing numbers and making a calculation

Given your conditions, there's no way around the if-else statements. You have to enforce the conditions somehow.

Instead of if-else, another option is a switch statement, but the outcome is essentially the same:

switch (true) {
    case Math.round(e.gamma) === 0:
        value = 0;
        break;
    case e.gamma < -2:
        value = -2;
        break;
    case e.gamma > 2:
        value = 2;
        break;
    default:
        value = 99;
}


Implement PageObjects using TestNg in selenium

Is LoginPageObjects also a LoginPageLocators?

LoginPageObjects extends LoginPageLocators

seems unlikely. Hence I would not make page object class extend locator class. I usually keep locator on the same page object class for sake of better cohesion. You may come across locators which are applicable for multiple page object classed but in any case page object class is not a page locator class.

public void verifyTitle(){

By and large convention has been to not keep verification/assertion in the page class. Only exception is the page object constructor which can be used to check is control is on write page.

Adding on to what Alexei already mentioned. Adding complete code example would help others to help you. Not everyone works with selenium/TestNG and would find it difficult to get context without complete code example.


Security risk? The client could pass in any arbitrary function as "save" and execute it.

A client can change your code, and it's there fault for not using the function as intended.

  variable "args" gets passed to the save function regardless of whether that method actually takes any args

save(path, *args)

This way it will see there is no arguments and not error.

  Instead of passing a generic save function, I could replace "save(path, args)" with "new_file = open(path, 'w')"

This is a better idea. This is as things like json.dump use a file object.
You could make it so that it works in a with statement, and return the file object.

print "Saving \"" + path + "\""

You should use str.format.

print "Saving \"{}\"".format(path)

You can add the ability of making it work with with statements with the below. If you want to know about these special functions look here.

class _handle_file_save:
    def __init__(self, path):
        self.path = path
        self.file_handler = open(self.path)

    def __enter__(self):
        return self.file_handler

    def __exit__(self, exc_type, exc_value, traceback):
        self.file_handler.close()

Now, we can enter your function without the save parameter. This will allow us to do what you want.

class _handle_file_save:
    def __init__(self, path, overwrite, *args):
        self.path = path
        self.overwrite = overwrite
        self.args = args

    def _open(self):
        if os.path.isfile:

        # ... Just copy the rest.

However we now have the problem of

  Doesn't check if appended filepath is also a locked/open file

And so we can make it a recursive function!

class _handle_file_save:
    def _open_recursive(self, path):
        try:
            self.file_handler = open(path, *self.args)
            print "Saving \"{}\"".format(path)
        except EnvironmentError:
            self._open_recursive(gen_alt_filename(path))

Lets now get the _open function to work now.

class _handle_file_save:
    def _open(self):
        if os.path.isfile(self.path):
            if overwrite:
                self._open_recursive(self.path)
            else:
                self._open_recursive(
                    gen_alt_filename(self.path))
        else:
            self._open_recursive(self.path)

You may want to change it so there is only one if statement. However you may not want the first else to be recursive.

If we wrap it all up we get:

class _handle_file_save:
    def __init__(self, path, overwrite, *args):
        self.path = path
        self.overwrite = overwrite
        self.args = args
        self.file_handler = None

    def _open(self):
        if os.path.isfile(self.path):
            if overwrite:
                self._open_recursive(self.path)
            else:
                self._open_recursive(
                    gen_alt_filename(self.path))
        else:
            self._open_recursive(self.path)

    def _open_recursive(self, path):
        try:
            self.file_handler = open(path, *self.args)
            print "Saving \"{}\"".format(path)
        except EnvironmentError:
            self._open_recursive(gen_alt_filename(path))

    def __enter__(self):
        self._open()
        if self.file_handler is None:
            raise TypeError('self.file_handler never set.')
        return self.file_handler

    def __exit__(self, exc_type, exc_value, traceback):
        self.file_handler.close()

You may want to change the error in __enter__.

This should work, however I don't know how to generate a locked file. But it seems like you know how to check.

Also it has the added support of allowing you to put all your file checking functions, I'm looking at you gen_alt_filename, into it to if you wish.

It's more complex, however it would work better then passing a save function as usage is just like open.

with _handle_file_save('file', False, 'rb') as file_:
    # Do something with `file_`


Generate combinations of a given sequence without recursion

First, a side note. What you call combination is usually called subset.
In a set of \$n\$ elements an average length of a subset is \$\dfrac{n}{2}\$. That is, generating a single subset takes \$O(n)\$ time. You cannot get a time complexity better than \$O(n2^n)\$.
The space complexity is a different matter. If you indeed need all the subset at the same time, then again the space complexity cannot be better than \$O(n2^n)\$. On the other hand, if you want one subset at a time, consider converting your function to a generator, which would yield subsets one at a time.
A more or less canonical way of generating subsets uses the 1:1 mapping of subsets and numbers. Each number a in the \$[0, 2^n)\$ range uniquely identifies subset of \$n\$ elements (and vice versa). Just pick the elements at the position where a has a bit set.
All that said, consider
def generate_subsets(arr):
    n = len(arr)
    for a in range(2 ** n):
        yield [arr[i] for i in range(n) if (a & (1 << i)) != 0]


First note that your code does not detect invalid input data.
For example, the string "XX" is just converted to a zero byte.
Detecting invalid input with strtoul() is a bit tricky, there is an
alternative suggestion below.

let data = NSMutableData(capacity: length/2)

creates an optional NSData. If that fails then the optional chaining

data?.appendBytes(&wholeByte, length: 1)

simply does nothing, i.e. the error is ignored. Better check the
success immediately:

guard let data = NSMutableData(capacity: length/2) else { return nil }

  How can I optimize the ugly i+=1 lines?

By using stride:

func dataFromHexString() -> NSData? {
    guard let chars = cStringUsingEncoding(NSUTF8StringEncoding) else { return nil}
    let length = characters.count

    guard let data = NSMutableData(capacity: length/2) else { return nil }
    var byteChars: [CChar] = [0, 0, 0]
    var wholeByte: CUnsignedLong = 0

    for i in 0.stride(to: length, by: 2) {
        byteChars[0] = chars[i]
        byteChars[1] = chars[i + 1]
        wholeByte = strtoul(byteChars, nil, 16)
        data.appendBytes(&wholeByte, length: 1)
    }

    return data
}

This does not change the performance. The time to convert a 512,000
character string is 0.0140 sec on my computer (test code at the end).

  Is cStringUsingEncoding(NSUTF8StringEncoding) the correct way to get the [CChar] from the string?

That is fine as far as I can see. There is also

self.withCString {
    // $0 is a pointer to the NUL-terminated UTF-8 string
}

which I personally prefer, but I could not detect a difference in
the performance.

  Since this is almost a direct translation from Objective-C, is there any way to make this more "Swifty," say by using map or stride, without sacrificing speed?

stride() is already used for the iteration. I do not see an use-case
for map() here.

But the performance can be improved considerably.
As observed here
and here, accessing the UTF-16 view
of a Swift string is very fast. This leads to the following implementation:

func dataFromHexString() -> NSData? {

    let utf16 = self.utf16
    guard let data = NSMutableData(capacity: utf16.count/2) else { return nil }

    var byteChars: [CChar] = [0, 0, 0]
    var wholeByte: CUnsignedLong = 0
    var i = utf16.startIndex
    while i != utf16.endIndex {
        byteChars[0] = CChar(truncatingBitPattern: utf16[i])
        byteChars[1] = CChar(truncatingBitPattern: utf16[i.advancedBy(1, limit: utf16.endIndex)])
        wholeByte = strtoul(byteChars, nil, 16)
        data.appendBytes(&wholeByte, length: 1)
        i = i.advancedBy(2, limit: utf16.endIndex)
    }
    return data
}

which converts the 512,000 character string in 0.00185 sec.
Note that invalid input is still not detected.

We can still make it faster by converting the UTF-16 code points
"manually" instead of using strtoul(). This is more code,
but again faster, and also detects all kinds of invalid input:

func dataFromHexString() -> NSData? {

    // Convert 0 ... 9, a ... f, A ...F to their decimal value,
    // return nil for all other input characters
    func decodeNibble(u: UInt16) -> UInt8? {
        switch(u) {
        case 0x30 ... 0x39:
            return UInt8(u - 0x30)
        case 0x41 ... 0x46:
            return UInt8(u - 0x41 + 10)
        case 0x61 ... 0x66:
            return UInt8(u - 0x61 + 10)
        default:
            return nil
        }
    }

    let utf16 = self.utf16
    guard let data = NSMutableData(capacity: utf16.count/2) else {
        return nil
    }

    var i = utf16.startIndex
    while i != utf16.endIndex {
        guard let
            hi = decodeNibble(utf16[i]),
            lo = decodeNibble(utf16[i.advancedBy(1, limit: utf16.endIndex)])
        else {
                return nil
        }
        var value = hi << 4 + lo
        data.appendBytes(&value, length: 1)
        i = i.advancedBy(2, limit: utf16.endIndex)
    }
    return data
}

The time to convert the 512,000 character string is now
0.0008 seconds. This is more than 17 times faster than the original code.

Test code:

let s1 = (0 ... 255).map { String(format:"%02x", $0) }.joinWithSeparator("")
let str = Repeat(count: 100, repeatedValue: s1).joinWithSeparator("")
print(str.characters.count) // 51200

let start = NSDate()
if let data = str.dataFromHexString() {
    let duration = NSDate().timeIntervalSinceDate(start)
    print(duration)
} else {
    print("failed")
}

The tests were done on a MacBook, with the program compiled in
Release mode.


Encoding multiple rows from prepared statement in php

I am using msqli not PDO, and procedural php not OOP.

While you should.

Because it will make the whole mess into three blimmin' lines

<?php
require 'connect.php';

$statement = $con->prepare("SELECT * FROM `lecturers_general` WHERE ? IN (lecturer_id, title, first_name, middle_name, last_name, course1, course2, course3, course4, course5, course6, office_number, office_building, department)");
$statement->execute([$_REQUEST["query"]]);
echo json_encode(['lecturers: ' => $statement->fetchAll()]);


Maximum value that satisfies a specific function

arange can build a descending vector. Building an ascending vector and reversing it seems wasteful. Consider

a = np.arange(10, 0, -0.01)

matrix1 is never modified, but its _find_mean is recomputed on each iteration. Yet another waste. Compute it once.
Instead of linear search, you may want to consider a bisection of the search interval.
else: pass achieves nothing, and can be safely omitted.
_find_mean is a kinda strange name for a function which

  finds the location of the maximum element in a matrix


Check your MySQL database. If you have another table called "websiteIsNotSecure" then you need to sanitize your database inputs. Also, it'd be easier to check security if we had some code to look at. You can't view PHP code, it's all parsed/executed on the server.


Good clear template code - well done!

I'd consider changing the name, as the class itself isn't an iterator, it's an iterator pair, or range, that wraps a container and provides a reversed view of it.

Constructor should be explicit.

We should use free-function rbegin() and rend() to give us greater flexibility of container types (e.g. C-style arrays) - fall back to the std versions in <iterator> if argument-dependent lookup fails.

It could be improved by overloading Reverse with a version that accepts a const Container:

template <typename ContainerT>
auto Reverse(const ContainerT& iContainer)
{
    return ReverseIterator<const ContainerT>(iContainer);
}

For this to work properly, we need to change the return type of begin() and end() to auto, so that we get const_reverse_iterator back from them.  If you're really stuck with C++11, then we'll have to add the trailing return type: auto begin()-> decltype(m_container.begin()), for example.  For my own convenience, I'll work with C++17 from here onwards.

Applying these suggested changes gives us:

template <typename ContainerT>
class ReverseContainerView
{
public:
    explicit ReverseContainerView(ContainerT& iContainer)
      : m_container{iContainer}
    {
    }

    auto begin() {
        using std::rbegin;
        return rbegin(m_container);
    }
    auto end() {
        using std::rend;
        return rend(m_container);
    }

private:
    ContainerT&  m_container;
};

template<typename ContainerT>
auto Reverse(ContainerT& iContainer)
{
    return ReverseContainerView<ContainerT>(iContainer);
}

template<typename ContainerT>
auto Reverse(const ContainerT& iContainer)
{
    return ReverseContainerView<const ContainerT>(iContainer);
}

and demo:

#include <iostream>
#include <vector>
int main()
{
    auto list = std::vector<int>{1, 2, 3};
    for (auto& i: Reverse(list)) {
        std::cout << ++i << ' ';
    }
    std::cout << '\n';
    for (const auto& i: list) {
        std::cout << i << ' ';
    }
    std::cout << '\n';

    const auto const_list = std::vector<int>{1, 2, 3};
    for (auto i: Reverse(const_list)) {
        std::cout << i << ' ';
    }
    std::cout << '\n';
}

Note that the proposed usage for (auto i: Reverse(std::vector<int>{10, 20, 30})) (where the constructor argument is an xvalue) won't work with the above code.  That's because the temporary has gone out of scope after the ReverseContainer was constructed but before the for loop completes, leaving a dangling reference in the container.  We'll need a version that captures and stores any rvalue type passed to it.

The easiest way I know to do this is to split the class into its two responsibilities: a base class to capture the wrapped container and a subclass to access the reversed view (we might want to put some or all of these classes into an inner namespace to hide them from users; I'll leave that question open here).

#include <iterator>
#include <type_traits>
#include <utility>

template <typename T, bool CopyValue = !std::is_lvalue_reference_v<T>>
struct ContainerContainer;

template <typename T>
struct ContainerContainer<T, false>
{
    // lvalue version: contains a reference to the container
    T& container;
    explicit ContainerContainer(T& container)
      : container{container}
    {}
};

template <typename T>
struct ContainerContainer<T, true>
{
    // rvalue version: move-constructs a new copy of container
    const T container;
    explicit ContainerContainer(T container)
      : container{std::move(container)}
    {}
};

template <typename Container>
class ReverseContainerView : ContainerContainer<Container>
{
    using Base = ContainerContainer<Container>;
public:
    explicit ReverseContainerView(Container&& container)
        : Base{std::forward<Container>(container)}
    {}

    auto begin() {
        using std::rbegin;
        return rbegin(Base::container);
    }
    auto end() {
        using std::rend;
        return rend(Base::container);
    }
};

template<typename Container>
auto Reverse(Container&& container)
{
    return ReverseContainerView<Container>(std::forward<Container>(container));
}

// test program
#include <iostream>
#include <vector>
int main()
{
    int list[] = {1, 2, 3};
    for (auto& i: Reverse(list)) {
        std::cout << ++i << ' ';
    }
    std::cout << '\n';

    const auto const_list = {1, 2, 3}; // initializer_list
    for (auto& i: Reverse(const_list)) {
        // ++i; ERROR: 'i' is read-only
        std::cout << i << ' ';
    }
    std::cout << '\n';

    for (auto& i: Reverse(std::vector<int>{10, 20, 30})) {
        // ++i; ERROR: 'i' is read-only
        std::cout << i << ' ';
    }
    std::cout << '\n';
}

From C++17 onwards, we don't really need the Reverse() helper function: we can instead simply provide a template deduction guide:

template<typename Container>
explicit ReverseContainerView(Container&& container)
    -> ReverseContainerView<Container>;

We might want to choose a shorter name for the class now that it's more visible to the users.


Capitalisation:
If you're gonna use variables like this: kendoGrid, dataItem, but then have variables like: destinationgrid and sourcegrid, then stick with one (preferably the first, because it's easier to read)
Optimizing:
It seemed for me, that removing this line increased the speed:

editable:   "popup",

Because with your code it popups for each data cell being removed, which is fine, if that's what you want
However, it seems with your code that it doesn't support the movement of more than one data cell at a time.
Note:
If you're wanting the user to select more than one nearly every time, then using popups is fine, but make it one popup per action.


How can I make this tax calculator cleaner?

You have 1 reputation point, and you make no use of functions or complex data structures. Because of this, I'm going to assume you're a beginner to coding.

Congratulations, beginner, on finishing a program and on submitting it for review! You will find that you can learn a huge amount from reviews, probably more stuff faster than by any other method.

Control & Data structures

You don't show any loops or functions, so I won't suggest using them. Yet.

PEP 8

I will suggest that you take a look at PEP-8. It's "THE standard" for writing Python code, so the sooner you start drinking the Kool-Aid, the sooner you'll stop getting criticized for not following it.

CAPS are for constants

One thing you'll find in PEP 8 is the notion of different letter-case conventions for different kinds of name. Variable names that change are generally in what is called snake_case, while "variables" that don't change (that are called "constants" despite the fact that you could change them) are spelled using ALL_CAPS.

In your code, you have some symbols that meet these criteria. Specifically, married_bracket_caps and single_bracket_caps are constants, and should be spelled that way.

You can argue about whether other symbols, that are initialized based on a single choice and never change later, are constant or not. And people do. ;-)

Error Checking

You don't check for errors. At this point, with no way to loop and try again, your only option would be to exit the program. But you should still get in the habit of validating your inputs, especially inputs that come from those pesky humans. Humans are notorious for providing bad inputs. You have this:

if marital_status == "M":
    standard_deduction = "24800"
    # marrital standard deduction
elif marital_status == "S":
    standard_deduction = "12400"
    # single standard deduction

Add this:

else:
    print("Eat flaming death, vile Terry!")
    sys.exit(1)

(Or some other message, if you'd like.)

Don't Repeat Yourself

There is a currently-popular "principle" of programming called "DRY" -- short for "Don't Repeat Yourself." A good programmer has dry code, dry socks, and a dry wit.

In your case, you are repeating a test:

if marital_status == "M":
    standard_deduction = "24800"
...

taxable_income = int(household_income) - int(standard_deduction)

if marital_status == "M":
    bracket = married_bracket_caps
...

Instead of repeating yourself, move the check down until you have all the data you need, and then do the test one time:

if marital_status == "M":
    bracket = MARRIED_BRACKET_CAPS
    standard_deduction = MARRIED_STANDARD_DEDUCTION

DRY your code, redux

Also, you have this:

elif taxable_income <= int(bracket[1]):
    tax = (int(bracket[0]) * .1)+(.12*(taxable_income - int(bracket[0])))

This is bad because it repeats a lot, and because it puts too much work in a single expression. Let's look at it:

tax = bracket-0-cap * some rate + (income - bracket-0-cap) * some other rate

You can dry this out by eliminating a lot of the calls. For example, why are you calling int() on numbers that YOU put into YOUR array as integers? They're already ints, you don't need to do that!

No Magic Numbers

What's .1? What's .12? Those are called magic numbers and they're bad.

Use constants (which you now know should be in ALL_CAPS) to replace these. Or use a lookup of an array (which is constant). Like:

tax = RATE_0 * income

or

tax = TAX_RATES[0] * income


Upload a photo with a unique name using PHP

// Return if no file has been submitted
        if (!isset($_FILES['photo'])) {
            return;
        }

        // Checks if image has been submitted
        if (isset($_FILES['photo'])) {

The last line there is redundant.  The first if has already done the complementary check.  You don't need a second if.  At that point, you can just run the code, as it will always run.

                $error_message = $_FILES['file_upload']['error'];
                $errors[] = $upload_errors[$error_message];

The $errors array holds error messages.  The $error_message variable holds an error type or error code.  It should probably be named in accordance with that.  Of course, you don't actually need a variable at all, since you never use it again.  You could just say

                $errors[] = $upload_errors[$_FILES['file_upload']['error']];