(php , mysql) Contact us form mysql injection

For security, bind user supplied values when including them in a query.

Here's what that could look like using mysqli and the information provided
https://www.php.net/manual/en/mysqli-stmt.bind-param.php

// renamed `textt` to `text`
$stmt = $mysqli->prepare('INSERT INTO `info` (`username`,`email`,`text`) VALUES (?,?,?);');
$stmt->bind_param($username, $email, $text);
$stmt->execute();
$stmt->close();

Here's what that would look like using PDO, should that connection be considered.
https://www.php.net/manual/en/pdostatement.bindparam.php

Perhaps consider renaming your column textt to something more descriptive?

Also, normally, you'd want to provide some validation on user supplied input to prevent bots and help prevent user error.

e.g. for the email address:

if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
  $email = $_POST['email'];
} else {
  // often handled with a message or alert funciton
  echo 'Please enter a valid email';
  $error = true;
}

e.g. for the username:

if(!ctype_space($_POST['username'])) {
    $username = trim($_POST['username']);
} else {
    // as before often handled by a message/alert function
    echo 'Please provide a valid email address';
    $error = true;
}

It's often helpful to store the IP address of the requester. The following can be spoofed, and there are better functions out there, but it is often better than nothing.

$ip_address = $_SERVER['REMOTE_ADDR'];

There are solutions to help ensure it's not a bot completing your form, e.g. reCAPTCHA and honey pots. They're not always appropriate from a UX, UI, security standpoint, but I feel that should be mentioned as well.

I hope this was helpful!


Why use multiplyexact?
I'm puzzled why you wrote this:

digitSum += Math.multiplyExact(Math.multiplyExact(remainder, remainder), remainder);

instead of this:
digitSum += remainder * remainder * remainder;

You already know that remainder is a single digit value so computing the cube of it will never overflow.
Extraneous check
Your final return statement could be reduced from this:

return (0 == quotient && digitSum == candidate);

to this:
return (digitSum == candidate);

Your while loop will only terminate on this condition:
quotient == 0 || digitSum > candidate

which means that when digitSum == candidate, quotient must always be 0.


Use size_t for sizes
Although the LeetCode question specifies that the constructor takes an int capacity, using an int to hold a size is not appropriate for two reasons:

int might not be big enough to handle all possible sizes that fit into the available memory.
int is signed, and now you have to deal with potentially negative numbers.

Also note that the standard library uses size_t for things like .size(), and the result of the sizeof operator is also a size_t. So it's best to internally store the capacity as a size_t. This will avoid compiler warnings about comparisons between signed and unsigned values.
Use types consistently
The one place you use size_t is in std::list<size_t> lru. But here, the list is actually holding keys. Everywhere else you write int key, so you should write std::list<int> lru here, otherwise your cache might not work correctly when using negative numbers for keys. The LeetCode question does not say whether or not negative keys are allowed, it only mentions only positive values are stored.
Make helper functions private
Helper functions like update() and clear() are not part of the public API as specified by the LeetCode problem. So make them private.
Use proper names
The function clear(), despite its name and even the comment above it, does not erase the cache. Instead, it just removes the least recently used element. Make sure the name (and also the comment) reflects this. I would name it something like pop_lru(), or perhaps just pop().
Also, the name update() does not match the comment above it. I would remove the comment, and give a more descriptive name: make_most_recent().
Useless use of const
It does not make sense to have a function return const void. Just write void.


Project Euler # 15 Lattice paths in Python

Performance Counter

When you use time.time(), you are getting the number of seconds since January 1, 1970, 00:00:00 UTC.  This value is (as I'm writing this) around 1565401846.889736 ... so has about microsecond resolution.

When you use time.perf_counter(), you are getting "a clock with the highest available resolution to measure a short duration".  As I was writing this, I retrieved the value 53.149949335 ... so it has approximately nanosecond resolution.

For profiling code, you want the highest resolution timer at your disposal ... so eschew time.time() in favour of time.perf_counter().

Timed Decorator

Since you are doing a lot of performance measurements in your exploration of Project Euler, you should package up the performance measurement code in a neat little package that can be easily reused.  You were given a decorator for this in an answer to your "Time & Space of Python Containers" question.  But here it is again, slightly modified for just doing timing:

from time import perf_counter
from functools import wraps

def timed(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = perf_counter()
        result = func(*args, **kwargs)
        end = perf_counter()
        print(f"{func.__name__}: {end-start:.6f} seconds")
        return result
    return wrapper

You can decorate a function with @timed, and it will report how long that function takes.  You can even decorate multiple functions!

And it moves the timing code out of your if __name__ == '__main__': block.

Use Test Cases

Project Euler 15 gives you the answer to a 2x2 lattice grid.  You should run that test case in your code, to give yourself confidence you are getting the correct answer.  Eg)

@timed
def count_lattice_paths(rows, cols):
    # ...

def pe15(rows, cols):
    paths = count_lattice_paths(rows, cols)
    print(f"{rows} x {cols} = {paths} paths")

if __name__ == '__main__':
    pe15(2, 2)
    pe15(20, 20)

A few import points.

The if __name__ == '__main__': block clearly runs two cases

a 2x2 lattice, and
a 20x20 lattice.

The pe15(rows, cols) calls count_lattice_paths(rows, cols) to get the result, and then prints out the result with a description of the case.
The count_lattice_paths(rows, cols) is the @timed function, so the time spent printing the result report in not counted in the timing.
The count_lattice_paths() method can be generalized to work with an NxM lattice; it doesn't need to be square, even though the problem asked for the result for a square lattice and gives a square lattice test case.

Count Lattice Paths (without a cache)

As you noticed, a 2x2 lattice is better represented by a 3x3 grid of nodes.

It should be obvious there is only 1 way to reach every node along the top edge.
It should be obvious there is only 1 way to reach every node along the left edge.

So, our initial array of counts would look like:

1 1 1
1 . .
1 . .

At each node (other than the top edge and left edge), the number of paths is equal to the sum of the paths to the node above it and the paths to the node to the left of it.  So, there are 1+1 = 2 paths to the node at 1,1:

1 1 1
1 2 .
1 . .

Since the value at each point is defined entirely by the values above and left of it, we can directly loop over each node, and compute the required values, and finally return the value at the lower right corner of the grid.  We don't even need to store the entire grid; we can compute the next row from the current row.

@timed
def count_lattice_paths(rows, cols):
    steps = [1] * (cols + 1)
    for _ in range(rows):
        for i in range(cols):
            steps[i+1] += steps[i]
    return steps[-1]


Cor.test inside for loop is very slow for large matrix processing

If you had profiled your code, you would have seen that unusually long time is taken by line:
corr_list[i - 1,] <- c(rNames[1], rNames[i], r$estimate, r$p.value)
It is probably because you are combining multiple type values into one vector.
So this should be mush faster:
f3 <- function(dat) {
  require(data.table)
  mainVar <- dat[1,]
  rNames <- rownames(dat)
  rez <- lapply(2:nrow(dat), function(i) {
    r <- cor.test(x = mainVar, y = dat[i,])
    c(r$estimate, r$p.value)
  })
  fin <- data.table(rNames[1], rNames[-1])
  fin <- cbind(fin, data.table(do.call(rbind, rez)))
  setnames(fin, c("top", "correlated", "cor", "p.value"))
  return(rez)
}

I <- 60
N <- 1000
dat <- MASS::mvrnorm(N, mu = rep(0, I), diag(I))
rownames(dat) <- paste0("G", 1:N)

# Comparison
res1 <- microbenchmark(
  f1(dat),
  f2(dat),
  f3(dat),
  times = 10
)
print(res1, unit = "s")
# Unit: seconds
# expr       min        lq      mean    median        uq       max neval cld
# f1(dat) 0.4333447 0.4609346 0.4880110 0.4863479 0.5050751 0.5782526    20   c
# f2(dat) 0.3585121 0.3729532 0.4021378 0.3979831 0.4269367 0.4899676    20  b
# f3(dat) 0.1483598 0.1610634 0.1782496 0.1787396 0.1934256 0.2273650    20 a

autoplot(res1)

Update
If we calculate correlation with base function and p.value - ourselves, we can get rid of for loop and do all of this much faster. Only problems my arise if your data contains missing values:
pcor <- function(r, n){
  t <- r * sqrt(n - 2) / sqrt(1 - r^2)
  p <- 2 * (1 - pt(abs(t), (n - 2)))
  p[p > 1] <- 1
  p
}

f4 <- function(dat){
  require(data.table)

  rNames <- rownames(dat)
  d2 <- t(dat)
  cors <- cor(d2[, 1], d2[, -1])
  cors <- t(cors)
  cp <- pcor(cors, ncol(dat))
  cp <- cbind(cors, cp)
  fin <- data.table(rNames[1], rNames[-1])
  fin <- cbind(fin, cp)
  setnames(fin, c("top", "correlated", "cor", "p.value"))
  return(fin)
}

I <- 60
N <- 1000
dat <- MASS::mvrnorm(N, mu = rep(0, I), diag(I))
rownames(dat) <- paste0("G", 1:N)

res1 <- microbenchmark(
  f1(dat),
  f2(dat),
  f3(dat),
  f4(dat),
  times = 10
)
print(res1, unit = "s")
# Unit: seconds
# expr         min          lq        mean      median          uq         max neval  cld
# f1(dat) 0.408167816 0.410614574 0.428363371 0.429430744 0.442042920 0.456887399    10    d
# f2(dat) 0.334446197 0.345779175 0.366422216 0.362465218 0.378226388 0.426838502    10   c
# f3(dat) 0.139088268 0.145095289 0.156048277 0.153321298 0.162591518 0.183544069    10  b
# f4(dat) 0.002363351 0.002428473 0.002615854 0.002483812 0.002797716 0.003117556    10 a


Stream operation with two dimensional array

Apologies for providing a full solution, I know you didn't ask for that, it was just easier for me to work through it by writing the code in full.

I'm initially approaching about by thinking about how would I solve this in a database using SQL, and then applying a similar approach in Java.

First thing to do here is group all the scores together by person. I'm going to end up with Map of some kind, keyed by the person. That means using the groupingBy collector. I need to provide a separate function for the key and the value. The value mapping is the interesting bit here, I was initially thinking I could just provide a list of the scores and average them in the next step, but then I stumbled across the averagingInt collector which saves me a step.

So now I have a map with each person's average score in. I don't need the names anymore, as I only need to return the score, so I'll just take the values() from the map and find the biggest. Keeping it streamy means using the max() method to get the result.

This seems to do the trick, and isn't too ugly.

public static void main(String[] args) {

     String[][] scores = { { "Amit", "70" }, { "Arthit", "60" }, { "Peter", "60" }, { "Arthit", "100" } };

     double highestAvg = Arrays.stream(scores)
           .collect(groupingBy(s -> s[0],
                               averagingInt(s -> parseInt(s[1]))))
           .values()
           .stream()
           .max(naturalOrder())
           .get();

     System.out.println(highestAvg)
}

It uses these static imports to keep things uncluttered

import static java.lang.Integer.parseInt;
import static java.util.Comparator.naturalOrder;
import static java.util.stream.Collectors.averagingInt;
import static java.util.stream.Collectors.groupingBy;

Note that I changed the average to a double because it saves another conversion and the result might need the decimals.

Something to think about - how could you change the data structure to clean this up further?


HTML table representing a database table and a sidebar

I do not like too much this:

var name = $(this).find('td:nth-child(2)').html();

I would generally use html5 data attribute on the tr row to pass the id.

example:

bla	bla	bla

bla	bla	bla

var selectedId = $(this).data("id");


Random password generator with choice of three strengths

A flexible and manageable approach would be to create a custom PasswordGenerator which will comprise all functionality for particular password levels. Putting it a separate module, thus it can be imported and used in any place of an application on demand.

The one of possible implementations (considering your conditions):

password_generator.py :

import string
import random

class PasswordGenerator:

    LOWERCASE = string.ascii_lowercase[:26]
    UPPERCASE = string.ascii_uppercase[:26]
    NUMBERS = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
    SPECIAL_CHARS = ["*", "&", "@", "!"]
    LEVELS = ("weak", "medium", "strong")   # password levels

    @staticmethod
    def _compose_passphrase(iter_num, char_types):
        return ''.join(random.choice(c_type) for i in range(iter_num)
                       for c_type in char_types)

    @classmethod
    def weak(cls):
        iter_num = 6    # number of iterations
        char_types = (cls.LOWERCASE,)
        return cls._compose_passphrase(iter_num, char_types)

    @classmethod
    def medium(cls):
        iter_num = 5
        char_types = (cls.LOWERCASE, cls.UPPERCASE)
        return cls._compose_passphrase(iter_num, char_types)

    @classmethod
    def strong(cls):
        iter_num = 2
        char_types = (cls.LOWERCASE, cls.UPPERCASE, cls.NUMBERS, cls.SPECIAL_CHARS)
        return cls._compose_passphrase(iter_num, char_types)

Client script prompt_password.py :

from password_generator import PasswordGenerator

while True:
    choice = input("Want to create a password? To make your choice for your password strength, "
                   "please respond with one of the following: weak/medium/strong ")

    if choice in PasswordGenerator.LEVELS:
        print(getattr(PasswordGenerator, choice)())   # calling a respective method (password level)
    else:
        break

Running prompt_password.py:

Want to create a password? To make your choice for your password strength, please respond with one of the following: weak/medium/strong weak
ylwwcj
Want to create a password? To make your choice for your password strength, please respond with one of the following: weak/medium/strong weak
kktnkx
Want to create a password? To make your choice for your password strength, please respond with one of the following: weak/medium/strong medium
jLiAoWaHbA
Want to create a password? To make your choice for your password strength, please respond with one of the following: weak/medium/strong strong
qG8@sM7*
Want to create a password? To make your choice for your password strength, please respond with one of the following: weak/medium/strong strong
tY8&eL7@
Want to create a password? To make your choice for your password strength, please respond with one of the following: weak/medium/strong best

Process finished with exit code 0


Doc comments:

You can be more clear in the doc comment about what the function does:

What is the input? (string, path)
Does it return anything? (no)
Does it throw exceptions? (yes, because os.remove and shutil.rmtree may throw)
What is the state after calling the function? (file/folder has been removed, except if there was a permission error or another error)

Exceptions:

Someone who calls removeanything("myfile") may expect that myfile does not exist anymore after the function call. However, in case of a permission error, it still does exist. I think this is an exceptional situation, so I recommend that you do not catch the PermissionError and instead propagate it to the caller.

Output:

Currently, the function communicates via print statements. This means that callers of the function have no way of finding out what actually happened. You could add a return value that indicates whether a file, a directory, or nothing was removed. Then you may think about removing the print statement, or enabling/disabling it via function argument, because users may want to remove files silently.

Tests:

It may be useful to separate the single test test_removeanything into multiple tests test_removeanything_deletes_file, test_removeanything_deletes_directory, test_removeanything_handles_permission_error. This way, if a test fails, the test name gives you some more information about what went wrong.

Often, functions that remove directories require them to be non-empty. Therefore, it makes sense to test the removal of both empty and non-empty directories.

If you change removeanything so that the PermissionError propagates to the user, you can use pytest.raises to test whether the exception was raised correctly.

Misc:

I think the name removeanything can be more specific. After all, the function does not remove a CD from my CD drive ;)


jQuery-like library for learning purposes

There is quite a performance problem with your code: it will rebuild the fn object and all its methods every time the lemon(selector, context) constructor gets called. You can avoid that behavior by using the module design pattern:

this.lemon = (function () {

    var fn = {
    /* The code for the fn object here
        init: function (selector, context) {
            var prop = this.prop;
            ...
    */

    return function lemon() {
        this.prop = {
            collection: []
        };
        fn.init.apply(this, fn.toArray(arguments));
    };

 })();

However, you will have to add a line var prop = this.prop; in the beginning of every method of the fn object that requires prop.

Also, when introducing a new global variable, it is better for the readability of your code to use this.myVar = myValue; or window.myVar = myValue;. In fact, the var keyword should only be used for local variables.

Finally, it is often recommended to put a space between the function keyword and the following parenthesis, but that's not mandatory.


An alternative approach would be to say that a length is measured in SI units (meters).

Also, if performance is not a concern, using a BigDecimal instead of a double would avoid potential rounding errors.

It could look like:

public class Length {
  private final BigDecimal meters;
  public Length(BigDecimal meters) { ... }
  public Length(BigDecimal value, Unit unit) { /*convert to m*/}

  public BigDecimal getLength(Unit unit) { /*convert to unit*/ }
  public BigDecimal getLength() { /*return length in SI, i.e. meters*/ }

  public int hashCode() { return meters.hashCode(); }
  public boolean equals(Object o) {
    /*usual checks */
    return meters.compareTo(other.meters) == 0;
  }
  //other methods
}

This also avoids having to arbitrarily choose a "base" unit (mm in your example).

Finally I would suggest defining an interface for Unit:

public interface Unit {
  BigDecimal toMeters(BigDecimal length);
  //and possibly additional helper methods:
  default BigDecimal convert(BigDecimal length, Unit sourceUnit) { ... }
}

Then your enum would be:

public enum StandardUnit implements Unit {
  MM("0.001"); //etc.

  private final BigDecimal multiplier;
  StandardUnit(String mulltiplier) { this.multiplier = new BigDecimal(multiplier); }
  public BigDecimal toMeters(BigDecimal length) { return length.multiply(multiplier); }
}

This will allow a more flexible design where you can add units by implementing the interface or use the provided standard units.


Finally, I used RAND(), for generate an "UniqueID", and we can add some letters after or else :

Thanks to NerdyDev and Bart Friederichs for solutions.

<?php

$reponse = $bdd->prepare("UPDATE tuto SET uniqueID=ROUND(RAND() * :tp) WHERE uniqueID='' AND title=''");

$uniqueID = $donnees['uniqueID'];

$tp = time();
$reponse->execute([':tp' => $tp]);

?>


MonoAlphabetic and PolyAlphabetic ciphers in Haskell

generalShift

Note the following about generalShift:

the alphabet argument never changes throughout the recursive calls
the only elements of alphabet accessed are the first and last characters
last is a potentially expensive function since it traverses the entire list to find the last element

To elaborate on point #2, note that the following calls are exactly the same:

generalShift "abcdefg...xyz" 10 'x'
generalShift "az" 10 'x'

Given these observations, why not just pass the first and last characters of the alphabet to generalShift, i.e.:

generalShift :: Char -> Char -> Int -> Char -> Char
generalShift firstChar lastChar positions letter = ...

elem

elem is another potential expensive call. I would detect alphabetic characters using <= comparisons with the end points of the upper- and lowercase character ranges:

isAlphabetic ch = ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z')

clean str = filter isAlphaBetic . map toLower
  -- or the other way around: map toLower . filter isAlphabetic

more generalShift

There is a much faster way to compute the shift of a letter using the fact that Char is an enumeration (i.e. an instance of the Enum class) and therefore the following functions are available:

fromEnum :: Char -> Int
toEnum :: Int -> Char

These work like the ord() and chr() functions in other languages.

Let's assume the first and last characters of the alphabet are the standard a and z. I've leave you to figure out exactly what the code should look like, but here are some hints:

To shift a letter _n_ positions in the range a..z:

1. Determine how far away from 'a' the letter is.
2. Add n to that distance.
3. If the distance computed in step 2 would place it beyond 'z',
   subtract the number of characters between 'a' and 'z' and
   try again.
4. Add the distance computed in step 3 to the letter 'a'
   and return it as the encoded letter.

There will be a bunch of calls to fromEnum and toEnum as well as perhaps the mod function might help here.

poliAlphabeticCipher

Nothing really wrong here, but I have a suggestion... it is customary to repeat the key if it isn't long enough for the entire message. I.e., if the key was [3,2,1] and the message was "Hello", you would repeat the key as many times as was needed to cover every letter of the message. The key used to encode the message in this case would be [3,2,1,3,2].

You can use the cycle function to repeat a list forever:

cycle :: [a] -> [a]
-- e.g. cycle [1,4,2] = [1,4,2,1,4,2,1,4,2,1,4,2...]

and then polyiAlphabeticCipher may be written as:

poliAlphabeticCipher keys text = zipWith shift (cycle keys) (clean text)

With that change monoAlphabeticCipher may be implemented using poliAlphabeticCipher:

monoAlphabeticCipher shift text = poliAlphabeticCipher [shift] text


Compare performance of Concurrent Dictionary with Dictionary+Locks

Comparison

A comparison of performance of 2 classes only makes sense if both adhere to the same specification. Does your class do what a ConcurrentDictionary does?

Review

Why would you allow access to the underlying dictionary? If you must allow it, return a IReadOnlyDictionary.
Checking arguments before taking a lock prevents unnecessary locks on bad input.
AddOrUpdate does not work; have you checked  if (result == value)?

int[] a = new int[]{ 0, 1 };
int[] b = new int[]{ 0, 1 };
Console.WriteLine(a == b);  // False

Or is this as designed?

What is the purpose of this? What if both arrays have different size?

 Parallel.For(0, value.Length,
 (i, state) =>
 {
     result[i] = result[i] + value[i];
 });


Password strength checker (Udemy course)

Use requests built-in validation
This:
if res.status_code!=200:
    raise RuntimeError(f'Error fetching: {res.status_code}, check the api and try again')
else:
    return res

should not raise manually; and should be replaced with
res.raise_for_status()
return res

Hash checking
In get_pw_lead_count, hashes_to_check should be marked : str. Also, if count is a string - likely, since it comes from a split() - you should cast it to int() before returning it.
Real arguments
args=list(input().split())

is not a standard way of retrieving arguments. Instead, use argparse and pass arguments via command line parameters.
It's also possible to retain stdin input as you have it, but you should in that case show a prompt.
Indentation
Count the number of spaces for each of these lines:
    if count:
         print(f"Change your \"{passwords}\" password as it's pwned {count} times")

Each should be a multiple of four.


Calculate difference of two ranges given

Make sure this is the signature they want. e.g. they do not expect the function to return vector, iterator or sthg. Also make sure they do not expect you to validate input. e.g. a1 <= a2 etc... after that you can remove redundant conditionals, they are already present in the for loops. And you can replace ternary operators with std::min/max for a more idiomatic c++. otherwise I could not find any missed case or off-by-one bugs.

void findDiff(int a1,int a2, int a3, int a4)
{
   cout<<"("<<a1<<","<<a2<<") - ("<<a3<<","<<a4<<") = \n";

    for(int i=a1; i<=std::min(a2, (a3-1)); i++) cout<<i<<"\t";

    for(int i=std::max(a1, (a4+1)); i<=a2; i++) cout<<i<<"\t";

    cout<<"\n";
}


There are still a couple of rouge non-PEP8-compliant variable names: serviceAll and hostsAll.

This is a minor detail, but to avoid too much nesting I would suggest inverting this condition if response.status_code == 200:. Then you can write it like this:

if response.status_code != 200:
    continue # or raise an exception

html = BeautifulSoup(response.text, "html.parser")

IMO, such code is much easier to read. These kind of checks are also called guards (https://en.wikipedia.org/wiki/Guard_(computer_science)).

Instead of iterating through all the td tags, I would store them in a list and then extract the necessary elements with an index:

td_elements = list(html.select('td'))
hosts_all = td_elements[3].text.split('\n')
service_all = td_elements[12].text.split('\n')

Next, I would like to focus on the print_stats function. It takes way to many parameters and has become tough to work with. I suggest storing all variables you extract from the HTML in a dictionary, which you can then pass to the print_stats function.

extracted_information = {
    'hosts_up': hosts_all[12],
    'hosts_down': hosts_all[13],
    'hosts_unreachable': hosts_all[14],
    'hosts_pending': hosts_all[15],
    'hosts_problems': hosts_all[24],
    'hosts_types': hosts_all[25],
    'service_ok': service_all[13],
    'service_warning': service_all[14],
    'service_unknown': service_all[15],
    'service_critical': service_all[16],
    'service_problems': service_all[26],
    'service_types': service_all[27],
}

Then you would call the print_stats function like this: print_stats(user, url, extracted_information).

Of course, we now have to rewrite the print_stats function itself. The Python format function can also take named parameters. For example: "{param1} and {param2}".format(param1="a", param2="b") would return string "a and b". Using this we can rewrite the template string and pass the "unpacked" extracted_information dictionary to the format function.

def print_stats(user, url, extracted_information):
    template = """{user}@{url}:
                Hosts
    Up\tDown\tUnreachable\tPending\tProblems\tTypes
    {hosts_up}\t{hosts_down}\t{hosts_unreachable}\t\t{hosts_pending}\t{hosts_problems}\t\t{hosts_types}
                Services
    OK\tWarning\tUnknown\tCritical\tProblems\tTypes
    {service_ok}\t{service_warning}\t{service_unknown}\t{service_critical}\t\t{service_problems}\t\t{service_types}"""

    print(template.format(user=user, url=url, **extracted_information))


Welcome to Python, and welcome to Code Review.

Classes

An instance of a class, where only one method is ever called, is not a good class.  Instead, use functions.

a = input("Enter a string: ")
vowel_count(a)
constant_count(a)

Class Constants & Members

If you do create a class, and that class has some global constant data, store that on the class itself, not on the instances of the class.

Constants should have UPPERCASE_NAMES, to distinguish them from non-constant data.  Moreover, if the data is constant, where possible use non-mutable objects, such as tuple (eg, (..., ..., ...)) over list (eg, [..., ..., ...]).

Non-public members of a class should begin with a single underscore.

class CntVowels:

    VOWELS = ("a", "e", "i", "o", "u")

    def __init__(self, string):
        self._string = string

    # ...

Eschew .lower()

When attempting to compare strings (or characters) case-insensitively, use .casefold() instead of .lower().  This properly handles many additional oddities, such as the German ß which is equivalent to ss.

x in y

Testing for existence of an item in a container is easily done with the in operator.  For example, this code:

for vowel in vowels:
    if letter == vowel:
        counter += 1

can be re-written more efficiently as:

if letter in vowels:
    count += 1

A String is a Container

It could even be re-written as:

if letter in "aeiou":
    count += 1

since a string is simply a container of letters.

Non-Vowels are not necessarily Consonants

Many characters which are not vowels are also not consonants, such as 4, &,  and . to name a few.

Avoid Name Shadowing

string is not a good variable name, because a module named string exists, and can be imported, and doing so results in the meaning of string changing depending on what is in scope.

It is even reasonable that you’d import string in this program, to get convenient access to all of the string.ascii_lowercase letters.


finding the conflicts in meetings given startTimes and end Times

Advice 1

int startTime;
int endTime;

I suggest you hide them with private access modifier:

private int startTime;
private int endTime;

Advice 2

Elaborating on Advice 1 you can add the getters for the two above fields:

public int getStartTime() {
    return startTime;
}

...

Advice 3

 Collections.sort(meetings,new Comparator<Meeting>(){
                @Override
                public int compare(Meeting o1, Meeting o2) {
                    return o1.compareTo(o2);
                }
            });

Since you already have the compareTo method in your Meeting class, you can write more succinctly:

Collections.sort(meetings);

Advice 4

What comes to Meeting.compareTo, you can write shorter:

@Override
public int compareTo(Meeting o) {
    return Integer.compare(startTime, o.startTime);
}

Advice 5

Consider writing a method that tests whether two given meetings are conflicting each other:

public boolean conflictsWith(Meeting meeting) {
    if (endTime <= meeting.startTime) {
        return false;
    }

    if (meeting.endTime <= startTime) {
        return false;
    }

    return true;
}

Advice 6

Consider checking in the constructor of Meeting whether startTime <= endTime:

private void checkStartAndEndTimes(int startTime, int endTime) {
    if (startTime >= endTime) {
        throw new IllegalArgumentException("Start time (" + startTime +
                ") >= end time (" + endTime + ").");
    }
}

Advice 7

public Meeting(int startTime, int endTime) {
                super();
                ...

Above super does not buy you anything, consider removing it.

Finally

The main algorithm is now a little bit more readable:

class FindConflictingMeetingsProblem {

    public static int findNumberOfConflicts(List<Meeting> meetings) {
        Collections.sort(meetings);
        int conflicts = 0;

        for (int i = 0; i < meetings.size() - 1; ++i) {
            if (meetings.get(i).conflictsWith(meetings.get(i + 1))) {
                conflicts++;
            }
        }

        return conflicts;
    }
}

Algorithm limitations

Consider this:

Meeting m1 = new Meeting(1, 10);
Meeting m2 = new Meeting(5, 9);
Meeting m3 = new Meeting(4, 7);
List<Meeting> meetingsList = new ArrayList<>();
meetingsList.add(m1);
meetingsList.add(m2);
meetingsList.add(m3);

The above will report 2, but there is 3 pairs of meetings that conflict each other.

Hope that helps.


A tiny improvement to reduce a string concatenation:

function aan ($string) {
    return (
        in_array(
            strtolower(substr($string, 0, 1)),
            array('a','e','i','o','u')
        ) ? 'an ' : 'a '
    ).$string;
}

In order to help get your logic for more cases (ie, your Honor or Hour examples), you may wish to visit the English StackExchange to get help in figuring that logic out. Then you can code that as well.


I refactored your service base code into another class, which raises an event DataChanged. This way you can subscribe to multiple queries and databases. I also created a SqlDatabaseDepedency class which starts and stops the SqlDepedency for a database and implemented in a singleton pattern using unity (singleton on dbName). I also used Microsoft Enterprise Library's data access block for better database code. Let me know what you think.

public class SqlDepedencyBroker
{
    public event EventHandler DataChanged;
    public string Query { get; private set; }
    private string DbName { get; private set; }
    private CancellationToken Token { get; private set; }
    public SqlDepedencyBroker(string query, string dbName = null, CancellationToken token = default(CancellationToken))
    {
        SqlDatabaseDepedency.RegisterDependency(dbName);
        this.Query = query;
        this.DbName = dbName;
        this.Token = token;
    }
    public async Task WatchQuery()
    {
        await Task.Yield();
        SqlDatabase db = this.DbName == null ? DatabaseFactory.CreateDatabase() as SqlDatabase : DatabaseFactory.CreateDatabase(this.DbName) as SqlDatabase;
        if (db == null)
            throw new InvalidOperationException();
        var cmd = db.GetSqlStringCommand(this.Query) as SqlCommand;
        if (cmd == null)
            throw new InvalidOperationException();
        cmd.Notification = null;
        SqlDependency dep = new SqlDependency(cmd);
        dep.OnChange += dep_OnChange;
        Token.ThrowIfCancellationRequested();
        db.ExecuteNonQuery(cmd);
        Token.ThrowIfCancellationRequested();
    }

    void dep_OnChange(object sender, SqlNotificationEventArgs e)
    {
        Token.ThrowIfCancellationRequested();
        var dataChanged = this.DataChanged;
        if (dataChanged != null)
            dataChanged(this, EventArgs.Empty);
        Token.ThrowIfCancellationRequested();
        Task t = WatchQuery();
    }
}
public class SqlDatabaseDepedency
{
    public string DbName { get; private set; }
    private string ConnectionString { get; set; }
    private SqlDatabaseDepedency(string dbName = null)
    {
        var db = dbName != null ? DatabaseFactory.CreateDatabase(dbName) : DatabaseFactory.CreateDatabase();
        if (db == null)
            throw new NotImplementedException();
        ConnectionString = db.ConnectionString;
        SqlDependency.Start(ConnectionString);
    }
    private static Lazy<IUnityContainer> _container = new Lazy<IUnityContainer>(() => new UnityContainer());
    private static IUnityContainer Container
    {
        get { return _container.Value; }
    }
    public static void RegisterDependency(string dbName = null)
    {
        lock (Container)
        {
            if (!Container.IsRegistered<SqlDatabaseDepedency>(dbName))
                Container.RegisterInstance<SqlDatabaseDepedency>(dbName, new SqlDatabaseDepedency(dbName));
        }
    }
    ~SqlDatabaseDepedency()
    {
        SqlDependency.Stop(ConnectionString);
    }
}


Don't put your method inside Kernel.
Rename ls_grep to something more descriptive, e.g. unlock_spreadsheet.
The two shell commands (cd and ls|grep) aren't needed. The code doesn't depend on the current directory, and you're not using the commands' output.
Don't use an instance variable (@input_folio) as a temporary variable inside a method. Make it a local variable.
The regex matches anything that begins with sevent digits. Use /\A\d{7}\z/ instead in order to match against the whole string.
Don't check if the file exists before deleting it, someone might delete it after you check and before you try to delete it. Instead, try to delete it and catch the possible exception.
Don't use recursion to repeat the method. Use a loop.

                puts <<-EDE.gsub(/^\s*>/, ' ')
                >
                >Lockfile not found for Folio # #{@input_folio}"
                >
                >If the file name doesn't match the folio number, get the file name
                >and use that instead of the Foilio number...
                >
                EDE

Remove the call to gsub:

                puts <<-EDE

 Lockfile not found for Folio # #{@input_folio}"

 If the file name doesn't match the folio number, get the file name
 and use that instead of the Foilio number...

                EDE

You may want to put those strings in global constants to avoid this decrease in indentation in the code.


Converting Array of Floats to UINT8 (`char`) or UINT16 (`unsigned short`) Using SSE4

why not load 4 packed __m128 and then store 32 Pixels at once

I think that's 16 pixels, but it's a good plan. The pack instructions were used inefficiently (in the linked question that was not really an issue) and that would be improved by processing more elements simultaneously. For example, something like this:

#define SSE_STRIDE 16

void ConvertToUint8(char* mO, float* mF, float* mB, unsigned numRows, unsigned numCols, unsigned numColsPad, float scalingFctr)
{
    unsigned ii, jj;
    __m128 a, b, c, d;
    __m128i ai, bi, ci, di, p0, p1;
    __m128 scalingFactor = _mm_set1_ps(scalingFctr);
    float *inptr;
    __m128i *outptr;

#pragma omp parallel for private(jj, a, b, c, d, ai, bi, ci, di, p0, p1, inptr, outptr)
    for (ii = 0; ii < numRows; ii++) {
        inptr = &mB[ii * numColsPad];
        outptr = (__m128i*)&mO[ii * numColsPad];
        for (jj = 0; jj < numCols; jj += SSE_STRIDE) {
            a = _mm_loadu_ps(inptr);
            b = _mm_loadu_ps(inptr + 4);
            c = _mm_loadu_ps(inptr + 8);
            d = _mm_loadu_ps(inptr + 12);
            inptr += SSE_STRIDE;
            ai = _mm_cvtps_epi32(_mm_mul_ps(a, scalingFactor));
            bi = _mm_cvtps_epi32(_mm_mul_ps(b, scalingFactor));
            ci = _mm_cvtps_epi32(_mm_mul_ps(c, scalingFactor));
            di = _mm_cvtps_epi32(_mm_mul_ps(d, scalingFactor));
            p0 = _mm_packs_epi32(ai, bi),
            p1 = _mm_packs_epi32(ci, di);
            p0 = _mm_packus_epi16(p0, p1);
            _mm_storeu_si128(outptr++, p0);
        }
    }
}

I've also changed some thing to unsigned, because some useless sign-extension was going on sometimes (depending on how it was compiled). inptr and outptr are now calculated outside the inner loop, normally we can expect the compiler to be pretty clever about that too but compiling with OpenMP support seemed to make Clang less clever, it put the actual multiplication between ii and numColsPad inside the inner loop. That's not good, because on Intel that imul would go to p1, and p1 is already completely packed with the float-to-int conversions and fp-multiplications (eg on Skylake both of those go to p01). That loop should be able to run at 1 iteration every 4 cycles in the best case on most architectures, but with that extra imul in there that wouldn't be possible.

To convert to uint16 something similar can be used, but with _mm_packus_epi32 and no packing to bytes.


Selecting one form to be visible using jQuery

Change the option values to the div ids

<option value="cf-query">I have a query</option>
…

Hide all elements with class cf-section.
Finally reference the value and show it, no need for the multiple if statements.

$("select").change(function() {
  $(".cf-section").hide();
  id = "#" + $(this).val();
  $(id).show("slow");
}

Now you can add as many as you want and your jQuery function code never changes.


Print the number of movies that was watched by more than 3 people

Make it a function

This should really be a function for test ability, reuse ability

It would need to be a function which accepts 2 parameters (The list we want to query, the amount of people have had to watch it)

And it will return the amount of times this happened

Add doc strings to said function, so after a while when you come back to this code, you still understand what you have written

For example:

def list_movies(movie_list, n):
    """
    a method what returns the count of movies watched by more then n people

    args:
        movie_list (list): The list of movies in [(movie, [names]), ..]
        n (int): The amount of times the movies has need to be watched

    returns:
       The count of movies that has been watched by more then n people
    """

Make proper tests

if you had properly tested this code, @Mathias's comment would probably not be necessary

There are a few good modules to test functionality doctest or unittests

Let's use doctest and add some tests to the docstring:

>>> count_movies_watched([('Spiderman 3', ['John', 'jake','Ronald']),('Gravity',['james','jake','john','gerald'])], 3)
1

>>> count_movies_watched([('Spiderman 3', ['John', 'jake','Ronald']),('Gravity',['james','jake','john','gerald'])], 4)
0

Without even writing a single line of code, it's already more clear, what this function will do and what a correct answer will be.

Improving Code

You can use list comprehension and the built in sum to get a count of movies
Use _ for variables you don;t use later on

Netting me:

sum([1 if len(names) > n else 0 for _, names in movie_list])

But this can also be improved, as @Mathias correctly states

sum will accept any iterable there is no need for the list comprehension
sum can add bools as well so no need for the awkward ternary

Netting me:

sum(len(names) > n for _, names in movie_list)

Putting it all together

import doctest

def count_movies_watched(movie_list, n):
    """
    a method what returns the count of movies watched by more then n people

    args:
        movie_list (list): The list of movies in [(movie, [names]), ..]
        n (int): The amount of times the movies has need to be watched

    returns:
        The count of movies that has been watched by more then n people

    >>> count_movies_watched([('Spiderman 3', ['John', 'jake','Ronald']),('Gravity',['james','jake','john','gerald'])], 3)
    1

    >>> count_movies_watched([('Spiderman 3', ['John', 'jake','Ronald']),('Gravity',['james','jake','john','gerald'])], 4)
    0
    """
    return sum(len(names) > n for _, names in movie_list)

if __name__ == '__main__':
    doctest.testmod()


This seems over-complicated.  A simpler solution would use a std::map or std::unordered_map for the counting:

std::unordered_map<int, std::size_t> counts;
for (auto const &element: container) {
     ++counts[element];
}

Instead of being tied to std::vector<int>, we could make the code much more flexible as a template, taking a pair of iterators (or, from C++20, a std::range) with any appropriate element type.  The signature might look something like:

template<typename Iter>
auto getFrequencies(Iter begin, Iter end)
   -> std::unordered_map<decltype(*Iter), std::size_t>;

We might use constraints or SFINAE to choose whether to return an ordered or unordered map, based on whether *Iter is ordered and/or hashable.


For each number in a first, second range you count how long does the sequence take to reach 1. It is definitely too much of the work: you'd surely encounter same numbers over and over again. Instead of recalculating sequence tails for them, it is much faster to remember and reuse such intermediate results. Since it is a contest problem I am not going to share any code.

Also, I am very interested in how did you come up with \$O(n^2)\$.


I like this, a lot. It's.. brilliant. Like .NET String objects, VBA strings are immutable, which means like in .NET, when "the quick brown fox" gets appended with "jumps over" and then "the lazy dog", it's 4 strings that have been generated, and thus the first one got copied 3 times; a VBA StringBuilder class is therefore definitely welcome to any VBA toolkit!

This is some serious code you've got here. Let's take a look.

So you've called the class clsStringBuilder. I know where you're coming from, but there's no real reason for this "cls" Hungarian prefix - I'd remove it, and call the class StringBuilder.

'******
'* v2 *
'******

Don't bother with that. I know version control is natively near-impossible with VBA, but there is no need to "version" code in comments nonetheless; do you actually maintain the version number? Why bother? Just remove it, it's useless clutter.

Private Const DEFAULT_CAPACITY As Long = &H10

Why not 16? Hexadecimal 10 is 16 right? I think it would be clearer to use a decimal notation. Actually that capacity is potentially confusing, especially given the hex notation. Is &H10 the number of bytes? Characters?

ReDim m_stringBuffer(0 To (DEFAULT_CAPACITY * 2) - 1) 'Each unicode character is 2 bytes

Ah, characters then. How about calling the constant DEFAULT_CHARACTER_CAPACITY? Nah, too long.. and I personally don't like the YELLCASE, I'd just call it InitialCharacterCapacity, but I've seen other people use ALL CAPS for constants - as long as you're consistent, it works :)

BTW that's a good comment you have there, but I wouldn't bother specifying "unicode" characters; it gets confusing when the IDE itself only supports ANSI strings!

I don't like prefixes and abbreviated names, so m_currLen would become currentLength and m_stringBuffer would become stringBufffer, or just buffer.

Actually since currentLength is in bytes, I'd call it currentByteLength, so as to avoid question marks when it comes to this:

Public Property Get Length() As Long
    Length = m_currLen / 2
End Property

Public Function Append(strString As String) As clsStringBuilder

strString, really? I doesn't get any more Hungarian than that! Also you should know that parameters are passed ByRef by default - I'd change the signature to this:

Public Function Append(ByVal value As String) As StringBuilder

The error handling isn't optimal - if anything blows up, you're bringing up the IDE for the end user to scratch their head and debug your code! That's not production-ready:

derp:
    Stop
    Resume

"derp" means nothing to me - I like following a "template" like this:

Public Sub Foo()
    On Error GoTo CleanFail

    'implementation

CleanExit:
    Exit Sub

CleanFail:
    'handle error
    Resume CleanExit
End Sub

You might also want to make sure Expand doesn't actually shrink the buffer. I think. ;)

Lastly, I'm not sure I understand why toString isn't following the convention and named in PascalCase like every public method - ToString would be better-looking.

Good job!


Create pairs of items with similarity constraints

The simplest answer I could come up with exploits the structure of the problem and gives a deterministic answer, but since I didn't specify the answer had to be random, I think it's valid.

Basically, the pairs [(0, 1), (1, 2), (2, 3), (3, 0)] are equivalent to some creative slicing of the list d_list = [0, 0, 1, 1, 2, 2, 3, 3]. I couldn't figure out how to slice it properly, so instead I used a hacky re-arrangement of d_list.append(d_list.pop(0)). This gives d_list = [0, 1, 1, 2, 2, 3, 3, 0] which I can then slice into pairs trivially.

Complete code below:

n_items = 5

nums = list(range(n_items))

d_list = []
for nn in nums:
    d_list.append(nn)
    d_list.append(nn)

d_list.append(d_list.pop(0))

pairs = []
for i1, i2 in zip(d_list[::2], d_list[1::2]):
    pairs.append((i1, i2))

It's definitely not the prettiest code, but it works.


First main problem is the code does not compile:

When you implement template classes. The compiler instantiates the templates on use. This means the compilation unit that is instantiating the class must have already seen the source for the template (if it has not then it marks it as unresolved) and then tries to resolve them at link time. In your case this does not happen.

main.cpp: Uses Stack<int> thus needs the constructor and destructor.
          But does not have them at this point. So waits for the linker to find one.

Stack.cpp: Contains only template definition and thus does **NOT** generate any code.
           Templates only become real code when there is an instantiation
           (implicit as done by the compiler in main.cpp or explicit when you do it).
           Since there is no instantiation there is no code.

This all means that main fill fail to link.

The easiest way to solve this:

Rename Stack.cpp to Stack.tpp
#include "Stack.tpp" from inside "Stack.h"

The reason to rename to Stack.tpp is that some build systems will try to build all source and since this is included by a header this can cause problems with some build systems. So it is best to change the name just to avoid any future problems. tpp is often used to hold template definitions.

Never do this:

while(!inFile.eof()) {
    getline(inFile, in);
    text.push_back(in);
    fileLines++;
}

Several problems:

If getline() fails with a real error (not EOF) you end up with an infinite loop.
The last line read reads up to (but not past the EOF).
So you have read the last line but EOF is not set. You then re-enter the loop try to get another line, this fails and sets EOF but nothing is done with in yet you still push in onto text. So you end up pushing the last line twice.

The correct way to read from a file is:

while(getline(inFile, in))
{
    // The loop is only entered if getline() successfully reads a line.
    // Thus it solves the two problems above.

    text.push_back(in);
    fileLines++;
}

This works because getline() returns a reference to a stream. When a stream is used in a boolean context it is converted to a type that can be used as a boolean (type unspecified in C++03 but bool in C++11). It is converted by checking the fail() flag. If this is true the conversion returns an object equivalent to false otherwise an object equivalent to true.

When passing big objects as parameters consider passing them by reference. If they are never modified pass by const reference. If you don't the compiler is going to generate a copy.

void parseLines(const std::vector<std::string> text, const int begin, const int end) {

Here you should probably pass text by const reference.

void parseLines(const std::vector<std::string> const& text, const int begin, const int end) {
//                                            ^^^^^^^^

Same thing here:

void parseRepeat(const std::string repeatLine, int &begin, int &end) {
// Should probably be
void parseRepeat(const std::string& repeatLine, int &begin, int &end) {
//                               ^^^

Casting is nearly always a sign that something is wrong with your design:

(unsigned int)fromLine

This should be a hint that fromLine is the wrong type. Since it is measuring a size and will never by less than 0 this is an indication that the correct type for the type is unsigned int (or probably size_t).

void parseLines(const std::vector<std::string> text, std::size_t const begin, std::size_t const end) {
    Stack<int> lyricStack;

    std::size_t fromLine = begin;
    std::size_t toLine   = end;

    while(fromLine <= toLine && fromLine < text.size()) {

atoi() is fast but non standard and not always available. An easier way is to just use the stream operators. This will always work and 99% of the time will be sufficiently fast. Only optimize out when you know it makes a difference.

Also this code is so dense it is nearly unreadable. White space is your friend.

void parseRepeat(const std::string repeatLine, int &begin, int &end)
{
    std::string numbers = repeatLine.substr(repeatLine.find(" ") + 1);
    begin = atoi((numbers.substr(0, numbers.find(" "))).c_str()) - 1;
    end = atoi((numbers.substr(numbers.find(" "))).c_str()) - 1;
}

Much easier to write with streams:

void parseRepeat(const std::string repeatLine, int &begin, int &end)
{
    // This line always has the form
    // #repeat <number> <number>
    std::stringstream   linestream(repeatLine);
    std::string         repeat;

    linestream >> repeat >> begin >> end;
}

Both NODE and Stack contain RAW pointers. Yet they do not obey the rule of three. This is very dangerous. The simple rule is your classes should never contain RAW pointers (all pointers should be wrapped in smart pointers) unless you are writing a smart pointer or container.

In this situation NODE would be easy to implement using smart pointer.

Also you do a work handling node inside stack. It simplifies the design if you move this work to the constructor of NODE. This makes the code in Stack much easier to read as it just handles the stack and the NODE can handle itself.

The Stack is arguably a container so it can have a pointer but you must implement the rule of three. This means you need to implement the Copy Constructor/Assignment operator/Destructor or make these methods private. The reason is that if you do not then the compiler will automatically  generate these methods. And the compiler generated version does not plat well with "OWNED RAW pointers".

{
    Stack<int>   a;
    a.push(4);

    Stack<int>   b(a);   // Copy made of a

    DO STUFF
} // Here B is destroyed.
  // But because you did not define a copy constructor b is a shallow copy of a
  // This means they both contain the same pointer. So b deletes it first.
  // Now A is destroyed.
  // This also deletes its pointer (the same as b) but it has already been deleted.
  // Your program is now free to produce nasal daemons (undefined behavior).

The simplest solution is to disable copy construction and the assignment operator.

You have over complicated push:

if(!head) {
    newNode->next = NULL;
    head = newNode;
} else {
    newNode->next = head;
    head = newNode;
}

Would this not be easier to write as:

newNode->next = head;
head          = newNode;

Also isEmpty() is over complicated:

if(!head) {
    return true;
}

return false;

Could be written as:

return head == NULL;


Determining if all strings are parsable to int

I find that negatives in method names lead to confusing code. For instance,

if (!ArePerPersonBILimitsInvalid(...))

  "Are there no BI limits that are invalid?"

becomes much more readable when we write it this way:

if (ArePerPersonBILimitsValid(...))

  "Are all BI limits valid?"

So let's fill in the blanks.

public static bool ArePerPersonBILimitsValid(IEnumerable<string> biLimits)
{
    return biLimits.All(IsBILimitValid);
}

Great, so now we need to write IsBILimitValid.

public static bool IsBILimitValid(string biLimit)
{
    if (string.IsNullOrWhiteSpace(biLimit))
    {
        return true;
    }

    int value;
    return int.TryParse(biLimit, out value) && value >= 1;
}

This way the code much more closely reflects your problem statement:

  loop through a list of strings and validate that all are parsable to
  int and not less than 1


Since you do not actually need the count of each character, it would be simpler to use a set and the superset operator >=:

def is_pangram(astr):
    return set(astr.lower()) >= set(string.ascii_lowercase):

Your two solutions are almost identical, though here

for char in astr:
    lookup[char.lower()] += 1

it would be faster to lowercase the whole string at once (like you already do in solution 2):

for char in astr.lower():
    lookup[char] += 1

Other than that, the only difference is defaultdict vs. Counter. The latter makes your code more elegant, but since the standard library implements Counter in pure Python, there may be a speed advantage to defaultdict.


I wouldn't consider that a Boggle solver, as you only consider words that start at [0, 0] and progress east, south, or southeast.  (With coordinates that are always nondecreasing, you need not have bothered using marker to prevent backtracking.)

A complete search will probably take an extremely long time.  You should use a dictionary that can check whether there are any words that begin with some prefix, so that you can prune fruitless search paths.  Use a trie data structure, or possibly a TreeSet<String>.

Board, N, and HasWord(…) all have improper capitalization.  It doesn't make sense to require N to be passed in explicitly, since it should be detectable from the board's dimensions.

Appending a character to a string can be simply written as prefix + board[i][j].

I would recommend redesigning the class with a more versatile interface, because printing the results to System.out limits reusability.

public interface BoggleSolutionHandler {
    public void foundWord(String word);
}

public class BoggleSolver {
    public static void solve(char[][] board, BoggleSolutionHandler callback, NavigableSet<String> dictionary) {
        …
    }
}

An iterator would be even nicer to use, but probably harder to implement since you can't take advantage of recursion:

public class BoggleSolver implements Iterator<String> {
    public class BoggleSolver(char[][] board, NavigableSet<String> dictionary) {
        …
    }

    @Override
    public boolean hasNext() {
        …
    }

    @Override
    public String next() {
        …
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }
}


Apart from the less-than-ideal variable and type names already mentioned you are doubling up on code just to check head first and then separately doing the same again for every other node. The only difference is that you need to modify head if the element to be removed is the first one. This can be condensed into a single loop:

int deleteSpecificItem(linked** head, int val)
{
    if (!head || !(*head)) return -1;

    linked* tmp = *head;
    linked* prev = NULL;

    while (tmp->value != val && tmp->next != NULL)
    {
        prev = tmp;
        temp = temp->next;
    }

    if (tmp->value == val)
    {
        if (prev)
        {
            prev->next = tmp->next;
        }
        else
        {
            *head = tmp->next;
        }
        free(tmp);
        return val;
    }

    return -1;
}

The way this works is: First we try to find the node which should be removed and we also keep a pointer to the previous node. Once the loop finishes there are several cases to check:

If the current value is not equal to the one we are looking then it's not in the list and we can return
If the current value is equal to the one we are looking for then tmp points to the node which needs to be removed

If we have a valid prev then rewire by skipping tmp
If we don't have a valid prev then apparently head needs to be moved
Now the current node is unlinked and we can delete it
We can also return val instead of remembering the value of the current node because we know that they are equal.

Regarding !head vs head == NULL: I tend to prefer !head if it's for simple pointer checks and prev->next == NULL when the expression is more complex. However some companies enforce the style NULL == head because a typo like typing = instead of == will yield in a compile error this way (you can't assign something to a constant) instead of an accidental assignment. I never managed to consistently do it that way (old habits die hard) and to be honest I've never run into a bug due to this (compilers these days spit out warnings for these kind of constructs).


Seems you are on the right way. But mostly depends how will the client use your factory and BasePackage.
Here are some my minor remarks for improvements:

Only BasePackage is to be public, all the implementation classes are to be hidden.
makePackage() should return BasePackage type.
To reduce possible 5..6 arguments think about varargs solution.
Yes, you may have factory as a static, because you don't have an internal state (at least for now).
Naming: if possible rename BasePackage to reflect your domain area. BasePackage for client perspective may be not clear. But it is ok if you have good package hierarchy.


Counting pairs of integers whose sum is less than a given threshold

A better algorithm

Your current algorithm has a worst case time of \$O(n^2)\$, when the list is half filled with zeroes, and half filled with k/2.  You can solve the problem in \$O(n \log n)\$ time by doing the following:

Sort the input.
Use two indices, one starting at the low end and one starting at the high end.  Call these indices i and j.
For each i, walk j down until a[i] + a[j] < k.  When this happens, add j-i to the solution count, and increment i.  Do not reset j.
Stop when i >= j.

Steps 2-4 solve the problem in \$O(n)\$ time, but the sort in step 1 takes \$O(n \log n)\$ time.  Here is a code snippet to illustrate the key part:

for (int i=0, j=len-1; i < j; i++) {
    while (j > i && a[i]+a[j] >= k)
        j--;
    count += j - i;
}


You get the StackOverflowError because the solve method is called recursively too many times for large inputs such as 29194.

The first time you call solve(0, ...), nothing is already computed, so this will recursively call:
 * solve(2, ...) and then solve(4, ...), and so on until it reaches 29194
 *solve(3, ...)and thensolve(6, ...), and so on until it reaches 29194

However, there's a simple trick to avoid all the recursion: iterate backwards. Call solve(n, ...) (yes, this will call solve(n+2) and solve(n+3), but those will finish fast without recurring). Then, call solve(n-1), then solve(n-2), and so on, until solve(0). Notice how this time all recursive calls will finish in one step, as the values will already be computed and available in dp.

So, before your call to solve(0, n), add the following code:

for (int i = n; i >= 0; i--) {
    solve(i, n);
}

and you will avoid the StackOverflowError.

Here it is in action: http://ideone.com/7Ou8qq

Note that this is the smallest change to your code that I could make to get it to run, so it's more like a hack. Optimally, you would change your algorithm to run in reverse order by default.


You should probably just change how the data is stored. You should have one list which contains all of a customers data. For instance, a dictionary that follows this template:

{"name": "a", "purchased": 12}

If you had a list of those, it would be trivial to sort them, using the list sorting functions.

customer_data = [
                    {"name": "a", "purchased": 12},
                    {"name": "c", "purchased": 23},
                    {"name": "o", "purchased": 7},
                ]
customer_data.sort(key=lambda customer: customer["purchased"])
print customer_data
# [{'name': '0', 'purchased': 7}, {'name': 'a', 'purchased': 12}, {'name': 'c', 'purchased': 23}]


Create a two-dimensional Gaussian kernel

The two-dimensional Gaussian function can be obtained by composing two one-dimensional Gaussians.

I changed your code slightly so that it would compile (and not optimize away the unused kernel):

#include <iostream>
int main()
{
    int rows = 20000, cols = 20000;
    const auto kernel = getGaussianKernel(rows, cols, 50, 50 );
    std::cout << kernel.total() << std::endl;
}

This runs in

3.90user 0.38system 0:04.29elapsed

Changing to precompute separate x and y Gaussian curves gives a 10x improvement in speed:

#include <opencv2/core/core.hpp>
#include <cmath>

cv::Mat getGaussianKernel(int rows, int cols, double sigmax, double sigmay)
{
    const auto y_mid = (rows-1) / 2.0;
    const auto x_mid = (cols-1) / 2.0;

    const auto x_spread = 1. / (sigmax*sigmax*2);
    const auto y_spread = 1. / (sigmay*sigmay*2);

    const auto denominator = 8 * std::atan(1) * sigmax * sigmay;

    std::vector<double> gauss_x, gauss_y;

    gauss_x.reserve(cols);
    for (auto i = 0;  i < cols;  ++i) {
        auto x = i - x_mid;
        gauss_x.push_back(std::exp(-x*x * x_spread));
    }

    gauss_y.reserve(rows);
    for (auto i = 0;  i < rows;  ++i) {
        auto y = i - y_mid;
        gauss_y.push_back(std::exp(-y*y * y_spread));
    }

    cv::Mat kernel = cv::Mat::zeros(rows, cols, CV_32FC1);
    for (auto j = 0;  j < rows;  ++j)
        for (auto i = 0;  i < cols;  ++i) {
            kernel.at<float>(j,i) = gauss_x[i] * gauss_y[j] / denominator;
        }

    return kernel;
}

0.32user 0.36system 0:00.69elapsed

(both versions compiled with GCC 7.1.0 with -O3 -march=native on an Intel i7-Q6700)

The calculations are reasonably independent, so OpenMP may help.  But when I tried, it always worked out slower - probably too much false sharing for it to be useful.

Note that my code doesn't initialize the kernel with zeros - it leaves it uninitialized, and instead writes to every element when it reaches it.  This saves two passes over the memory.  I precompute the denominator for the same reason, though that's only truly valid for a kernel of infinite size.

Also note that I changed the calculation of mid-point to divide by 2.0 rather than by 2 - I wasn't sure whether the truncation was intentional or not.

A further speed increase is gained by using OpenCV to work on a row at a time:

cv::Mat getGaussianKernel(int rows, int cols, double sigmax, double sigmay)
{
    auto gauss_x = cv::Mat_<float>(cols, 1);

    const auto x_mid = (cols-1) / 2.0;
    const auto y_mid = (rows-1) / 2.0;

    const auto x_spread = 1. / (sigmax*sigmax*2);
    const auto y_spread = 1. / (sigmay*sigmay*2);

    for (auto i = 0;  i < cols;  ++i) {
        auto const x = i - x_mid;
        gauss_x[i][0] = std::exp(-x*x * x_spread);
    }

    auto kernel = cv::Mat_<float>(rows, cols);
    for (auto i = 0;  i < rows;  ++i) {
        auto const y = i - y_mid;
        kernel.row(i) = gauss_x * std::exp(-y*y * y_spread);
    }

    const auto denominator = std::accumulate(kernel.begin(), kernel.end(), 0);

    return kernel / denominator;
}

0.17user 0.00system 0:00.17elapsed

This is also shorter, and arguably easier on the eye.  In this version, I show an alternative to precomputing the denominator - use std::accumulate to add it together afterwards.

The simplest and fastest version, though, is to use the Gaussian distribution provided by OpenCV, and just matrix-multiply the two together:

#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>

cv::Mat getGaussianKernel(int rows, int cols, double sigmax, double sigmay)
{
    auto gauss_x = cv::getGaussianKernel(cols, sigmax, CV_32F);
    auto gauss_y = cv::getGaussianKernel(rows, sigmay, CV_32F);
    return gauss_x * gauss_y.t();
}

Do note that if you intend to use the kernel for filtering, it's best to keep it separated, and perform horizontal and vertical passes each with a one-dimensional kernel.


Bash script to check available name in Github

The code is nice and short, and it is easy to read.

I'm surprised that it works at all. Sending the out=$(…) command to the background sounds as if the code might continue before curl had the chance to fill the output. Do you get the same results without the &? I'd expect that more names are reported as available then.

As long as the & is in the program, I would verify the results manually.

I also don't see the point of running the requests in parallel. It's only 10 * 26 requests, which are answered anyway within 5 minutes.

Update: The Shell Command Language specification says:

  If a command is terminated by the control operator  ( '&' ), the shell shall execute the command asynchronously in a subshell.

This means that the variable assignment cannot affect the out variable at all. This in turn means that the output you posted does not correspond to the code you posted. Please check again.

If you can reproduce the behavior, please write down all details that might influence it. I tried to reproduce it, and I got exactly the result I expect after reading the specification: all names are not available.


You can also consider a very elegant, recursive solution:

def insert(self, value, node=self.root):
   if node == null:
      return Node(value)
   if value < node.value:
      node.left = self.insert(value, node.left)
   else
      node.right = self.insert(value, node.right)

Although, please mind that in case of large trees, efficiency of that solution is slightly lower (because of call stack)


Script to download Annual Reports (~70,000 in total) from a Website

Yes, right now this would be inefficient, I'd definitely say that using
a predictable filename would be the first key change here, if the link
target or description isn't usable as part of the filename, consider
hashing it.  Simply enumerating all links is, well, suboptimal:  What
if, even if previous files are kept around and not overwritten, between
runs the contents of the website changes (seems likely, doesn't it?) and
suddenly the order of the files being download doesn't match what's on
disk?  Definitely do something about that.

Secondly, the code's separating the creation of that pickle file because
it's supposed to be run multiple times?  A bit odd, but as an impromptu
database, why not.  I usually consider pickle files somewhat ephemeral
since the format is (was?) specific to Python.

And then simply check if the file exists and skip it (maybe also check
if it's non-empty; going further before downloading the full data the
HTTP header for the size of the returned content could also be compared,
again, before actually downloading the full files).

The range over the data frame I'd have expected to be simpler, but
right now I can't find if there's an easier way (not using the index,
but simply looping over the values themselves that is).

f.write(requests.get(...).content) - that's gonna buffer the full file
in memory I think.  Better don't do that, instead either requests
might have some facility to write directly to files (or a file-like
object), or alternatively the download content would have to be read
piece-by-piece into a smallish buffer, alternating it with writing that
buffer to the output file.

Finally the formatting could be more consistent (whitespace between
expressions mostly).  Take a look at
PEP8 and perhaps an
autoformatter to do that
automatically.  Also leftover comments should be removed.

Right so overall it's effective, but for production code there's lots of
things that could be done, especially making it a more fully fleshed out
script (read: parse command line arguments, have default parameters for
e.g. the output directory; etc.).  The parsing is fine and the selectors
again are succinct and easy to read.


Here are some general optimizations that I usually do.

When you have multiple var declarations you can separate with "," making it a bit easier to read and less of a hassle to write:

var mydiv = $("#mydiv").empty(),
    mywid = $("#wd").slider("value"),
    myhet = $("#ht").slider("value"),
    etc = etc.....

Also when I name my variables, ids, classes, etc. it's good to put names that reference what's inside the element, or the role it plays. It will help you remeber what does what when you get into big projects with lots of these declarations.

As a rule of thumb, if you have to call on an element more than once, you should cache its value. This way jQuery doesn't have to jump into the DOM and look for that element each time you call it. You should also try to limit the scope of elements jQuery has to look through to find the one you want. You can use the type of element previous to the id/class. For example:

$("#mydiv").doSomething();
$("#mydiv").doSomethingElse();

Instead do:

var mydiv = $("div #mydiv");

$(mydiv).doSomething();
$(mydiv).doSomethingElse();

Like you said, you are just starting out with jQuery, and with that I highly recommend this screencast by Jeffrey Way called 30 Days to Learn jQuery. He does a really good job of explain some basic principals as well as some more complex concepts.


Something nice about hackage help/documentation pages like the one you linked: you can go straight to the source code by clicking on the links on the right side of the page.  Looking at the source, there is an instance for Monoid b => Monoid (a -> b), which is not quite exactly what you're trying to do, since it restricts b to types with a Monoid implementation.  It uses a nice trick where it implements this monoid in terms of the other monoid.

The Data.Monoid code:

instance Monoid b => Monoid (a -> b) where
    mempty _ = mempty
    mappend f g x = f x `mappend` g x

If you have any difficulty understanding it, keep in mind that the mempty and mappend functions are for different monoids on the left hand side than they are for the right hand side.

I can think of 2 ways of getting 2 a -> bs to combine: throw away the first one, or throw away the second one.  Neither seems similar to what you're trying to do (or particularly useful).

Besides the (already noted) problem that . as an implementation of mappend won't typecheck, there's another problem: mempty.  As written, it'll typecheck, but the type signature of your mempty is a -> a, while it should be just a.  mempty is a value in the monoid.

I'd be tempted to change the definition to mempty = id, but id :: a -> a not a -> b.  You could try to make a constant function that just returns some particular b, but since you have no idea what type b will be, that's not possible.

In general, haskell's type system is very nice -- not only can it catch type errors, but it can serve as documentation, provide a bit of heuristic guidance and help you organize your thoughts.  When something doesn't typecheck, it means what you're trying to do doesn't quite make sense.


def getInfo():
    global info
    while 1:

Don't use while 1 to symbolize an infinite loop; it does not look very pythonic. A better way to write this would be to use True.

try:
    #This will bring the required info as pandas df
    info = retriveInfoFromDB()
except:
    pass

Don't just except; you should be catching a specific type of exception. In this case, the exception you would catch would be whatever exception could possibly be raised from retriveInfoFromDB.

server_socket.bind(address)
while(1):
    print "Listening"

and

global info
while 1:
    print "Information retrieval running"

Why did you use different styling for the while loop in both of these loops? Yes, they should both be using True rather than 1, but why did you put ()s around one's conditional and nothing around the other's conditional?

In my opinion, you should not be using ()s because they make code look more cluttered and less pythonic.

Be careful with these lines:

server_socket = socket(AF_INET, SOCK_DGRAM)
server_socket.bind(address)

These lines are both capable of raising an error.

The python socket library comes with it's own error called socket.error. It split up into a tuple: (errno, string) Where errno is the error number raised by the system call, and string is a descriptive error message of the errno.

To be safe with these lines, just encase them in a try/except statement:

try:
    server_socket = socket(AF_INET, SOCK_DGRAM)
    server_socket.bind(address)
except socket.error as error_message:
    print "Error #%d: %s" % (error_message[0], error_message[1])
    sys.exit(-1)

At the end of the except, I added a function call to quit the program with an exit status of -1 (this tells external programs that there was in running this application).

I think it should be a good idea to exit because, if you are having socket problems, the code is probably not going to work in the first place so it would be best to just exit the code.

Note: an error might be able to arise from

recv_data, addr = server_socket.recvfrom(2048)

If an error can come from here, I recommend that you catch it as I showed above, but I don't think you should have to quit out of the program for it.

The variable names

th1 = threading.Thread(target=runServer)
th2 = threading.Thread(target=getInfo)

are not very descriptive for a variable. Yes, I know it is a thread; the variable name should not tell me that.

The variable name should tell me what the variable is going to be used for. For example, you could call th1 something along the lines of server_listener.

I recommend a different approach to your multi-threading.

In this loop right here:

while True:
    print "Listening"
    recv_data, addr = server_socket.recvfrom(2048)
    server_socket.sendto(info.to_json(path_or_buf = None, orient = 'records', date_format = 'epoch', double_precision = 10, force_ascii = True, date_unit = 'ms', default_handler = None), addr)

Things can get a little hung up with all the reading and the writing; especially reading and writing of that size.

I recommend opening up a new thread every time you have a new connection, and then closing it every time you are done reading and writing the connection.

That way, if your program gets hung up on one connection, the rest won't be affected.

Here is what I mean:

while True:
    connection = threading.Thread(target=read_and_write_data)
    connection.start()

Where read_and_write_data is

def read_and_write_data():
    global info
    global server_socket

    print "Listening"
    recv_data, addr = server_socket.recvfrom(2048)
    server_socket.sendto(info.to_json(path_or_buf = None, orient = 'records', date_format = 'epoch', double_precision = 10, force_ascii = True, date_unit = 'ms', default_handler = None), addr)

Sorry for the poor naming of that function.

To make splitting up into different threads per connection easier, I made the variables address, and server_socket. That way, different functions can easily access the same information; it would be a pain and unnecessary to re-make the socket every time a new thread was created.

And, no need to worry about closing the thread: the thread will automatically close after it's target has finished running.

Python's naming case for variables and functions is snake_case, not camelCase. Your functions getInfo and runServer should be snake_case. See PEP 8, the official Python style guide.

Putting it all together:

from socket import *
import threading
import pandas as pd
import json
import time
import datetime
import thread

#Global Info variable
info = pd.DataFrame()

try:
    server_socket = socket(AF_INET, SOCK_DGRAM)
    server_socket.bind(address)
except socket.error as error_message:
    print "Error #%d: %s" % (error_message[0], error_message[1])
    sys.exit(-1)

def get_info():
    # same code

def run_server():
    while True:
        connection = threading.Thread(target=read_and_write_data)
        connection.start()

def read_and_write_data():
    global info
    global server_socket

    print "Listening"
    recv_data, addr = server_socket.recvfrom(2048)
    server_socket.sendto(info.to_json(path_or_buf = None, orient = 'records', date_format = 'epoch', double_precision = 10, force_ascii = True, date_unit = 'ms', default_handler = None), addr)

server_listener = threading.Thread(target=run_server)
info_reader = threading.Thread(target=get_info)

server_listener.start()
info_reader.start()


In my opinion your code it's not so bulky but I would do something like below with few changes. I have not tested it too much but it should works.

I will use FilenameUtils for easy manipulation with files like getting basename or extension of file - it will save you some of the lines and also it is one of the most used library for file manipulation.

I would remove String getFileName and String getFileExtention and create self-described function and delete in code comments. I also removed return false for InterruptedException - I would like to get another draft of the name in the next iteration.

I dont like spaggetti code when some string is creating like (with +):

return name + dateFormat.format(new Date()) + ext;

so here I would use StringBuilder or String.format or something like that.

Below is what I have done in few minutes.

import org.apache.commons.io.FilenameUtils;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileBackup {

    private static final String pattern = "-dd_M_yyyy-hh_mm_ss.";
    private static final DateFormat dateFormat = new SimpleDateFormat(pattern);

    /**
     * Creates new file. If file with given name exists, then backups
     * it by renaming and adding time stamp to file name;
     *
     * @param filePath the fully qualified name of file

     * @return the file on success; otherwise returns null
     *
     * @throws IOException
     */
    public static File backupAndCreateFile(String filePath) throws IOException {
        return failedBackuOfExistingFile(filePath) ? null : new File(filePath);
    }

    private static boolean failedBackuOfExistingFile(String filePath) {
        File fileOnPath = new File(filePath);
        return  fileOnPath.exists() && !successBackupFile(fileOnPath);
    }

    private static boolean successBackupFile(File fileToBackup) {

        while (true) {

            File backupDraft = new File(generateBackupName(fileToBackup.getAbsolutePath()));
            if (!backupDraft.exists()) {
                return fileToBackup.renameTo(backupDraft);
            }
            fileWithGeneratedNameExistsNowSleepForSomeTime();
        }
    }

    private static void fileWithGeneratedNameExistsNowSleepForSomeTime(){
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static String generateBackupName (String filePath) {
        String fileName = FilenameUtils.getBaseName(filePath);
        String fileExtension = FilenameUtils.getExtension(filePath);
        return new StringBuilder().append(fileName)
                .append(dateFormat.format(new Date()))
                .append(fileExtension)
                .toString();
    }
}


Review of a C++ missing characters snippet

Instead of starting from a zero-ed bitset and then set them to true one by one, you could start with all true, set to false one by one and then use std::bitset::none() to break the loop.

But, apart from this small thing, std::string will probably preallocate memory (on the heap or on the stack; it's implementation dependent), whether or not you add a letter.  My advice would be to use an std::array with a fixed size of 26 (or your own stack implementation of a string) to directly store the letters, and remove the bitset and std::string.

That should simplified the code.  As the 26 chars will be stored in 7 int, copying or overwriting that size from the stack should be blazing fast (the cache lines of a modern processor is 32 bytes) compared to multiple math operations and a potential heap allocation.


Audio processing with normalized [0.0, 1.0] domain

Prefer C++ headers

Instead of <math.h>, it's better to include <cmath> and qualify names such as std::log.

Prefer constants to macros

Re-write pi as a strongly-typed, scoped variable rather than a preprocessor macro.  Same for 2*pi if you really feel the need.

Manage line lengths

Some lines are very long.  In many cases, they just need newlines adding (e.g. bodies of inline functions can have their own lines).

In the case of the std::clamp() call, it's probably worth using variables to give a name to the candidate value before clamping.

Easier sizeof

Instead of recomputing the size of bufferLeft and bufferRight like this:

    memset(&bufferLeft, 0, blockSize * sizeof(double));
    memset(&bufferRight, 0, blockSize * sizeof(double));

It's easier and clearer to just use the whole array size:

    memset(&bufferLeft, 0, sizeof bufferLeft);
    memset(&bufferRight, 0, sizeof bufferRight);

Personally, I'd generally prefer std::fill to match types and ensure the intention is clear:

    std::fill(std::begin(bufferLeft), std::end(bufferLeft), 0.0);
    std::fill(std::begin(bufferRight), std::end(bufferRight), 0.0);

Then I don't need to think about whether all-bits zero is the same as 0.0 or not.


Combining json responses of recursive web service calls with PHP and curl

public static function CallAPI($method, $url, $data = false)

Use lowercase first letter for method and function names. callAPI.
Use null rather than false as default value for $data as this more truly represents what is happening (no value has been passed).
Once in your method, you are not doing anything to validate that the parameters passed are as expected. For example, $method and $url should, at a minimum be validated as non-zero length strings.  Perhaps URL also needs to be validated as valid URL and method to be one of set of values you are expecting (i.e. POST,PUT,GET,DELETE,etc.). $data should be validated as null or non-zero length string. If these validations do not pass, you should fail out of this method (perhaps with InvalidArgumentException or similar) and not ever attempt to make a curl call.

$curl = curl_init();

Here, you just assume your curl_init() works.  You should should check for failure and handle appropriately (log error, throw Exception, etc.).
Consider moving your curl initialization sequence into its own static method which would initiate and store the curl handle on the class, making it available to the callAPI method.  There is no reason for you to continually set up and tear down curl handles for each API call.  You probably only need to do this once (changing settings on handle as appropriate.
This centrally stored handle will also be something you will need if you want to be able to optimize your code to making API calls in parallel (more on this below).

switch ($method)
{
    case "POST":
        curl_setopt($curl, CURLOPT_POST, 1);

        if ($data)
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        break;
    case "PUT":
        curl_setopt($curl, CURLOPT_PUT, 1);
        break;
    default:
        if ($data)
            $url = sprintf("%s?%s", $url, http_build_query($data));
}

Rather than having logic here in switch consider actually having distinct get(), post(), put(), delete(), etc. methods on your class.  Each method can make necessary config settings on curl handle and then call the central method which makes the API call and assembles the response data structure.

An incomplete implementation for this might be structured as follows:

public static function get($url, $data) {
    // make setting changes to curl handle here
    // then call call API method, which at this point is just a
    // request/repsonse handler
    return self::callAPI($url, $data);
}

curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_HEADER, 1);

Consider moving these option settings to common initialization method as noted previously.

// Request json
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Accept: application/json'));

Again, probably best set during handle initialization

$APIResult['error'] = curl_error($curl);
$APIResult['info'] = curl_getinfo($curl);
$APIResult['header'] = $header;
$APIResult['body'] = $body;

Consider building this as object rather than associative array, as this really seems to be more of a set of object data rather that a hashmap type of data structure.  You might over time also find a need to add behaviors around these properties such that having your own APIResult class or similar makes sense.  Passing around an object dependency with known properties and behaviors might be preferable to just passing around a data structure.

public function GetHotels($nodeId) {

Again consider naming getHotels() and adding validation for parameter.
This method doesn't return anything!  What is the point of having this public method if it doesn't do anything for the caller?

$node = Node::find($nodeId);

Is $node a meaningful variable name here? $coordinates perhaps?

$apiKey = 'prtl6749387986743898559646983194'; // This is the test key

This should not be defined here in this method.  At a minimum it should be a constant on this class, but would be better still if this was stored in application configuration and not in this code at all.

$checkindate = '2016-12-17';
$checkoutdate = '2016-12-18';
$guests = 2;
$rooms = 1;

Why are these hard-coded?

$url =
'http://partners.api.skyscanner.net/apiservices/hotels/liveprices/v3/'
. $market . '/'. $currency . '/'. $locale . '/'. $entityid . '/'.
$checkindate . '/'. $checkoutdate . '/'. $guests . '/'. $rooms;

Consider having URL base as class constant and having a method to build the full URL

// First call to initiate session, no actual results retrieved
$APIResult = APIServices::CallAPI('GET', $url, array("apiKey" => $apiKey));

If you incorporate other suggestions, this might look like:

$APIResult = APIServices::get($url, array("apiKey" => $apiKey));

$debugResult = $APIResult['body'];

What is purpose of this?

if (!empty($APIResult['info']['redirect_url']) ) {
    $APIResult =  APIServices::CallAPI('GET', $APIResult['info']['redirect_url']);

If you know your API is going to give you redirect, just set curl to follow. Don't write a bunch of nested code to handle these redirects.  What if there are two redirects here?  Your code fails.

    $json = json_decode($APIResult['body'],true);

Why would you call this variable $json when it does not contain JSON, but rather a data structure resulting from JSON deserialization? Call the variable something that is meaningful to what it is actually storing.
What if json_decode() fails (i.e. server sent you something that is improperly formatted)?

    //Concatenate the json results
    $result = $APIResult['body'];

Why are you continuing to work with the raw JSON string here?  You already have a meaningful data structure from the previous line of code.  Concatenating JSON together DOES NOT WORK, as you will get an invalid JSON string.  JSON is ONLY used for data transport, not as a mechanism to build a data structure.  Focus on building an appropriate data structure and then serialize to JSON for delivery.

    while ($json['status'] <> 'COMPLETE') {
        $APIResult =  APIServices::CallAPI('GET', $APIResult['info']['redirect_url']);
        $json = json_decode($APIResult['result'],true);
       //Concatenate the json results
       $result = $result . $APIResult['body'];
    }

And last but not least.  I think you might strongly consider making these API calls in parallel, as that will be the fastest way for this script to operate (though it would consume more memory as a trade-off).  Take a look at curl_multi_* functions (or a library which can better handle your curl operations rather than you coding them manually).  This relates back to earlier point of needing to store curl handle on the class such that each individual call to callAPI method (or the wrapper methods).  To implement parallel calls you would likely need to store curl_multi handle on the class, with each iteration of this loop adding a new curl handle to the multi-handle and returning data from each API call to be aggregated by calling getHotels() method.

I will link you to a lightweight class I had written at one point to manage multi_curl handles geared towards a RESTful use case.  Feel free to use in your application or for inspiration.

https://github.com/mikecbrant/php-rest-client

In general, and without seeing your full class implementation, I am worried that your class is doing too much.  Why would one class need to know all of the following?

How to initiate can configure cURL calls. Ideally this could take a valid cURL wrapper object as a dependency and not have to do anything other than formulating the request and handling the response.
The low-level details of formulating requests against this specific API (i.e. URL naming, redirection handling, etc.)
The logic for deriving localization, geography, etc. based on the request/requestor.
The specifics of performing a hotel search.
The specifics of getting details for an individual hotel


First of all, try to write code for pure components without using a class:

It will be your App.js

const App = ({ children }) => (

    {children}

);

export default App;

It will be your Layout.js

const Layout = ({ children, type }) => (

    type == 'wrap' ? (

          {children}

    ) : (

         {children}

    )

);

export default Layout;

It will be your Login.js

const Login = () => (
  <Layout type="no-wrap">
    Login
  </Layout>
);

export default Login;

If you don't need to use a Layout component inside the Login component, just don't do it.

For example:

Layout.js

const Layout = ({ children }) => (

      {children}

);

export default Layout;

LayoutNoWrap.js

const LayoutNoWrap = ({ children }) => (

    {children}

);

export default LayoutNoWrap;

Login.js

const Login = () => (
  <LayoutNoWrap>
    Login
  </LayoutNoWrap>
);

export default Login;


Translating warning codes as messages to be printed

Store the variable part of the message in a variable, and do the printing after the switch, for example:

int XB3DS_Warn_Code (int Warn_Code)
{
  const char * msg;
  switch(Warn_Code)
  {
    case WARN_Failed_To_Connect_To_Display:
      msg = "Failed to connect to display.";
      break;
    case WARN_Width_Or_Height_Is_Unacceptable:
      msg = "Width or height is unacceptable.";
      break;
    case WARN_No_Visual_Is_Matched_For_Screen:
      msg = "No visual is matched for screen.";
      break;
    case WARN_The_Window_Mode_Is_Unacceptable:
      msg = "The window mode is unacceptable.";
      break;
    case WARN_Insufficient_Memory_To_Allocate:
      msg = "Insufficient memory to allocate.";
      break;
    default:
      msg = "Unknown error.";
  }
  fprintf(stdout, "[  WARNING  ]: %s\n", msg);
  return Warn_Code;
}

Now the case statements only have the absolutely necessary code. It's the most basic kind of refactoring: extracting values to variables and filling them in a template later. Another variant would be extracting common logic to a helper function. I also added a default case that was missing: it's always good to have.

Also, instead of fprintf(stdout, ...) why not use simply printf(...) ?

Finally, as @black pointed out, "What's the point to return what you get passed?" Better change the method signature to return void. Even better, return the message instead of printing, so that the rest of your code can do whatever it needs with it, for example:

const char * XB3DS_Get_Warn_Message (int Warn_Code) {
    const char * msg;
    // the switch ...
    return msg;
}

void XB3DS_Handle_Warning (int Warn_Code) {
    const char * msg = XB3DS_Get_Warn_Message(Warn_Code);
    fprintf(stdout, "[  WARNING  ]: %s\n", msg);
}

Change the rest of your code to call XB3DS_Handle_Warning instead of your current XB3DS_Warn_Code. Right now you just want to print to stdout. But maybe someday you will want to log to a file, or show as part of a GUI. Then you won't need to touch XB3DS_Get_Warn_Message anymore, but change the simpler XB3DS_Handle_Warning helper.


I have some minor tips about naming:

weight is entirely different than mass, thus I advice you to change that, because some users might be annoyed by this common confusion, if it is present in the user interface of the app. See Mass versus weight
CalculatorBrain does not really feel related to BMI. Maybe BMICalculator would be a better fit here

When it comes to your struct, if that is all you are planning to do with it, this gets quite useless. Instead, I would simply use a function, taking two Double parameters (to avoid String conversion). Also, I would not use ((heightInCM / 100) * (heightInCM / 100)), because it does an unnecessary multiplication between two known numbers, two of 100 in this case. This would be an example:

func calculateBMI(massInKilograms mass: Double, heightInCentimeters height: Double) -> Double {
    return mass / ((height * height) / 10000)
}

It is shorter and, in my opinion, more elegant and efficient. And now you do not need to initialize a struct and call one of its methods each time, instead you only need to call it:

calculateBMI(massInKilograms: x, heightInCentimeters: y)


First, I'll comment on your code, and then I'll discuss a more "Pythonic" way to do it using features in the Python standard library.

There's no docstring. What does the function do?
You start out by reversing the list. This is a destructive operation that changes the list. The caller might be surprised to find that their list has changed after they called longest_repetition! You could write alist = reversed(alist) instead, but it would be even better if you didn't reverse the list at all. By changing the >= test to > you can ensure that the earliest longest repetition is returned, while still iterating forwards over the input.
You build up a list contender that contains the most recent series of repetitions in the input. This is wasteful: as contender gets longer, the operation element in contender takes longer. Since you know that this list consists only of repetitions of an element, why not just keep one instance of the element and a count of how many repetitions there have been?
You only update largest when you found a repetition. That means that if there are no consecutive repetitions in the input, largest will never be updated. You work around this using an if statement at the end to decide what to return. But if you always updated largest (whether you found a repetition or not) then you wouldn't need the if statement.
By suitable choice of initial values for your variables, you can avoid the if not alist special case. And that would allow your function to work for any Python iterable, not just for lists.

So let's apply all those improvements:

def longest_repetition(iterable):
    """
    Return the item with the most consecutive repetitions in `iterable`.
    If there are multiple such items, return the first one.
    If `iterable` is empty, return `None`.
    """
    longest_element = current_element = None
    longest_repeats = current_repeats = 0
    for element in iterable:
        if current_element == element:
            current_repeats += 1
        else:
            current_element = element
            current_repeats = 1
        if current_repeats > longest_repeats:
            longest_repeats = current_repeats
            longest_element = current_element
    return longest_element

So is there a more "Pythonic" way to implement this? Well, you could use itertools.groupby from the Python standard library. Perhaps like this:

from itertools import groupby

def longest_repetition(iterable):
    """
    Return the item with the most consecutive repetitions in `iterable`.
    If there are multiple such items, return the first one.
    If `iterable` is empty, return `None`.
    """
    try:
        return max((sum(1 for _ in group), -i, item)
                   for i, (item, group) in enumerate(groupby(iterable)))[2]
    except ValueError:
        return None

However, this code is not exactly clear and easy to understand, so I don't think it's actually an improvement over the plain and simple implementation I gave above.