Largest Prime Factor of Number in PHP or QBasic

Finding prime factor is a common problem. Because they are hard to find, prime numbers are used in cryptography. You can read more  here.

Now, in your question, you are looking for the largest prime factor of a huge number $n. Your approach is to test all numbers from 1 to $n. While this is accurate, is is not optimal, as you can see it takes more than 6 hours.

First loop : $n=600851475143 iterations

The first thing I would change is the loop logic : since you are looking for the largest prime factor, begin with $n instead of 1 and exit ($n-$ans iterations) :

for($x = $n; $x >= 1; $x--)
{
    if('$x is factor')
        if('$x is prime')
            break;
}

Then, because you are not looking for $n or 1 or 2 or 3, I would exclude them all ($n-$ans-4 iterations) :

for($x = $n-1; $x > 1; $x--)
{
    if('$x is factor')
        if('$x is prime')
            break;
}

Then, you are looking for a factor $x, such as $x1*$x2 = $n, which implies that if $x2 != 1 && $x2 <= sqrt($n) and $x2 is a factor, $x1 = $n/$x2 is a factor too that is larger than $x2 (sqrt($n)-$n/$ans-1 < 775146 iterations). Note that either or both $x1 and $x2 can be prime. Also note that floor() is because we are working with integers and (int) is for PHP7+ compatibility :

for($x1 = (int)floor(sqrt($n)); $x1 > 3; $x2++)
{
    if('$x1 is not a factor')
        continue;
    $x2 = $n/$x1;
    if('$x1 is prime')
        break;
    if('$x2 is prime')
        break;
}

There are ways to do better but since we switched from 600G to 775K it should be enough.

Second loop : $x/2 iterations

Loops in loops are the first thing to resolve when optimizing code. If you loop from 1 to 1000 in a loop from 1 to 1000, that is 1000000 iterations ; in your case it is a bit more complicated to evaluate but I think it is close to $n*$n/2 = 633457474756096856 iterations (!). with the first loop reviewed, is is close to 775146*775146/2 = 300425660658 iterations = 300G iterations : better but still huge !

First thing to do is to break on the first $y != 1 found, if $x1 is not a prime number you do not need to find all its factors (iterations are hard to evaluate but get in mind that all $x1 with factors of 2 and 3 gets their loop reduced from $x1/2 to 2 or 3) :

for($y = 1; $y < $x1/2; $y++)
{
    if($x1 % $y == 0)
    {
        $first_factor = $y;
        break;
    }
}

Then instead of doing $x1/2 do sqrt($x1) as in the loop 1 optimisations :

$first_factor = null;
for($y = (int)floor(sqrt($x)); $y > 1; $y--)
{
    if($x % $y == 0)
    {
        $first_factor = $y;
        break;
    }
}
if(is_null($first_factor))
{
    $ans = $x;
    break;
}

I personaly won't but you can do a faster prime check implementing first one hundred (or so) prime numbers and testing them for factor of $y first.

Code review

Please use functions, you will have a light performance loss due to internal PHP stack behavior but your code will be much cleaner and reusable (for the next Project Euler problems...).

Adjusting all the code gives you something running under 100ms : https://3v4l.org/jXd3E

function greatest_prime($n)
{
    for($x1 = (int)floor(sqrt($n)); $x1 > 3; $x1--)
    {
        if($n % $x1 != 0)
            continue;
        $x2 = $n/$x1;
        if(is_prime($x1))
            return $x1;
        if(is_prime($x2))
            return $x2;
    }
}
function is_prime($x)
{
    for($y = (int)floor(sqrt($x)); $y > 1; $y--)
        if($x % $y == 0)
            return false;
    return true;
}
var_dump(greatest_prime(600851475143));


Two easy improvements
Check up to the square root of n rather than n/2.  So for 101 you only need to check n up to 10 not 50. If your number isn't prime then 1 of it's factors must be less than it equal to its square root.
Don't check multiples of 2, so do a single test to see if the number can be divided by 2 then only test odd numbers starting at 3.
So if you test 101 for primeness these's changes mean that instead of testing for divisibilty by  2..50 you only test  2,3,5,7,9
Other things to consider
Use the primes below square root n.  So if you know that 2,3,5,7 are the only primes below square root of 101 you only need to test for divisibilty by these numbers to show 101 is prime.
A more complex solution would be to look at a deterministic version of the Miller Rabin test as described here this works well if you just want to know if a specific value is prime.
Most efficient if you want all primes below n would be a prime number sieve


Top Active Answerers on a Stack Exchange site

Dumping some SEDE experience in as well as a SQL review.
SEDE Specific things first
Parameters
SEDE caches the results of a query if it is run with the current data set (caches are cleared when the data is refreshed). If you run the same query twice, the second time will return the cached data. If the query has not been run, then you need to be logged in to refresh the cache. If the query has been run, then you do not need to be logged in to SEDE to see the data. As a consequence, if you share links, you should pre-populate the cache too.
Your query is parametrized, and as a result, you do not have any cached results... BUT.... SEDE parameters are of the form ##Name:Type?Default##. Use this to your advantage. By supplying a default value your query will likely be 'prepopulated'
So, set up your parameters like:

##DaysSinceActivity:int?30##
##NumberOfUsers:int?1000##

That way, people clicking through will have the default values populated, and will possibly get a better experience.
Display Name
In SEDE you can sort the data based on the columns. The [User Link] column does not sort by the name though, it sorts by the URL for the user, which, in essence, does an alphabetic sort of the user-id because that is where the URL starts to change....
Add the Display Name in as a result column as well as the [User Link] so people can sort the data alphabetically.... (because people like to know where they are...).
Ranking
Consider adding a RANK column as well, so people an sort by other columns, and still see their ranking.
SQL
you have already seen inconsistencies in the capitalization of the keywords... You have chosen upper-case, which is fine, but then these should all be upper-case:

and
null
Count
is
etc.

Bug
You supply the last-access date as a parameter, but then you ignore it:
AND Users.LastAccessDate > DateAdd(Day, -31, GetDate())

code it to 31 all the time.... hmmm.


Recursive right-to-left segmenting (tokenizing) of strings in Python

Here are some general comments:

Having a function mutate a global variable is a bad practice. In this case, it may seem easy enough to reason about what is going on, but I guarantee that at some point it will lead to an insidious bug that is hard to track down because you have no idea who is changing the global variable and when.
Recursion is not necessary here; it over-complicates the solution and may make it difficult to change/update the code.

The code itself is rather concise, but the weird data-flow out of the function makes it difficult to understand what's going on. This is complicated because the function is recursive and so you then have to keep track of the calling stack when figuring out how segmented_morphs is being changed.

I don't think the re module is really necessary here, I bet that it is heavier that just searching for strings and doesn't seem to offer any benefit. I've kept it for now, but I might offer another solution without it.

Here's how I would approach the problem:

import re

def segment_word(word, morphs):
    regex = re.compile('(' + '|'.join(morphs) + ')' + '$')
    splitter = lambda s: (regex.split(s) + [None])[:2]

    segments = []
    word, end = splitter(word)
    while end is not None:
        segments.append(end)
        word, end = splitter(word)

    if word:
        segments.append(word)

    return segments[::-1]

def segment_phrase(phrase, morphs):
    return [s for w in phrase.split() for s in segment_word(w, morphs)]

Here's a version without re, I'm not super happy about either. Neither version seems particularly elegant.

def segment_word(word, morphs):
    segments = []
    previous_length = -1
    while len(word) != previous_length:
        previous_length = len(word)
        for morph in morphs:
            if word.endswith(morph):
                segments.append(morph)
                word = word[:-len(morph)]

    if word:
        segments.append(word)

    return segments[::-1]


Selecting form controls that are either inside or outside a rectangle

You can make things more concise with LINQ.  Here's one way that should work:

List<Control> getControls(Control container, Rectangle rect, bool bContained = false)
{
    rect = RectangleToClient(rect);
    return (from Control ctl in container.Controls
                  where rect.IntersectsWith(ctl.Bounds) == bContained
                  select new List<Control> { ctl }.Union(ctl.Controls.OfType<Control>()))
                  .SelectMany(x => x).ToList();
}

This basically does the same thing, filters the collection according to bContained.  Creates a collection of  lists that each contain the parent control and its sub-controls.  Then flattens them into one list.


Compare performance of simple addition on one to many cores

So for my skill level there are some minor recommendations.
So for me Feedback would be a little bit more readable in this form:

let feedback input =
    [   sprintf "you picked %s" input
        "now running" ] |> List.iter Console.WriteLine

There are some brackets that can be reduced, so simple write.

Console.WriteLine "q to quit else continue with keypress"

And finally there is no need to ignore unit, since ignore is a code smell and you actually don not need them so just ignore them.

And that is what I changed it to:

module Program

open System
open System.Diagnostics

[<AutoOpen>]
module timingStuff =
    // no side effects
    let secondsToTicks = (*) (1000L * 10000L)

    let prettyNumbers (x:int) = String.Format("{0:#,0}", x)

    // no side effects if stop has side effect (but here it has)
    let rec addOne x stop =
        let r = x + 1
        if stop() then r
        else addOne r stop

    // with side effects
    let pickRunmode() =
        "choose number of processes to spawn (default 1)" |> Console.WriteLine
        Console.ReadLine()

    let feedback input =
        [   sprintf "you picked %s" input
            "now running" ] |> List.iter Console.WriteLine

    let quitOrContinue() =
        Console.WriteLine "q to quit else continue with keypress"
        Console.ReadKey().KeyChar <> 'q'

    let finished stopticks = fun _ -> Stopwatch.GetTimestamp() >= stopticks

    let printResult result start =
        let final = (Stopwatch.GetTimestamp() - start |> TimeSpan).TotalSeconds
        let pretty = prettyNumbers result
        sprintf "performed %s operations in %f seconds" pretty final |> Console.WriteLine

    let op duration start =
        duration
        |> secondsToTicks
        |> (+) start
        |> finished
        |> addOne 0

    let opAsync duration start procs =
        [ for i in [ 1..procs ] -> async { return op duration start } ]
        |> Async.Parallel
        |> Async.RunSynchronously

[<EntryPoint>]
let main argv =
    let loop _ =
        let input =
            match Int32.TryParse(pickRunmode()) with
            | true, i -> i
            | _ -> 1
        input |> string |> feedback
        let start = Stopwatch.GetTimestamp()
        let result =
            opAsync 1L start input
            |> Seq.sum
        printResult result start

        quitOrContinue()

    while loop() do ()
    0


Converting a string to a list of key-value pairs

First, you can use std::getline to extract key-value pairs from the original string. This can be done by passing , as a delimiter to std::getline:

while (std::getline(iss, token, ',')) { ... }

Notice that you don't have to perform any checks on the stream this way. Once std::getline will reach the end of the stream it will set the eofbit on it, so the loop condition will evaluate to false on next iteration.

Next, use can use std::string::find to find an index of the occurrence of the = character in strings filled by std::getline:

size_t pos = token.find('=');

After that use can use this index to extract two substrings - your key and your value:

flag.name    = token.substr(0, pos);
flag.value   = token.substr(pos + 1);

Notice that you can omit the second argument of std::string::substr, since it has the default value of std::string::npos. This value is very huge (in fact, it equals to the maximum value that can be represented by a size type of std::string), but std::string::substr never reads past the end of line, so everything will be good.

Tie all this together and you'll get a small and readable solution:

std::string input("ab=xy z,time a=1s");
std::istringstream iss(input);

std::vector<Flag_name_value> flags;

std::string token;
Flag_name_value flag;
while (std::getline(iss, token, ',')) {
    size_t pos   = token.find('=');
    flag.name    = token.substr(0, pos);
    flag.value   = token.substr(pos + 1);
    flags.push_back(flag);
}


Grouping consecutive numbers into ranges in Python 3.2

You could use this one-liner to generate groups of consecutive integers in a list:

from itertools import groupby, count

groupby(numberlist, lambda n, c=count(): n-next(c))

Then to finish it off, generate the string from the groups.

def as_range(iterable): # not sure how to do this part elegantly
    l = list(iterable)
    if len(l) > 1:
        return '{0}-{1}'.format(l[0], l[-1])
    else:
        return '{0}'.format(l[0])

','.join(as_range(g) for _, g in groupby(numberlist, key=lambda n, c=count(): n-next(c)))
# '1-3,6-7,10'

This assumes they are in sorted order and there are no duplicates.  If not sorted, add a sorted() call on numberlist beforehand.  If there's duplicates, make it a set beforehand.


STOP. Do not use system("pause"). This is not portable. If you
haven't already, read
this
Stop using using namespace std. Read
this.
I mentioned this in your last review as well.
You don't need to use std::endl for every new line of your output
table. Doing so flushes the output stream needlessly.
You don't need two vectors. Just two for loops and one vector will
suffice. Take a look at the example below.
For beginner code, I think you have good documentation(comments).
Although for some people, it might err on the side of excessive.
You could have initialized the array with the first three primes.
That would have cut down the number of iterations.

 long primes[MAX] = {2,3,5};
 int count(0);             // Count primes found

Example:

#include  <iostream>
#include <vector>
#include <iomanip>

using std::cin;
using std::cout;
using std::endl;
using std::setw;

int  main()
{
    int counter = 0;
    std::vector<int> primes;

    int N, output;
    cin >> N;
    output = N;
    for (int i=2; N > 0; ++i)
    {
        bool  isPrime = true;
        for (int j=0; j < primes.size(); ++j)  //First pass(i==2), will not enter second loop because size() == 0
        {
            if (i % primes[j] ==  0)
            {
                isPrime = false;
                break;
            }
        }

        if (isPrime)
        {
            primes.push_back(i);
            --N;
            cout  <<  i  <<  "\n";
        }
    }

    for(int i=0; i < output; i++)
    {
        if (i % 5 == 0)      // For a new line on first line of output
            cout << "\n";      // and on every fifth line that follows

        cout << setw(10) << primes[i];  // Provide space between numbers
    }
    cout << endl;

    return  0;
}


MemoryStream ms = _Remaining == null ? new MemoryStream() : _Remaining;

This is exactly what the null-coalescing operator is for:

MemoryStream ms = _Remaining ?? new MemoryStream();

int count = await _Process.StandardOutput.BaseStream.ReadAsync(_Buffer, 0, _Buffer.Length);

Why are you using BaseStream? Without it, you could work directly with chars instead of bytes, which saves you having to use Encoding to convert those bytes back to string.

  Is there something I can reliably do to keep from creating new MemoryStreams?

Yes: don't use MemoryStream at all. Instead, I would use StringBuilder, since it allows you to remove characters from its start, which is exactly what you need. As an added advantage, it works with chars, not bytes.

  Is there an entirely better way to do it than using async and await?

Your use of async-await seems reasonable to me. Though I'm not sure it's actually necessary: I think synchronous methods would have worked just as well.


Counting occurrences of a word in a file

Your code is way more complicated that it needs to be. Let's look at it in detail

Scanner scan = new Scanner(System.in);
System.out.println("Please enter the filename: ");
filename = scan.nextLine();
Scanner scan2 = new Scanner(System.in);
System.out.println("Please enter a word: ");
wordname = scan.nextLine();

You're creating 2 Scanner object when you just need one to read both the filename and the word to search. You can reuse the Scanner you already have.

fr = new FileReader(filename);
br = new BufferedReader(fr);

Writing this generally means that something is wrong. You're opening a stream to a resource but, in case there is an exception, they won't be closed: the

fr.close();
br.close();

part of the code won't be reached. This creates a resource leak. Starting with Java 7, you can use a try-with-resources statement so that every opened resource is properly closed, regarless of the outcome (expection or not).

Then,

while((s = br.readLine()) != null){
    stringLine = stringLine + s;
    //System.out.println(s);
    stringLine = stringLine + " ";
    counLine ++;
}

concatenates Strings in a loop, which is a bad practice: Strings are immutable and every time you use + a new object is created each time. Instead, what you want to use is a StringBuilder. But in this case...

stringArray = stringLine.split(" ");
arrayLength = stringArray.length;

You're splitting in an array all the Strings you concatenated before, meaning you did all that work for nothing: you could have just created an array and populate it in the first place.

Now this is what the main loop is doing:

Start at the first word;
Look up a word equal, ignore case, to this word;
If one is found, move all the words after that to the left;
Continue with the second element, until the end of the array

So to put it another way, this is traversing the array as many times as there are elements, which can be a lot. Now imagine if the array is very long, this can take a very long time.

You don't even need to do this: you can just traverse the array a single time and determine if the current element matches your searched word.

This could be a proposed implementation: it uses the built-in LineNumberReader (to match your enhancement), wraps it inside a try-with-resources. Then each line read is split around a space and the words are compared against the word to search.

Sample code:

public static void main(String[] args) throws IOException {
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter the filename: ");
    String filename = scan.nextLine();
    System.out.println("Please enter a word: ");
    String wordname = scan.nextLine();

    int count = 0;
    try (LineNumberReader r = new LineNumberReader(new FileReader(filename))) {
        String line;
        while ((line = r.readLine()) != null) {
            for (String element : line.split(" ")) {
                if (element.equalsIgnoreCase(wordname)) {
                    count++;
                    System.out.println("Word found at line " + r.getLineNumber());
                }
            }
        }
    }
    System.out.println("The word " + wordname + " appears " + count + " times.");
}


i do not think this is really a good idea (sorry to say that)...

why is is not a good idea? it's breaking the concept of segregaton of concerns:

a Logger is responsible for logging
a Profiler is responsible for measuring execution time
a Logger is NOT responsible for keeping track of items (who is responsible for cleaning these entries?)

another issue i see is that you create a new logger whenever you want to write something into you log, i don't see any reason for that...

what would i suggest?

create a timesheet

public class Timesheet{

   private final Map<TimeStamp, KeyValue kv> entries;
   private final Logger logger;

    public Timesheet(Logger logger){
        this.logger = logger
        entries= ...
    }

    public Timesheet kv(Object key, Object value) {
        TimeStamp timestamp = new TimeStamp();
        entries.put(timestamp , new KeyValue(key, value));
        log.debug("adding key/value {}/{} at {}", key, value, timestamp );
        return this;
    }

    public Timesheet msg(Object msg) {
        logger.debug(msg);
        return this;
    }

    public Timesheet elapsed() {
        logger.debug("time elapsed {}", calculateTimeElapsed());
        return this;
    }

}

not all is implemented here, it should just girve you an idea of how you could do it...

Timesheet timesheet = new Timesheet(LoggerFactory.getLogger("jsonLogger")); //now availible for all classes
timesheet.msg("hello");
timesheet.kv("foo", "bar");
Thread.sleep(1234);
timesheet.elapsed();

some final words...

i think it is not a good idea of using KeyValue pairs - if you know what kind of entries these are, give them a proper name!

i think if you would have choosen a more compliant name (Log is really confusing) your idea would not have been so bad...


First of all, you are using a static variable (growthmultipler) inside the instance of a class. This is fatal if you have more than one instance of this class. Because you always use 2*growthmultipler, you don't need it. Use +=2  instead.

You don't need to prealloc data in the constructor. It will be done if it's needed.

You don't need to handle "size == 0" separately. You only have to handle "size >= length".

You don't have to create a new class if you want to grow data.

In pop() you should test to not get negative (and throw an exception). And normally a pop function returns the value.

In summary it might look like this:

public class stackAlist{
    int[] data;
    int size;

    public stackAlist(){
        size = 0;
        data = new int[size];
    }

    public void push(int value){
        if(size>=data.length) {
            int [] ndata = new int[data.length+2];
            System.arraycopy(data, 0, ndata, 0, size);
            data = ndata;
        }
        data[size] = value;
        size += 1;
    }

    public int pop() {
        int ret=0;
        if(size>0) {
            size -= 1;
            ret = data[size];
            data[size] = 0;
        }
        return ret;
    }
    .....


You could try and force the option to be selected.  Because jQuery doesn't throw errors when it doesn't have a set of elements, you can use this to your advantage inside an if statement. Couple this with jQuery's chaining and you can do something like:

function setSelect() {
    var desiredOption = $("#selectVal").val();
    if (desiredOption == '') {
        $("#selectVal").focus();
        return false;
    }
    if (!$('#mySelect option[value="' +desiredOption+ '"]').prop("selected", true).length) {
        alert('No such option');
    }
    $("#selectVal").select();
}

  Updated fiddle: http://jsfiddle.net/SPvrA/7/


Below is my attempt. I wrote generic serialization using Generics and cereal. So all that's needed is to derive Generic and add empty Serialize instances. Function save first writes the type of the value, which is then checked by load. So when loading a list of events, we can check wich ones belong to the given type we want to change and drop all others (deserializeMany).

I dropped Applicable completely. Usually the problem with existential data types is that there is only a limited set of things you can do with them, so you can replace such a data type directly with the action, like a function that acts on a given object ag -> ag. See also my question Why (or why not) are existential types considered bad practice in functional programming?.

I also changed the open class of events for a given type (open in the sense any module can define additional events for an object) to a closed one - every WithEvent instance has exactly one data type that describes its possible events. This makes it somewhat easier to handle, in particular avoids some cumbersome situations where it's necessary to explicitly give types when applying events, and it's also less verbose.

{-# LANGUAGE DeriveDataTypeable, DeriveGeneric, ScopedTypeVariables,
             TypeFamilies, FlexibleContexts #-}
module Test where

import Control.Monad
import qualified Data.ByteString as BS
import Data.Maybe (catMaybes)
import Data.Typeable
import Data.Serialize
import Data.Maybe (catMaybes)
import GHC.Generics

-- * Generic serialization of events

-- ** Generic serialization of classes that know their type

save :: (Serialize a, Typeable a) => a -> Put
save x = put (show $ typeOf x) >> put x

-- | Returns 'Nothing' if the serialized event is of a different type.
-- Note that that's different from parsing error.
load :: forall a . (Serialize a, Typeable a) => Get (Maybe a)
load = do
    t <- get
    if t == show (typeRep (Proxy :: Proxy a))
      then Just <$> get
      else return Nothing -- some other type

serialize :: (Serialize a, Typeable a) => a -> BS.ByteString
serialize = runPut . save

-- | Read given events and returns the ones that apply to @a@.
deserializeMany :: (Serialize a, Typeable a) => [BS.ByteString] -> Either String [a]
deserializeMany = liftM catMaybes . mapM (runGet load)

-- ** WithEvent

class (Serialize (Event a), Typeable (Event a)) => WithEvent a where
    type family Event a
    apply :: Event a -> a -> a

fold :: (WithEvent a) => [Event a] -> a -> a
fold = flip (foldr apply)

-- * Example

-- ** Foo

data Foo = Foo

data SomeOtherEvent = SomeOtherEvent
  deriving (Show, Read, Typeable, Generic)

instance Serialize SomeOtherEvent where

instance WithEvent Foo where
    type Event Foo = SomeOtherEvent
    apply SomeOtherEvent Foo = Foo

-- ** Person

data Person = Person { name :: String, age :: Int }
  deriving Show

data PersonEvent
    = SetName String
    | SetAge Int
  deriving (Show, Read, Typeable, Generic)

instance Serialize PersonEvent where

instance WithEvent Person where
    type Event Person = PersonEvent
    apply (SetName n) p = p { name = n }
    apply (SetAge a) p = p { age = a }

-- ** Tests

nobody :: Person
nobody = Person "" 0

events :: [PersonEvent]
events = [SetName "Mr.Wrong", SetAge 42]

serialized :: [BS.ByteString]
serialized = serialize SomeOtherEvent : map serialize events

person :: Either String Person -- is `Person {name = "Mr.Wrong", age = 42}`
person = flip fold nobody <$> deserializeMany serialized


Based on feedback from JavaScript chat. Credit to @Zirak and @Chris

You want a hash of white listed error messages for each method

var whitelistMap = {
    "get": ["not_found"],
    "insert": ["conflict"],
    "delete": []
}

You want a whitelist error handler factory. This will include the "getaddrinfo" code for every method which is basically a try again short cutting.

It will check whether the error message is in the whitelistMap for that method and if so will let that error through.

otherwise it simply throws

function makeWhitelistCallback(method, thing, cb) {
    return error.whitelist(function _errors(err) {
        if (err.syscall === "getaddrinfo") {
            UserModel[method](thing, cb);
        } else if (whitelistMap[method].indexOf(err.error) !== -1) {
            return true;
        } else {
            return false;
        }
    }, cb);
}

And the rest of the code simply calls the whitelist callback factory

var UserModel = pd.make(Model,{
    get: function _get(id, cb) {
        this.nano.get(id,
            makeWhitelistCallback("get", id, cb)
        );
    },
    insert: function _create(json, cb) {
        this.nano.insert(json, json._id,
            makeWhitelistCallback("insert", json, cb)
        );
    },
    delete: function _delete(name, cb) {
        var that = this;
        this.get(name, function _getRev(err, body) {
            that.nano.destroy(name, body._rev,
                makeWhitelistCallback("delete", name, cb)
            );
        });
    }
});


Test whether or not a 4x4 matrix is a magic square

The size of the matrix is hard-coded all over the place.  You made a good attempt to define const int SIZE = 4 in main(), and you pass SIZE to your functions.  However, you still hard-code int matrix[][4], int row[4], and int column[4] in the function signatures.  In addition, fillMatrix() says "Enter four values for row ".

There are several possible remedies.

The simplest is to #define SIZE 4, and don't bother passing the size around anymore.  It's more of a C-style approach, but at least the size will be centrally defined.
You could store the matrix in a std::array<std::array<int>> (C++11), a std::vector<std::vector<int>>, or a std::valarray<std::valarray<int>>.  Then the helper functions could obtained the dimensions by calling .size().
You could flatten the matrix into a one-dimensional array, and pass the size.
You could define a Matrix class.


I think that one of the pros you listed for style 2 - "Conditional is centralized in one location and not duplicated" is sufficient all by itself to tip the scale to style 2.

Non-duplication of code is a very powerful idea, particularly in a system under development. There is always the possibility that something will change. Duplicated code is very fragile, because of the possibility of overlooking one or more instances. Even if you don't overlook an instance, changing multiple instances of duplicated code is always harder than changing one single instance of non-duplicated code.


Return Set with random unique Integer numbers between min and max range

Generating unique random numbers within a range

A good way to generate unique random numbers within a range is to create a list with the desired unique numbers, and then shuffle it.

  private Set<Integer> getRandomUniqueNumberSet(int min, int max) {
    List<Integer> numbers = IntStream.rangeClosed(min, max).boxed().collect(Collectors.toList());
    Collections.shuffle(numbers);
    return new LinkedHashSet<>(numbers);
  }

Don't used boxed types when you don't need null values

This method takes Integer parameters, which may be null:

private Set<Integer> getRandomUniqueNumberSet(Integer min, Integer max)

But the implementation doesn't handle the case when these values are null.
And it doesn't make sense to support such ranges.
Change those types to primitive int.

The same goes for the local variables Integer index and Boolean loop.

Why ThreadLocalRandom?

As per the javadoc, "use of ThreadLocalRandom is particularly appropriate when multiple tasks use random numbers in parallel in thread pools". I doubt that's necessary in your use case, in which case I suggest to use an instance of Random instead.


You are not compliant with the style guide. For example:

x and a aren't good variable names;
You don't follow the naming convention (e.g. factory should be Factory and workerFunction should be worker_function);
The inline comments should be replaced with docstrings;
Extraneous whitespace (e.g. for i in range( times ): should be for i in range(times):); and
Compound statements (e.g. except EOFError: pass should be on two lines).

The Pythonic replacement for lots of elif clauses is a dictionary. There are numerous ways to implement this, e.g.:

lotteries = {1: {'name': 'Nebraska Pick Three',
                 'func': factory.repeater
                 'args': (3, factory.factoryLogic, [0, 9, 1])},
             ...}

This simplifies the printout at the start:

print("Make a choice: ")
for key in sorted(lotteries):
    print("{0}. {1}".format(key, lotteries[key][name]))

and input validation:

if int(x) not in lotteries:

and the output:

lottery = lotteries[x]
print lottery['func'](*lottery['args'])

If you do want to stick with the current text block, Python does have multiline strings:

s = """Three quote marks
       makes a string
       multiline."""

For help on formatting, see Avoiding Python multiline string indentation.

The class implementation seems pointless - you have an __init__ that does very little (self.a is never referenced again), and two instance methods that don't need any class or instance attributes. If you want an OOP approach, I would be tempted by something like:

class Lottery:

    def __init__(self, rules):
        self.rules = rules

    def draw(self):
        ...

You can then put instances into the dictionary:

lotteries = {1: {'name': 'Nebraska Pick Three',
                 'lottery': Lottery(...)},
             ...}

and the code gets even simpler:

lottery = lotteries[x]['lottery']
lottery.draw()

You will have to come up with a method for representing the different rules. I would suggest having a Boolean for when repeat draws are allowed, rather than a sample, instead of calling a separate method as you do now. Different lotteries could alternatively be subclasses, rather than instances, of Lottery.

Here's an example implementation (note: for Python 3.x):

import random

class Lottery:
    """Simulate a specified lottery."""

    def __init__(self, name, rules):
        """Define the lottery name and draw rules."""
        self.name = name
        self.rules = rules

    def draw(self):
        """Simulate a single draw of the lottery."""
        output = []
        for rule in self.rules:
            output.extend(self._draw_rule(rule))
        return output

    def _draw_rule(self, rule):
        """Helper function to draw a single rule."""
        if rule.get('repeats', False):
            output = [random.randint(rule.get('min', 1), rule['max'])
                      for _ in range(rule.get('picks', 1))]
        else:
            output = random.sample(range(rule.get('min', 1), rule['max']+1),
                                   rule.get('picks', 1))
        return output

lotteries = {1: Lottery('Nebraska Pick Three',
                        [{'picks': 3, 'max': 9, 'repeats': True}]),
             2: Lottery('Nebraska Pick Five',
                        [{'picks': 5, 'max': 38}]),
             3: Lottery('Powerball',
                        [{'picks': 5, 'max': 75}, {'max': 15}])}

def play():
    """Allow the user to choose a lottery and simulate a draw."""
    print("Select a lottery:")
    for key in sorted(lotteries):
        print("{0}: {1.name}".format(key, lotteries[key]))
    while True:
        try:
            choice = int(input("Make a choice: "))
        except ValueError:
            print("Please enter an integer.")
        else:
            if choice in lotteries:
                break
            print("Not a valid choice.")
    print(lotteries[choice].draw())

if __name__ == "__main__":
    play()

And its output:

>>> play()
Select a lottery:
1: Nebraska Pick Three
2: Nebraska Pick Five
3: Powerball
Make a choice: foo
Please enter an integer.
Make a choice: 42
Not a valid choice.
Make a choice: 1
[1, 7, 9]
>>> play()
Select a lottery:
1: Nebraska Pick Three
2: Nebraska Pick Five
3: Powerball
Make a choice: 2
[34, 33, 20, 7, 35]
>>> play()
Select a lottery:
1: Nebraska Pick Three
2: Nebraska Pick Five
3: Powerball
Make a choice: 3
[75, 4, 12, 31, 55, 2]

Here I have used a simple dictionary implementation of the rules, with sensible defaults to minimise the input needed.


Using decorated methods in a subclass of deque to dump its state to a JSON file

I don't think that what you're doing is good style. I think you're adding a lot of extra complexity and places for things to go wrong, or become hard to understand, or whatever. I don't think you lose anything by just making very small methods that call super and your special method. I talk about those options at the bottom of the post.

With that out of the way, I think you can accomplish your goal as written and currently designed much more safely by using descriptors and metaclasses. I don't think this is as good as the methods at the bottom of the post, but to review the code as written here is what I would say.

What you're trying to do is (semi-automatically) change how certain data elements are retrieved and executed when called. To me, this sounds like a descriptor. Descriptors allow you to override how you set, get, or delete an attribute on an object, like so (example taken from above documentation link):

class RevealAccess(object):
    """A data descriptor that sets and returns values
       normally and prints a message logging their access.
    """

    def __init__(self, initval=None, name='var'):
        self.val = initval
        self.name = name

    def __get__(self, obj, objtype):
        print('Retrieving', self.name)
        return self.val

    def __set__(self, obj, val):
        print('Updating', self.name)
        self.val = val

>>> class MyClass(object):
...     x = RevealAccess(10, 'var "x"')
...     y = 5
...
>>> m = MyClass()
>>> m.x
Retrieving var "x"
10
>>> m.x = 20
Updating var "x"
>>> m.x
Retrieving var "x"
20
>>> m.y
5

Note - if there were a way to safely identify the underlying data structure being modified when any of these operations is called, then that is what you should put the descriptor on (as that's what you actually want). Because I don't know of a safe way to do that, I suggest the approach below.

For yours, what you need is a descriptor that auto-calls super for you. Note - it's important to use super to handle cases of multiple-inheritance; as pointed out in the comments, your current implementation will only ever call the deque method directly, instead of taking the time to deal with __mro__. In the implementation below, we:

Use the __get__ method to automatically get the class (objtype) and self (obj) of the instance (not the descriptor). This provides enough information for us to call super().
Use getattr to get the attribute in question from the result of super, and lets us ignore the complexities of __mro__.
Create a wrapper function (don't forget to use functools.wraps) that calls the wrapped function with the appropriate arguments, and then the extra function you specified.
__get__ returns the wrapped function, and now MyClass.<<attr_name>> will be that function

from functools import wraps

class AutoSuperDescriptor(object):
    def __init__(self, attr_name, extra):
        self.attr_name = attr_name
        self.extra = extra

    def __get__(self, obj, objtype):
        wrapped_function = getattr(
            super(objtype, obj), self.attr_name
        )
        extra_bits = self.extra

        @wraps(wrapped_function)
        def wrapper(yourself, *args, **kwargs):
            result = wrapped_function(
                yourself, *args, **kwargs
            )
            extra_bits(yourself)
            return result

        return wrapper

You create your descriptor by providing enough information to find the overwritten attribute, as well as the function we want to add on to the end. For example, you might do this:

class FileMirroredDeque(deque):
    append = AutoSuperDescriptor("append", updates_file)

If that meets your needs, then you're done.

But wait, there's more

It's pretty tedious and error-prone to do this by hand for each method you want to apply this to. Wouldn't it be nice if there was a way to just tie into the creation of a class and have it do this for us?

There is, and the answer is metaclasses. Metaclasses are a really complex, and really powerful, tool in the Python toolbox. Anytime you find yourself using them you should think really, really whether that is the best way to do it. I don't think this is one of those times (see start of this answer), but if you wanted to do that, I think we'd have to do something like this:

Define a way to identify the elements that should be overridden at class initialization.
Define a way to identify what extra behavior needs to be added to them.
Add the behavior.

The third one is easy - we implemented it with our descriptor up above.

The first two are a little more complicated, and have a few options. We could choose between adding kwargs to the class initialization:

class FileMirroredDeque(
    deque,
    metaclass=SuperChargerMetaclass,
    methods_to_supercharge = [""],
    method_to_supercharge_with = "method_name"
):

I think this would get clunky and obscure things. Instead, I'm going to propose that we define a special attribute (I used the __<<name>>__ naming convention, which is a no-no, but I thought made it clearer for demonstrative purposes) to list the attributes to override, and then set an attribute on the extra method itself to find it. The final implementation of the class looks like so:

def supercharger(func):
    func.__is_supercharger = True
    return func

class FileMirroredDeque(
    deque, metaclass=SuperChargerMetaClass
):
    __supercharge__ = [
        "__delitem__",
        "__iadd__",
        "__imul__",
        "__setitem__",
        "append",
        "appendleft",
        "extend",
        "extendleft",
        "insert",
        "pop",
        "popleft",
        "remove",
        "reverse",
        "rotate",
    ]

    @supercharger
    def _update_file(self):
        with open(self.path, "w") as f:
            json.dump(list(self), f, indent=self._indent)

    def __init__(
        self,
        cache_path,
        maxlen=None,
        clean=False,
        file_indent=None,
    ):
        super().__init__((), maxlen)

        self.path = cache_path
        self._indent = file_indent
        self._bak_file = None

        if clean:
            self._update_file()  # Overwrite contents of file.
            return  # Don't import data from file.

        with open(
            self.path, "a+"
        ) as f:  # Creates file if it doesn't exist
            f.seek(
                0, 0
            )  # Seek back to beginning of file for json decode.
            contents = f.read()

        try:
            contents = json.loads(contents or "[]")
            self.extend(
                contents
            )  # initializes internal list with persistent data or empty list.

        except json.decoder.JSONDecodeError:
            new_file = (
                os.path.basename(self.path)
                + datetime.datetime.utcnow().strftime(
                    "_%Y_%m_%d_%H_%M_%S"
                )
                + ".bak"
            )

            new_path = os.path.join(
                os.path.dirname(self.path), new_file
            )

            print(
                f"File: {self.path} was not valid JSON. It will be copied to {new_path} and a new "
                f"file will be created."
            )

            shutil.copyfile(self.path, new_path)
            self._bak_file = new_path

But how do we actually get this to happen? Like so!

class SuperChargerMetaClass(type):
    _SUPERCHARGER_ATTRNAME = "__supercharge__"

    @classmethod
    def _get_supercharger(cls, klass_attrs):
        return next(
            method
            for name, method in klass_attrs.items()
            if getattr(method, "__is_supercharger", False)
        )

    def __init__(cls, name, bases, attrs):
        supercharger = cls._get_supercharger(attrs)
        superchargees = attrs.get(
            cls._SUPERCHARGER_ATTRNAME, ()
        )

        for method_to_supercharge in superchargees:

            attrs[
                method_to_supercharge
            ] = AutoSuperDescriptor(
                method_to_supercharge, supercharger
            )

        return super().__init__(name, bases, attrs)

In the __init__ method (__new__ would probably work too, but I ended up getting this to work as __init__ so I left it), we get the "supercharger" method to append to our functions, and our list of "superchargees" that need the behavior added to them. From there, its just a matter of making the relevant attribute look to our descriptor instead of whatever (if anything) was there before.

Despite being personally proud of coming up with that, I still feel pretty strongly that its the wrong way to go. As such, I wanted to show how easy this would be. For example, if you inherit from deque:

class FileMirroredDeque(deque):

    # _update_file and __init__ unchanged

    def __delitem__(self, idx):
        super().__delitem__(idx)
        self._update_file()

    # Same for each method

If you don't actually want inheritance, or want to deal with multiple inheritance, then you could just use composition instead, like so:

class FileMirroredDeque:

    def __init__(self, cache_path, maxlen=None, clean=False, file_indent=None):
        # Only addition to __init__
        self.data = deque((), maxlen)

        # Any references to self with the intent of hitting the deque should now reference self.data

    def __delitem__(self, idx):
        self.data.__delitem__(idx)
        self._update_file()

    # Same for each method

We can actually take that a step further then, by creating a generic descriptor that handles file mirroring any arbitrary collection, like so:

class FileMirroredCollection:

    # This is virtually identical to your previous __init__
    def __init__(self, collection, cache_path, clean=False, file_indent=None):
        self.collection = collection
        self.path = cache_path
        self._indent = file_indent
        self._bak_file = None

        if clean:
            self._update_file()  # Overwrite contents of file.
            return  # Don't import data from file.

        with open(self.path, 'a+') as f:  # Creates file if it doesn't exist
            f.seek(0, 0)  # Seek back to beginning of file for json decode.
            contents = f.read()

        try:
            # You'd need to have some intelligent way to extend the arbitrary collection; duck typing is your friend here
            self.collection.extend(json.loads(contents or "[]"))  # initializes internal list with persistent data or empty list.

        except json.decoder.JSONDecodeError:
            new_file = os.path.basename(self.path) \
                       + datetime.datetime.utcnow().strftime("_%Y_%m_%d_%H_%M_%S") + ".bak"

            new_path = os.path.join(os.path.dirname(self.path), new_file)

            logger.warning(f"File: {self.path} was not valid JSON. It will be copied to {new_path} and a new "
                           f"file will be created.")

            shutil.copyfile(self.path, new_path)
            self._bak_file = new_path

    def _update_file(self):
        with open(self.path, 'w') as f:
            json.dump(list(self.collection), f, indent=self._indent)

    def __get__(self, obj, objtype):
        self._update_file()
        return self.collection

    def __set__(self, obj, value):
        self.collection = value
        self._update_file()

    def __delete__(self, obj):
        del self.collection
        self._update_file()

class FileMirroredDeque:

    def __init__(self, cache_path, clean=False, file_indent=None, max_len=None):
        self.data = FileMirroredCollection(deque((), max_len), cache_path, clean, file_indent)

        # other stuff

This still needs a bit more work (e.g. this doesn't handle self.data.append very well), but you can see how it might be useful to separate your concerns.

Lastly, there are a few other miscellaneous improvements that might benefit you, including:

Support for more formats - json is nice, but what if I want to serialize it another way?
Not writing to file every time; this will be inefficient if you have lots of small changes. Potentially include a flush method, or some way to identify that you need to write any recent changes.
As I allude to with the generic descriptor approach, supporting other data structures could be good - you might not want a deque forever, and as-is you're pretty locked down.


Your use of goto is wholly unjustified, not just because goto is taboo, but because your code has flow-of-control that is hard to follow.  Furthermore, the use of goto is not even an effective way to achieve your goal of compactness.

Before addressing the core concern about goto, I'd like to point out that there is a lot of junk in your code:

Your compiler should have warned you:

beehive.cpp:12:11: warning: unused variable 'val' [-Wunused-variable]
    lld n,val;
          ^
1 warning generated.

You do compile with warnings enabled, right?
#include <iostream> and #include <cstring> are superfluous.  (Put the remaining ones in alphabetical order.)
using namespace std; is superfluous, and even if you used anything in the std namespace, a blanket import like that is a harmful habit.
The debug flag is unused.
typedef unsigned long long int llu; is never used.  Furthermore, the problem guarantees 1 ≤ n ≤ 109, so a long would be sufficient for n.

As you suspected, a function call would help.  Your main() should look like this:

int main() {
    long n;
    while ((1 == scanf("%ld", &n)) && (-1 != n)) {
        puts(is_beehive_number(n) ? "Y" : "N");
    }
    return 0;
}

That provides two very important improvements over your code:

You can see at a glance what the purpose and structure of your program are.  The clutter within the loop is all gone, replaced by a function whose purpose is obvious.  The loop is properly structured — the phony while (true) is replaced by a useful test.
There is now proper separation of concerns.  main() loops, reads the input cases, and prints the results.  Most importantly, the is_beehive_number() is a pure calculation function that accepts a long and returns a bool.

When the calculation code is in its own function rather than embedded in the loop, the flow of control can be expressed so much better!

bool is_beehive_number(long n) {
    if (--n % 3 != 0) return false;
    double sq = sqrt(4 * (n / 3) + 1);
    if (sq != (long)sq) return false;
    n = sq;
    return (n & 1);
}

I don't understand the mathematics behind your code; I just transformed the code mechanically.


Upgrade Firefox Quantum with logging and version check

To sudo or not to sudo

  I'm also wondering if it's better to only run the commands that need it with sudo or if I should rerun the whole script as sudo after prompting for the password like this:

if [[ "$EUID" != 0 ]]; then
    warning "Please run as root"
    sudo "$0" "$@"
fi

Can the script do its job without root permissions? This script cannot, because it wants to modify files that are normally only editable by root, such as /opt and /usr/bin. Therefore, the script requires root permissions. A good way to handle this is to check if the user has root permission, and exit if that's not the case, for example:

if [[ "$EUID" != 0 ]]; then
    warning "Please run as root"
    exit 1
fi

There's really no need to include the complexity of getting root permission in the script. With the above simple check, the user can either switch to the root user, or rerun the script with sudo. The rest of the script can assume the privilege (and responsibility) of root.

About logging

  I first wanted to save the logs to a log file at "$HOME/.logs/ffupgrade.log", but I'm not sure whether that is good practice or whether I should log to syslog.

I don't really know. But I can reason about it.

Does this really belong to syslog? The script upgrades Firefox. Let's look at something similar, for example, what happens when you upgrade software using the standard package manager of a Linux system. I just upgraded something in a Debian system I have at hand, and it didn't log anything about it in syslog. It may be relevant whether the upgrade is happening on explicit user action or automatically. I would conclude that when a user upgrades a package manually, it's not noteworthy enough to add to syslog.

On the other hand, what happens if you keep logging to ~/.logs? It accumulates forever without cleanup. You might want to log somewhere else that is subject to log a rotation policy in your systems by default, or document how to set it up in the script. This could be a valid argument, except that I doubt your Firefox upgrade logs will ever accumulate to anything significant. So... I would not bother about rotation. If the script is only going to run as root, then I would log somewhere more visible than ~/.logs, let's say /var/log.

  When logging to a file, I would add another variable logfile at the beginning and adapt the functions like so (similarly for success and warning)

I would add a logger function to encapsulate that logic, overriding the logger program, and then you won't need to touch the other functions.

Use local for local variables

It's good to use local for local variables in functions to avoid setting values in the global scope, which can be a source of nasty errors.

Double quote variables used on the command line

$fflink here should be enclosed in double-quotes:

ffinstalled_version="$($fflink --version | sed 's/[^0-9]*//g')"

Comparing versions

I have a doubt about comparing versions.
The script removes all non-numeric characters, and then compares values lexicographically.
Are you sure that will work reliably?
It would have been good to include some example versions in comments, to help assure readers.

Also, to remove non-numeric characters, I would use tr -cd 0-9 instead of sed 's/[^0-9]*//g'.

Verify exit codes

The script does some things, and tells some things to the user that might not be true, for example here:

sudo chmod 755 "$ffbin"
success "permissions set"
sudo ln -s "$ffbin/firefox" "$fflink"
success "symlink created"
sudo rm "/opt/$fffile"
success "tarball removed from /opt"
success "Firefox was upgraded"

Even if those commands fail, the script will print success messages, and happily carry on.

Use better variable names

What is vind?

Use verbose mode more

I would add -v to all interesting commands that support it, for example rm, mv.

Replace 1>&2 with >&2

The default file descriptor redirected is 1, no need to spell it out explicitly.

Simple is better than complex

[ $# != 1 ] is probably more natural and therefore easier to understand than [ $# -ne 1 ].


The first simplification is for the Required check. All you need to do here is check that the value is not null, you don't care about the type. Then you can do the type-specific check later. So remove the outermost if...else and simply have:

if (validationField.Requiered && DBNull.Value.Equals(validationField.Name]))
    return false;

The next section is a bit more difficult. However, one approach would be something like:

var dataString = dataRow[validationField.Name].ToString();
return dataString == Convert.ChangeType(dataString, validationField.Type).ToString();

What we're doing here is using .NET's Convert.ChangeType method to change from the string to your desired primative type. Then, if the string representation of the converted item exactly matches the original string, we say that the string must exactly represent the converted item, meaning it is of the correct data type. You may want to also pass in an IFormatProvider for additional safety.

Putting those two code blocks together would pretty much give you your full method. You may need one additional check for the max length of a string though.

Other than the above alternatives, your code mostly looks good. One thing I'd do is scrap the result variable, and return directly from inside your if statements. The this. prefixes are also unnecessary for PascalCased method names.

As a more general design note, it might be preferable to do this validation at a different point in your process. For example, DataColumns can be set to require a particular Type, and can also be told whether or not to accept null values using the AllowDBNull property, meaning the table will largely do this validation for you.


Reading a text file, need help cleaning exception handling

First off, in Java 7 all of this is obsolete if you use 'try with resources'

NavigableSet<String> dictionary = new TreeSet<>();
try (BufferedReader br = new BufferedReader(new FileReader("/Users/ameya.patil/Desktop/text.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        dictionary.add(line.split(":")[0]);
    }
} catch (Exception e) {
    throw new RuntimeException("Error while reading dictionary");
}

If you have to work on an earlier JDK consider these points :

Both snippets you supply are not exactly equivalent. i.e. if closing the file fails, the first snippet will throw a RuntimeException wrapping the exception of the close(). The second snippet will throw a RuntimeException wrapping the original exception.

Again in SE 7 using the try with resources you'll be able to see both exceptions :  the original exception is thrown and it has the exception upon close() attached as a suppressed exception.

So I think style is irrelevant, you want the original exception (which may even not be related to I/O). If you can use SE 7, use that, otherwise go for snippet 2 (add logging for the exception on close())


Making a dynamic parser to collect data from a javascript enabled webpage

One of the potential disadvantages of HTML-parsing vs interacting with the page via Selenium API is that you would not be able to examine the current state of the page - e.g. determine which elements are visible, get only visible text of an element, click buttons and links, execute JavaScript. In other words, you would miss all the dynamic behaviors.

But, on the other hand, every selenium command is an HTTP request - JSON over HTTP which introduces tons of overhead. And, if your page is completely loaded and you just need to only extract the data itself, then it does make perfect sense to avoid going through selenium API.

I would only fix a couple of things in your current implementation:

I don't particularly like the ___3OWY9 and ___3BmxE in the class names - these parts look dynamically generated and it feels like this can change. I would use a CSS selector and a partial match on a class attribute:

With post.querySelector("[class^=ProductPrice__promo_price]")

and

With post.querySelector("[class^=ProductPrice__price]")

and I would also use a CSS selector for getting the product description:

With post.querySelector("h4 > a")

Note that querySelector would return a single element - hence, you would not need (0) part after the item.


Performance of the String searching algorithm

int i;
    for(i=1;i<pattern.length();)
    {
        if(pattern.charAt(i)==pattern.charAt(index))
        {
            lsp[i]=lsp[index]+1;
            i++;
            index++;
        }
        else
        {
            if(index!=0)
            {
                index=lsp[i-1];
            }
            else
            {
                lsp[i]=0;
                i++;
            }
        }
    }

That's a while loop. There's no need to use for here.

    int i = 1;
    while(i<pattern.length())
    {
        if(pattern.charAt(i)==pattern.charAt(index))
        {
            lsp[i]=lsp[index]+1;
            i++;
            index++;
        }
        else
        {
            if(index!=0)
            {
                index=lsp[i-1];
            }
            else
            {
                lsp[i]=0;
                i++;
            }
        }
    }

You might want to use more descriptive variables in your code, because I have the hardest time trying to understand what lsp is. The i and j variables aren't helping either: are you traversing two collections? In what way?

Your class names are weird, what does Gogl mean?

More descriptive variables and classnames will help you when you view your code at a later point in time. If you don't feel like explaining the algorithm in code, at least put the name of the algorithm together with a link as a comment in the code.


Copying data from a table into a two-dimensional array

If you need an object[,] your code is as good as i can see it being since a data table is an object[][] at its base (After digging through several different data structures that make up the DataTable.  DataTable has DataRow[] which has DataColumn[] leading to an object[][] after boxing and pulling the actual data value).

Converting between the array structures will require code and while you may be able to do it with linq it would not be as readable as nested for loops (My personal opinion only).

The only enhancements I would suggest would be to store the row and column counts and limit the size of the array to the actual data size. This means you would not have data.Data.Tables[0].X.Count in multiple places and if you found a better way to figure out the counts would only need to change it in 2 places, one for the rows and one for the columns.

int rowCount = data.Data.Tables[0].Rows.Count;
int columnCount = data.Data.Tables[0].Columns.Count;

object[,] arr = new object[rowCount, columnCount];

for (int i = 0; i < rowCount; i++)
{
    for (int j = 0; j < columnCount; j++)
    {
        arr[i, j] = data.Data.Tables[0].Rows[i][j];
    }
}

You could use a foreach loop on the Row.ItemArray and maintain the count but I dont think it would be any faster


For something easy to read and maintain I'd use set_difference and set_intersection which would work well on sorted ranges with no duplicates:
std::set_intersection(a.begin(), a.end(), b.begin(), b.end(), std::back_inserter(both));

only_a.reserve(a.size() - both.size());
std::set_difference(a.begin(), a.end(), b.begin(), b.end(), std::back_inserter(only_a));

only_b.reserve(b.size() - both.size());
std::set_difference(b.begin(), b.end(), a.begin(), a.end(), std::back_inserter(only_b));

...but that requires that you iterate over the ranges three times, and I think you are looking for something more efficient.
First, I would not start by copying a and b into only_a and only_b respectively. Instead, take inspiration from the example implementations for the standard functions I linked to above and create your own similar algorithm. This requires that Ts can be compared with operator<:
#include <algorithm>
#include <iterator>

template <class T>
void decompose(std::vector<T>& a,
               std::vector<T>& b,
               std::vector<T>& only_a,
               std::vector<T>& only_b,
               std::vector<T>& both)
{
    // Sort the input or require the input to be sorted like some algorithms do
    // If you'd like the input to be unchanged, make a and b const and make
    // copies of them instead and sort those copies.
    std::sort(a.begin(), a.end());
    std::sort(b.begin(), b.end());

    // clear destination vectors or skip this if you want to append instead
    only_a.clear();
    only_b.clear();

    // the actual algorithm - loop for as long as both vectors have elements

    auto ait = a.begin();
    auto bit = b.begin();

    while(ait != a.end() && bit != b.end()) {
        if(*ait < *bit) {
            only_a.push_back(*ait++);  // can only be in a
        } else if(*bit < *ait) {
            only_b.push_back(*bit++);  // can only be in b
        } else {
            both.push_back(*ait++);    // must be in both
            ++bit;
        }
    }

    // Add the remaining elements if not both ait and bit have reached their end()
    if(ait != a.end()) std::copy(ait, a.end(), std::back_inserter(only_a));
    else if(bit != b.end()) std::copy(bit, b.end(), std::back_inserter(only_b));
}

Or make it even more generic and let it work with iterators only and add the possibility for the user to supply a Compare functor. This do require the ranges to be sorted in the same order as they would be if the Compare functor was used with std::sort on the ranges. The default Compare functor is here std::less<> that, if not specialized for the type involved, uses operator< to compare the elements.
#include <functional> // less
#include <iterator>   // iterator_traits

template <
    class First1, class Last1, class First2, class Last2,
    class OnlyAinserter, class OnlyBinserter, class BothInserter,
    class Comp = std::less<typename std::iterator_traits<First1>::value_type>
    // class Comp = std::less<> // <- is sufficient in C++14 and forward
>
void decompose(First1 ait, Last1 aend, First2 bit, Last2 bend,
               OnlyAinserter onlyait, OnlyBinserter onlybit, BothInserter bothit,
               Comp comp = Comp{})
{
    // loop for as long as both vectors have elements
    while(ait != aend && bit != bend) {
        if(comp(*ait, *bit)) {
            *onlyait++ = *ait++;  // can only be in a
        } else if(comp(*bit, *ait)) {
            *onlybit++ = *bit++;  // can only be in b
        } else {
            *bothit++ = *ait++;   // must be in both
            ++bit;
        }
    }

    // Add the remaining elements if not both ait and bit have reached aend/bend
    if(ait != aend) std::copy(ait, aend, onlyait);
    else if(bit != bend) std::copy(bit, bend, onlybit);
}

Which can then be called like this using the default Compare functor:
decompose(a.begin(), a.end(), b.begin(), b.end(),
    std::back_inserter(only_a), std::back_inserter(only_b), std::back_inserter(both));

Or like below, supplying a Compare functor. In this example the ranges are required to be sorted in descending order:
decompose(a.begin(), a.end(), b.begin(), b.end(),
    std::back_inserter(only_a), std::back_inserter(only_b), std::back_inserter(both),
    [](auto& A, auto& B) { return A > B; } // std::greater<>
);


Your script is vulnerable to a header-splitting attack.  Due to the poor design of PHP's mail() function, it is actually quite easy to introduce that kind of security hole.

In summary, if…

any part of the mail headers consists of user-supplied input,
and you didn't make any effort to prohibit newlines or escape that input,

then you will have a program that can send mail to any recipient of the attacker's choice.

Validation problems

As @EmanuelePaolini points out, you do make an attempt to validate $_POST['email']:

$email = check_input($_POST['email'],"Email address is required.");
# …

if (!preg_match("/([\w\-]+\@[\w\-]+.[\w\-]+)/",$email))
{
    show_error("E-mail address is not valid.");
}

However, the regular expression is not anchored with ^ and $ at each end.  Therefore, the code confirms that $_POST['email'] contains an e-mail address, but it fails to enforce that it contains nothing but a single e-mail address.

On the other hand, the regular expression is also too strict: it rejects many valid characters that can legally appear in an e-mail address.  Read RFC 5322 Sec 3.4 for the specification, or this summary of the older RFC 822 standard.


Find the nth term of a sequence that consists of Fibonacci and prime numbers interleaved

You could use a few tricks to implement the two sequences more efficiently, but the short version of my answer is that most significant performance improvements you could make involve some relatively advanced math, and the smaller improvements do more to improve your code's readability than its performance.

Useful improvements to prime

If you keep a list of the primes you find, you only need to check if those divide the new numbers you are checking, rather than checking every number up to the number you are looking at.

You could also skip over even numbers in the outer loop (use range(3, max, 2)), thus avoiding checking even numbers that you can be sure aren't prime (you would need to add a special case for 2).

The inner loop (j) can stop at i/2, because no number can be evenly divided by a number more than half its size. Similarly, you can stop the loop at when you pass the square root of n, but you would have to implement that by squaring the factors because sqrt is limited by the inaccuracy of floating-point numbers.

Using all of these suggestions, the code might look a little like this:

def nth_prime(n):
    if n == 1:
        return 2
    primes = [2]
    for candidate_prime in range(3, MAX, 2):
        for p in primes:
            if (p ** 2 > candidate_prime):
                break # candidate is prime
            if (candidate_prime % p == 0)
                break # p divides candidate; candidate is not prime
        if no primes divided candidate_prime:
            primes.append(candidate_prime)
            if len(primes) == n:
                return candidate_prime

Additional optimizations for determining whether a number is prime are discussed on the Wikipedia page on the subject.

These improvements will only start to have noticeable effects when you start looking at very large primes, so you might also want to use itertools.count to look at all numbers instead of stopping at 100.

(If you really want to stop at 100, you could also just make a list of the prime numbers up to 100 and index that for maximum efficiency.)

Links to mathematical solutions

To really improve efficiency, this answer suggests the solution in this blog post, but this is probably overkill unless you really want to be able to calculate very large fibonacci numbers very fast (I can't tell that there's a delay in your function until somewhere far above n=10000).

This question goes into depth about how to find the nth prime number, but the final point is important to note:

  tl;dr: Finding the nth prime can be efficiently done, but the more efficient you want it, the more mathematics is involved.

Other suggestions

The following suggestions aren't really about efficiency (if they change the efficiency of your code, the difference will be immeasurably small), but they might make your code a little cleaner.

In the loop you're using for the Fibonacci sequence, you can just write t1, t2 = t2, t1 + t2 to update both values in one line.
When creating the nth Fibonacci number, you can just loop over range(n); there's no need to adjust the ends of the loop. And if you're not using the index i in that loop, Python convention is call it _, so you end up with for _ in range(n).
Using Python's less-than-well-known for/else feature might let you eliminate the flag variable. If you put an else block after a loop in Python, it will run only if you do not break out of the loop, which allows you to avoid flag variables.

for i in some_list:
    if condition(i):
        break
else:
   do_this_if_condition_was_never_true()


Can I accomplish this task without using so many foreach loops?

Depends.

If you want to stick with database-agnostic abstraction such as Doctrine, there is no way to avoid loops.

But if you want an efficient solution, you can write a database-specific query to copy all records in a single query. For example, for mysql it would be something like

INSERT INTO invitation (field1, field2, status, talker)
  SELECT field1, field2, ?, ? FROM talker

and then bind $status and $talker to this query.


A key problem is that this code only returns the kind of poker hand.  Given that subsequent code will need to compare hands, like which straight is better, it makes sense that this code not only rate the kind of hand, but also provide info like top card in a straight, or rank of the cards that make up 2-pairs.
Inconsistent use of magic numbers and macros.  Why MAXTYPES and then 12.

//int type[MAXTYPES] = { [0 ... 12] = 0 }, *types ;
int type[MAXTYPES] = { 0 };

Recommend to avoid declaring variables of different types on the same line.  Instead consider initializing as part of the declaration

// int type[MAXTYPES] = { [0 ... 12] = 0 }, *types ;
// types = count_types( sorted, type );
int type[MAXTYPES] = { [0 ... 12] = 0 };
int *types = count_types( sorted, type );

Odd to use a enum for the suits and then magic numbers for return codes

    switch (hand[i].nSuit) {
        case spades:    suits[0]++; break;
        ...
        else return 9;

Flush code can be simplified.  Only need to check if the cards all have the same suit as the first.  Similar code can be used to determine a straight with sorted cards

bool flushsuit = true;
for (int i = 1; i < MAXHAND; ++i) {
  if (hand[0].nSuit != hand[i].nSuit) {
    flushsuit = false;
    break;
  }
}

The redundant code for check of pairs, 3-of-a-kind, etc. can also be simplified.  Given their similarities, consider combining code

#define RANK 13

group[MAXHAND+1] = { 0 };
rankcount[RANK] = { 0 };
for (int i = 0; i < MAXHAND; ++i) {
  int rank = hand[i].nType;
  rankcount[rank]++;
  group[rankcount[rank]]++;
}

if (group[5]) return five_of_a_kind;
if (group[4]) return four_of_a_kind;
if (group[3] && group[2] > 1) return full_house;
if (group[3]) return three_of_a_kind;
if (group[2] > 1) return two_pair;
if (group[2]) return pair

Functions that do not change pointed-to objects, use const

 // int checkhand (struct Card_s * hand);
 int checkhand (const struct Card_s * hand);

To determine if the hand is a straight, without sorting, consider a bit array:

unsigned ranks = 0;
for (int i = 0; i < MAXHAND; ++i) {
  int rank = hand[i].nType;
  ranks |= 1u << rank;
}

// Replicate lo_ace as hi_ace
ranks |= (ranks & ACE) << RANK;

#define FIVE_IN_A_ROW 0x1F
bool IsStraight = false;
while (ranks) {
  if (ranks & FIVE_IN_A_ROW == FIVE_IN_A_ROW) {
    IsStraight = true;
    break;
  }
  ranks >>= 1;
}


I played around with this for a good half hour without any luck. I was consistently getting ~57 seconds on my crappy M3 laptop.

As a last ditch effort though, I changed

(->> abundants
     (filter #(< % num))
     set)

to

(->> abundants
     (filterv #(< % num)) ; Note the v
     set)

And got it down to 25 seconds! Since you seem to be using a faster computer than me, you'll likely get an even lower time.

Why does this cause such a dramatic change? ¯\_(ツ)_/¯. filterv is strict while filter is lazy, but I have no idea why that makes such a difference here. I would have expected it to be slower since the strict filtering would require a full iteration on its own, then the adding to the set would require another full iteration. Apparently something else is going on. I'll update this answer if I think of what may be happening.

I cleaned up the code a bit too, although none of the other changes made any performance impact. These are mostly just personal stylistic and practice recommendations. See the comments:

(def lower-limit 12) ; Defining these so they aren't magic,
(def upper-limit 28123) ; especially since upper-limit is used in two places

(defn sum-div [num]
  (->> (range 2 (inc (int (Math/ceil (Math/sqrt num)))))
       (filter #(= (mod num %) 0))
       (map (fn [x]
              (let [d (/ num x)]
                (if (= x d)
                  x
                  [x d]))))
       (flatten) ; I personally prefer wrapping for consistency
       (distinct)
       (apply +) ; apply is generally regarded as more idiomatic for summing
       (inc))) ; Use inc instead of (+ 1)

(def abundants
  (->> (range lower-limit upper-limit)
       (map #(vector % (sum-div %)))
       (filter #(> (second %) (first %)))
       (map first)
       (set)))

(defn is-sum-of-two-abundants?
  [num]
  (let [sub-ab (->> abundants
                    (filterv #(< % num))
                    (set))]
    (some (fn [ab]
            (sub-ab (- num ab)))
          sub-ab)))

(time
  (->> (range (inc upper-limit)) ; Use upper limit
       (remove is-sum-of-two-abundants?) ; remove is literally equal to (filter (complement ...))
       (apply +)))

"Elapsed time: 26714.867469 msecs"
=> 4179871


Wrap a js function with a fixed this arg

is there a better way to achieve this functionality?

You can use Function.bind() to create a function with the this context bound to Wyg.Editor:

const node = document.getElementById('myFavoriteNode');
node.addEventListener('click', Wyg.Editor.nodeClickedEvent.bind(Wyg.Editor));

See this demonstrated in the snippet below.

Notice that const was used instead of let - unless there is a reason to re-assign node, use const. This will avoid accidental re-assignment.

const Wyg = {};
Wyg.Editor = class {

    static nodeClickedEvent(event){
        const clickedNode = event.target;
        console.log('nodeClickedEvent() - this: ', this);

    }
};
const node = document.getElementById('myFavoriteNode');
node.addEventListener('click', Wyg.Editor.nodeClickedEvent.bind(Wyg.Editor));
<button id="myFavoriteNode">click this favorite node</button>


Queries to get unpaid and unpaid invoices

There seems to be a section in your code that you repeat three times. This can probably be placed in a separate function. Something like this:
function getInvoiceTotal($status, $onlyOverdue = FALSE)
{
    $query = Capsule::table('tblinvoices');
    $query->select(Capsule::raw('SUM(total) as total'))
          ->where(['userid' => $_SESSION['uid'],
                   'status' => $status]);
    if ($onlyOverdue && ($status == 'Unpaid')) {
        $query->whereDate('duedate', '<=', Carbon::now()->format('Y-m-d'));
    }
    return $query->get()->total;
}

add_hook('ClientAreaPageInvoices', 1, function($vars) {
    return ['totalAberto'  => getInvoiceTotal('Unpaid'),
            'totalVencido' => getInvoiceTotal('Unpaid', TRUE),
            'totalPago'    => getInvoiceTotal('Paid')];
});

Regretably I don't have Laravel installed so I cannot test this code, but I think the general idea is clear. Perhaps someone with more knowledge of Laravel can add to this answer?
Some notes:

I changed array(....) to [....].
I didn't understand the json_decode(json_encode()) bit. Perhaps to go from objects to arrays? I don't see what's wrong with using the actual objects. Here's where I have most doubt that my code is correct, since I haven't tested it.
I left out a lot of variables you used. Using variables, with good names, can make code easier to read, but in really good code, when a variable is only used once, it shouldn't be necessary.
I strongly advise you to write your code in English only. I had to find out what the meaning of 'Aberto', 'Vencido' and 'Pago' is. Not every programmer speaks Protuguese.


The intermediate reversals seem like a bit of a trick question and are not really necessary to solve this problem. They are a complicated way to describe reordering a sequence indexed
0 ... n by taking items n, 0, n-1, 1, n-2, 2 ...
alternating from which end you take each time.

If you abandon the idea of creating the intermediate strings described it becomes more about how to select the right character from the input string for each position :

(ns reversefun.core)

(defn reverse-fun [s]
  (->> (interleave (reverse s) s)
       (take (count s))
       (apply str)))


Calling a global popup from nested vue components

Global Event Bus is a solution but since you have to listen emits in components's mounted or created lifecycle hook, it's getting duplicated in each instance.

I had same 'issue' and resolved it by mounting my popup component dynamically and setting it into prototype of my Vue instance.

Example;

import Vue from 'vue';
import Popup from '@/components/Popup.vue';

Vue.prototoype.$popup = new Vue(Popup).$mount();

Imagine you have show method in your Popup component. Now with this injection you can use it in any component as;

this.$popup.show();


Modify parameter data before creating an instance of a class in PHP

I don't think you're taking advantage of the library you're using. The Carbon class extends the standard DateTime class, and as per the documentation, it can handle the instantiation of a Carbon object from a string representation, an integer timestamp, or any object implementing the DateTimeInterface interface. In particular, the Carbon::parse method is really just a wrapper for the constructor, which parses its argument anyways.
Taking advantage of this built-in capability, you could define the Badge class constructor as follows.
public function __construct(string $name, $achievedAt)
{
    $this->name = $name;
    $this->achievedAt = new Carbon($achievedAt);
}

You could also set the default value of the $achievedAt parameter to be 'now', which Carbon would correctly interpret and represent as the current date and time.
public function __construct(string $name, $achievedAt = 'now')
{
    $this->name = $name;
    $this->achievedAt = new Carbon($achievedAt);
}

This has the added benefit of removing the onus of adding the date parsing boilerplate from the caller, and they can now simply pass in the date argument if and when they need to (I'm assuming it's possible for user events to trigger achievements that merit badges, thus circumventing the need to parse a date-time string in those instances).
<?php

namespace App\Domain\Badge;

use Carbon\Carbon;

class KilometerBadge extends Badge
{
    /**
     * Kilometer Badge Constructor
     *
     * @param int $kilometers Kilometers walked or something.
     * @param array $activity Associative-array containing activity info.
     */
    public function __construct(int $kilometers, array $activity)
    {
        parent::__construct('kilometer-badge-' . $kilometers, $activity['start_date']);
    }
}

The creation of the ActivityNumber class is likewise simplified.
<?php

namespace App\Domain\Badge;

use Carbon\Carbon;

class ActivityNumber extends Badge
{
    public function __construct(array $activities, $activity)
    {
        parent::__construct('kilometer-badge-' . count($activities), $activity['start_date']);
    }
}

Note that if the Carbon::parse method fails, it will throw an InvalidArgumentException, which you need to make sure you're checking for.
With that being said, if the "kilometer-badge-x" badge you're creating in both classes is the same idea being created with two different classes, you might want to refactor.
If you had multiple badge types (BlueBadge and GreenBadge, for example), then each would have its own class.
class BlueBadge extends Badge
{
    //
}

class GreenBadge extends Badge
{
    //
}

If you wanted multiple ways of constructing a single badge type, you could look into the Factory pattern. In this case, you could have a class BlueBadgeFactory in which you define two static methods, createFromKilometers and createFromActivities, both of which would return an instance of a BlueBadge object.
class BlueBadgeFactory
{
    public static function createFromKilometers(int $kilometers, string $achievedAt) : BlueBadge
    {
        //
    }

    public static function createFromActivities(array $activities, array $activity) : BlueBadge
    {
        //
    }
}

I'm not familiar with the project you're working on, but it might be helpful to create a base AbstractBadgeFactory class from which each concrete badge factory class inherits some functionality.
Now that you've represented each badge with a single, distinct class with each badge type inheriting from a single Badge superclass, you can now more simply take advantage of polymorphism (you don't have to check whether an object is an instance of the KilometerBadge or the ActivityNumber badge, for instance - pun intended).
Here's a pretty contrived example to write a function that renders an array of badges.
function renderBadges(array $badges) : void
{
    foreach ($badges as $badge)
    {
        renderBadge($badge);
    }
}

The above function simply calls the following renderBadge function, which takes a Badge argument and renders it.
function renderBadge(Badge $badge) : void
{
    $badge->render();
}

This assumes, of course, that you actually define a method render in the Badge class. By defining it as abstract, you would force each badge type to override it, thereby providing a unique implementation per badge type.
The reason this example is contrived is because you don't want a render function on your Badge objects, since it presupposes the output format. Instead, you might define a BadgeWriter superclass, some subclasses like BadgeJSONWriter and BadgeHTMLWriter for API and Browser requests, respectively, and then you would pass in the badge in question to the writer object so that each writer badge object simply contains badge information and each writer object just takes that information and simply writes it to a specific format.
I hope this helps; comments, corrections, questions, and feedback are always welcome.


Refactoring a class / map of query parameters that are passed between layers

It's cleaner and possible to create types of Parameter class, such as CarParameter, MotoParameter, and use Spring type conversion.

First your signature would become something like

@RequestMapping(".../car/...")
public Journal createCarsJournal(@RequestParam CarParameter params) {
    return carsJCreator.create(params);
}

@RequestMapping(".../moto/...")
public Journal createMotosJournal(@RequestParam MotoParameter params) {
    return motosJCreator.create(params);
}

To build the customized conversion, check out Guide to Spring Type Conversions.


From looking at it, the name of your function toggleSaveStream is lying, calling it twice will not make it toggle, it will look at the the status of the user and set the status accordingly. So I would simply call it updateSaveStreamButton.

Since it does that, you could call it at first, de-activating the button, and then once the user is loaded call it again.

Then you would simply have

<button id="saveStream" class="button-icon button-small save disabled>" title="">

And then

initialize: function() {
    this.updateSaveStreamButton();
    this.listenTo(User, 'change:loaded', this.updateSaveStreamButton);
},

updateSaveStreamButton: function () {
    var userLoaded = User.get('loaded');
    var templateHelpers = this.templateHelpers();

    this.ui.saveStreamButton.toggleClass('disabled', userLoaded);
    this.ui.saveSelectedButton.attr('title', userLoaded ? templateHelpers.saveStreamMessage : templateHelpers.cantSaveNotSignedInMessage);
}

This sounds too easy, so feel free to point what I am missing ;)


Your solution just doesn't work

Your validation check always fails. Yes int(value) != int is always true. I don't think an instance of a class will ever be the class that it's an instance of.
Your mutating a class variable. The tool you're utilizing forces you to take instances, normally there's a pretty good reason.

If we remove the previous error and run your code we can easily see, there's no point in having more than one instance of a Player.

>>> a = Person()
>>> b = Person()
>>> a.moods['happy'].__set__(a, 8)
>>> b.moods['happy'].__get__(b, None)
8  # Ok, that's not right...

I don't believe you've actually tried to code you've provided. And honestly what's the point in a single-data non-singleton class? The provided code is just untested garbage.

You're using it wrong

If it's not evident enough that you're fighting a tool that is pure sugar. Then you're not doing it right. The instance has to keep the state of the instance, and the descriptor has to interact with a varying amount of instances to interact with their state correctly.

If anything of the instance's leaks out into the descriptor, or vice versa. Then you're going to have a bad, bad time.

Since descriptors are to be tied onto classes I'm making a Mood class. Since the descriptor needs to have a place to store data. We can define that in the __init__ of Mood. To note, because you may not notice this by yourself. self._values can be mutated to bypass the validator. Using self._values[mood] = value is not how you update values, use setattr(self, mood, value).

In addition to fixing OneDigitNumericValue, you should make it take an argument that is the validator for the function. If you need another validator it'd be better and simpler to make a simple hard to mess-up function. Rather than making lots of potentially broken descriptors.

def single_digit(value):
    if 0 <= value <= 9:
        return
    raise ValueError("The value is invalid")

class Validator:
    def __init__(self, validator):
        self.validator = validator
        self.name = None

    def __set_name__(self, owner, name):
        self.name = name

    def __get__(self, instance, owner) -> object:
        return instance._values[self.name]

    def __set__(self, instance, value) -> None:
        self.validator(value)
        instance._values[self.name] = value

class Mood:
    happy = Validator(single_digit)
    angry = Validator(single_digit)
    sad = Validator(single_digit)

    def __init__(self):
        self._values = {}
        self.happy = 5
        self.angry = 5
        self.sad = 5

    def update_states(self, states):
        for mood, value in states.items():
            setattr(self, mood, value + getattr(self, mood))

And it actually works:

>>> a = Mood()
>>> b = Mood()
>>> a.happy = 3
>>> a.happy
3
>>> b.happy
5
>>> a.update_states({'happy': 3})
>>> a.happy
6


Finding Pythagorean Triple that sums to 1000

Any pythagorean triple is in form of

  $$ k(u^2 - v^2), 2kuv, k(u^2 + v^2) $$

where u, v, and k are positive integers with u > v, u − v odd, and with u and v  coprime. The sum is therefore

  $$ ku(u + 2v) $$

(the restrictions still apply).

Now your job is factor 1000 into 3 terms (not so many ways to do so, 1000 = 5*5*5*2*2*2) and determine if those terms can be represented with u and v being coprime with an odd difference.


Is my code Declarative (RxSwift) ? Please help me to explain why not?

In order for code to be declarative, it must express an invariant. Something that is true throughout the entire life of the variables involved. In other words, a direct chain from input to output. Think Excel. In Excel, every cell in the spreadsheet is either an input variable or a transformation of one or more cells which recursively go back to input variables and that's what makes it declarative.

Your code is not declarative because it doesn't specify what user action would cause processPhotoApiService to get called.

https://medium.com/@danielt1263/imperative-vs-declarative-programming-a74f6cceff0e


using namespace std

Since none of the standard library features you use are prefixed by std::, I will assume that you have using namespace std; somewhere. Actually, you should avoid using namespace std; and fully qualify the standard library functions and classes with std:: instead. Your code won't be much longer, and you may avoid potential problems such as name clashes.

Use std::array

One thing that can be noticed is that you know that you will return a collection of exactly three std::vector<char>. You know the size at compile time, therefore you don't need a dynamic container, a fixed-sized one is enough. Let's make that explicit and have your function return an std::array<std::vector<char>, 3> instead.

Check for potential errors

ifstream is (fileName, ifstream::binary); is great. It's how it should be used. However, it may fail, for example if the file fileName does not exist. You should check whether such an error occured before resuming the function:

std::ifstream is (fileName, std::ifstream::binary);
if (not is)
{
    // handle errors (e.g. throw an exception)
}

Note that operator! (here not) is used to check for errors. If it yields false, it means that an error occured when opening the std::ifstream.

Accessing a std::vector underlying array

You used the C++98 way &vec[0] to get the underlying array of an std::vector. Actually, when reading code, knowing what it does can be pretty hard, and that's partly due to the order of evaluation of the operators that may not be obvious for everyone. You can use vec.data() instead. This method was not available for std::vector before C++11, and that's probably why you found the solution &vec[0].


Most efficient way to iterate through arrays/can I use .times method in place of while method?

If you're interested in more idiomatic Ruby, my advice would be to thoroughly understand Array, Enumerable, and the functional style enabled by using blocks.

The functional style allows you to use the output of one method directly as input to another method without intermediate variables. This is known as method chaining, and it reduces the number of intermediate variables you need to create.

Let's start with your array creation:

# Initializes array and iterator.
x = []
i = 0

# Stores 4000 random numbers 0..1 in array 'x'
while i < 4000
  x << rand(2)
  i += 1
end

First, a bit about code comments. These are a bit gratuitous, as these repeat what the code says. Good comments should explain why something was done, not what is being done. If you feel that the code is non-obvious enough that you'll need a what comment, then it's time to think about refactoring so the code is a bit more self-explanatory.

I've been programming in Ruby for years and have never needed an iteration variable or a while loop. Why? Because the iteration methods such as Array's each or Enumerable's each_with_index are so powerful. So, as you mentioned, you could use times and do this:

x = []
4000.times do
  x << rand(2)
end

This is an improvement, but in this case we can do better. If you look at the constructor options for Array, you'll notice that you can specify the size and also pass a block for an initial value. Therefore, this can be written as:

Array.new(4000){ rand(2) }

#=> [1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0...]

The output is the same: a 4000-element array consisting of random zeros and ones.

Now let's look at what you want to do next, according to your comment:

# Initializes array for the purpose of storing zeros and ones in separate
#  arrays for the sake of counting how many instances of each occur in the sample

So we want to separate the array into two buckets, based on their value. Thinking functionally, we should ask if, instead of iterating over intermediate output and creating a new data structure (which is also intermediate output because it will be thrown away once you count them), is there something we can do directly to the array? It turns out that the Enumerable module contains partition which can take a block that does exactly that.

Array.new(4000){ rand(2) }.partition{ |digit| digit.zero? }

#=> [[0, 0, 0, 0, 0, 0, 0, 0, ...], [1, 1, 1, 1, 1, 1, 1, 1, ...]]

Partition will separate the array into two sub-arrays: one for which the block returns true; and the other for which the block returns false. Note that I also used the zero? method which is available for numbers (see Fixnum#zero?) where I could have just said digit == 0. Either one is fine, but using zero? allows me to use a shortcut. This is equivalent:

Array.new(4000){ rand(2) }.partition(&:zero?)

#=> [[0, 0, 0, 0, 0, 0, 0, 0, ...], [1, 1, 1, 1, 1, 1, 1, 1, ...]]

This is known as the Symbol#to_proc trick which I won't go into detail here, but it basically allows you to shorten a block in the form {|x| x.method} to &:method. Whenever you want to call the same method on every item in an array, it is useful. You'll see this quite often in Ruby code these days.

Now, you don't really want these sub-arrays, you just want to know how many zeros and ones there are. Again thinking functionally, for each element in the array, you'd like its size. Enumerable's map is useful for transforming each element of an array.

Array.new(4000){ rand(2) }.partition(&:zero?).map{ |subarray| subarray.size }

#=> [2038, 1962]

Which, using the Symbol#to_proc trick can be shortened to

Array.new(4000){ rand(2) }.partition(&:zero?).map(&:size)

#=> [1994, 2006]

So there you have it: using idiomatic Ruby and functional style, you can reduce the first 28 lines down to a single short, yet readable line. To answer question #1, any speed difference would be insignificant with arrays of this size. (Thought it would be interesting to benchmark the two approaches with huge arrays)


Improving readability of 3d math in Java

@DaveNewton Not necessarily, sometimes it's Groovy :-)

Advantage

code/syntax compatible with java.
Operator overrides allow you to write your code so it looks more like your comment i.e. operators rather than methods

Disadvantage

Groovy is slower than java (but this can be reduced with Groovy++)


Detect how long an HTML button is pressed

500 and 1000 should be constants.

Where you have them now you need to look through to find them in code when you want to change them. I know this is an example, but they're also meaningless. 500 doesn't tell you why half a second matters, but TIMEOUT tells you what the purpose of the number is. Declare your time values at the top of the function with clear names that denote what they're for.


Cute idea. It's not so simple, though.
For example, compare the outputs of
echo 'a   b'

with
$ echo 'a   b'

(because of word splitting).
Also, it fails for compound commands like
for i in a b c ; do echo $i ; done

(because everything after the first ; is another command).
Some commands might fail depending on the contents of the current directory, e.g.
$ [[ a = ? ]]

(if it works, try running touch 1 2 3).


Your solution is hardcoded for matrices of size 3x3 - why not support matrices of arbitrary size as well? It's also difficult to maintain and debug your code, i.e., it's easy to mess up somewhere when you are indexing your rows and columns. Also, imagine you wanted to consider larger matrices: what a nightmare to now modify your existing logic!
A more robust solution could turn to numpy. Specifically, you can check row and column sums by doing m.sum() and m.sum(axis=1), and compute the sums of the diagonals via m.trace() or by sum(np.diag(m)) and sum(np.diag(np.fliplr(m)).
As a general comment, just return a boolean value from your function. Let the main program decide what do with this value, i.e., whether to print "this is good", "This is a Lo Shu Magic Square", or whatever. In this way, your verifier function stays clean and more generic.


I don’t like the idea of storing the password hash in a cookie. It is easy to steal and grants unlimited access. The cookie is transmitted with every single HTTP request. I would prefer using an access token with limited lifetime. Anyway most people store passwords in their browser and this is easy to steal as well – so this seems not to be a massive security break.

The bigger problem is that your login only relies on the password – you don’t need to know the corresponding username to login. This makes brute forcing a lot easier. And more important: your login will break, if two users use the same password. Then user2 will (unintentionally) gain access to user1’s account.

PS: As mentioned in comments, don’t loop over every line in your table, use a WHERE clause instead. And I don’t understand, what you are trying to achieve with your mysql_num_rows code block…