Google Analytic Webcrawler for every country code

PEP8

This is the official Python style guide. If you are interested in good naming conventions and other good practices, you can start here.

Among other things, you code would benefit from:

variable name using lower_snake_case;
class name using PascalCase;
comments delimited using # and not raw strings in the code;
redundant/useless parts of the code removed.

A first rewrite would yield:

import re
import time

import requests
import pandas as pd
from bs4 import BeautifulSoup, SoupStrainer

SESSION = requests.Session()

# This is the Google Analytics Selector Section
class GoogleSession:
    def fetch_google_xml(self, URL, country_code):
        response = SESSION.get(f"{URL}{country_code}")
        return BeautifulSoup(
                response.text, 'xml',
                parse_only=SoupStrainer('channel'))

google_session = GoogleSession()

def google_trends_retriever(URL, country_code):
    xml_soup = google_session.fetch_google_xml(URL, country_code)
    print(country_code)
    titles = xml_soup.find_all('title')[1:]
    traffics = xml_soup.find_all('ht:approx_traffic')
    return [
            (title.text, re.sub("[+,]", "", traffic.text))
            for title, traffic in zip(titles, traffics)
    ]

def create_pd_trend(data):
    check_panda = pd.DataFrame(
            google_trends_retriever(google_URL, data),
            columns=['Title', 'Score'],
    )
    if len(check_panda) == 0:
        print('No available data')
    else:
        return check_panda

# This is the Country Code Selector Section
country_code_list = []

class CountryCodeSession:
    def fetch_country_code_html(self, URL):
        response = SESSION.get(URL)
        return BeautifulSoup(
                response.text, 'html.parser',
                parse_only=SoupStrainer('table'))

country_code_session = CountryCodeSession()

def parse_row(url):
    rows = country_code_session.fetch_country_code_html(url)
    for row in rows.find_all(['td', 'tr']):
        cells = row.find_all('td')[2:3]
        for cell in cells:
            value = cell.string
            country_code_list.append(value[:2])

def iterate_list(data):
    i = 1
    while i <= 239:
        selected_country_code = get_data_from_list(i)
        print(create_pd_trend(selected_country_code))
        i += 1
    else:
        print('Has reach the end of i', i)

def get_data_from_list(num):
    key = num - 1
    for i in country_code_list[key:num]:
        return str(i)

if __name__ == '__main__':
    # URL Section
    google_URL = "https://trends.google.com/trends/trendingsearches/daily/rss?geo="
    country_code_URL = "https://countrycode.org/"
    # -------------
    start = time.time()
    print("hello")

    # Country Code Section
    parse_row(country_code_URL)
    # ---------------------

    # Google Analytics Section
    iterate_list(country_code_list)
    # -------------------------
    end = time.time()
    print(end - start)

Loop like a native

When I saw

def get_data_fromList(num):
    key = num-1
    for i in country_code_list[key:num]:
        return str(i)

I wondered why you would write such convoluted code. Extracting a sublist of one element to iterate over it and return the first one… You can simplify that to

def get_data_from_list(num):
    return str(country_code_list[num - 1])

But I wondered why using a method for that, and saw how you iterated over indices to call this function. Don't. Use a for-loop as it is meant to be used: by iterating over the content directly.

This would yield:

import re
import time

import requests
import pandas as pd
from bs4 import BeautifulSoup, SoupStrainer

SESSION = requests.Session()

# This is the Google Analytics Selector Section
class GoogleSession:
    def fetch_google_xml(self, URL, country_code):
        response = SESSION.get(f"{URL}{country_code}")
        return BeautifulSoup(
                response.text, 'xml',
                parse_only=SoupStrainer('channel'))

google_session = GoogleSession()

def google_trends_retriever(URL, country_code):
    xml_soup = google_session.fetch_google_xml(URL, country_code)
    print(country_code)
    titles = xml_soup.find_all('title')[1:]
    traffics = xml_soup.find_all('ht:approx_traffic')
    return [
            (title.text, re.sub("[+,]", "", traffic.text))
            for title, traffic in zip(titles, traffics)
    ]

def create_pd_trend(data):
    check_panda = pd.DataFrame(
            google_trends_retriever(google_URL, data),
            columns=['Title', 'Score'],
    )
    if len(check_panda) == 0:
        print('No available data')
    else:
        return check_panda

# This is the Country Code Selector Section
class CountryCodeSession:
    def fetch_country_code_html(self, URL):
        response = SESSION.get(URL)
        return BeautifulSoup(
                response.text, 'html.parser',
                parse_only=SoupStrainer('table'))

country_code_session = CountryCodeSession()

def parse_row(url):
    rows = country_code_session.fetch_country_code_html(url)
    return [
            cell.string[:2]
            for row in rows.find_all(['td', 'tr'])
            for cell in row.find_all('td')[2:3]
    ]

def iterate_list(country_codes):
    for country_code in country_codes:
        print(create_pd_trend(str(country_code)))
    else:
        print('Has reach the end of i', len(country_codes))

if __name__ == '__main__':
    # URL Section
    google_URL = "https://trends.google.com/trends/trendingsearches/daily/rss?geo="
    country_code_URL = "https://countrycode.org/"
    # -------------
    start = time.time()
    print("hello")

    # Country Code Section
    country_code_list = parse_row(country_code_URL)
    # ---------------------

    # Google Analytics Section
    iterate_list(country_code_list)
    # -------------------------
    end = time.time()
    print(end - start)

Stop writting classes

Your classes add absolutely no value over a single function. You don't store state that you reuse after each call. You don't share state between several functions. They are plain functions in a namespace, just let them be plain functions.

This code can benefit from using a class, but not like that.

Parse bytes, not text

lxml, which is the underlying parser used when instructing BeautifulSoup to decode 'xml' explicitly works with raw bytes rather than decoded text. This is to be able to detect explicit encoding declarations and decode the rest of the document appropriately; so you will never have decoding errors.

This means that you need to feed the response.content rather than response.text to BeautifulSoup when parsing XML.

Manage your state properly

Your code heavily relly on global variables and printing data to work. This is the worst part of your code as it make it barely reusable and harder to test properly (think unittest or doctest).

Instead of using global variables, pass them around as parameters and return them from your functions.

Instead of printing results, return values from your functions. This make it easier to extract and massage data into your liking.

There is also the global SESSION that is used throughout the code. I'd encapsulate that into a class to have a single session per instance so you can easily crawl several addresses if need be.

My take on the problem would be:

import re
from functools import partial

import requests
import pandas as pd
from bs4 import BeautifulSoup, SoupStrainer

class GoogleAnalysis:
    def __init__(self, url):
        session = requests.Session()
        self.get_url = partial(session.get, url)

    def _fetch_xml(self, country_code):
        response = self.get_url(params={'geo': country_code})
        return BeautifulSoup(
                response.content, 'xml',
                parse_only=SoupStrainer('channel'))

    def _retrieve_trends(self, country_code):
        soup = self._fetch_xml(country_code)
        titles = soup.find_all('title')[1:]
        traffics = soup.find_all('ht:approx_traffic')
        return [
                (title.text, re.sub("[+,]", "", traffic.text))
                for title, traffic in zip(titles, traffics)
        ]

    def trends(self, country_code):
        df = pd.DataFrame(
                self._retrieve_trends(country_code),
                columns=['Title', 'Score'],
        )
        df['Country Code'] = country_code
        return df

def country_codes(url='https://countrycode.org/'):
    response = requests.get(url)
    soup = BeautifulSoup(
            response.text, 'lxml',
            parse_only=SoupStrainer('table'))
    return [
            cell.string[:2]
            for row in soup.find_all(['td', 'tr'])
            # Some rows don't define row.find_all('td')[2] so filter out
            for cell in row.find_all('td')[2:3]
    ]

def main(url):
    google = GoogleAnalysis(url)
    codes = country_codes()
    return pd.concat([
        google.trends(country_code)
        # Country codes are repeated twice, we only need them once
        for country_code in codes[:len(codes) // 2]
    ])

if __name__ == '__main__':
    import time
    start = time.perf_counter()
    print('Hello!')
    trends = main('https://trends.google.com/trends/trendingsearches/daily/rss')
    print(trends.to_string(index=False))
    print(time.perf_counter() - start)

Note the print(trends.to_string(index=False)) at the end, this could be whatever you like, either printing to CSV or using trends.groupby to redo your old formatting. The idea here is that the computation is done without printing anything. You get to format the data at the end however you like.


Getting all possible letter combinations of a word

I see some things that may help you improve your code.

Consider separating input and output

Right now, the unscramble function does both the permutation and the printing of both outputs and errors. A more modular (and likely more maintainable) approach would separate these into separate functions.

Return something useful from functions

Every single one of the routines is declared as returning void.  Something is wrong there.  For example, the unscramble routine could return the number of permutations or 0 on error.

Throw errors rather than printing error messages

The user of your code may be creating a GUI with no command line available and will not appreciate having your code printing instead of indicating an error to the calling code.  The two ways that C++ programs generally signal an error are either by throwing an exception (if the circumstance really is exceptional) or by returning a value that indicates an error.

Eliminate global variables

Eliminating global variables allows your code to be more readable and maintainable, both of which are important characteristics of well-written code.  Global variables introduce messy linkages that are difficult to spot and error prone.  Either the file name or better, a std::ostream reference, should be passed rather than having the filename be a global variable.  Better still, have subroutines simply operate by passing a string in or out and collect the I/O elsewhere.

Use standard algorithms

You might want to use std::next_permutation to accomplish this.  It would make the code much simpler, and you're already including the required header.


Parse sequence of characters detecting formatting categories

It looks like you're trying to extract information from a string. This is most often done through regexes as they are often faster than your own code while being less complex.
Because as of writing, you have no clear description of your goal, I'm inferring these assumptions from your code:

You want to split every sequence of characters in your string in one of the categories bold, italic and normal, determined by the characters being enclosed in 2, 1 or 0 asterisks.
You want to preserve the order of the original string.

If we disallow asterisks in the normal text, a regex for this is rather simple. I recommend exploring what it does on regex101.
\*\*(?P<bold>.+?)\*\*|\*(?P<italic>.+?)\*|(?P<normal>[^*]+)

Notably, the | character matches on the first match it finds, from left to right, meaning that a match will always try to match bold, then italic, then normal.
In Python, we can iterate over all the matches using re.finditer. For every match, lastgroup will return the name of the captured group, so we can use that in our print statement and also use it to get the actual match that we're interested in.
def fun(text=None):
    if text:
        for match in re.finditer(r'\*\*(?P<bold>.+?)\*\*|'  # match bold lazily
                                 r'\*(?P<italic>.+?)\*|'  # match italics lazily
                                 r'(?P<normal>[^*]+)',  # match normal greedily
                                 text):
            print(f'{match.lastgroup.upper()}: {match.group(match.lastgroup)}')

It should be noted that if the function is called plenty of times and performance is of concern, you should compile the regex once before using it in fun.
The regex used in this example is very primitive because you haven't specified your constraints or even what the function is meant to do. By specifying your question better and explaining how edge cases like ** a ** *** and **ab*cd** should behave, a more complete answer can be given.
Everything below this is in response to your 'philosophical question':

The regex answer [...] has worse performance.

I did some testing using timeit on the original string (multiplied in size anywhere between 0-3000 times) on differing number of runs and found that the regex approach is consistently 1.5 times faster than the original solution as long as the print statements are included.
Because printing it is unlikely to be your actual use-case, I modified both functions to return a tuple of all bold, italic and normal matches. I was surprised to find that your code is generally twice as fast.

The proposed solution is still much harder to understand (if it were not for the comments).

The comments are exactly what make the regex a relatively readable solution compared to yours. By commenting what the individual parts do, someone that needs to use the code can quickly see what the code achieves. The cost is that it may require more time to figure out how the code works.
Note that this extra cost also diminishes as you get more experience. For some, figuring out how your code achieves its goal is more difficult than understanding the regex. Regexes are very powerful, quite popular, and are used in many languages. This means that when one encounters a regex construct they know what to look for and how to read it. Your solution, meanwhile, is based on a few implicit assumptions like "every other string from the split is the thing we want to match". Someone that reads your code has to discover these assumptions because they're not explicitly written down.

The proposed solution is still much harder to [...] debug.

If nothing else, it's easy to pinpoint where the issue if there is one: in the regex. Given the input, it shouldn't be hard to figure out why the regex is failing if you inspect it using a tool like regex101. It may be difficult to correct the regex, but at least you won't have a scavenger hunt for where your bug is.

Should I just ignore cyclomatic complexity hints in the future?

Avoiding a high cyclomatic complexity mostly comes down to avoiding nesting a little more. This ensures that you have a more linear (and therefore more comprehensible) flow to your code.
The algorithm you used requires quite a bit of nesting which is not readily avoidable. You can, however, make some improvements by using the if as a guard. Using list comprehension, you can also eliminate the final for-if-else loop.
def fun_unnested_order(text=None):
    if not text:
        return None

    res = []
    bold_splits = text.split('**')  # Odd entries are bold, even entries are italicized or normal.
    for i, s in enumerate(bold_splits):
        if i % 2 == 1:  # Store bold
            res.append((s, 'bold'))
        else:
            italic_splits = s.split('*')  # Odd entries are italicized, rest normal.
            # Replace the for-if-else loop with list comprehension
            res += [(e, 'italic') if i % 2 == 1 else (e, 'normal')
                    for i, e in enumerate(italic_splits)]
    return res

This example is 30% slower than your original code using the same timeit setup.

So is it the better code?

It depends on your viewpoint. If performance is of concern, you should go for greybeard's answer as it is around 30% faster than your original code.
If readability is of concern, I would take the regex version any day of the week. While many may consider regexes black magic, it is widely applicable to many problems in most if not all popular languages. Most crucially perhaps, the regex solution doesn't require a complex algorithm, which means it's easier to develop and less error-prone.
Again, in terms of readability, it's about the familiarity of the programmer. If you are unfamiliar with regexes, list comprehensions and/or list slicing, your original version is the option to go for.
In the end, there is no one implementation that wins across all categories. You should familiarize yourself with the different ways to approach the problem and then tackle it in a way you deem the best solution.


Check if a string is palindrome or two strings are the opposite of each other

Of course there are possible improvements. First, if you can already use C++17 std::string_view, use that for greater flexibility, specifically decoupling from how the strings are stored.

Next, minimize the number of variables involved. Take special notice that string::data() and string::size() are often a bit more involved than a simple field-access due to SSO.

I also changed the argument-names to a and b because there isn't really any difference between them which would justify a specific order.

constexpr bool opposite(std::string_view a, std::string_view b) noexcept {
    auto size = a.size();
    if(size != b.size())
        return false;
    for(auto pa = end(a), pb = begin(b); size; --size)
        if(*--pa != *pb++)
            return false;
    return true;
}

Or using standard <algorithm>s and reverse-iterators:

    return std::equal(begin(a), end(a), rbegin(b), rend(b)); // C++14
    return a.size() == b.size() && std::equal(begin(a), end(a), rbegin(b));

Apply the same to palindrome(), but also take note that if you tested the first half against the last half, there's no need to thereafter test the remainders each against each other. That would just duplicate the work.  Incidentally, that eliminates the int-variable, which might have been too small.

constexpr bool palindrome(std::string_view s) noexcept {
    for(auto left = begin(s), right = end(s); left < right;)
        if(*left++ != *--right)
            return false;
    return true;
}


Nicer way to check if string contains all words from an array

You could use something like this:

$string = 'Hello, people at Stackoverflow';
$array = array('Hello', 'People');
$i = count(array_intersect($array, explode(" ", preg_replace("/[^A-Za-z0-9' -]/", "", $string))));
echo ($i) ? "found ($i)" : "not found";

Outputs:

  found (1)

(array_intersect is case sensitive)

Or if you'd like to make it a function, then you could do something like this:

function contains($needles, $haystack) {
    return count(array_intersect($needles, explode(" ", preg_replace("/[^A-Za-z0-9' -]/", "", $haystack))));
}

$string = 'Hello, people at Stackoverflow';
$array = array('Hello', 'People');
$i = contains($array, $string);
echo ($i) ? "found ($i)" : "not found";


The main issue with your function is that it can't correctly search for null or undefined.

findDeep(['foo', 'bar', 'bam'], i => i === null); // (1)
findDeep(['foo', 'bar', null], i => i === null);  // (2)
findDeep(['foo', , 'bam'], i => i === undefined); // (3)

(1) and (2) both return null and (3) returns undefined even though there is no such value.

I would rather make the function return an object, similar to ES2015
generators.
Separate index argument is excessive if you are
ok with mutating keys.
I would rename test to
pred for
"predicate"
and item to value to take advantage of ES2015's shorthand properties.
let is the new var.

function findDeep(dict, pred, keys = Object.keys(dict)) {
    if (keys.length === 0) {
        return { match: false };
    }

    let value = dict[keys.pop()];

    if (pred(value)) {
        return { match: true, value };
    }

    if (value !== null && typeof item === 'object') {
        let result = findDeep(value, pred);

        if (result.match) {
            return result;
        }
    }

    return findDeep(dict, pred, keys);
}

Last, please keep the coding style consistent: note the space (or no space) after if and the indentation.


Complexity
One method for determining how complex your code is, is called cyclomatic complexity. You basically count the number of branches in the code to determine its complexity. I count about 10 in the above code snippet. A cyclomatic complexity of 10 is often considered the maximum you should have in good readable code. (This is of course subjective.) By that standard, this code is fine. I do think the code could be made more clear, though.
Infinite Loops
I generally hate infinite loops in code unless it's some top-level thing like an event loop that realistically should never stop. The infinite loop you've created is not one of those cases. It has a very clear criteria for stopping. When the value is either greater than the greatest value along this path, or less than the minimum value along this path, or equal to any value along the path. Fixing that will make the code clearer, though I don't know if it will reduce the number of conditions to check. It might be worth breaking it out into a separate function. Something like this:
void whateverFunctionThisIs(AVLTree* avlt)
{
    //...
    if (avlt->root == NULL) {
        new = &(avlt->root);
        parent = NULL;
    }
    else
    {
        new = findPositionInTree(avlt->root);
    }

    if (new == NULL) {
        return;
    }
    // ...
}

That immediately reduces the complexity of that function from 10 to 3. Now we can rewrite the loop in its own function like this:
AVLNode* findPositionInTree(AVLNode* parent)
{
    struct AVLNode* new = NULL;

    int found = 0;
    do {
        if (parent->value > value)
        {
            if (parent->left)
            {
                parent = parent->left;
            }
            else
            {
                new = &(parent->left);
                found = 1;
            }
        }
        else if (parent->value < value)
        {
            if (parent->right)
            {
                parent = parent->right;
            }
            else
            {
                new = &(parent->right);
                found = 1;
            }
        }
        else
        {
            found = 1;
        }
    } while (!found);

    return new;
}

Even though we have the same number of if statements, it seems clearer to me without the break and return statements. And this function only has a cyclomatic complexity of 8.
Reducing ifs
You could reduce the number of if statements if you don't actually need to use parent after the loop ends by inverting the sense of the inner-most ifs. For example, instead of:
if (parent->right)
{
    parent = parent->right;
}
else
{
    new = &(parent->right);
    found = 1;
}

you could do this:
if (parent->right != NULL)
{
    new = &(parent->right);
    found = 1;
}
parent = parent->right;

At this point parent is NULL so you can't use it for anything in the future, so I really don't like that idea. But it does eliminate 2 if statements thereby reducing your complexity. (If you're using the infinite loop, then the found = 1; becomes just a break and parent is no longer NULL. But that feels gross to me.)


Sorting 10,000 unique randomly-generated numbers

Apart from the compiler errors, implementation issues and code style suggestions others have pointed out, your shuffling algorithm is fundamentally flawed.

Wikipedia explains it nicely:

  Similarly, always selecting i from the entire range of valid array
  indices on every iteration also produces a result which is biased,
  albeit less obviously so. This can be seen from the fact that doing so
  yields nn distinct possible sequences of swaps, whereas there are only
  n! possible permutations of an n-element array. Since nn can never be
  evenly divisible by n! when n > 2 (as the latter is divisible by n−1,
  which shares no prime factors with n), some permutations must be
  produced by more of the nn sequences of swaps than others. As a
  concrete example of this bias, observe the distribution of possible
  outcomes of shuffling a three-element array [1, 2, 3]. There are 6
  possible permutations of this array (3! = 6), but the algorithm
  produces 27 possible shuffles (33 = 27). In this case, [1, 2, 3], [3,
  1, 2], and [3, 2, 1] each result from 4 of the 27 shuffles, while each
  of the remaining 3 permutations occurs in 5 of the 27 shuffles.

To demonstrate this bias, I changed your code to only create three elements per array and ran it sixty million times. Here are the results:

Permutation    Occurences
[1, 2, 3]:     8884128
[2, 3, 1]:     11111352
[3, 1, 2]:     8895318
[3, 2, 1]:     8891062
[2, 1, 3]:     11107744
[1, 3, 2]:     11110396

If your shuffling algorithm were correct, one would expect a relatively uniform distribution. However, the standard deviation is huge at about 1215764 (or ~2%) which should ring alarm bells. For comparison, here are the results of using the proven Fisher–Yates shuffle:

Permutation    Occurences
[1, 2, 3]:     10000566
[2, 3, 1]:     9998971
[3, 1, 2]:     10000640
[3, 2, 1]:     10000873
[2, 1, 3]:     9998249
[1, 3, 2]:     10000701

As one would expect from a correct implementation, the standard deviation is low at about 1105 (or ~0.002%).

Here's the correct implementation for reference:

for (int i = numbers.length - 1; i > 0; i--)
{
    int swapIndex = random.nextInt(i + 1);
    int temp = numbers[i];
    numbers[i] = numbers[swapIndex];
    numbers[swapIndex] = temp;
}

However, another problem presents itself even with a correct shuffling algorithm:

A pseudo-random number generator is limited by its period, i.e. it can only produce a certain number of unique shuffles:

  [...] a shuffle driven by such a generator cannot possibly produce more distinct permutations than the generator has distinct possible states.

java.util.Random has a period no larger than 248 which is unable to produce an overwhelming majority of the 10000! (approximately 2.85 × 1035659) possible permutations of your array. The default implementation of SecureRandom isn't much better at no more than 2160.

In the case of such a long array, the Mersenne Twister is a more adequate choice with a period of 219937-1 and excellently uniform distribution (although still not enough to produce all the possible permutations. At some point, it makes more sense to look into true random number generators that are based on physical phenomena).

So, in my opinion, the real moral of the story is this:

  Take special care when working with randomness or pseudorandomness as the consequences of tiny mistakes can be hard to detect but devastating. Use Collections.shuffle instead of reinventing the wheel. For your (presumably) casual use, you might not need to worry about these inadequacies at all. On the other hand, it doesn't hurt to be aware of them.


Your code does work but there are indeed better ways of doing this.

Some details could be improved in your current function:

You could replace which(!(1:max_id %in% x$id)) with setdiff(seq(min_id, max_id), x$id). It's more legible, and, more importantly, it does not rely on the fact that your IDs are the n first integers. (Consider for instance which(!(2:5 %in% c(2, 3, 5))): it does not return 4.)
start is assigned to 0 but is never modified, so you could get rid of this local variable.

But the main point is that growing a dataframe in a loop is generally not a good idea, as most of the time you can find better options. Here are two possible solutions:

1) With base R

y <- data.frame(id = seq(min(x$id), max(x$id)))
x <- merge(y, x, all.x = TRUE)
x$value[is.na(x$value)] <- fill_value

2) With tidyr

library(tidyr)

complete(x, id = seq(min(id), max(id)), fill = list(value = fill_value))


Appears you are storing cleartext passwords and doing a 1:1 comparison.  This is bad.

You can clean the code up by doing the following and executing 1 query to MySQL:

require_once('mysqli.php');
// successful login variables
$q = $dbc -> prepare("SELECT email,dbClearTextPassword,accountActive FROM accounts WHERE email = ?");
$q -> bind_param('s', ($_POST['email']));
$q -> execute();
$q -> store_result();

// check to see if you returned any information from your query
if ($q->num_rows == 0) {
  // email doesn't exist in db .. #fail
  exit;
}

if ($q['accountActive'] != '1') {
  // email account is not active .. #fail
  exit;
}

// check the password matches
if ($_POST['clearTextPassword'] == $q['dbClearTextPassword']) {
  // do some of your fancy code to process the successful login
} else {
  // do some other fancy code to process a login failure
}

$dbc->close();


You could compress the code as follows. It doesn't check for early exit conditions, but since it's running on the front-end anyway, i.e. not at high volumes, the performance won't be noticeably degraded.

function chipStack(n){
    var chipValues = [1000,500,300,100,50];
    var stack = [];
    chipValues.forEach(function(e,i){
        stack.push(Math.floor(n / e));
        n -= (stack[stack.length-1] * e);
    })
    return stack;
}


Show first n elements of array, and count elements not shown

<?  if ($count = $this->likes->count()) {

It is more common to use the long form of the opening tag.  The second tag is only optionally supported by PHP installations.  Also, it can suddenly stop working if your host adjusts the configuration (possibly accidentally during an upgrade).

<?php
    if ($count = $this->likes->count()) {

It's also more common to put the code on a new line after the opening tag.  Unless you're opening and closing the PHP block on the same line.

If you're interested, there is a PHP Coding Standard.  Personally I don't always follow it, but I find it a good way to make decisions on issues that aren't important to me.  It also makes your code more portable.

            if ($r >= $visible) { break; };

I'd break this up into multiple lines for readability.

            if ($r >= $visible) {
                break;
            }

The final semi-colon is unnecessary there.  It doesn't harm anything (perhaps a wasted clock cycle on the null instruction), but neither does it contribute anything.

        if ($count > $visible) {

I might write this as

        if ( $hidden > 0 ) {

The reason being that you then go on to output $hidden.  You also might consider moving the definition of $hidden to be directly before this if statement.  That puts all the code related to $hidden together and makes it easier to follow the logic.

Alternately, you could stay with the original if and replace $hidden with $count - $visibility.  Then you don't need to define $hidden at all.


PHP MYSQL loop to check if LicenseID Values are contained in mysql DB

First of all: both code and table design can (have?) to be improved:

Tables must be normalized and can be improved by removing data and duplicates

Users table can (?) have username only as natural PK (pure id eliminated)
Optional: licence table will be better understandable if FK will have same name as for Users table (username)

For-cycle for your task is not-so-good style of coding:

You can just test result (size of array) of SELECT idLicense WHERE idLicense = $licenseID (SQLGuru: Fixme!!!)
Total amount of licences per user can be extracted from table with single SELECT COUNT(idLicense) WHERE idUser = '$username' (SQLGuru: Fixme again!!!)


Small improved std::list to manage doubloons and pointers

I see no reason to have this be an entirely new data structure that inherits from std::list<T>. All of the new member functions you've defined are really just wrapper functions that could just be delegated to std::list<T> functions or functions that could be implemented as regular procedural functions.

For example, the contains() and at() and insertItem() (which should really just be named insertItemBefore()) functions could simply be:

namespace list_util {

template <class T>
bool contains(const std::list<T>& l, const T& elem)
{
    return std::find(l.begin(), l.end(), elem) != l.end();
}

template <class T>
T& at(const std::list<T>& l, std::size_t index)
{
    assert(index < l.size());
    auto begin = l.begin();
    std::advance(begin, index);
    return *begin;
}

template <class T>
bool insertItemBefore(std::list<T>& l, const T& ref_item, const T& elem)
{
    auto itemItr = std::find(l.begin(), l.end(), ref_item);

    // if we found the item, itemItr != l.end()
    if (itemItr != l.end()) {
        l.insert(itemItr, elem);
        return true;
    }
    return false;
}

}

You'd have to #include<algorithm> and #include<iterator> for this to work. Notice that the index parameter is now std::size_t to avoid having to check for negative indexes. They could then simply be called as: list_util::contains(the_list, elem); and list_util::at(the_list, the_index);.

Moreover, containsDoubloons() could be implemented using std::find() and destroyContents() is really just a call to std::list<T>::clear():

namespace list_util {

template<class T>
bool containsDoubloons(const std::list<T>& l)
{
    for (auto it = l.begin(); it != l.end(); ++it) {
        const auto beginItr = std::next(it);
        if (beginItr != l.end() &&
            std::find(beginItr, l.end(), *it) != l.end()) {
            return true;
        }
    }
    return false;
}

template<class T>
void destroyContents(std::list<T>& l)
{
    l.clear();
}

}

Moreover, since the new functions we've written are completely generic and use the STL iterators for all operations, there's no reason to limit them only to std::list<T>. We could allow any container of containing T to be a parameter. An example is the contains() function:

template < template <class> class C, class T>
bool contains(const C<T>& cont, const T& elem)
{
    return std::find(cont.begin(), cont.end(), elem) != cont.end();
}


Bad practice to have try / catch in constructor?

Catching an exception and just printing stack trace and proceeding like nothing happened is certainly Very Bad. What if no one is watching the standard error stream (where e.printStackTrace() dumps its output)? In your case, you'll probably end up with NullPointerException later on, since newManager is not set. It could be one second from now, or one year from now, depending on when someone is trying to use newManager. You want to fail fast instead.

There's nothing wrong in throwing exceptions from constructors. Just make sure that, wherever you catch it, you handle it appropriately.


Its a good or bad practice, execute some async code inside class constructor?

Constructors are always synchronous and should succeed to create an object immediately. If your async call doesn't block that and you don't care about the success of your async call, then it is not a bad practice to call the function without awaiting it, and immediately .catch and handle any possible rejections.
In general, if you don't need the return value of an async call and you don't want to wait for it to complete, you should not await it. But, you should still handle rejections with a .catch; even if you do nothing: something().catch(() => {})

in the situation where you need to execute async code that does not return anything, it is necessary to execute then and catch? what are the implications of executing async code without then and catch?

Having a then is unnecessary, and would only be useful if you wanted to do something when the Promise has resolved, but if the Promise can be rejected you must have a catch.
If you do not catch a rejected promise you will have an unhandledPromiseRejection which, if left unhandled, will crash your process in a future version of Node.js.
If you did care about the return value, or you want the caller to be able to handle rejections, you can make the constructor private and then add a static async factory function that uses the private constructor:
class MyClass {

  private constructor(
    someParameter,
    anotherParameter,
  ) {
    // No async calls here
  }

  static async create (
    someParameter,
    anotherParameter,
  ) {
    await something();
    return new MyClass(someParameter, anotherParameter);
  }

}

Then you would use MyClass.create(x,y) to instantiate it, instead of new MyClass(x,y).


Could you do it this way which would mean you're only traversing the array once?

var obj = {};

for (var i=0; i < arr.length - 1; i = i + 2) {
    obj[arr[i]] = arr[i+1];
}


I'm sure there are other ways to improve it but here are a few quick points:

Start from the end and work your way back, that way once you've found one palindrome you're done!
You only have to check half of the digits for equality.
We can shave off some time by avoiding Array.Copy / Array.Reverse

Something like this:

var limit = ?
for (int i = limit; i > 0; i--)
{
    number = i;
    string s = number.ToString();
    char[] charArray = s.ToCharArray();

    bool isEqual = true;
    int halfLength = charArray.Length / 2; // will skip the middle digit
    int max = charArray.Length - 1;
    for(int j = 0; j < halfLength; j++)
    {
        if(charArray [j] != charArray[max - j])
        {
            isEqual = false;
            break;
        }
    }

    if (isEqual)
    {
        palindrome = number;
        break; // stop evaluating here
    }
}


Solution to Max Range Sum challenge on CodeEval

Just for clarity, I'd split the code into a couple of methods. One to parse input, and one to find the best yield.

To tackle the latter first: Have a look at Enumerable#each_cons, and Enumerable#reduce (aka inject).

Given an array of gains/losses (values) and the length to examine (days), you can find the "best streak" like so:

values.each_cons(days).map { |streak| streak.reduce(&:+) }.max

In English: Take each consecutive "streak" of days values; map each of these streaks to its sum; take the maximum of these sums. As an example:

days = 3
values = [1, 2, -1, 3, 4]

streaks = values.each_cons(days).to_a              # => [ [1, 2, -1], [2, -1, 3], [-1, 3, 4] ]
sums = streaks.map { |streak| streak.reduce(&:+) } # => [2, 4, 6]
max = sums.max                                     # => 6

There are two other things to handle, to solve the task: Return zero if the best gain is actually a loss, or if there are not enough values to satisfy days.

In all, you might do something like:

def best_streak(days, values)
  return 0 if values.count < days
  gain = values.each_cons(days).map { |streak| streak.reduce(&:+) }.max
  gain > 0 ? gain : 0
end

As for parsing the input, your current code is ok, though I'd still handle it separately.

def parse_line(line)
  days, *values = line.strip.split(/[;\s]/)
  [days.to_i, values.map(&:to_i)]
end

This basically just splits the line in to its parts, treating the first number as the number of days, and the rest as the values.

To put it all together, you can do something like:

File.open(ARGV[0]).each do |line|
  days, values = parse_line(line)
  puts best_streak(days, values)
end

However, it seem that in the CodeEval context, input is passed on STDIN; not in a file. So really it should probably be:

STDIN.each_line do |line|
  days, values = parse_line(line)
  puts best_streak(days, values)
end

There may be a more efficient way to do all this, but this is probably the most readable.


If you already parse the date string using DateTime, then it's better to format using that resulting date object instead of parsing again with strtotime, for example:

$startDate = new DateTime($this->start_date);
$startPretty = $startDate->format('F Y');

If $current is true, then there's no need to parse $this->end_date.
You can move that to the else block instead:

if($current) // currently works at this job
{
    $endDate = new DateTime(); // current date/time
    $endPretty = 'Present';
}
else
{
    $endDate = new DateTime($this->end_date);
    $endPretty = $endDate->format('F Y');
}

These conditions don't do what you think they do:

if($diff->y = 0)
{
    // ...
}
elseif ($diff->y = 1)
{
    // ...
}

The = operator assigns. This is not a check for equality.
The result of an assignment is the assigned value.
So the above statements are actually evaluated like this:

if(0)  // always false, $diff->y was set to 0, no matter what it was before
{
    // ...
}
elseif (1)  // always true, $diff->y was set to 1, no matter what it was before
{
    // ...
}

That is, first $diff->y is set to 0, the expression evaluates to false,
then in the elseif, $diff->y is set to 1, the expression evaluates to true.
To see the problem, set start_date to 2 or more years before end_date.
The result will always be 1 year difference instead of 2, 3 or more.

What you really wanted is the equals operator == like this:

if($diff->y == 0)
{
    // ...
}
elseif ($diff->y == 1)
{
    // ...
}


Translating binary data from a file into a very large base-ten integer

byte[] bytes = Files.readAllBytes(outFile.toPath());

Reserving the fully needed space ensures not using extra space, and no reallocations.

    StringBuilder sb = new StringBuilder(bytes.length * 2);
    for (byte b : bytes) {
        sb.append(String.format("%02X", b));
    }
    BigInteger dataInt = new BigInteger(sb.toString(), 16);

Then however it would be faster to do:

    BigInteger dataInt = new BigInteger(1, bytes);

with the caveat, that this is a big endian interpretation. Reverting the bytes would be fast too however.

The actual algorithm unfortunately uses floating point, but that is your choice.
You could look at the sources of their implementation of toString(radix).

Also BigInteger has some interesting methods, like modPow or remainder.

Whether or not the loops can be optimized, pow multiplied by base, or the loop entirely eliminated. that is something interesting I leave upto you.


Upload Image From URL via PHP (In a safe way)

I'm trying to make a simple code to upload an image directly from a
url.

You mean download.

How I can make it more safe?

Is there any reason why you want to retain the original file name, after applying the basename function ? This should protect against basic path traversal attempts like ../../
but you could as well rename the file altogether. If you are storing a record in a database, using an ID would be a good choice + adding the file extension (but not allow any file extension - see below).
This would be better than taking a chance and figuring out the possible pitfalls with your function. You are not controlling the file name and trusting user input is where the danger lies.
Not to mention that there may some creative attempts involving Unicode characters or whatever. Easier said than done, but I can't guarantee your code is 100% safe at this point.
The biggest problem here is that someone could supply the URL of a webshell with a .php extension, that your script will happily download to the upload folder. If that folder is under your website root, an attacker may then be able to call http://example.com/upload/shell.php to and take over your server. It's something you can test easily.
Because that's what your script does, it will download anything upon request.
At a minimum, that upload folder should not be under the website root. So the problem is not just the file name but the extension, and where that upload folder resides.
Also, there is no guarantee that the filename will be unique. You seem to be handling the scenario in some way that we don't know about.


Well, in the first place I have a question as to why you would need this specific pattern of tokens; it seems for a very specific use case.

Secondly, you use a pretty consistent naming convention in your code (which is very good), but the shortened names and abbreviations make it difficult for a person to understand your code quickly (in my opinion).

Lastly, if you are  looking for less code and more speed with the same functionality, I can propose this:

import random
import secrets
import string

FRAGMENT_ALPHABET = string.ascii_letters + string.digits
FRAGMENT_SEPARATOR_OPTIONS = ('.', '-')
FRAGMENT_MIN_LENGTH = 30
FRAGMENT_MAX_LENGTH = 34

def _generate_fragment(length: int, prepend_separator: bool):
    prefix = ''
    if prepend_separator:
        prefix = secrets.choice(FRAGMENT_SEPARATOR_OPTIONS)

    s = ''.join(
        secrets.choice(FRAGMENT_ALPHABET)
        for _ in range(length))

    return prefix + s

def token(num_parts: int = 3):
    return ''.join(
        _generate_fragment(
            length=random.randint(FRAGMENT_MIN_LENGTH, FRAGMENT_MAX_LENGTH),
            prepend_separator=i > 0)          # only False for the first fragment
        for i in range(num_parts))

In this code:

In my opinion (opinions can be very subjective) the code is still readable, but has less functions and those have explicit long names, which helps users to understand it faster.
I also put some general parameters as uppercase module variables at the top of the file; this makes it easier to modify and (in my opinion) also easier to read/understand in the code.
The execution time is less. Comparing the two versions using timeit like this for both versions (with Ubuntu and Python3.6):

>>> timeit.timeit('token()', 'from __main__ import token', number=10000)

I get these results, showing my version as faster using about 8 % less time:

Version    Time      Time comparisson
yours      2.222258   100.0 %
mine       2.060732    92.7 %


I can add this property to class Zone, but I don't want that anybody
  could access it from outside.

Which 'access' do you have in mind? through JSON (send you a 'fake' direction for zone1,2) or through code?

Either way, I don't think that by not adding it to the Zone class you will improve the security of your solution?

How do you decide on which parser to use when you receive a json string? BTW, your second json string looks wrong to me (the last direction param)

  [{"Caption":"Tab1","IDs":[4,6],"Direction":"1"},{"Caption":"Tab2","IDs":[9]},"Direction":"3"]

Why do you need Zone1 and Zone2? They're identical so why not simply use Zone? Even your ZoneBaseParser creates Zone objects and has no notion of Zone1 or Zone2.

Maybe you have a predefined set of zones (up to 4) and you need an index. Add an index property, if that's the case.

Your question is interesting but, instead of implementing a solution to the current problem (which would involve reflection), I'd focus on rethinking the json format and the classes and remove the problem altogether.

Quick and easy:

[DataContract]
private class ZoneJson
{
     [DataMember]
     public int ZoneType { get; set; }//could use an enum instead of int
     [DataMember]
     public int ZoneIndex { get; set; }//if a zone index is needed
     [DataMember]
     public string Caption { get; set; }
     [DataMember]
     public IList<int> IDs { get; set; }
     [DataMember]
     public Direction Direction { get; set; }
}

Or, a more generic approach:

[DataContract]
private class ZoneJson
{
     [DataMember]
     public int ZoneType { get; set; }//could use an enum instead of int
     [DataMember]
     public int ZoneIndex { get; set; }//if a zone index is needed
     [DataMember]
     public string Caption { get; set; }
     [DataMember]
     public IList<int> IDs { get; set; }

     //a json string containing additional params
     //might be set for certain ZoneTypes and it's contents can vary, based on ZoneType
     [DataMember]
     public string JsonParams { get; set; }
}

Next, you can add a Zone3Params class to implement the storage for Zone3 params (direction):

[DataContract]
[KnownType(typeof(Direction))]
public class Zone3ParamsJson : ZoneParamsBase
{
    [DataMember]
    public Direction Direction { get; set; }
}

and parse any defined zone type like this:

public class ZoneParserBase : IZoneParser<Zone>
{
    public virtual IList<Zone> Parse(string json)
    {
        IList<Zone> zones = new List<Zone>();
        try
        {
            IList<ZoneJson> parsedZones = json.FromJSON<IList<ZoneJson>>();

            foreach (var parsedZone in parsedZones)
            {
                var zone = new Zone
                {
                    //don't forget the index and type
                    ZoneType = parsedZone.ZoneType,
                    Caption = parsedZone.Caption,
                    Contents = new List<Module>()
                };
                foreach (var id in parsedZone.IDs)
                {
                    var module = currentPage.CreateModule(id);
                    zone.Contents.Add(module);
                }
                //parseParams
                if(zone.ZoneType==3)
                {
                    var params = parsedZone.JsonParams.FromJSON<Zone3ParamsJson>();
                    zone.Params = params;//zone.Params would be something like ZoneParamsBase
                }
                zones.Add(zone);
            }

            return zones;
        }
        catch
        {
            return null;
        }
    }
}


You should use the functools.wraps function, it makes sure the docstring/name/etc gets passed through
Instead of "ajax not supported" shouldn't it be: "only ajax supported"?
Shouldn't you respond with a Status Code 400 or something if not using ajax when you should be
Why do you want to check this? What's the point of enforcing ajax calls, won't that just make testing harder?


Your code is valid. However note that

sizeof(list_int.element)

and

sizeof(list_chat.element)

return the size of a pointer, but it is not the de size of the type of elements into array. So, for instance, you need to write

sizeof(*list_int.element)


Why does it need to be this complicated? PHP has builtins for changing the seed of the random number generator, and for shuffling strings.

function shuffleString($input, $seed = 2000) {
    srand($seed); // set the random generator seed
    $shuffled = str_shuffle($input);
    srand(); // to ensure that the seed is reset
    return $shuffled;
}

This might be less efficient (I haven't benchmarked them) but it's simpler and more readable. Sometimes it's fun to reinvent the wheel, but there are usually shortcuts that can be taken.


You've got a security vulnerability here just waiting to be exploited based on the fact you use the same interface for "The human" and "The Filesystem".

All you need is for somebody to create a file with:

open my $fh, '>', 'path/*'

And that will get glob-expansion during traversal.

Which means you DON'T want to use glob at a level other than the user-facing function call for the sake of convenience.

The user facing function should probably use use Text::Glob::glob_to_regex so you can generate a "match rule" and re-use it for subsequent operations,
instead of relying on glob to return a list of files.

When the function calls itself, it should use opendir + readdir which is not subject to glob expansion.

Your code also assumes a lot about OS File Path semantics.

So for Filesystem manipulation, I would probably suggest lots of File::Spec or Path::Tiny, as they're far more battle tested against Path handling, and the later provides a few helper functions that will make tree traversal and iteration much more obvious. ( And importantly, much safer )

As for the Exporter call, this style is more recommended:

use Exporter 5.57 qw( import );

This simply creates the import sub on your package instead of fussing with @ISA and thus eliminates the need for Exporter to be part of your inheritance tree.

If you want to support versions of Exporter older that 5.57, this is equally effective and can be expected to work on a stock 5.6 perl:

use Exporter ();
*import = \&Exporter::import;

Example

The following code constructs a diabolical directory that will result in graph traversal happening not once, but several times.

#!/usr/bin/env perl
use strict;
use warnings;

## Creating an example "Evil" directory to traverse.

use Test::TempDir::Tiny qw( tempdir );
use Path::Tiny qw( path );

my $dir = tempdir();

# Problem directories
path( $dir, "evil/*" )->mkpath;
path( $dir, "evil/*/starfile" )->touch;
path( $dir, "evil/**" )->mkpath;
path( $dir, "evil/**/doublestarfile" )->touch;

# Normal Files
path( $dir, "evil/child/deep" )->mkpath;

path( $dir, "evil/child" )->mkpath;
path( $dir, "evil/child/a" )->touch;
path( $dir, "evil/child/b" )->touch;
path( $dir, "evil/child/deep/a" )->touch;
path( $dir, "evil/child/deep/b" )->touch;

## Evil directory now constructed, emulated simplified recursion
## using glob

our $DEPTH = 0;
our $PAD   = '';

sub list_files_recursively {
  my ( $path ) = @_;
  STDERR->print("${PAD}?: $path\n");
  local $DEPTH = $DEPTH + 1;
  local $PAD   = ' ' x $DEPTH;
  my @out;
  ###### DONT DO THIS ######
  for my $leaf ( glob $path ) {
  ###### DONT DO THIS ######
    if ( -d $leaf ) {
      STDERR->print("${PAD}d: $leaf\n");
      push @out, list_files_recursively( $leaf . '/*' );
    }
    else {
      STDERR->print("${PAD}f: $leaf\n");
      push @out, $leaf;
    }
  }
  return @out;
}

for my $entry ( list_files_recursively( "$dir/*" ) ) {
  print $entry . "\n";
}

print "Expected layout:\n";
system("find",$dir,"-type", "f" );

Executing this code will reveal list_files_recursively "visits" the same files multiple times.

Full output here omitted for brevity

The most important part is to note what happens when it tries to list the children of the directory called **

  d: /tmp/7LYkL6zdrB/test_pl/default_1/evil/**
  ?: /tmp/7LYkL6zdrB/test_pl/default_1/evil/**/*
   f: /tmp/7LYkL6zdrB/test_pl/default_1/evil/**/doublestarfile
   f: /tmp/7LYkL6zdrB/test_pl/default_1/evil/*/starfile
   f: /tmp/7LYkL6zdrB/test_pl/default_1/evil/child/a
   f: /tmp/7LYkL6zdrB/test_pl/default_1/evil/child/b
   d: /tmp/7LYkL6zdrB/test_pl/default_1/evil/child/deep

Yes, that's thinking "Hey, it looks like 'child/deep' is a child of **".

Which it really really isn't.

And there are probably plenty more glob rules that can be exploited here, * is just the most dangerous.

For instance, glob interprets spaces as token delimiters, so glob "a b"  -> 2 entries, not 1.


Checking that an entered date is before the current date

Just wanted to chime in:

Nobody mentioned this, but isValidDate() to determine whether 1 date is earlier than another date is frankly terrible. Call it isEarlierDate()
Where are the variables? Are those variables all defined outside of this function. That does not look good.
If there is one thing you learn today it is that this

if(day<=dayCurr)
    return true;
else
    return false;

should always be written as

return day<=dayCurr

As per @Heslacher, write out your variable names

This is my over-commented counter-proposal:

function isEarlierDate(){

  return year < currentYear || //Last year is in the past
         year == currentYear && month < currentMonth || //This year, earlier month is in the past
         year == currentYear && month == currentMonth && day < currentDay || //..
         false; //This is clearly not an earlier date
}


Don't parse it through string manipulation, use the XML libraries in the framework.  I'd recommend LINQ to XML.  Parse it and make your changes.

var xmlStr = @"<root>
<item>asdf</item>
<item>asdf</item>
<item>asdf</item>
</root>";

var doc = XDocument.Parse(xmlStr);         // parse from string
//var doc = XDocument.Load("arrays2.xml"); // or load from file
var items = doc.Descendants("item");       // find all item elements
var index = 1;
foreach (var item in items.ToList())  // ToList() required since we're modifying the document
{
    var name = "x" + index++;
    var nameAttr = new XAttribute("name", name);           // create the name attribute
    var value = (string)item;                              // read the value as a string
    var newNode = new XElement("string", nameAttr, value); // create the new element
    item.ReplaceWith(newNode);                             // replace the current one
}
//doc.Save("arrays2_formatted.xml"); // save the changes to the file


magic strings,
DB connection not closed,
DB errors not handled,
no prepared statements with safe query parameters,
injectable request and query parameters,
mix of UI and logic code,
no HTML encoding,
2 of the 3 comments are very redundant with the line they comment.


You have a fn which creates the internal object. Maybe call it something more precise, like Collection or MakeCollection. Since the argument to the fn will be an array or an NodeList, you can concisely assign each property of the argument to the instance with Object.assign, no need for manual iteration.

When possible, consider using dot notation instead of bracket notation - dot notation is shorter, easier to read, and works better with minifiers. See the eslint rule.

Right now, you're creating new methods for the instance every time the library is called. It would be more efficient to put them on the prototype instead, eg:

_o.fn.prototype.eq = function(num) {
  // ...

But since it's 2020, it would make sense to at least write with modern ES2015 syntax, and use a class:

class Collection {
  constructor() {
    // ...
  }
  eq(num) {
    // ...
  }

Using modern syntax often makes code more concise and easier to read, which means less surface area for bugs, as well as more methods available for use. If you need compatibility for obsolete 6+ year old browsers, use Babel to transpile it into ES5 syntax automatically for production (but keep your source code modern!).

In your eq method, something else that keeps code easy to read is when variables aren't reassigned unnecessarily. For example, if you see a variable created at line 5, and you see it used on line 25, if you aren't sure if you're reassigned it, you'll have to look closely to each line 6-24 to be absolutely certain of its value at 25. But even with that, I'm quite doubtful that the numeric verification in the eq provides any benefits - not even jQuery does such a thing. I think you may as well just return the num property on the instance. Worst-case, if the user provides an invalid argument, they'll get undefined in return, which is probably fine as-is.

eq(num) {
  return this[num];
}

Though, if you wanted to emulate jQuery, eq should return a new collection, including the wrapper, not the underlying element:

eq(num) {
  return new Collection(this[num]);
}

If you want the library to be similar to jQuery, something that would be helpful would be if it doesn't throw when the collection is empty. If the elms turn out to be empty, currently, you return null, which means that to be safe, a consumer of the library would often enough have to do something like:

const $elms = $('.foo');
if ($elms) {
  $elms.display('inline-block');
}

instead of unconditionally calling $('.foo').display('inline-block'), which looks much cleaner. The first method has the same issue, though if this is deliberate, that's fine.

Your first method is doing something markedly different from jQuery's - yours takes a selector and searches for a descendant matching the selector, while jQuery's doesn't (jQuery's just extracts the first element in the collection). For those already experienced with jQuery, this has good potential to cause confusion. To find a selector-matching descendant of the first element in the collection, consider renaming your method, maybe to something like firstDescendant.

In each of your class methods, rather than assigning to f_condition if it doesn't exist on the first line:

addClass(className, f_condition) {
  f_condition = f_condition || function() {
    return true;
  };

Consider using default arguments instead:

addClass(className, f_condition = () => true) {

An option to make your addClass, removeClass, toggleClass, and display loops less repetitive would be to have a helper function which iterates over all elements in the collection, and executes a callback if a test provided by a different callback is passed:

_iterate(test, callback) {
  for (let i = 0; i < this.length; i++) {
    if (test(this[i], i, this)) {
      callback(this[i]);
    }
  }
}
addClass(className, f_condition = () => true) {
  this._iterate(f_condition, elm => elm.classList.add(className));
  return this;
}

For the display method, argument overloading is a bit messy in Javascript. You can do it if you want, but I think the code's logic would be easier to follow and it would make more intuitive sense to consumers if an object with multiple optional properties was passed instead:

display({ newDisplay = 'block', test = () => true } = {}) {
  this._iterate(test, elm => elm.style.display = newDisplay)
  return this;
}

Another benefit to this is that you don't need to reassign anything.

Put it all together:

;(function() {
  window._o = function(selector) {
    if (!selector) {
      throw new Error("Cannot create Object from " + selector);
    }
    return new _o.Collection(
      selector instanceof HTMLElement
        ? [selector]
        : document.querySelectorAll(selector)
    );
  }
  _o.Collection = class Collection {
    constructor(elems) {
      Object.assign(this, elems);
      this.length = elems?.length || 0;
    }
    *[Symbol.iterator]() {
      for (let i = 0; i < this.length; i++) {
        yield this[i];
      }
    }
    eq(num) {
      return new Collection(this[num]);
    }
    first() {
      return new Collection(this[0]);
    }
    firstDescendant(selector) {
      // don't forget to check if elms[0] exists first:
      return new Collection(this[0]?.querySelector(selector));
    }

    _iterate(test, callback) {
      for (let i = 0; i < this.length; i++) {
        if (test(this[i], i, this)) {
          callback(this[i]);
        }
      }
    }
    /***/
    /* className features */
    addClass(className, f_condition = () => true) {
      this._iterate(f_condition, elm => elm.classList.add(className));
      return this;
    }
    removeClass(className, f_condition = () => true) {
      this._iterate(f_condition, elm => elm.classList.remove(className));
      return this;
    }
    toggleClass(className, f_condition = () => true) {
      this._iterate(f_condition, elm => elm.classList.toggle(className));
      return this;
    }

    /***/
    /* show - hide */
    display({ newDisplay = 'block', test = () => true } = {}) {
      this._iterate(test, elm => elm.style.display = newDisplay)
      return this;
    }
  };
})();
.demo {
  width: 50px;
  height: 50px;
  margin: 5px;
  background: orange;
}

.blue {
  background: #045acf;
}

  write a separate mini-library before the main code?

You can if you want a bit more experience figuring out how such a library would be made, but for anything you expect to maintain (or that others will maintain), I'd recommend using one of the common libraries that are already tried-and-tested and have thorough documentation, Q+A, and support (like jQuery). Otherwise, any reader of the code will first have to internalize your library before actually getting to any of the meat of what the main script does. It's a good amount of overhead without any real benefit. Not that you can't create helper functions (or an object of helper functions) for yourself, but it's not the best idea to reinvent the wheel with serious code.


LINQ queries to fetch first and last name

You can achieve this by using the group by clause to create an aggregated list constrained by Unique_Location_ID and Item_Type_Identifier. To make the query more readable, store the names in local variables using the let clause.

Dim name As String = (
    From row In (From r In db.ItemDetails Where r.Unique_Location_ID = locationID And r.Item_Type_Identifier = 1 Select r)
    Group row By row.Unique_Location_ID Into rows = Group
    Let firstName = (From row In rows Where row.Category_Attribute_Identifier = 2 Select CStr(row.Value)).FirstOrDefault()
    Let lastName = (From row In rows Where row.Category_Attribute_Identifier = 3 Select CStr(row.Value)).FirstOrDefault()
    Select String.Concat(firstName, " ", lastName).Trim()
).FirstOrDefault()

I also advice you to not use underscores in public members as suggested in the .net general naming conventions. So, if possible, rename the members to UniqueLocationID, ItemTypeIdentifier and CategoryAttributeIdentifier.


Casting calls with the same parent class

I'm not sure if there is enough context for me to fully understand the restrictions you are wporking with but I will try anyway... 25 years ago an elder university student half-jokingly taught me that the solution to any problem is always to "add another layer of indirection." In this case, split handleUpdate so that each message type has their own handler object and place the type specific request handling into those classes. Furthermore, separate each type specific response handler into their own class (to maintain single responsibility principle) and inject that dependency to each update handler.
I.e. move type specific handling to the module where the type is still known. The function of the instanceof-block you want to get rid of will now effectively be moved to the if-block in the handleUpdate method and you don't need to repeat it again in the response handling code.


I think you want to use transactions. Within a transaction, you can certainly do INSERT + INSERT + SELECT the UserInfoID + the final INSERT. Commit the transaction at the end, after all successful, rollback on any exception.

Rather than using the low level database APIs like managing Connection, PreparedStatement, ResultSet, yourself, I strongly recommend to use a framework for this, such as Spring's JDBC template or Apache's DbUtils. Once you step on that road life will get easier and you won't look back.


Generate a deck of cards in Clojure / Clojurescript

There are a few minor improvements you can make here that lead to a fairly elegant implementation.

First, using flatten is rarely a good idea, because rather than just dealing with the top-level structure of the thing you hand it, it reaches down into its inner structure, thus making it brittle when you change the representation of your data. Therefore, you should instead use apply concat in place of flatten in your code.

However, as @ChrisMurphy points out, the for macro already supports list products, so you can replace the usage of flatten or apply concat and the two usages of for with a single usage of for that produces a flat sequence.

Then, instead of writing out the full range of numbers from 1 to 13, you can use the range function to replace that vector with (range 1 (inc 13)) or something equivalent.

Finally, rather than manually deconstructing and reconstructing each map in your lambda that you pass to map-indexed, you can use the assoc function to simply add the :card-id mapping.

With these changes, you end up with a solution that looks like this:

(defn new-deck []
  (map-indexed
   #(assoc %2 :card-id (inc %1))
   (for [suit [:spade :heart :diamond :club]
         rank (range 1 (inc 13))]
     {:suit suit :rank rank})))


Your line

while again != 'no' or 'n'

is incorrect: again != 'no' or 'n' is evaluated to (again != 'no') or 'n' which is True as 'n' evaluates to True in any case.
You have to use again != 'no' and again != 'n' here
    or again not in ['no', 'n'].

Anyway, I replaced it with while True and added a break statement. This allows to exit from the loop exactly when we need it. (Otherwise we get unnecessary message that our answer is not correct.) Also your again variable never changed, so your loop in any case is infinite.

I also did several improvements that you can see in the code, and updated the spelling to match the NATO phonetic spellings.

import random

phonetic = {'a': 'alfa', 'b': 'bravo', 'c': 'charlie', 'd' : 'delta',
            'e': 'echo', 'f': 'foxtrot', 'g': 'golf', 'h': 'hotel',
            'i': 'india', 'j': 'juliett', 'k': 'kilo',
            'l': 'lima', 'm': 'mike', 'n': 'november', 'o': 'oscar',
            'p': 'papa', 'q': 'quebec', 'r': 'romeo',
            's': 'sierra', 't': 'tango', 'u': 'uniform', 'v': 'victor',
            'w' : 'whiskey', 'x': 'x-ray', 'y': 'yankee', 'z': 'zulu'}
# made this a bit more pep8-compliant

print("Welcome to the IkeaFish Phonetic Trainer.\nAnswer 'no' or 'stop' to stop the program.")
# n can be valid answer, so it is not good to use it a stop-word

while True:

    letter, word = random.choice(list(phonetic.items()))
    # we can pick both elements at once

    if random.choice([True, False]):
        answer = input('What does this letter {} stand for: '.format(letter))
        correct = word
    else:
        answer = input('What does this word {} stand for: '.format(word))
        correct = letter

    answer = answer.lower()
    # make answers case-insensetive

    if answer in ['no', 'stop']:
        break

    if answer == correct:
        print('Correct')
    else:
        print('Wrong answer', letter, 'stands for', word)


Prefer typed constants over #defines:

NO_OF_BITS should be a const unsigned int or const size_t and should also be a private member of BitArray, since it is not used elsewhere.

Also, NO_OF_BITS is a bad name for the constant. Num of bits in what? Num of bits in an integer. So named it accordingly.

As it was already suggested, use CHAR_BIT from <climits>. Also, adding unsigned to the sizeof call doesn't really make a difference.

The ALL_UPPERCASE notation should be reserved for macros and macro constants, to differentiate those from actual C++ entities (the preprocessor is like a mini-language inside C++ that doesn't live by the same rules). PascalCase or even camelCase are more modern notations for typed constants.

Summing up, it could look something like this:

    class BitArray {
    private:
        static const unsigned int IntBits = CHAR_BIT * sizeof(int);
    ...
    };

Side note: constexpr would have been my choice over const if this was C++11.

Use unsigned types if a value should never be negative:

ssize_t is the "signed" variant of size_t. You are using ssize_t as the template parameter for the size of your bit array. The message you pass to readers of your code with this is that the size of a bit array could be negative. I don't think this would make any sense. Either use std::size_t or a plain unsigned int.

Make consistent use of const and bool:

BitArray<n>::test() does not modify the bit array, so it should be a const method. E.g.:

int test(unsigned int) const;
                       ^^^^^

The const will also go in the method definition.

Also, test() has no business returning an int. It is a true or false query, so it should return a bool.

You don't need memset to zero init an array:

C++ has always had the ability to zero initialize arrays in an object constructor. Most people are not aware of it an still use the verbose and error prone memset. Read the entry about zero initialization on cppreference. Also a related question on SO. You can rewrite your constructor like this:

template<ssize_t n>
BitArray<n>::BitArray()
    : array()
    // zero initialized
{ }

Don't use dynamic allocations where a static will do:

BitArray<10>* bs = new BitArray<10>();

Sure that code is just a usage sample, but still, there is no real need to dynamically allocate the object. The ability to declared objects by value is one of the nicest features of C++, so use it instead of a dynamic alloc when it makes sense.

// No need to 'new' it in this case.
BitArray<10> bs;

Pointers/dynamic memory are normally only used when you need to extend the lifetime of an object beyond its scope of declaration. This is not the case in your example.

Not to mention, of course, that the object in your sample code is never deleted and thus leaks memory.


As I said in the comments:

  For errors, that's harder to say. Use exceptions for validation errors, catch them in the CSV reading loop, so you can continue reading. You'll have to decide what state to leave the Product class in if you do a partial read. If you don't mind passing the constructor an array of this data, even an optional array, you could do all the setting there $this->{"set$key"}($value) etc. But the big advantage is throwing an exception before the constructor completes destroys the object. Because the constructor can't return the instance in that case

Something like this

class Product
{

    private $imageUrl = false;

    public function __construct(array $data = []){
          if(!empty($data)){
             foreach($data as $line=>$value){
                if(isset($this->{$key})){
                  $this->{"set$key()"}($value);
                }
             }
         }
    }

    public setImageUrl($image){
          if(empty($image)) throw new InvalidArgumentException("Image is empty");
           $this->imageUrl= $image;

    }
}

There are a few tricks here, but you have to set the default to false for if(isset($this->{$key})) to work, but it's faster then property_exists.  This part will dynamically call setimageUrl in this case. The lowercase i doesn't matter much in setImageUrl as user defined methods/function are case insensitive.

The other part I said is this:

  This is my Opinion, 1. CSVImport , unless you also need to do arrays, in which case make another method for reading the data from the file, but it should be part of the class. The class won't work well without the CSV data. You'd have to make changes to both if fields are added etc.. You can also remove a loop by importing where the foreach is and using the file reading loop instead. 2. Product setters, if you ever need to manually create a product, you want them to do the validation too. 3. Should be part of validation, bad data goes in set, good data comes from get

Most of that is pretty self explanatory.  For #3 the ->setImageUrl($this->websiteUrl.$imagePath); is part of the input data. So that is fine.  You don't want to have to pass them separately.  In fact with data loading in the constructor of the Product you can skip that method completely as it becomes:

 private function parseProductData($productData)
 {
     return new Product($productData);
 }

So that alone saves you a call to list and a call to parseProductData for each product.

I can give you more examples if you need them

I would do the CVSImport something like this (untested)

class CSVImport extends ProductImport
{
    private $websiteUrl;

    private $errors = [];

    public function __construct($websiteUrl)
    {
        $this->websiteUrl = $websiteUrl;
    }

    public function import($csvData)
    {
        $productCollection = new ProductCollection();
         //you could do file reading here with a while loop
        foreach ($csvData as $line=>$rowData) {
            try{
                $productCollection->addProduct(new Product($rowData));
            }catch(Exception $e){
                $this->errors[$line] = get_class($e)."::{$e->getCode()} {$e->getMessage()} in {$e->getFile()} on {$e->getLine()}";
            }

        }

        return $productCollection;
    }

    //or for max flexabillity you can do it here
    public function readCsv($filename){
        if(!file_exists($filename)) throw new Exception("Could not find file $filename".);//etc.

        $f = fopen($filename, 'r');

        $header = fgetcsv($f); //get header row
        $len = count($header);

        $line = 0;
        $rowData= [];
        while(!feof($f)){
            ++$line;

            try{
                $current = fgetcsv($f);

                if(count($current) != $len) throw new Exception("Delimter count missmatch on line $line of $filname");

                $rowData[$line] = array_combine($header, $current); //combine [$haders => $current]
            }catch(Exception $e){
                $this->errors[$line] = get_class($e)."::{$e->getCode()} {$e->getMessage()} in {$e->getFile()} on {$e->getLine()}";
            }
        }

        return $rowData;
    }

    public function getErrors(){
        return $this->errors;
    }

    public function hasErrors(){
         return count($this->errors)
    }

}

So you see the try/catch is almost the same, you could combine these two methods readCsv and import. But then you cannot accept array as data only the file. That's up to you.

The basics are that you can do new Product($data) and it does all the setting of the data using it's set methods.  Then if you throw exceptions in those set methods it not only helps you when using them manually, but when constructing a product from the CSV, the product dies as the exception is thrown. Then we catch that, keep track of it, and move on to the next row.  Each part handling it's own concerns.

In any case now it's all nice and clean, the other option would be to make a class just for reading CSV data, that takes headers as an argument, and does some mapping on them etc.  But its a lot easier to find then putting the CSV stuff in some random place.

Cheers.


Safely using android 'Context' inside threads

I think it's a bit of overhead.

Depending on what you need to do with the Context, you can the Application Context instead of the Activity itself. This context is available while the process runs, so there no leakage is possible.

In my experience, Activities being leaked have been caused by singletons initialized by passing the Activity instance (as a Context). Be careful also with Views, as they hold a reference to the Context.

Using the StrictMode with the setClassInstanceLimit and a bit of logging has helped me catch these leaks quite fast.


No optimisation so far but a few comments to make your code easier to read/improve :

1 Don't do "using namespace std;"

2 Give your variables meaningful names.

3 Declare your variables in the smallest possible scope. Also, you should declare and define in the same times when it's possible. That would make things much easier (such as int res = nChoosek(r,re); instead of res*=nChoosek(r,re);).

4 Be consistent. You use for(i=0;i<re;i++) {foo;} and then, a few lines later i=0; while((r-re-i) > 1){foo; i++;}. Using another for loop would have have been a better option : for (i=0; i<r-re-1; i++) {foo;}

5 Enable the warnings in your compiler. A few weird things such as the useless statement in for(i-0;i<n;i++) should be detected.

6 Add a comment about the algorithm you've used.

Once this is done, we'll be in better conditions to start thinking about optimisations.


Finding the Bayesian estimates for the top 100 products on NutraPlanet

I just put this together, so I haven't tested it or anything, there might be bugs and someone else PLEASE come along and improve upon it, but I think this might be a good starting point to answering this question:

OOP version of OP's code:

$ReviewPrinter = new ReviewPrinter("http://www.nutraplanet.com/top_100", 2);
echo $ReviewPrinter->printReviews();

class ReviewPrinter{
    public $products;
    public $locations;
    public $reviewUrlFragments;
    public $minimumNumberOfVotesToSaveProduct;

    public function __construct($locations, $minimumNumberOfVotesToSaveProduct){
        if(empty($locations) || empty($minimumNumberOfVotesToSaveProduct)){
            return false;
        } else {
            $this->minimumNumberOfVotesToSaveProduct = $minimumNumberOfVotesToSaveProduct;
            $this->locations = array($locations);
            $this->setReviewUrlFragments();
            $this->products = $this->getProducts();
            $this->calculateBayesianEstimate();
            $this->sortProducts();
        }
    }

    public function sortProducts(){
        usort($this->products, function ($a, $b) {
            if ($a["bayesian_estimate"] == $b["bayesian_estimate"]) {
                return 0;
            }
            return (($a["bayesian_estimate"] < $b["bayesian_estimate"]) ? 1 : -1);
        });
    }

    public function setReviewUrlFragments(){
        $localReviewUrlFragments = array();

        foreach($this->locations as $location) {
            preg_match_all("%/product/(.*?)\.html%is", @file_get_contents($location), $matches);
            $localReviewUrlFragments = array_merge($localReviewUrlFragments, $matches[1]);
        }

        $this->reviewUrlFragments = array_unique($localReviewUrlFragments);
    }

    public function getProducts(){
        $functionScopeProducts = array();

        foreach($this->reviewUrlFragments as $productReviewUrlFragment) {
            $reviewUrl = "http://www.nutraplanet.com/manufacturer/" . $productReviewUrlFragment . "/reviews";

            preg_match_all("%&nbsp;(.*?)	%is", @file_get_contents($reviewUrl), $matches);

            $localProducts = array();
            $localProducts['name'] = "http://www.nutraplanet.com/product/".$productReviewUrlFragment.".html";

            $votes = $this->getVotes($matches[1]);

            $localProducts["vote_distribution"] = $votes["votes"];
            $localProducts["review_average"] = $votes["average"];
            $localProducts["num_votes"] = $votes["num_votes"];

            // Only add if there is a vote for the product
            if ($localProducts["num_votes"] >= $this->minimumNumberOfVotesToSaveProduct) {
                $functionScopeProducts[] = $localProducts;
            }
        }

        return $functionScopeProducts;
    }

    public function getVotes($match){
        $votes = array();
        $sum_votes = 0;
        $total_votes = 0;
        $vote_star = 1;

        // In ascending order, 1-star to 5
        foreach($match as $vote_count) {
            $votes[] = $vote_count;
            $total_votes += $vote_count;
            $sum_votes += ($vote_count * $vote_star++);
        }

        $product["votes"] = $votes;
        $product["average"] = ($total_votes < 1) ? 0 : ($sum_votes / $total_votes);
        $product["num_votes"] = $total_votes;

        return $product;
    }

    public function calculateBayesianEstimate(){
        /**
         * Algorithm used:  (WR) = (v ÷ (v+m)) × R + (m ÷ (v+m)) × C
         * where:
         * WR = Weighted rating
         * R  = Average rating
         * v  = Number of votes
         * m  = Minimum votes required
         * C  = Mean vote across the whole report
         */
        $m = $this->getMinNumberOfVotes();
        $C = $this->getAverageReviewAverage();

        for ($i = 0, $len = count(&$this->products); $i < $len; $i++) {
            $R = &$this->products[$i]["review_average"];
            $v = &$this->products[$i]["num_votes"];
            &$this->products[$i]["bayesian_estimate"] = (($v / ($v+$m)) * $R) + (($m / ($v+$m)) * $C);
        }
    }

    public function getAverageReviewAverage(){
        $total = 0;

        foreach($this->products as $product) {
            $total += $product["review_average"];
        }

        return $total / count($this->products);
    }

    public function getMinNumberOfVotes(){
        # NOTE: Where is $minVote set or created?
        foreach($this->products as $product) {
            if (!isset($minVote) || ($product["num_votes"] < $minVote)) {
                $minVote = $product["num_votes"];
            }
        }

        if (!isset($minVote)) {
            $minVote = 0;
        }

        return $minVote;
    }

    public function printReviews(){
        $output = "
";
        foreach($this->products as $product) {
            $product["vote_distribution"] = implode("	", $product["vote_distribution"]);
            $product = implode("	", $product);
            $output .= "
" . $product . "
";
        }
        $output .= "
";

        return $output;
    }
}

Obviously, there should be separation of concerns, which this does not implement, etc.

++++
EDIT
++++

Implemented comments

// Usage:
$ReviewPrinter = new ReviewPrinter("http://www.nutraplanet.com/top_100", 2);
echo $ReviewPrinter->printReviews();

class ReviewPrinter{
    private $products;
    private $locations;
    private $reviewUrlFragments;
    private $minimumNumberOfVotesToSaveProduct;

    public function __construct($locations, $minimumNumberOfVotesToSaveProduct){
        if(empty($locations) || empty($minimumNumberOfVotesToSaveProduct)){
            $c = 2 - (empty($locations) ? 1 : 0) - (empty($minimumNumberOfVotesToSaveProduct) ? 1 : 0);
            throw new Exception("Construct expects 2 parameters, $c given.");
        } else {
            $this->minimumNumberOfVotesToSaveProduct = $minimumNumberOfVotesToSaveProduct;
            $this->locations = array($locations);
            $this->setReviewUrlFragments();
            $this->products = $this->getProducts();
            $this->calculateBayesianEstimate();
            $this->sortProducts();
        }
    }

    private function sortProducts(){
        usort($this->products, function ($a, $b) {
            if ($a["bayesian_estimate"] == $b["bayesian_estimate"]) {
                return 0;
            }
            return (($a["bayesian_estimate"] < $b["bayesian_estimate"]) ? 1 : -1);
        });
    }

    private function setReviewUrlFragments(){
        $localReviewUrlFragments = array();

        foreach($this->locations as $location) {
            preg_match_all("%/product/(.*?)\.html%is", @file_get_contents($location), $matches);
            $localReviewUrlFragments = array_merge($localReviewUrlFragments, $matches[1]);
        }

        $this->reviewUrlFragments = array_unique($localReviewUrlFragments);
    }

    private function getProducts(){
        $functionScopeProducts = array();

        foreach($this->reviewUrlFragments as $productReviewUrlFragment) {
            $reviewUrl = "http://www.nutraplanet.com/manufacturer/" . $productReviewUrlFragment . "/reviews";

            preg_match_all("%&nbsp;(.*?)	%is", @file_get_contents($reviewUrl), $matches);

            $localProducts = array();
            $localProducts['name'] = "http://www.nutraplanet.com/product/".$productReviewUrlFragment.".html";

            $votes = $this->getVotes($matches[1]);

            $localProducts["vote_distribution"] = $votes["votes"];
            $localProducts["review_average"] = $votes["average"];
            $localProducts["num_votes"] = $votes["num_votes"];

            // Only add if there is a vote for the product
            if ($localProducts["num_votes"] >= $this->minimumNumberOfVotesToSaveProduct) {
                $functionScopeProducts[] = $localProducts;
            }
        }

        return $functionScopeProducts;
    }

    private function getVotes($match){
        $votes = array();
        $sum_votes = 0;
        $total_votes = 0;
        $vote_star = 1;

        // In ascending order, 1-star to 5
        foreach($match as $vote_count) {
            $votes[] = $vote_count;
            $total_votes += $vote_count;
            $sum_votes += ($vote_count * $vote_star++);
        }

        $product["votes"] = $votes;
        $product["average"] = ($total_votes < 1) ? 0 : ($sum_votes / $total_votes);
        $product["num_votes"] = $total_votes;

        return $product;
    }

    private function calculateBayesianEstimate(){
        /**
         * Algorithm used:  (WR) = (v ÷ (v+m)) × R + (m ÷ (v+m)) × C
         * where:
         * WR = Weighted rating
         * R  = Average rating
         * v  = Number of votes
         * m  = Minimum votes required
         * C  = Mean vote across the whole report
         */
        $m = $this->getMinNumberOfVotes();
        $C = $this->getAverageReviewAverage();

        for ($i = 0, $len = count(&$this->products); $i < $len; $i++) {
            $R = &$this->products[$i]["review_average"];
            $v = &$this->products[$i]["num_votes"];
            &$this->products[$i]["bayesian_estimate"] = (($v / ($v+$m)) * $R) + (($m / ($v+$m)) * $C);
        }
    }

    private function getAverageReviewAverage(){
        $total = 0;

        foreach($this->products as $product) {
            $total += $product["review_average"];
        }

        return $total / count($this->products);
    }

    private function getMinNumberOfVotes(){
        # NOTE: Where is $minVote set or created?
        foreach($this->products as $product) {
            if (!isset($minVote) || ($product["num_votes"] < $minVote)) {
                $minVote = $product["num_votes"];
            }
        }

        if (!isset($minVote)) {
            $minVote = 0;
        }

        return $minVote;
    }

    public function printReviews(){
        $output = "
";
        foreach($this->products as $product) {
            $product["vote_distribution"] = implode("	", $product["vote_distribution"]);
            $product = implode("	", $product);
            $output .= "
" . $product . "
";
        }
        $output .= "
";

        return $output;
    }
}


Triggerful Ruby Gem: create dynamic callbacks to methods

1) get rid of conditionals

I think your main problem here is the nested conditionals that litter your code. This increases complexity and tends to be less readable.

You can get rid of those conditionals using a method like this :

def make_callable(object)
  case object
  when Proc, Method then object
  when Trigger      then ->(*args){ object.trigger(*args) }
  else                   ->(*args){ public_send object, *args }
  end
end

so you can do things like :

@event = make_callable(event)
@callbacks = callbacks.map{ |c| make_callable c }

This way, all your callbacks will respond to call uniformly, so you won't need conditionals anymore.

2) use inheritance

As i see it, your @progression instance variable masks the need for two different behaviors, which means two different classes : a "silent" trigger, and a "verbose" one that extends the former.

class Trigger

  # factory method to instantiate the right type of callback.
  # I slightly changed the signature from the original #initialize
  # as I thought it would make more sense this way,
  # but it is possible to keep the original one with minor tweaks
  #
  def self.factory(verbose, event, *callbacks)
    verbose ? Verbose.new(event, *callbacks) : new(event, *callbacks)
  end

  def initialize(event, *callbacks)
    @event = make_callable(event)
    @callbacks = callbacks.map{ |c| make_callable c }
  end

  # SNIP : this class would also expose add_callback, remove_callback, etc.

  def trigger(*args)
    @callbacks.each{ |c| c.call(*args) }
  end

  private

  def make_callable(object)
    case object
    when Proc, Method then object
    when Trigger      then ->(*args){ object.trigger(*args) }
    else                   ->(*args){ public_send object, *args }
    end
  end
end

class Trigger::Verbose < Trigger
  def trigger(*args)
    event_data = @event.call(*args)
    super(*args, event_data)
  end
end

As you can see, this simplifies the logic a lot, and makes clear that we have two different behaviors, which is invaluable for consumers of your API.


This is a pretty straightforward and readable implementation, and I see how it can be used. Here are some suggestions:
Use Modern OpenGL
It looks like you're using OpenGL 1.x. That's really old OpenGL. You should be using OpenGL 3 or later, really. It's supported on all major platforms. It's not too difficult to learn if you already know OpenGL 1 and it offers a lot of benefits.
Keep Track of Your Texture Target
While a texture ID is certainly an important piece of information to keep around, it's not the only piece you need. Almost all texture-related functions in OpenGL require a texture target instead of or in addition to a texture ID. If you don't keep it around you'll either end up needing it and not having it, or being forced to always use one particular texture target, which is not ideal.
Naming
While your variable names are decent, they could be even better. For example, in both resizeBuffer() and imageToByteBuffer() you have an argument named size. What units is size in? Bytes? Pixels? Vertices? You should be more explicit with a name like numBytes or size_in_bytes, or whatever's appropriate.
Also the function name imageToByteBuffer() is confusing. From the name, it seems like it's going to read a file at a path and return a byte buffer containing the pixels from the image at that path. But the second half of the function looks like it does something else. I'm not familiar enough with the Java libraries to understand when file.isFile() would return false, and what else a file would be if not a file. (I assume since it's a URL it might be a network resource?) I would recommend making 2 functions - one for reading a local file and one for reading a remote file (or whatever the else path does), with appropriate names and call them from imageToByteBuffer. Something like this:
if (file.isFile())
{
    return imageFromLocalFile(path);
}
else
{
    return imageFromRemoteFile(path, size); // or whatever it should be called
}

Also, how does a caller know what to pass in for size? Isn't that something that is discovered by reading the file?


Calculate min/max values for (un)signed integral number of up to 64 bits

Your argument validation could be de-duplicated.

Here, take a look:

MinMaxI:
    if (_bits < 2 || _bits > 64)
    {
        throw new System.ArgumentOutOfRangeException("_bits", _bits,
         String.Format("2 <= _bits <= 64"));
    }

MinI:
    if (_bits < 2 || _bits > 64)
    {
        throw new System.ArgumentOutOfRangeException("_bits", _bits,
         String.Format("2 <= _bits <= 64"));
    }

MaxI:
    if (_bits < 2 || _bits > 64)
    {
        throw new System.ArgumentOutOfRangeException("_bits", _bits,
         String.Format("2 <= _bits <= 64"));
    }

MaxN:
    if (_bits < 1 || _bits > 64)
    {
        throw new System.ArgumentOutOfRangeException("_bits", _bits,
         String.Format("1 <= _bits <= 64"));
    }

They're practically the same!

I'd make a method like this (I'm not really familiar with C# syntax, so let me know if I made a mistake)

private static void validateBitsArgument(ulong _bits, ulong min, ulong max)
{
    if (_bits < min || _bits > max)
    {
        throw new System.ArgumentOutOfRangeException("_bits", _bits,
         String.Format("{0} <= _bits <= {1}", min, max));
    }
}

And then include it like this:

public class Bits
{
    public static void MinMaxI(ulong _bits, out long _min, out long _max)
    {
        validateBitsArgument(_bits, 2, 64);

        _min = ~(long)0 << (int)(_bits - 1);
        _max = -1 - _min;
    }

    public static long MinI(ulong _bits)
    {
        validateBitsArgument(_bits, 2, 64);

        return ~(long)0 << (int)(_bits - 1);
    }

    public static long MaxI(ulong _bits)
    {
        validateBitsArgument(_bits, 2, 64);

        return -1 - (~(long)0 << (int)(_bits - 1));
    }

    public static ulong MaxN(ulong _bits)
    {
        validateBitsArgument(_bits, 1, 64);

        return _bits == 64 ? ~(ulong)0 : ~(~(ulong)0 << (int)_bits);
    }

    private static void validateBitsArgument(ulong _bits, ulong min, ulong max)
    {
        if (_bits < min || _bits > max)
        {
            throw new System.ArgumentOutOfRangeException("_bits", _bits,
         String.Format("{0} <= _bits <= {1}", min, max));
        }
    }
}

And voila, shorter code.


Prefer value type semantic

Try to make classes default constructible and equality comparable whenever this makes sense. Currently your Optional class doesn't fulfil neither. The following code will not compile

class A { int a; A() = delete; };

int main()
{
  Optional<A> i;
}

Even though it might make sense to have an optional. Also consider this example

struct B { B() { /* insert something super long */ } }:

int main()
{
  Optional<B> opt_b; // this line takes really long!
}

Here is an example of how to use std::aligned_storage to use uninitialised memory. I think this could help you as well.

Do not return by value if you can

The line

T get() const { return val_; }

Makes a copy of T while returning val_. Imagine val_ is a very big std::string. This could be very expensive in code which calls get() multiple times. If you want read-only access, prefer to use

const T& get() const& noexcept { return val_; }

instead.

Make use of move assignments

Currently you have to copy values into your optional. But what, if you just want to move something big that you want to return from a function? You
need to add constructors for rvalue-Ts.

Optional(T&& value)
 : val_{std::move(value)}
 , is_set_{true} {}