Finding area and perimeter of rectangles and circles that are instance of interface region

In my point of view you cannot implement
area() and perimeter() any clearer or simpler.

In the toString() method I would somehow separate the values and also not print  with two times and length not at all.
Here is my suggestion:

 public String toString() {
       return "<" + with + " x "+ length + ", area:" + this.area() + " perimeter: "+ perimeter() + ">";
    }

In Rectangle[] selectRectangle(Region[] region) I would use an ArrayList to avoid the loop to count the number of Rectangles.

public static Rectangle[] selectRectangle(Region[] region) {
    ArrayList<Rectangle> result = new ArrayList<>();
    final int lastIndex = region.length;
    for (int i = 0; i < lastIndex; i++) {
        if (region[i] instanceof Rectangle) {
            result.add((Rectangle) region[i]);
        }
    }
    return result.toArray(new Rectangle[result.size()]);
}


Function outcome: consistent approach and easy logging

Is this a working program? In other words, have you tried to compile this? I'd be very surprised it compiled.

#include <hash_map>

This header does not exist in the C++ Standard Library. If you want a hash map, you need to use #include <unordered_map> and use the C++11 standard.

typedef const CStatus Status;

I'm pretty sure that something like: const Status S_SUCCESS doesn't compile as that resolves to: const const CStatus S_SUCCESS.

#ifndef S_SUCCESS
#define S_SUCCESS CStatus::CS_SUCCESS
#endif // S_SUCCESS

#ifndef S_UNDEFINED_ERROR
#define S_UNDEFINED_ERROR CStatus::CS_UNDEFINED_ERROR
#endif // S_SUCCESS

You have an error in the comment for the S_UNDEFINED_ERROR macro.

Your RegisterState function could also be slightly simplified:

// Static Functions
static Status registerState(const tstring &stateMsg)
{
    // Post:
    auto res = states.emplace({nextState + 1, stateMsg});

    // if state has been inserted
    return res.second ? Status(++nextState) : Status(res.first->first);
}

const tstring& toString() const
{
    return (states.find(state) == states.end()) ? states[state] : _T("Undefined");
}

I'm not familiar with what a tstring is but this function should be marked static (as only static members can access static member variables) and you shouldn't be returning the string by const value. Let the caller decide whether or not they want to make it const.

operator tstring() const
{
    return toString();
}

operator int() const
{
    return state;
}

What is the point of these and what do they return? These should be removed as they aren't going to be useful to your API. The entire point of your API is to allow the user to easily create new States without having them know too many of the internal implementation details.

bool operator!=(const CStatus& obj) const
{
    return state != obj.state;
}

Implement this in terms of operator==():

bool operator!=(const CStatus &ob) const
{
    return !(state == obj.state);
}

Finally, with this setup, your user will not be able to add any states during compile time. They will only be able to add checks during runtime (most likely during program startup). You should change your description to reflect this.


Sqlite select and delete operation using C API in Swift

You did not specify what precisely you were looking for, so a few general observations:

You do not need sqlite3_db_cacheflush. When you perform SQL updates, they are written to disk immediately (unless you are using transactions). You can do your inserts, updates, and deletes, leave the database open, and you’ll be fine.

Use Error, not NSError. I would advise against NSError (unless you needed Objective-C backward compatibility). In Swift, we would define our own Error type:
enum DatabaseError: Error {
    case sqlError(Int32, String)
}

And then
guard sqlite3_prepare_v2(database, sql, -1, &statement, nil) == SQLITE_OK else {
    throw DatabaseError.sqlError(sqlite3_errcode(database), String(cString: sqlite3_errmsg(database)))
}

Then, when catching errors, the codes and the error messages are more easily retrieved.

Failure of sqlite3_open_v2 will leak. When handling sqlite3_open_v2 failure, make sure to close the database or else resources allocated to it will never get freed. I know that this seems unintuitive, but the documentation is clear (emphasis added):

Whether or not an error occurs when it is opened, resources associated with the database connection handle should be released by passing it to sqlite3_close() when it is no longer required.

Method names. You have a method called deleteById(_:), which does not make it clear what you are deleting. Besides the use of a preposition and parameter name in the method name is common in Objective-C, but not Swift. I would suggest deleteUser(id:) or something like that. That makes the domain and functional intent of the method clear, and moves the parameter label where it belongs.

Be careful with string interpolation of SQL. In your user deletion routine, you are building the SQL statement through string interpolation of the identifier. That happens to work because the parameters are numeric, but can be problematic with string parameters. Usually we would use a prepared statement and then bind values to ? placeholders in the SQL.

Methods that throw should not return optionals. Optionals are useful when writing functions that must return either nil or some
value. But in this case, you always either return a value or throw
errors, so use of optionals is not needed any only complicates the
calling point. Remove the ? in the return values of E.g.,
enum DatabaseError: Error {
    case sqlError(Int32, String)
}

func deleteUser(by identifier: Int64) throws -> Int32 {
    let sql = "DELETE FROM user WHERE id = \(identifier)"

    guard sqlite3_exec(database, sql, nil, nil, nil) == SQLITE_OK else {
        throw DatabaseError.sqlError(sqlite3_errcode(database), String(cString: sqlite3_errmsg(database)))
    }

    return sqlite3_changes(database)
}

func findAllDepartments() throws -> [Department] {
    var statement: OpaquePointer? = nil
    let sql = "SELECT id, name FROM department"

    guard sqlite3_prepare_v2(database, sql, -1, &statement, nil) == SQLITE_OK else {
        throw DatabaseError.sqlError(sqlite3_errcode(database), String(cString: sqlite3_errmsg(database)))
    }

    defer {
        sqlite3_finalize(statement)
    }

    var departments: [Department] = []
    while sqlite3_step(statement) == SQLITE_ROW {
        departments.append(Department(id: sqlite3_column_int64(statement, 0), name: String(cString: sqlite3_column_text(statement, 1))))
    }

    return departments
}

Strive for highly cohesive, loosely coupled types. In this case, you have some other code opening the SQLite database and passing the sqlite3 pointer to the Database class. This is bad because it tightly couples the caller with the Database class, littering SQLite calls in multiple classes. It also is problematic because the Database type is less cohesive, not encompassing all the SQLite calls.
If, for example, you replace SQLite with some other storage mechanism at some later date, you are going to have to not only replace your storage class, Database, but go through all the caller code, too.

Database is tightly coupled with model types. In a similar vein as my previous point, we generally want to keep model objects and database objects a little less tightly coupled than this. For example, rather than having Department specific methods in our base Database class, you would want to define a protocol for fetching and storing of data. Or, at the very least, I would move Department and other model-specific methods in their own extensions, to avoid cluttering the main Database class with model-specific methods.

Consider SQLite wrapper class. Before you write your own SQLite wrapper class, you might want to consider one of the existing ones out there. They have already wrestled with many of the basic considerations and might have interfaces to handle this.

Just a few observations.


Print the length of words as input to a histogram with horizontal bars

Overall this look pretty good. It's very straightforward, and easy to read. Here are a few things I'd work on improving:
Better Naming
I can live with c, i and j. Those are fairly reasonable short names. But I'd rename accum to length or word_len because what you're accumulating is the length of the next word. It's easier to read. Likewise, for nchar, I'd rename it to either histogram or num_chars (or numChars, or whatever your preference is).
Functions Separate Responsibility
Your code is doing 3 things:

Initializing your variables
Getting the words from the user (during which it calculates the histogram)
Displaying the histogram

I'd make at least 2 functions. Initializing the array is fine where it is for now. In the future, you might have more complex data structures you use to keep track of statistics, so you would probably create a initialization function for those.
You could have a function for calculating the histogram and another for displaying it. Something like:
void CalcHistogram(int histogram[10])
{
    int c;
    int length = 0;

    while ((c = getchar()) != EOF && length < 10) {
        if (c != ' ' && c != '\n' && c != '\t') {
            ++length;
        }
        else {
            ++histogram [ length ];
            length = 0;
        }
    }
}

and
void DisplayHistogram(const int histogram[10])
{
      for (int i = 0; i < 10; ++i) {

        printf("%d ", i);

        if (histogram [ i ] > 0) {
            for (int j = 0; j < histogram [ i ]; ++j) {
                putchar('x');
            }
        }
        putchar('\n');
    }
}

As you can see, I also made the loop control variables local to the loop.
By separating the display into its own function, you can replace it with something more sophisticated later (like displaying it graphically, or instead sending it over the network, or whatever), without changing any of the logic of calculating it.
Error Handling
You aren't checking for errors at all. If the user enters a word longer than 10 characters, it suddenly stops taking input and prints out the histogram. That will be surprising to users. I'd at least output a message saying the input was too long, or something like that, if length (accum) gets over 10.
While I'm taking about user interface stuff, I notice that you don't prompt the user for what kind of input to enter. It might be worth adding a simple printf() to tell them what your program expects.


Runtime compiler for getting/setting runtime property values

First, a trivial optimization: there is no reason for dyn to be dynamic: all it does is to make the Target invocation dynamic, which here only makes it slower.

On my computer, this makes Get/Set about 25 % faster.

Another possibility is to use Expression instead of CallSite. Since Expression is not as dynamic as dynamic, it can compile to simpler code. For me, using this results in 50 % better speed than your code after applying the previous optimization.

The code:

public class TypeWrapper
{
    private readonly object dyn;
    private readonly Dictionary<string, Action<object, object>> setters
        = new Dictionary<string, Action<object, object>>();

    private readonly Dictionary<string, Func<object, object>> getters
        = new Dictionary<string, Func<object, object>>();

    public TypeWrapper(object d)
    {
        this.dyn = d;
        Type type = d.GetType();
        foreach (var p in type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
        {
            string name = p.Name;

            var wrappedObjectParameter = Expression.Parameter(typeof(object));
            var valueParameter = Expression.Parameter(typeof(object));

            var setExpression = Expression.Lambda<Action<object, object>>(
                Expression.Assign(
                    Expression.Property(
                        Expression.Convert(wrappedObjectParameter, type), p),
                    Expression.Convert(valueParameter, p.PropertyType)),
                wrappedObjectParameter, valueParameter);

            this.setters.Add(name, setExpression.Compile());

            var getExpression = Expression.Lambda<Func<object, object>>(
                Expression.Convert(
                    Expression.Property(
                        Expression.Convert(wrappedObjectParameter, type), p),
                    typeof(object)),
                wrappedObjectParameter);

            this.getters.Add(name, getExpression.Compile());
        }
    }

    public void Set(string name, object value)
    {
        var set = this.setters[name];
        set(this.dyn, value);
    }

    public object Get(string name)
    {
        var get = this.getters[name];
        return get(this.dyn);
    }
}


Best practices:

So I'll just shortly go through some of the basic beginner mistakes and best-practice "violations" I encounter around here, and tell you how well you did :)

Formatting:

On this front that's an awesome job, well done

Abstraction:

The code's a little lacking in that respect. The general goal in Java is to program against interfaces. This means:

ArrayList<Integer> uneatenLeaves = new ArrayList<Integer>();

becomes (after applying the Diamond Operator)

List<Integer> uneatenLeaves = new ArrayList<>();

Naming:

Naming is one of the hardest things to get right when coding. It's extremely important to have names speaking for themselves, variables containing "exactly what it says on the tin".
This allows to grasp the meaning of code much quicker.

array and n aren't really good names. If I understand the code correctly, jumpNumbers and limit would be better names.

Actual code-review

As already mentioned in a comment, this problem seems to be a variation of the Sieve of Eratosthenes, which is used for finding prime numbers.
Can you see the parallels yet?

To make it simple, you want a way to model two states. The better choice than a number (going from roundabout -2.150.000 to 2.150.000) is a boolean, which is either true or false.

Now we also know how often that state needs to be modeled, each leaf gets a separate boolean. If we pass the leaf with a caterpillar it gets eaten, and is no more there. The simplest way to model that is setting the symbolizing boolean to false.

Another interesting construct here is the do-while loop. A caterpillar eats the next leaf, if (and only if) the next leaf exists. The next leaf is calculated by \$A_j * increment\$ or even \$current + A_j\$. In combination with the number of leaves this makes a nice "terminating condition":

while (nextLeaf < leaves.size)

now we just do that for each caterpillar and suddenly we end up at following pseudocode:

// leaf 0 has already been eaten, since caterpillars always start there
foreach (jump_size in jump_numbers) {
    current = 0;
    while (next_leaf < leaf_count) {
       current = current + jump_size;
       eat current;
    }
}

Implementing this into actual code is left as an exercise to the reader ;)


Testing out a program that calculates the days left in the month

Don't use using namespace std
Prefer using \n over std::endl
The last return 0 is not necessary in this case as the compiler will generate it for you
When using the ternary operator you can just assign at the start instead of having to do it in both branches
Not part of the code but you should check your spelling

I'm not sure if you do the input on purpose to learn how it works but it can be done without user interaction.
Have a look at ctime as it offers many functions that can be useful here.

Here's a small program showcasing how to use those functions:

#include <ctime>
#include <iostream>

int main() {
    std::time_t time = std::time(nullptr);
    auto today = std::localtime(&time);

    int day = today->tm_mday;
    int month = today->tm_mon + 1;
    int year = today->tm_year + 1900;
    int month_length = 30;

    constexpr int february = 2;
    if (month == february) {
        month_length = is_leapyear(year) ? 29 : 28;
    }

    std::cout << month_length - day << " days remain in this month.\n";
}

Since the is_leapyear function is trivial I left it out.

Of course if you're using C++20 then you can just use chrono which offers an amazing amount of time and date related functions.


Dynamic programming with Project Euler #18

Your code is correct, fast, and I'd like to emphasize that you thoroughly include types for your functions, which greatly helps readability.

While arrays offer fast performance, I'd say that in this case operations with indexes and bounds of the arrays cloud the main idea considerably. Therefore I'd offer to use lists and functions native to lists that avoid indexing (the same could be also achieved with arrays, by writing similar functions for them).

The main idea, computing the maximum path lengths for one row, can be then nicely described by zipping:

-- OPT(r,i) = v_ri + max(OPT(r+1,i), OPT(r+1,i+1))
opt :: [Int] -- ^ the current row
    -> [Int] -- ^ the maximum paths from the previous row
    -> [Int]
opt row mxs = zipWith (+) row $ zipWith max mxs (tail mxs)

Then, computing the maximum path can be expressed as folding opt over a list of lists that represents a triangle:

-- Given a triangle (the first row containing `n` elements, the last row 1
-- element), compute the maximum path.
max_path :: [[Int]] -> Int
max_path = head . foldr opt (repeat 0)

where we start with an infinite list of zeros. This is safe, as we always only access a finite number of elements of this starting list.

While the algorithm remains the same, avoiding explicit indexing makes it more readable.

Minor notes:

it's customary to write f . g $ x instead of f $ g $ x to emphasize function composition
putStrLn . show can be replaced by just print

(I suggest you to try out hlint, which gives many interesting hints how to improve a Haskell program, including the two above.)


Before you optimize this, make sure that it actually needs optimization and that you're not wasting your time. Have you checked that this is a performance bottleneck in your application?

One way to optimize this is to store your excluded words in a datastructure like a Trie. This will let you see if some word in in the trie potentially faster than iterating through a list.


Is this the best way to print dynamic percent value?

Standing on the shoulders of @rolfl…

I would prefer to use a carriage return to return the cursor to the beginning of the line, as it's a bit less fragile than backspacing.

public static void main(String[] args) {
    // Java's Printwriter.format() doesn't tell you how many characters
    // it produced; 30 characters is an overestimate to ensure that
    // the entire "Percent completed: ***%" string gets overwritten.
    final String CLEARLINE_FMT = "\r%30s\r";

    try {
        for (int i = 0; i < 100; i++) {
            System.out.printf("\rPercent completed: %3d%%", i);
            Thread.sleep(500);
        }
        System.out.printf(CLEARLINE_FMT + "Done!\n", "");
    } catch (InterruptedException e) {
        System.out.printf(CLEARLINE_FMT + "Interrupted!\n", "");
    }
}

Or, if you want to print "100%" instead of "Done!":

public static void main(String[] args) {
    // Java's Printwriter.format() doesn't tell you how many characters
    // it produced; 30 characters is an overestimate to ensure that
    // the entire "Percent completed: ***%" string gets overwritten.
    final String CLEARLINE_FMT = "\r%30s\r";

    try {
        for (int i = 0; ; i++) {
            System.out.printf("\rPercent completed: %3d%%", i);
            if (i >= 100) {
                System.out.println();
                break;
            }
            Thread.sleep(500);
        }
    } catch (InterruptedException e) {
        System.out.printf(CLEARLINE_FMT + "Interrupted!\n", "");
    }
}


Avoid globals

last_allocated is only used to communicate the result of set_data_to_block back to malloc. Returning the result is much cleaner.
Avoid special cases

There is no need to special case the initial allocation. If you do not want to rely on ((header *) heap)->next == NULL initially, you may want to provide an initialization method (which I recommend anyway).


Get JSON script code with pushing to heatmap

Scope of Variables

Unless imei is used outside of the code in your post (which would be grounds for making it off-topic), then you should declare it as local to the function using var (or let if you want it to have block scope. The same is true for filtered and heatmap. That way those variables won't be global, which could cause confusion if you did use var to declare a variable inside a function but not before that.

For more information on that topic, see the section Keep your scopes close and your scope even closer on this page.

Accessing DOM elements multiple times via $()

DOM lookups are slow. It is wise to cache them once in a variable and then refer to the variable when needed. This is also mentioned in the aforementioned article under the section Cache DOM Lookups

Those lookups could be added above the function (possibly assigned in a DOM ready function like jQuery's $(function(){}), though it is argued that isn't necessary with modern browsers):

var map = $('#map');
var selectedVehicles = $('#selectVehicles');
var startDate = $('#startDate');
var endDate = $('#endDate');

Then those variables can be used later on when the function is run- for example:

var url = $('#map').data('request-url2');

Can be updated to use map:

var url = map.data('request-url2');

And map could also be used when setting up the Google Map instance, since presumably that is the same element used for the map.

Using parseInt() without a radix

If you are going to use parseInt(), it is wise to specify the radix using the second parameter - unless you are using a unique number system like hexidecimal, octal, etc. then specify 10 for decimal numbers.

  Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified, usually defaulting the value to 10.1

So I would update the line:

imei = parseInt($('#selectVehicles').val());

To pass the radix 10:

imei = parseInt($('#selectVehicles').val(), 10);

That way, if a value like 022 is entered, it isn't interpreted as the octal value (I.e. Decimal number 18).

1https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#Parameters


Feedback Request on Title Capitalization Function Converted From JavaScript to PHP

First things first: You definitely don't need to be making multiple regex function calls while looping the elements generated by a splitting regex function.  Time for an almost complete rewrite.  preg_replace_callback() is the tool that I recommend to do all the heavy lifting.

Normally, I like to do everything in a single regex expression, but the retaining of the multiple spaces is a simple operation that is sensibly set apart.

There WILL be other fringe cases that other reviewers may shout out (e.g. handling multibyte characters or calling preg_quote() on the incoming blacklist words to avoid any regex pattern conflicts with special characters, and let's not forget about troublesome Mr McGee) but I am going to only focus on the quality of data that you have presented.

There will be other ways to write the pattern but I have a high appreciation for the clarity of (*SKIP)(*FAIL) it basically consumes substrings that should be disqualified and then discards them.  The pipe after the skip-fail non-capturing group will match qualifying consecutive letters. The fullstring matches are passed to the custom function where the first letter is converted to uppercase, then returned.  Finally the fully modified string is returned from the preg_replace_callback().

My regex pattern uses negative lookaheads with the start and end of string anchors (^ & $) to implement the rule regarding capitalizing the first and last word.  Word boundaries (\b) are a great way to isolate a whole word (or parts of a hyphenated word).

Code: (Demo)

$tests = [
    ['this is a test', 'This Is a Test', false],
    ['why sunless tanning is A hot trend', 'Why Sunless Tanning Is a Hot Trend', false],
    ['Satin Sheets are a Luxury you Can Afford', 'Satin Sheets Are a Luxury You Can Afford', false],
    ['the Dangers Of Hiking Without Proper Shoes', 'The Dangers of Hiking Without Proper Shoes', false],
    ['an hour or so', 'An Hour or So', false],
    ['Of the meaning Of Of', 'Of the Meaning of Of', false],
    ['Thing With     Extra Spaces', 'Thing With Extra Spaces', false],
    ['Thing with     extra spaces', 'Thing With     Extra Spaces', true],
    ['Observations of isolated pulsars and disk-fed X-ray binaries.', 'Observations of Isolated Pulsars and Disk-Fed X-Ray Binaries.', false]
];

function APATitle($title, $keepMultipleSpaces = false, $blackList = [])
{
    if (!is_string($title)) {
        return false;
    }

    $blackList = $blackList
        ? array_map('strtolower', (array)$blackList)
        : ['a', 'an', 'and', 'at', 'but', 'by', 'for', 'in', 'nor', 'of', 'on', 'or', 'so', 'the', 'to', 'up', 'yet'];

    if (!$keepMultipleSpaces) {
        $title = preg_replace('~\s+~', ' ', $title);
    }

    return preg_replace_callback(
        '~(?!^)\b(?:' . implode('|', $blackList) . ')\b(?!$)(*SKIP)(*FAIL)|\b[a-z]+\b~',
        function ($m) {
            return ucfirst($m[0]);
        },
        strtolower($title)
    );
}

foreach ($tests as [$input, $expectedOutput, $keepMultipleSpaces]) {
    $output = APATitle($input, $keepMultipleSpaces);
    echo ($output === $expectedOutput ? 'SUCCESS' : 'FAILURE') . ":\t\"{$input}\" became \"{$output}\"\n";
}

Output:

SUCCESS:    "this is a test" became "This Is a Test"
SUCCESS:    "why sunless tanning is A hot trend" became "Why Sunless Tanning Is a Hot Trend"
SUCCESS:    "Satin Sheets are a Luxury you Can Afford" became "Satin Sheets Are a Luxury You Can Afford"
SUCCESS:    "the Dangers Of Hiking Without Proper Shoes" became "The Dangers of Hiking Without Proper Shoes"
SUCCESS:    "an hour or so" became "An Hour or So"
SUCCESS:    "Of the meaning Of Of" became "Of the Meaning of Of"
SUCCESS:    "Thing With     Extra Spaces" became "Thing With Extra Spaces"
SUCCESS:    "Thing with     extra spaces" became "Thing With     Extra Spaces"
SUCCESS:    "Observations of isolated pulsars and disk-fed X-ray binaries." became "Observations of Isolated Pulsars and Disk-Fed X-Ray Binaries."


Shift vowels towards the end of a Single Linked List

Don't do using namespace std

Here's a SO question which should provide you more information about this.

For loops are here to help you

You could write

int i = 20;
while (i>=0)
{
    enqueue (&head, &tail, rand()%26+65);
    i--;
}

in a much clearer way using a for-loop : for (int i=20; i>=0; i--) or for (int i=0; i<21; i++). I prefer the latter because I tend to count forward and not backward and it makes much clearer the fact that you want 21 iterations.

Avoid boilerplate and useless code

if (ch == 'a' || ch =='e' || ch=='i' || ch=='o' || ch=='u')
    return true;
return false;

could be simply written :

return (ch == 'a' || ch =='e' || ch=='i' || ch=='o' || ch=='u');

Avoid magic numbers

Even if I can guess them, I don't want to learn the ascii code for the different characters.
You could rewrite enqueue (&head, &tail, rand()%26+65); in a more explicit way : enqueue (&head, &tail, rand()%26+'A');

Be consistent with your brackets

Using brackets for single statement is a personal preference but if you do use them for the then-block, then please use them for the else-block as it makes things look "balanced".

Add a bit of documentation
I know it's tedious and not so interesting and I usually try to avoid to ask for it but here, I am getting a but confused by the two functions taking two lists as parameters and trying to understand what is intended for both of them.

This being said, I have to go and I'll try to have a deeper look later on.

In the meantime, here's your code with the comments above taken into account :

#include<iostream>

struct node
{
    char ch;
    node *next;
};

void enqueue (node **head, node **tail, char val)
{
    node *newn = (node *)malloc(sizeof(node));
    newn->ch = val;
    newn->next = NULL;

    if (*head == NULL)
    {
        *head = newn;
        *tail = newn;
    }

    (*tail)->next = newn;
    (*tail) = newn;
}

void print (node *head)
{
    while (head!=NULL)
    {
        std::cout<<head->ch<<" ";
        head = head->next;
    }
    std::cout<<std::endl;
}

bool isVowel (char ch)
{
    ch |= 32; // make it lowercase
    return (ch == 'a' || ch =='e' || ch=='i' || ch=='o' || ch=='u');
}

node* segregateVowels (node *head, node *tail)
{
    if (head == NULL || head->next == NULL)
        return head;

    node *temp = head;
    node *fin = tail;

    while (temp->next!=fin)
    {
        std::cout<<temp->ch<<" "<<fin->ch<<std::endl;
        if (isVowel(temp->next->ch))
        {
            node *shift = temp->next;
            temp->next = temp->next->next;
            tail->next = shift;
            shift->next = NULL;
            tail = shift;
        }
        else
        {
            temp = temp->next;
        }
    }

    if (temp->next!=NULL && isVowel(temp->next->ch))   /* Handling the case where the last element is a vowel   */
    {
        node *toMove = temp->next;
        temp->next = temp->next->next;
        tail->next = toMove;
        toMove->next = NULL;

    }
    else
    {
        temp = temp->next;
    }

    if (isVowel(head->ch))                  /*  Handling the case where the first element is a vowel    */
    {
        node *toMove = head;
        head = head->next;
        toMove->next = temp->next;
        temp->next = toMove;
    }

    return head;
}

int main()
{
    srand(time(NULL));

    node  *head = NULL, *tail = NULL;

    for (int i=0; i<21; i++)
    {
        enqueue (&head, &tail, rand()%26+'A');
    }

    print(head);

    head = segregateVowels (head, tail);

    print(head);
}


Partitioning strings into substrings of fixed length

Alternative solution is to keep it really simple:

(defn extract-int [s start end]
  (Integer/parseInt (subs s start end)))

(defn split-id [s]
  (list
    (extract-int s 2 5)
    (extract-int s 5 8)))

I believe that hardcoding two calls to extract-int is a simpler and more elegant way to meet the requirement than a solution which involves a map. Sure it's nice to use abstraction with higher-order functions, but YAGNI principle applies.


A variable name input is confusing. After all, input is a Python built-in.
standard_deviation calls mean too many times (add a debug printout to mean to see). Better do

def standard_deviation(input):
    input_mean = mean(input)
    return math.sqrt(mean([(x - input_mean) ** 2 for x in input]))

Median can be calculated in \$ O(\log n)\$. Sorting a list in \$O(n \log n)\$ just for a median is an overkill.


Rebol Function to Categorize Items in a Block

It's a useful function, and exists in underscore.js as groupBy.  So I'd probably call it group-by.  It might be useful to go function by function in underscore and use their names, possibly even putting them in the namespace _ if requested...although that's a little bit ugly.

The one thing I'll say about the interface in general, is that it's a bit too bad that what's coming back here is a block! and not a map!.  I feel like if you're reorganizing data in this pattern so that you can access it by key, then doing the linear searching both during the creation and later accesses isn't optimal.

Though perhaps rather than being a separate data type that map! should be a "hint" about an access pattern that is made on a block, like:

foo: [a [b c] d [e f] ... xyz [lmno pqrs]]
hint foo [map-access]
data: select foo 'd

Anyway, that's the only major point I'd bring up.  Minor stuff might be that you're using func and /local:

categorize: func [items [block!] test [any-function! block!] /local out value target][

Using function and letting the locals be scanned for, is more readable and maintainable:

categorize: function [items [block!] test [any-function! block!]] [

Performance-wise, the difference is negligible.  Remember that the scan only happens once here:

  delta-time [foo: func [a b /local c d] [c: 10 d: 20 return a + b + c + d] loop 10000 [foo 1 2 3 4]]
  == 0:00:00.009

  delta-time [foo: function [a b] [c: 10 d: 20 return a + b + c + d] loop 10000 [foo 1 2 3 4]]
  == 0:00:00.009022

In fact, the performance difference is generally lost in the noise.  You can repeat such tests and find the FUNC version taking longer than the FUNCTION version.

out: copy []

I've been scolded for using copy [] to create blocks, because you're "wasting a series" as a template, when that series is never used.  More relevantly, I think, is that it's a habit prone to accidentally leaving off the copy and suffering the consequences.  I have a proposal out to say that block~ none would create an empty block and there would be generators for all the types of that form.  But until that happens you might want to use make block! here.


Convert Byte array into collection of items of different types

case nameof(UInt16):
           return 2;

       case "Byte":
           return 1;

Be consistent. nameof is clearly preferable.

private void ConvertArray(byte[] response, ref object[] items)
{
    int index = 0;
    for (int i = 0; i < items.Length; i++)
    {
        var item = items[i];
        var itemType = item.GetType();
        var itemSize = SizeOf(item.GetType());

The last line should use the variable itemType.
The sole point of items seems to be to extract types. So why is the parameter not params Type[] types?

        if (itemSize == 0)
        {
            continue;
        }

Would it be better to throw an exception?

        else if (itemSize == 1)
        {
            items[i] = response[index];
        }

That's a bug waiting to happen in the future when you add support for sbyte.

        {
            var method = typeof(BitConverter).GetMethod($"To{itemType.Name}");
            var returned = method.Invoke(null, new object[] { response, index });
            items[i] = Convert.ChangeType(returned, itemType);
        }

Ugh. I would much rather use T4 to generate the entire method and get rid of the reflection. That would probably also eliminate the need for Sizeof.

If you're using a recent .Net (e.g. .Net Core 2.1) then I think some combination of Span<T> and Memory<T> will do what you want. Over the past year or so, Microsoft has done a lot of work on C# features for byte-level memory manipulation. You can probably create a struct for the contents of the packet and coerce the byte[] into your struct with one or two lines of code.


Returning an array of integers with 1000 elements

Your approach is not incorrect. It will get the job done (albeit, slower). If you want to improve your approach, keep reading. But first a few points on your code:

Points on Your code

intArrayHolder seems a bit wordy to me. I believe intArray or even array would serve your purpose, without sacrificing readibility. Same for randomNextInt.
for (int i = 0; i < intArrayHolder.length; i++) is redundant because the length of intArrayHolder will be equal to size owing to the fact that you declared it like so. for (int i = 0; i < size; i++) will serve you better.
Please note that random.nextInt(size + 1) does  not return an integer between 1 and 1000. It returns an integer in the range \$[0, 1001)\$, i.e. a number \$x\$ such that \$0\leq x < 1001\$. If you do a count, you will find that you are actually getting \$1001\$ elements. The extra number is \$0\$. To fix it, you must write int randomNextInt = random.nextInt(size) + 1; It is quite easy to understand: you just add a \$1\$ to shift the range from \$[0,1000)\$ to \$[1,1001)\$, i.e. the correct range.
((!isDuplicate) && (randomNextInt != 0)) can  be shortened to !(isDuplicate || ramdomNextInt == 0), by using De Morgan's laws. It would be even better if you flip the condition and force next iteration before adding the element to the array.
A general advice is to update the loop counter only once. People generally estimate the number of times the loop will execute by stealing a glance at the for (... statement. A while loop is preferred when the number of iterations is unknown or updation is irregular.
You seem to be using snake_case along with camelCase. The standard in Java is to use camelCase.

Therefore, the refactored code would be:

import java.util.Random;

public class Domain {

    public int[] randomIntArray(int size) {

        Random random = new Random();
        int array[] = new int[size];

        int i = 0;

        while (i < size) {
            boolean isDuplicate = false;
            int randomInteger = random.nextInt(size) + 1;

            for (int j = 0; j < i; j++) {
                if (array[j] == randomInteger) {
                    isDuplicate = true;
                    break;
                }

            }
            if (isDuplicate) {
                continue;
            } else {
                array[i++] = randomInteger;
            }

        }
        return array;
    }
}

A Better Solution

Your solution's best case running time is \$\Omega(n^2)\$. Moreover, as Boris the Spider pointed out: "... there is absolutely no guarantee that Random.nextInt() won't decide to return 1 for ever and ever. ..." Therefore, it might be possible that your code never terminates (although it will be very unlikely). You can make it faster in the following manner:

import java.util.Random;

public class Domain {

    public int[] randomIntArray(int size) {

        Random random = new Random();
        int array[] = new int[size];
        // populate the array with sequential values
        for (int i = 0; i < size; i++) {
            array[i] = i + 1;
        }
        // "shuffle" the array
        for (int i = 0; i < size; i++) {
            int j = random.nextInt(size - i) + i;
            // swap
            int temp = a[i];
            a[i] = a[j];
            a[j] = temp;
        }
        return array;
    }
}

It's running time is linear i.e. \$\Theta(n)\$1. I am basically describing the Fisher-Yates shuffle

Some Background Info: The Big-O stuff

The Big-O notation is used to define an upper limit of the number of operations executed (the maximum running time, in simpler terms). For example, if the exact number of iterations based on a given parameter (like the number of elements, digits, etc) called \$n\$ is
$$2n^2+3n-4$$
we can say that a reasonable upper limit is \$3n^2\$. In the Big-O notation, the constant term gets absorbed. When we represent this in the Big-O notation, we say: "the (maximum) running time is proportional to \$O(n^2)\$".

People tend to forget the other two notations: the Big-Omega (\$\Omega\$) and the Big-Theta (\$\Theta\$) The former defines a lower limit and the latter is the Big-O and the Big-Omega combined together. In the example above, the lower limit can be \$2n^2\$. Absorbing the constant, we say:"the (minimum) running time is proportional to \$\Omega(n^2)\$". The function can therefore be bounded within both upper and lower limits, or both the upper and the lower limits are in the order of \$\Theta(n^2)\$.

Your code has no upper limit. It only has a lower limit. So, only the \$\Omega\$ is defined for your code (unless we set out to do a lengthy mathematical analysis of the behaviour of the nextInt() function).

I suggest that you read the related Wikipedia articles. (I didn't cover \$o, \omega\$ and \$\theta\$, that's your homework). Remember, Google is your friend!

1 Assuming that the nextInt() method takes \$O(1)\$ (i.e. constant) time to execute.


Manipulate Hash to typecast true/false for certain values

Code should be as declarative as possible (usually by using functional style):

def transform
  special_values = {"1" => true, "0" => false}
  Hash[preferences.map { |k, v| [k.to_sym, special_values.fetch(v, v)] }]
end

However, Hash[...] is very ugly and I prefer a more OOP approach with Enumerable#mash, so I'd really write preferences.mash { |k, v| [k.to_sym, special_values.fetch(v, v)] }.


Create nested named object using variables as key

New Object != Better Performance

First of all, your notion of "new object is faster" isn't "right" all the time. This might be trivial for smaller objects, but for thousands of records and possibly nested objects, this isn't right.

Though you do create lesser code by reconstructing a new object, but not done right, you might end up eating more memory.

If you don't dereference the other object properly, it may sit there and just eat up memory. This will give you the "It's dead" page in Chrome.
If you do successfully dereference it, due to the size of the object (like you said, thousands), the GC will take time clearing it from memory, seconds at a time. In this event, there will be noticable "choking" of the browser, and stuttering or worse, freezing of animations. Been there, not good user experience.

Use the almighty server

If you are getting this data from the server, it's better that the server handle this operation. Servers are usually faster than the browser, use it to your advantage. That way, you do less on the browser, and prioritize more important tasks, like giving the user a good UI and fast interaction.

Doing it all client side

Now if you can't do it somewhere else but the server, there are ways to speed it up, or at least not freeze the server.

Web Workers

A modern way of doing it is handing it over to another "thread" by making Web Workers do it.

Keep them small

Keeping your loops small. I usually notice a significant lag when iterations go more than 500 (it's not a magical number, just an observation). Keep your loops small, and avoid that long freeze.

Chunk it up

In addition to keeping the data small, if you have more data to churn than just the 500, consider using timers. Timers with 1ms intervals don't really execute 1ms later. They execute at least 1ms later, and when JS is not busy. You can use that to your advantage and schedule short tasks at intervals without breaking the UI. Of course, the operation becomes asynchronous, so you might want to build a crude callback system for this.

var intervalChurn = setInterval(function(){...loop 100 at a time...},0);

Keep the data flat

Nesting introduces more complexity to the data. Say you have an array of 10 objects. If you loop through that array, it's just 10 iterations. But what if that 10 items have 5 nested properties that you also want to loop through. So thats 5 nested properties times 10 items, giving you 50. Nesting more will introduce more iterations.

Use a library

Some of the bright minds in the development world might have already developed functionality similar to what you are Trying to do. Don't reinvent the wheel. In fact, you are doing something similar to Underscore's omit().


Extracting elements from multiple sorted lists efficiently

This is sooo off-topic for CR... but, since it is related to a previous answer, and since I want to see a blown mind ....:

consider the following code:

class Value<T> {
    private final T value;
    private final int[] arraypointers;
    private final int arraycursor = 0;

    Value(T value, int maxindex) {
        this.value = value;
        this.arraypointers = new int[maxindex];
    }

    public void addIndex(int pointer) {
        arraypointers[arraycursor++] = pointer;
    }

    ... some other stuff.
}

OK, the above class will be used as follows... consider the example data system, the value 4 appears in list1 and list5.

This would be stored as:

Value v = new Value(4, k);
v.addIndex(1);
v.addIndex(5);

Now, start with a LinkedList:

LinkedList<Value<Integer>> values = new LinkedList<>();

Then, iterator though each of your loops, and merge the values in to the linked list:

for (int datapointer = 0; datapointer < datalists.size(); datapointer++) {
    ListIterator<Value<Integer>> valit : values.listIterator();
    List<Integer> = datalists.get(datapointer);
    for (Integer addval : data) {
        boolean found = false;
        while (valit.hasNext()) {
            if (addval.compareTo(valit.next().value) >= 0) {
                found = true;
                Value<Integer> val = valit.previous();
                if (val.value.equals(addval) {
                    // update existing value
                    val.addIndex(datapointer);
                    // leave the iterator point backwards to
                    // allow for dup values in the data.
                } else {
                    // add a new value
                    Value<Integer> val = new Value(addval, k);
                    val.addIndex(datapointer);
                    valit.add(val);
                    // leave the iterator pointing backwards.
                    // but need to move it back one.
                    valit.previous();
                }
            }
        }
        if (!found) {
            Value<Integer> val = new Value(addval, k);
            val.addIndex(datapointer);
            valit.add(val);
            valit.previous();
        }

    }
}

then, convert the LinkedList in to an ArrayList

List sortedvalues = new ArrayList<Value<Integer>>(values);

Right, here we now have a sorted list of Values<Integer>. Each Value has pointers back to the list(s) they came from.

The space complexity for this is \$O(kn)\$ and we got there by doing a complexity \$O(kn)\$ nested loop (the inside while loop does not count because it is on an iterator that is outside the for loop, and it is part of the same complexity as the inner for loop)...

OK, so that is the \$O(kn)\$ preprocessing.

The lookup is a case of doing a binary search on the ArrayList (\$O(\log n)\$) and then iterating over the index pointers (\$O(k)\$).

Thus, the search is \$O(k + log n)\$.

Voila!

Working solution

Right, putting all the pieces together in a working solution:

Value.java

import java.util.Arrays;

class Value<T extends Comparable<T>> implements Comparable<Value<T>> {

    private final T value;

    private final T[] indices;

    public Value(T value, T[] data) {
        super();
        this.value = value;
        this.indices = data;
    }

    public void setIndex(int index, T val) {
        if (indices[index] == null) {
            indices[index] = val;
        }
    }

    public T[] getIndices() {
        return Arrays.copyOf(indices, indices.length);
    }

    public int compareToValue(T o) {
        return value.compareTo(o);
    }

    @Override
    public int compareTo(Value<T> o) {
        return value.compareTo(o.value);
    }

    @Override
    public int hashCode() {
        return value.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        return obj instanceof Value && value.equals(((Value<?>)obj).value);
    }

    @Override
    public String toString() {
        return String.format("%s -> %s", value, Arrays.toString(indices));
    }
}

MultiListIndex.java

package listsearch;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class MultiListIndex<T extends Comparable<T>> {

    private final List<Value<T>> index;
    private final Class<T> clazz;
    private final int width;

    public MultiListIndex(Class<T> clazz, Collection<List<T>> data) {
        this.clazz = clazz;
        this.width = data.size();
        this.index = preprocess(new ArrayList<>(data));
    }

    private final List<Value<T>> preprocess(List<List<T>> data) {
        LinkedList<Value<T>> processed = new LinkedList<>();
        Value<T> target = null;
        for (int listid = 0; listid < data.size(); listid++) {
            ListIterator<Value<T>> valit = processed.listIterator();
            Iterator<T> datait = data.get(listid).iterator();
            while (datait.hasNext()) {
                final T toadd = datait.next();
                boolean found = false;
                while (valit.hasNext()) {
                    final int compare = (target = valit.next()).compareToValue(toadd);
                    if (compare >= 0) {
                        // we have a match, or gone past.
                        valit.previous();
                        found = true;
                        if (compare == 0) {
                            target.setIndex(listid, toadd);
                        } else {
                            Value<T> newtarget = new Value<>(toadd, Arrays.copyOf(target.getIndices(), width));
                            valit.add(newtarget);
                            newtarget.setIndex(listid, toadd);
                            if (newtarget != valit.previous()) {
                                throw new IllegalStateException("Bad math!");
                            }
                        }
                        break;
                    }
                    target.setIndex(listid, toadd);
                }
                if (!found) {
                    Value<T> newtarget = new Value<>(toadd, buildArray(clazz, width));
                    valit.add(newtarget);
                    newtarget.setIndex(listid, toadd);
                }
            }
        }
        return new ArrayList<>(processed);
    }

    @SuppressWarnings("unchecked")
    private static final <T> T[] buildArray(Class<T> clazz, int size) {
        return (T[])Array.newInstance(clazz, size);
    }

    public List<T> searchValues(T value) {
        Value<T> key = new Value<>(value, null);
        int pos = Collections.binarySearch(index, key);
        if (pos < 0) {
            pos = -pos - 1;
        }
        if (pos >= index.size()) {
            return Arrays.asList(buildArray(clazz, width));
        }
        return Arrays.asList(Arrays.copyOf(index.get(pos).getIndices(), width));
    }

}

MultiListMain.java

package listsearch;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MultiListMain {

    public static void main(String[] args) {
        List<List<Integer>> lists = new ArrayList<List<Integer>>();

        List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(3, 4, 6));
        List<Integer> list2 = new ArrayList<Integer>(Arrays.asList(1, 2, 3));
        List<Integer> list3 = new ArrayList<Integer>(Arrays.asList(2, 3, 6));
        List<Integer> list4 = new ArrayList<Integer>(Arrays.asList(1, 2, 3));
        List<Integer> list5 = new ArrayList<Integer>(Arrays.asList(4, 8, 13));

        lists.add(list1);
        lists.add(list2);
        lists.add(list3);
        lists.add(list4);
        lists.add(list5);

        MultiListIndex<Integer> search = new MultiListIndex<Integer>(
                Integer.class, lists);
        // System.out.println(dataInput);

        System.out.println(search.searchValues(0));
        System.out.println(search.searchValues(1));
        System.out.println(search.searchValues(2));
        System.out.println(search.searchValues(5));

    }

}

Output

[3, 1, 2, 1, 4]
[3, 1, 2, 1, 4]
[3, 2, 2, 2, 4]
[6, null, 6, null, 8]


Find all distinct triples less than N that sum to S

Your unique-triples-less-than-n is unnecessarily complex because you can state it recursively. S. Kucherenko's answer tries to achieve this but is also unnecessarily complex.
A simple recursive formulation is here, but this assumes that enumerate-integers returns an empty list if called with values from > to.

 (define (unique-tuples m from to)
    (if (= n 0) '(())) ; one empty tuple
        (flatmap (lambda (n)
                   (map (lambda (t) (cons n t))
                        (unique-tuples (- m 1) (+ n 1) to)))
                 (enumerate-integers from to))))

This unfolds as recursive calls e.g. like this:

 (u-t 3 1 4) = (flatmap ... '(1 2 3 4))
             = (flatten '(,(map (lambda (t) (cons 1 t))
                                (u-t 2 2 4))
                          ,(map (lambda (t) (cons 2 t)) ;; X
                                (u-t 2 3 4))
                          ,(map (lambda (t) (cons 2 t))
                                (u-t 2 4 4))
                          ,(map (lambda (t) (cons 2 t))
                                (u-t 2 5 4))))

and e.g. if you look at line marked with X, this takes recursively (unique-tuples 2 3 4), i.e. 2-tuples whose first integer is between 3 and 4, so the list is '((3 4)), and then for every element of that list, we add 2 at the beginning, so map returns '((2 3 4)).

Then just

(define (unique-triples n) (unique-tuples 3 1 n))

The results need to be filtered afterwards for the sum.


I'll preface this by saying that I'm not a Haskell programmer, so take my comments advisedly.

I would appreciate a short comment specifying the behaviour of each type and function. For example:

-- The point of intersection between a ray and a plane.
hitPlane :: (Fractional a) => Ray a -> Plane a -> V3 a

This allows a reader to quickly understand the purpose of a function without having to read the code to find out. Also it provides a specification that can be checked against the implementation.
In geometry the term ray usually refers to the half-line with a starting point and direction. So a ray does not necessarily hit a plane, and the type of hitPlane ought to be:

hitPlane :: (RealFrac a) => Ray a -> Plane a -> Maybe (V3 a)

If you intend your Ray type to be a full line, then it ought to be called Line instead, to avoid confusion. But even a full line might not have a point of intersection with a plane, because it might be parallel to the plane. In this case there will be a division by zero error: it would be better to avoid this and return Nothing.
I don't understand all the details of the class constraints. hitPlane requires both Num a and Fractional a but if I understand the standard Haskell type documentation, the latter implies the former, so the Num a is redundant. Similarly for hitQuad, where Num a is redundant given that you have Floating a.
hitQuad requires Epsilon a and Floating a, but I don't see how either of these classes is necessary. I would have expected just Ord a, Fractional a, and this combination is the same as RealFrac a.
Some of the helper functions could be usefully made into top-level functions. For example, the implementation of hitQuad finds the plane containing a triangle of points. But this operation is generally useful:

-- The plane containing three points, with a normal chosen so that
-- the points are clockwise when looking in the normal direction.
planeContaining :: (Num a) => (V3 a, V3 a, V3 a) -> Plane a
planeContaining (a, b, c) = Plane a (cross (b - a) (c - a))


I'm not a fan of "sanitizing" data.  There isn't a clear definition of what "sanitizing" means, other than that it takes untrustworthy input and somehow makes it valid.  It might entail discarding the invalid parts of the input — which is not what you are doing here.  Escaping is a clearer term to describe what you are doing.

Repeated string concatenation is considered poor practice for performance.  Since JavaScript strings are immutable, it would be better to devise a solution that constructs the string "all at once".

The documentation on developer.mozilla.org suggests the following solution for escaping a regular expression:

  Escaping user input to be treated as a literal string within a regular
  expression can be accomplished by simple replacement:

function escapeRegExp(string){
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

I strongly recommend replacing your custom solution with the standard recipe (including a citation).


Looks just fine, I think. Only some really minor things come to mind

For font-family, it's good to always end with a generic font face style; in this case it'd be sans-serif. Arial is of course as "web-safe" as it gets, but still.
Why does #nav have a position: absolute rule, but no actual positioning (left, top, etc.) values? I imagine you're doing some JS positioning, but you should still have a fallback position (or just set position: absolute in the JS, so it's only there when needed).
You could consider using :last-of-type instead of explicitly giving elements a last class. Depends on what browsers you're targeting
Remove the a:active rule; you've already commented it out of the code.
You may want to do a box-shadow function that does the vendor-prefix magic, similar to your border-radius
You have one @themeColor, but also a bunch of different hard-coded colors (e.g. border colors on .content). So while it's easy to change the @themeColor, you'll probably still have to go through and change every other color to better match the new theme. If you can, use the color functions to derive the rest of the palette from @themeColor or make a more comprehensive list of color variables (even if they're only used once, it's still nice to be able to define the whole color scheme in 1 place).


Firstly some style.

Short named variables don't help readability at all. c1, c2, s1, s2 are a bad idea. I know this is just a challenge and not production code but keeping a consistent style is a good habit.

Secondly I would start by using the string.Contains() method. It will find if a specified substring exists and should help clean up some of the code.

In this train of thought I decided to start with all the possible substrings in the first string and then search the list of all strings.

public static IEnumerable<string> LongestCommonSubstrings(List<string> strings)
{
    var firstString = strings.FirstOrDefault();

    var allSubstrings = new List<string>();
    for(int substringLength = firstString.Length -1; substringLength >0; substringLength--)
    {
        for(int offset = 0; (substringLength + offset) < firstString.Length; offset++)
        {
            string currentSubstring = firstString.Substring(offset,substringLength);
            if (!System.String.IsNullOrWhiteSpace(currentSubstring) && !allSubstrings.Contains(currentSubstring))
            {
                allSubstrings.Add(currentSubstring);
            }
        }
    }

    return allSubstrings.OrderBy(subStr => subStr).ThenByDescending(subStr => subStr.Length).Where(subStr => strings.All(currentString => currentString.Contains(subStr)));
}

This will also allow us to do a .FirstOrDefault() on the linq and get the largest ( due to the orderby() calls.

(To test I used a static list of strings instead of a file:)

public static void Run()
{
    var input = new List<string>{
        "GATTACA",
        "TAGACCA",
        "ATACA",
    };

    var t = new Stopwatch();
    t.Restart();
    var lcs = LongestCommonSubstrings(input);
    t.Stop();

    Console.WriteLine("All Common substrings: \r\n{0}", string.Join("\r\n", lcs));
    Console.WriteLine("Finished in {0} msec.", t.ElapsedMilliseconds);
    Console.ReadLine();
}

DISCLAIMER: Haven't fully tested the above code. May harm your brain/computer.


Calculate food company sales for the year

Your code looks good, I have some minor suggestions:

Separate getting the data and outputting it

I would prefer reading something like this:

for product_info in product_informations(productfile):
    # Handle out-put of product_info

To separate concerns more clearly.

Use _ to signify un-used values

for category, brand, sales_lastyear, sales_thisyear in rows:
    categorycounts[category] += int(sales_thisyear)

The values brand and sales_lastyear are not used, so you do not need to give them a name:

for category, _, _, sales_thisyear in rows:
    categorycounts[category] += int(sales_thisyear)

Be explicit with file.write

If you want to write to a file, print will work just fine, but I suggest being the most explicit and using file.write.

This also helps separation of concerns because it forces formatting to be handled separately. (See str.format in the next paragraph)

Do not repeat yourself

    print("Total sales for the company in 2015:", totalsales, file=reportfile)
    print("Total sales for the company in 2015:", totalsales)

Only the output destination changes.

You can either save the message in a variable:

sales_info = "Total sales for the company in 2015:{}".format(totalsales)

reportfile.write(sales_info)
print(sales_info)

Or use a loop:

for destination in (sys.stdout, reportfile):
    print("Total sales for the company in 2015:{}".format(totalsales), file=destination)

.format is also preferred over str + str and print(x, y) for its extensibility and readibility.

Indent in generator expressions

It is weird to see a for at the start of a line as part of a generator comprehension, because it looks like a loop statement, some indenting will clarify that it is part of a generator comprehension:

rows = (line.rstrip().split(',')
            for line in productfile if line.rstrip())


Take a desired string, iterate through objects to see if it exists in a given field and append a number until a unique string is found

There's certainly room for improvement.

Move that that Select(stringFieldFunction).ToList() out of the while loop. Iterating an IEnumerable might be quite expensive, and there's no need to repeat that work when you find a duplicate.
Select only those strings that have originalString as a prefix. That will reduce the amount of items you need to check against when adjusting the suffix.
Instead of making a list, turn those results into a (hash)set, for faster lookup.

Regarding EF complaining: apparently it doesn't support those StringComparsion overloads, so it'll have to fetch all rows from the database and run your Any predicate in memory, which may be slower as expected. Maybe an alternative approach like using ToUpperInvariant can be translated to SQL?

Applying the above changes will give you the following:

private string GetUniqueValue<T>(string value, IEnumerable<T> items, Func<T, string> getValue)
{
    var possibleDuplicates = items
        .Select(getValue)
        .Where(val => val.StartsWith(value, StringComparison.InvariantCultureIgnoreCase))
        .ToHashSet();

    var result = value;
    var suffix = 1;
    while (possibleDuplicates.Contains(result))
    {
        result = value + "_" + suffix;
        suffix += 1;
    }
    return result;
}

Addendum

As t3chb0t and ErikE already pointed out, if you want the benefits of Linq-to-SQL, then you need to use IQueryable<T>. Not only that, you also need to make sure that you're using the Queryable Linq extension methods, not the Enumerable variants.

The difference is that Enumerable methods have Func<> parameters, while the Queryable variants have Expression<Func<>> parameters. An Expression is a data structure that represents a piece of code, which makes translation to SQL possible. Because stringFieldFunction is a Func, not an Expression<Func>, the Enumerable.Select variant is used. That cannot be translated to SQL, so all data has to be loaded from the database before the Select (and any subsequent operation) can be performed on it.

To recap: use IQuerable<T>, make sure you're using Queryable Linq methods, and only use supported methods within your expressions.


Some general notes:

GetEnum function:

Select Case value
        Case 0
            GetEnum = "none"

This kind of hard-coding of values is very risky, if you change the enumeration your function will break. It should be Case none ...

EvaluateHand

What if you have not exactly 5 numbers?
you're right, usage of GoTo should be very limited, you could avoid majority of it by ElseIf or Select Case
also, I wouldn't have went so much details like the snippet below, just set the flags during the For, then check the flags at the end and set score

 If bucket(i) = 3 Then
            If twoFlag Then
                score = fullhouse
                GoTo Eval

I don't think an array is the best fit for this purpose, I'd suggest to use a dictionary, like here below:

Private Function EvaluateHand_MJ(ByVal dice As Variant) As String
    Dim values As New Dictionary
    Dim i As Long
    Dim result As Combination

    result = Combination.none

    With values
        For i = LBound(dice) To UBound(dice)
            If .Exists(dice(i)) Then
                .Item(dice(i)) = .Item(dice(i)) + 1
            Else
                .Add dice(i), 1
            End If
        Next i

        Select Case .Count  ' check number of distinct values
        Case 1          ' all dices are the same, must be a yacht
            result = Combination.yacht
        Case 2         ' two distinct numbers: four (4+1) or a fullhouse(3+2)
            If .Item(.Keys(1)) = 2 Or .Item(.Keys(1)) = 3 Then
                result = Combination.fullhouse
            Else
                result = Combination.four
            End If
        Case 3         ' 3 distinct: two pairs (2+2+1) or a three (3+1+1)
            For i = 1 To 3
                Select Case .Item(.Keys(i))
                Case Is = 2
                    result = Combination.twopair
                Case Is = 3
                    result = Combination.three
                End Select
            Next i
        Case 4         ' 3 unique numbers and a pair
            result = Combination.pair
        Case 5         ' straight (1 or 6 missing) or nothing
            For i = 1 To 6
                If Not .Exists(CStr(i)) Then
                    If i = 1 Then
                        result = Combination.bigstraight
                    ElseIf i = 6 Then
                        result = Combination.smallstraight
                    End If
                End If
            Next i
        End Select
    End With

    EvaluateHand_MJ = GetEnum(result) & " "
End Function


Using HikariCP and JDBC to store data for a Minecraft plugin

Something which occurs to me is that catching the exception and not rethrowing is a very bad practice. Printing the stack trace is helpful, it tells the consumer of your API that something went wrong, but it is inflexible (it cannot be redirected to another IO device) and, more importantly the failure itself is swallowed. The program keeps on running after an exception, but there is no fallback behavior and the situation seems critical. Consider rethrowing the exception or, better yet, removing the try...catch construct entirely.


There are some things that you could do to improve your code:

First of all, your functions clearly lack documentation. Unless you know a little bit about graph theory, it is quite hard to guess that BFS and DFS stand for "Breadth-First Search" and "Depth-First Search". While the names may appear to be long, using the names breadth_first_search and depth_first_search would be really clearer.
Also, docstrings to document what your functions do would be great. For example, you could write what theGraph is supposed to be since there is no obvious Graph structure to be used around. Documenting your functions, what are the parameters, what is the return type and what may be the preconditions and postconditions really matters :)
Also, your code is too dense. You should add more spaces where it improves readability. My advice to follow the guidelines in the PEP 8, the Python style guide. These guidelines are really good to write readable code.
By the way, the PEP 8 says that you shouldn't check the len of a collections to know whether there are elements in or not. Therefore, you should change this line:

while len(queue)!=0:

...to this one:

while queue:

These lines:

explored=np.empty(n,bool)
for i in range(0,n):
    explored[i]=False

...can be reduced to a one-liner thanks to numpy.zeros:

explored=np.zeros(n,bool)

And since you don't use n except for constructing excepted, you may as well get rid of n and use numpy.zeros_like to construct expected:

explored = np.zeros_like(theGraph, bool)

While it is good for modules to have examples of how the module works, you generally do not want these examples to be run, unless when you explicitly run the module as a stand-alone. If you want your code to be a module, put the example part of the code in what we could call a "main block" (I don't know whether there is an official name):

if __name__ == '__main__':

    n=6 #number of nodes

    theGraph=[set() for i in range(n)]

    theGraph[0].add(1)
    theGraph[0].add(2)

   # Rest of your example
   # code goes here...


Normalizing `DateTime` values to strings

TimeSpan.FromMinutes(1) and TimeSpan.FromHours(1) are much easier to read than new TimeSpan(0, 1, 0) and new TimeSpan(1, 0, 0).

Consider using multiple return statements, instead of just the one.

Stick to the naming conventions: change the parameter DateTime to dateTime, and the variable TimeDifference to timeDifference.

It's a good idea to document that this is relative to UTC time, otherwise users might get strange behaviour like this:

var twoHoursAgo = DateTime.Now.AddHours(-2);
Console.WriteLine(twoHoursAgo.ToNormalizedString());

Just now


Updating number of votes with a "Like" button

Formatting
On the whole, there are several indentation problems through out your code.  Here is made the most obvious example:
        if let pfObject = objectArray?[indexPath.row] {
                     cell?.parseObject = object
var votes: Int? = pfObject["votes"] as? Int

The second line has two extra levels of indentation over what it should have.  The third line needs three more indentation levels to be in the correct place.
Xcode will pretty much put every single line of code exactly where it belongs.  All you have to do to get your indentation correct is simply not fight Xcode.  Even if you disagree with Xcode about how something should be indented, it's usually a lot easier to just do it Xcode's way because everyone else tends to give in to Xcode... and it's a lot less effort.  (For a personal example, I tend to feel like case statements within a switch should be indented one level from the switch statement, but Xcode disagrees... and it's a lot less work for me to just let Xcode have it its way.)

Delegates

var delegate : CellButtonDelegate?

Delegates should always be weak.  Without making a delegate weak, you're almost always setting up some sort of a retain cycle.  But what's more important, people expect for delegates to be marked as weak.  If you want to replicate the typical "delegate" pattern, but for some reason need the default strong reference, then you need to call your property by something other than "delegate".

Computed Properties
I have several comments about this property:
internal var buttonEnabled : Bool? {

    get {

        return loveOutlet.enabled

    } set {

        loveOutlet.enabled = newValue!
    }
}

First of all, internal is the default access level.  As you marked nothing else as public or private, everything in your code actually has this internal access level.  Above all else, we should prefer consistency.  If you're going to mark internal things with the internal keyword, you're now going to need to mark every property, method, extension, protocol, class, struct, enum, and function (and whatever else I forgot) with its access modifier.  Anything else is inconsistent.  But marking them all is too verbose.  We all know (or should know) that internal is the default level, and if we mark all the internal things as internal, it just becomes an unconstructive cluttered keyword.  I would only ever recommend marking something as internal in a class where basically everything else is already marked as public or private.  In that case, internal indicates "No, I didn't forget to mark this one--yes, it really is internal, I promise."
Next, there's a whole lot of white space in this.  In fact, you consistently have a ton of vertical white space throughout the entirety of your code.  Let's use white space more constructively, shall we?  Every single line of this property is all associated to this property.  By eliminating the blank lines in the middle, it helps the eye associate all of these lines together visually (in a way far more immediately obvious than the curly braces do).
Finally, let's talk about optionals... Your loveOutlet doesn't appear to be defined in this file, so I don't know if it is an optional or if it is a non-optional but the enabled property is optional.  I don't know what has led you to marking this buttonEnabled property as a Bool? rather than a non-optional Bool, but based on the force-unwrapping in your setter, it seems clear that this should probably be a non-optional.  We should allow the user to pass nil for the buttonEnabled property--how can that even make sense?  It clearly doesn't make sense, because if they ever do, we simply crash.  This is supremely bad design.  Swift gives you the power to clearly dictate which properties can and cannot be set to nil.  What you've done here is created a property that can be set to true, false, or "crash my app please".
So more realistically, this property should look about like this:
var buttonEnabled: Bool {
    get {
        return loveOutlet.enabled
    }
    set {
        loveOutlet.enabled = newValue
    }
}

If loveOutlet is optional (in this case, for it to compile, it'd have to be an implicitly unwrapped optional), or its enabled property is optional, then we can go for one of these two options in the get:
loveOutlet?.enabled ?? false

or
loveOutlet.enabled ?? false

if true then true else false
let isEnabled = pfObject["isEnabled"] as! Int
if isEnabled == 1 {

    cell?.buttonEnabled = true

} else {

    cell?.buttonEnabled = false

}

Here, we see another issue with overuse of vertical white space, poor optional management, and a pattern that I simply don't understand: if true then true else false.
This as! Int can cause an app crash in multiple ways.  First, the value can simply not exist for the key.  Second, the value could exist, but not be convertible to an Int.  If this is a dictionary representing JSON, the value could be a string, floating point, or bool.  If it's not representing JSON, it could be anything.  But we can rewrite this safer and using significantly fewer lines:
cell?.buttonEnabled = (pfObject["isEnabled"] as? Int) == 1

Although, arguably, we'd really want to fix our model so that the value for the "isEnabled" key is actually a bool, then we can write something that makes a bit more sense:
cell?.buttonEnabled = (pfObject["isEnabled"] as? Bool) ?? false

Optional Safety
It's really unfortunate that being safe with optionals is an optional thing at all.  It seems mostly a hold-over from the short period of time after Swift was introduced and before Objective-C's nullability annotations.
Despite this, we should still strive to always be as safe as possible with our optionals.  Force-unwrapping nil is always a crash.
if(parseObject != nil) {

        if var votes: Int? = parseObject!.objectForKey("votes") as? Int {
            votes!++

            parseObject!.setObject(votes!, forKey: "votes")
            parseObject!.saveInBackground()

            print(votes!)
        }

        delegate?.buttonClicked(self)
    loveOutlet.enabled = false

    }

Here, we have not been safe with our optionals.  And the worst part here is that there's not even an imaginably good reason for this lack of safety--we're checking for nil in an if statement and only force-unwrapping within that block.
The most dangerous problem with this is that it's not thread safe.  If thread 1 checks that foo is non-nil, finds it is not, then enters the if block, then thread 2 sets foo (an instance variable) to nil, then back on thread 1, we're in the if block and force unwrap, we've now crashed (despite having checked against nil).  This is why we should prefer the if let construct.
if let pObj = parseObject {
    // safely use pObj as a constant, unwrapped, thread-safe, locally-scoped version of parseObject
}

The next line is particularly strange.  It's a clear indication that we're aware of the if let/if var syntax, but we've used it in a mysterious and strange way.
(For the record, I absolutely never want to see votes!++ in my code base, and if a developer on my project checked that code in, I'd be looking to move that dev to a different platform.  It's horrendous...)
You've used if var to properly check for nil... but then you specify the type as an optional which still has to be unwrapped, despite having already checked against nil.  If we simply don't specify the type, votes would be a non-optional that doesn't need to be force unwrapped.
We should also generally prefer let variables to var variables.  In fact, we should default to let and only change it to var when we absolutely must modify the value.  I don't think votes is something we absolutely must modify.
Finally, keep in mind we can unwrap multiple values in a single if let statement.  I'd prefer to see this code snippet as something more like this:
if let
    pObj = parseObject,
    votes = pObj.objectForKey("votes") as? Int {
        pObj.setObject(votes + 1, forKey: "votes")
        pObj.saveInBackground()
}
delegate?.buttonClicked(self)
loveOutlet.enabled = false

(The actual logic for when to call buttonClicked() and set the outlet disabled may be slightly different, but I wanted to provide you with this example.)


class CommandStorage(object):
    """Stores multi-part commands.

    Performs fast lookups returning the command and any arguments which were
    not part of the command.
    """

    def __init__(self, commands={}):
        self._root = {}
        self._commands = {}

Do you really need to store all the data twice?

        for cmd, func in commands:

That should be commands.items(), guess you've never used the parameter

            self[cmd] = func

    def _lookup(self, line):
        parts = line.split(' ')
        found = None
        found_container = None
        container = self._root
        command_parts = 0
        for i, part in enumerate(parts):
            if part not in container:
                return found_container, found, parts[command_parts:]
            container = container[part]

The recommended way to structure something like this to catch the KeyError, so:

try:
    container = container[part]
except KeyError:
    return found_container, found, parts[command_parts:]
else:
    proceed

As it stands, your code looks up the container[part] twice.

            if None in container:

Using None to store the actual value is counter-intuitive. That's not what None usually means.

                found_container = container
                found = container[None]
                command_parts = i + 1

Having these three pieces of data feels ugly.

        return found_container, found, parts[command_parts:]

I think the problem is your data structure. Your collection of dicts of dicts of dicts is tricky to navigate.

    def __setitem__(self, cmd, func):
        container = self._root
        parts = cmd.split(' ')
        for part in parts:

I'd combine these last two lines

            container = container.setdefault(part, {})
        if None in container:
            raise ValueError('Command %s already exists' % cmd)
        container[None] = func
        self._commands[cmd] = func

    def __getitem__(self, line):
        return self._lookup(line)[1:]

I think this is a bad idea. This function doesn't act like [] typically acts in python. So just make this a regular method

    def __contains__(self, item):
    def __delitem__(self, cmd):
    def __iter__(self):
    def __len__(self):
    def __nonzero__(self):
    def iterkeys(self):
    def iteritems(self):
    def itervalues(self):

You've implemented all these functions to make it act like a dictionary. But its not a dictionary. Unless the object is designed to provide the features of a dictionary, don't attempt to provide the dictionary interface.

    def __repr__(self):
        return '<CommandStorage(%r)>' % self._commands.keys()

Here's how I'd approach it. Don't use nested dicts, just store everything in one dict. __setitem__ becomes trivial:

def __setitem__(self, cmd, func):
    parts = tuple(cmd.split(' '))
    if parts in self._commands:
        raise ValueError('Command %s already exists' % cmd)
    else:
        self._commands[parts] = func

Then, _lookup becomes:

def _lookup(self, line):
    parts = tuple(line.split(' '))
    # start with longest match, work backwards
    # first match found will be longest match
    for index in xrange(len(parts), -1, -1):
        try:
            function = self._commands[parts[:index]]
        except KeyError:
            pass # no match found, try next one
        else:
            break # match, stop search
    else:
        function = None # if all else fails, report None as function

    return function, list(parts[index:])


Add data into lists at runtime, from a database

regarding your concerns.

1) I do not believe this initialization is a problem but if later on it will be a problem, you can always change it to lazy initialization.

2,3) I just paste a similar code that I find more readable and improves your loop when you want to find the parent area.

    public class Data
    {
        public List<Area> Areas = new List<Area>();

        public Data(string[,] areasArray)
        {
            for (int i = 0; i < areasArray.GetLength(0); i++)
            {
                var areaName = areasArray[i, 0];
                var parentAreaName = areasArray[i, 1];

                if (string.IsNullOrEmpty(parentAreaName))
                {
                    Areas.Add(new Area() { Name = areaName });
                }
                else
                {
                    var parentArea = Areas.First(a => a.Name == parentAreaName);
                    parentArea.SubAreas.Add(new Area() { Name = areaName });
                }
            }
        }
    }

You can probably still improve the loop but I guess you will lost readability, so I would leave it like this unless you face a real performance issue.

Regards


Retrieving a thumbnail photo for an ActiveDirectory account

Without changing the code significantly what you need is a seam to insert a different LDAPConnection, and possibly properties. To create the seam for LDAPConnection you've got a couple of different options

Create a class that extends from the current to and overrides getAdConnection()
Constructor inject a LDAPConnectionFactory to the object and use that to replace getAdConnection()

Once you've done one of these you can inject your mock and make some assertions about how the search in being conducted and return a result structure.


Here are some comments.
- If you are only @page as a way to communicate with scarpe_single_page, why not make it a parameter?

def scrape_duty_station
    agent = Mechanize.new
    page = agent.get(web_link)

Avoid extra indent when one of the cases is simpler and can be dealt with easily.

Also, about your ranges. They should really be named constants.

    return scrape_single_page(page.links[5...30]) unless page.links[5].text =~ /^next/i
    arr = [page] + (l_i(page,5)..l_i(page,6)).collect{|i|agent.get(web_link+"/#{i}")}
    arr.each {|p| scrape_single_page p.links[7...31] }
  end

If you are using any statement more than once, it may be worthwhile to facter it out to a function.

  def l_i(page, link)
    page.links[link].href.match(/\d+/).to_s.to_i
  end

Does position have a constructor? If not, it would be nice to create one for it. If yes, it would be better to use it.

  def scrape_single_page(pages)
    pages.each do |p|
      Position.new(p.text,p.href,p.href.match(/\d+/).to_s,
            Station.where(:web_link => self.web_link).first).save
    end
  end


Is this a correct use of the std::cout and std::cin basefields/conversions?

it's safe to say that this is a good example of how I can use different representations in different basefields correctly in C++ ?

I presume you stream manipulators.

  I'm referring to the use of:

std::hex in the std::istringstream case
the use of std::cout.setf() and std::cout.unsetf() in the "output section"

These are examples of stream manipulators:

I would not do this:

#if __cplusplus < 201103L
#include <stdint.h>
#else
#include <cstdint>
#endif

In one version you are putting the functions in the global namespace (stdint.h) the other you are putting the functions in the std namespace. This will cause problems and may give you different results on different compilers.

This seems like you are doing it the hard way:

 if (argc >= 2) {
    switch (argc) {
    case 2:
      std::istringstream(argv[1]) >> std::hex >> bucket["EAX"];
      break;
    case 3:
      std::istringstream(argv[1]) >> std::hex >> bucket["EAX"];
      std::istringstream(argv[2]) >> std::hex >> bucket["EBX"];
      break;
    case 4:
      std::istringstream(argv[1]) >> std::hex >> bucket["EAX"];
      std::istringstream(argv[2]) >> std::hex >> bucket["EBX"];
      std::istringstream(argv[3]) >> std::hex >> bucket["ECX"];
      break;
    case 5:
      std::istringstream(argv[1]) >> std::hex >> bucket["EAX"];
      std::istringstream(argv[2]) >> std::hex >> bucket["EBX"];
      std::istringstream(argv[3]) >> std::hex >> bucket["ECX"];
      std::istringstream(argv[4]) >> std::hex >> bucket["EDX"];
      break;
    default:
      std::cout << "Too many arguments, exiting now\n";
      exit(EXIT_FAILURE);
    }

Why not a loop?

 if (argc < 2 || argc > 4) {/*ERROR MSG AND EXIT*/}

 std::vector<std::string>  mapIndex = { "EAX", "EBX", "ECX", "EDX" };
 for(int loop = 1; loop < argc; ++loop)
 {
     // PS: just using mapIndex to keep it as close to your original
     //     code as possbile. If I had done this from scratch I would
     //     have just put the values into a four element array.

     std::istringstream(argv[loop]) >> std::hex >> bucket[mapIndex[loop-1]];
 }

The use of std::hex in this situation is correct.
It marks the input stream and the next value (if an hex integer) is correctly read.


For the moment, let's ignore is_vowel itself, and just look at the higher level: what we're doing is copying data from some source to some destination, while removing any items that meet some specified criteria.

As it happens, the standard library already has an algorithm to do exactly that: std::remove_copy_if (I know: crappy name; not clear what it really does--but that really is what it does).

So, I will posit that at the top level, this is how we should be carrying out the overall task:

remove_copy_if(some_input, some_output, your_criteria);

In the case of files, we can use istream_iterators for the input and an ostream_iterator for the output, making this something like:

std::ifstream file{"data.txt"};
std::ofstream outfile{"new.txt"};

file >> std::noskipws;

std::istream_iterator<char> in{file}, end;
std::ostream_iterator<char> out{outfile};

std::remove_copy_if(in, end, out, is_vowel);

Looking at is_vowel itself: it can be defined a number of different ways, depending on the degree to which you care about speed vs. space usage. If you care primarily about space, storing the vowels in a string and searching that string (e.g., as suggested by @utnapistim) is a perfectly fine method. Under the circumstances (copying from one file to another) the I/O will almost certainly be (quite a lot) slower than the processing, so this is probably the most sensible approach.

For another possibility, however, let's assume our source and destination were just strings in memory instead, so we wanted to optimize for speed instead. In this case, we might consider a somewhat different approach. One possibility would be an array (or vector) of Booleans, one for each possible char value, specifying whether that character is a vowel. We probably want to wrap this up in a neat little class so we don't need to deal with the details.

class is_vowel {
    bool table[std::numeric_limits<unsigned char>::max()];
    static const char vowels = "aeiouAEIOU";
public:
    // Here we set up our table. We start by initializing everything to `false`
    // then we set the entries that really do represent vowels to true.
    is_vowel() : table(false) {
        for (auto ch : vowels)
            table[ch] = true;
    }

    bool operator()(unsigned char ch) { return table[ch]; }
};

Unfortunately, it's not always easy to decide which sort of approach will be the best for a given circumstance, but such is life sometimes.

There are also a few intermediate points that probably don't make sense for this specific case, but can for similar cases. For example, here we're dealing with such a small number of items (around 10) that searching the string isn't particularly slow. If we had a list of, say, a few hundred items we wanted to remove, searching the whole list every time could get pretty slow--for such cases, we might consider sorting the list of items to remove, and using a binary search.

I'm starting to get into pretty hypothetical areas though, so perhaps I should just stop for now... :-)


Event Dispatching Thread

Since Swing is not thread safe, all Swing UI component creation and modification should be done on the Event Dispatching Thread (EDT).  It isn’t a problem with this program, but you could run into it if you also created (say) a javax.swing.Timer in your initiation.

It is an easy change to create the GUI on the EDT.  Instead of Gui gui = new Gui(); use:

SwingUtilities.invokeLater(Gui::new);

But I Won???

Play a game, with these moves:

 O | X | O
---+---+---
 X |   | X
---+---+---
 O | X | O

And then put the final X in the center.  You win in two directions at once, but because count == 9, the game is a draw?

Separate GUI / Logic

It looks like you tried to separate the GUI from the game logic, but:

TicTacToe still accesses/manipulates JButton objects
TicTacToe shows JOptionPane dialogs

So, it is not separate from the Swing GUI; you could not reuse it in an SWT or JavaFX application.

The TicTacToe class should have functions something like:

bool isValidMove(int x, int y)
void makeMove(int x, int y)
bool isGameOver()
Player getWinner()

and the GUI should convert buttons into x, y locations, display messages, etc

static

Can you play a second game?  No.  There is no way to reset count for a new game.  It would continue to count above 9 with additional moves!

Can you play two games at once?  No!  There is only one board object.  Two simultaneous games would corrupt each other’s board and count variables!

Why are these variables static?  It prevents multiple TicTacToe objects from being created.  If you removed static from the variables, you could start a new game by creating a new TicTacToe object (and resetting the GUI).

Advanced: Also, you could allow the computer to experiment with different moves, and look several moves in the future, ... but only if you could create these extra TicTacToe boards which aren’t the ones being displayed in the UI.

Simplify Logic

            if(count % 2 == 1) {
                button.setText("X");
            }
            if(count % 2 == 0) {
                button.setText("O");
            }

If count % 2 is not 1, it must be 0.  Use an else clause:

            if(count % 2 == 1) {
                button.setText("X");
            } else {
                button.setText("O");
            }

This test is very verbose:

        if(board[0][0] != null && board[0][0].equals(board[1][1]) && board[1][1].equals(board[2][2])) {

Who can win on any turn?  The player that just made a move, of course.  And their symbol is stored in string (a terrible variable name, by the way).

So if the above test was to pass, all the symbols would equal string, so you could write it a little more concisely as:

        if(string.equals(board[0][0]) && string.equals(board[1][1]) && string.equals(board[2][2]) {

If you defined constants (or better, used enum if you are familiar with them):

    public final static String PLAYER_X = "X";
    public final static String PLAYER_O = "O";

and explicitly set the contents of board[][] to either one of those objects, then you could safely test for object identity, instead of equality:

        if(board[0][0] == player && board[1][1] == player && board[2][2] == player) {


Empty Constraint

You do not allow to create an empty list.

cdef AABBList* aabb_list_create(AABB* start):

However, the pop methods don't check against the empty constraint. In fact, when popping the sole node, you end up with an error.

For instance,

 cdef AABB* aabb_list_pop_first(AABBList* lst):
        cdef AABBListItem* item = lst.first
        cdef AABB* box = item.box
        lst.first = item.next     // <- if item.next is NULL
        lst.first.prev = NULL     // <- lst.first will be NULL, and .prev is an error
        free(item)
        lst.length -= 1
        return box

Single Remaining Item after Pop

Furthermore, when after pop a single item remains, it should be set as both first and last on the list.


Filter out unwanted substrings while generating all possible relevant substrings

Use a generative approach

Iterating over all possible permutations and filtering out the invalid ones results in lots of wasted work.  Move the filtering operation earlier so many invalid permutations are not generated in the first place.

For example, permute() contains for i in range(1, slen + 1), but we know that an octet can only be up to 3 digits long.  Change the loop to for i in range(1, min(4, len(s)+1)). Also, if first is not a valid octet skip the recursive call (none will result in a valid address).

Something like this:

def period_partition(s, k):

    def is_valid_octet(s):
        # section ranges 0 - 255 and `00` or `000`, `01` are not valid but 0 is
        return s == '0' or not s.startswith('0') and 0 < int(s) < 256

    if s and k:
        for i in range(1, min(4, len(s)+1)):
            first, rest = s[:i], s[i:]
            if is_valid_octet(first):
                yield from (f"{first}.{p}" for p in period_partition(rest, k-1))

    elif s and is_valid_octet(s):
        yield s

testcases = [
    ("", 1),
    ("1234", 2),
    ("19216811", 3),
    ("192168111234", 3),
    ("192168111234", 4),
    ("19216811123444", 4),
    ("192168111234444", 4),
]

for s, k in testcases:
    print(f"\nperiod_partition({s!r}, {k})")

    for partition in period_partition(s, k):
        print(f"  {partition}")

Note: I modified period_partition() to be a generator yields all valid partitions.  Use list() if you need an actual list.


Are these MySQL Abstraction Classes safe from SQL Injection?  Can they be made safe?

Active record instances are not "models". They are anti-patterns which RoR likes call that way. And what you are implementing there is an active record.

And no, those queries are not safe. They are wide open for SQL injection, because, instead of using proper SQL prepared statements, you opted for concatenation.

As for build building model, you have to understand that model is a layer. One of two in MVC. The other being - presentation layer (made of controllers, views and templates). You might read this answer, but I am no sure how much of it you will be able to assimilate.

I think your first priority should be to read the hashphp PDO tutorial and then watching the list if lecture that you can find a the bottom of this post. And only then try another stab at the whole "mvc thing".


Implementation of a doubly linked list in Java

removeLast() assigns last to temp, which may be null.  If the list is empty, you will call toString() on null.

Otherwise, it is a pretty well made list.

I would change the names of your functions/class.

DoublyLinkList becomes DoublyLinkedList
addFirst becomes pushFront
removeFirst becomes popFront
removeLast becomes popBack
displayList becomes display ( because we know a list is calling it )
displayNode becomes display

As general advise about naming, the words you are using to describe what is happening are good hints at what names the functions/class should be.  For example, you use Doubly Linked List in the title of this post, and you use the word "popped" as output to the remove functions.


I'm not 100% sure how idiomatic this is, but since your data is so structured, it might be worth representing the entire structure as just that: a POD struct that contains the exact sizes and layout desired.

struct Metadata {
    uint64_t serial;
    char _padding_[METADATA_BYTES - 8];
};

struct Segment {
    char bytes[2048];
};

struct Stripe {
    Metadata metadata;
    uint64_t hash_array[512];
    uint32_t size_array[512];
    Segment segment_array[512];
};

(There is probably a better way of doing the padding.)

This means that the layout in memory is exactly the same as the layout on disk, and new Stripe will allocate the appropriate amount of memory with all the components contiguous as desired, without having to do the specific placement yourself. This means you can just allocate the structure, then file.read(stripe, sizeof(Stripe)) and file.write(stripe, sizeof(Stripe)) directly.

You could put a wrapper class around it:

class Stripe {
    Stripe_struct data;

    // methods...
}

Or just convert the original Stripe struct to a class itself.


The first few are probably OK, but you really shouldn't be publishing solutions to Project Euler problems online: don't spoil the fun for others!

This said, there are several things you could consider to improve your code. As you will find if you keep doing Project Euler problems, eventually efficiency becomes paramount. So to get the hang of it, you may want to try and write your program as if being asked for a much, much larger threshold. So some of the pointers I will give you would generally be disregarded as micro optimizations, and rightfully so, but that's the name of the game in Project Euler!

Keeping the general structure of your program, here are a few pointers:

Why start with [0, 1] when they tell you to go with [1, 2]? The performance difference is negligible, but it is also very unnecessary.
You don't really need several of your intermediate variables.
You don't need to pop the last value, just ignore it when summing.
An important thing is that in the Fibonacci sequence even numbers are every third element of the sequence, so you can avoid the divisibility check.

Putting it all together:

import operator

def p2bis(n) :
    fib = [1, 2]
    while fib[-1] < n :
        fib.append(fib[-1] + fib[-2])
    return reduce(operator.add, fib[1:-1:3])

This is some 30% faster than your code, not too much, but the idea of not checking divisibility, but stepping in longer strides over a sequence, is one you want to hold to:

In [4]: %timeit p2(4000000)
10000 loops, best of 3: 64 us per loop

In [5]: %timeit p2bis(4000000)
10000 loops, best of 3: 48.1 us per loop

If you wanted to really streamline things, you could get rid of the list altogether and keep a running sum while building the sequence:

def p2tris(n) :
    a, b, c = 1, 1, 2
    ret = 2
    while c < n :
        a = b + c
        b = c + a
        c = a + b
        ret += c
    return ret - c

This gives a 7x performance boost, not to mention the memory requirements:

In [9]: %timeit p2tris(4000000)
100000 loops, best of 3: 9.21 us per loop

So now you can compute things that were totally unthinkable before:

In [19]: %timeit p2tris(4 * 10**20000)
1 loops, best of 3: 3.49 s per loop

This type of optimization eventually becomes key in solving more advanced problems.