Converting std::chrono::time_point to/from std::string

Headers and typenames

We're missing

#include <chrono>
#include <cmath>
#include <cstdint>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

And we consistently misspell the types std::size_t, std::time_t, std::uint64_t.

A name collision

On systems that define a global log10 as well as std::log10, there's ambiguity on the calls to our log10.  I suggest using a name that conveys intent, such as digits() (even that's a bit risky - it would be better in a private namespace).  It costs nothing to make it terminate if passed 0 as argument, too:

static constexpr std::size_t feconds_width(std::size_t x)
{
    return x <= 1 ? 0 : 1 + feconds_width(x/10);
}

Interface consistency

The two alternative forms for toString() need to be instantiated differently, depending on the timepoint's denominator value.  If we make Double default to double, then both can be called without explicit template arguments.

Incidentally, did you measure a performance difference between the two implementations that proved a benefit?  If so, it's worth quantifying that in a comment so that future readers understand that it's worthwhile having both versions.

Document the assumption

This code only works when converting to or from TimePoint classes which have the same epoch as std::time_t.

Prefer to return values over status codes

Rather than returning a status code, I'd prefer to throw an exception when conversion fails; then the return value can be used directly.  Failure in toString() seems especially unlikely - I think the only possible cause is running out of room in the output string and being unable to allocate more.

if (!oss) throw std::runtime_error("timepoint-to-string");
return oss.str();

If you really dislike exceptions, it's still easier on the caller to return a std::optional rather than return a boolean and modify a reference argument.

Be careful with negative times

If tt<0, then tt%60 can be negative.  That's not what we want.  However, since we create a std::tm, we can read seconds from that:

auto tm = std::localtime(&tt);
if (!tm) throw std::runtime_error(std::strerror(errno));
oss << std::put_time(tm, "%Y-%b-%d %H:%M:")
    << std::setw(Precision+3) << std::setfill('0')
    << std::fixed << std::setprecision(Precision)
    << tm->tm_sec+zeconds;

Peek the '.' instead of reading it

If we leave '.' in the input stream, we can read that as part of a floating-point value:

double zz;
if (iss.peek() != '.' || !(iss >> zz))
    throw std::invalid_argument("decimal");
using hr_clock = std::chrono::high_resolution_clock;
std::size_t zeconds = zz * hr_clock::period::den / hr_clock::period::num;
timePoint += hr_clock::duration(zeconds);

Test cases seem inconsistent with the code

The test cases use month names, which require a %b conversion, not %m.
We could do with a few more test cases.

Consider a streamable wrapper

If your main use-case is to stream dates in and out, it may be better to bypass returning a string, and instead create an object that knows how to stream directly to a std::ostream.  As I don't know if that's your intended use, I won't demonstrate that.

Simplified code

#include <cerrno>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>

template<typename Double = double,
         std::size_t Precision = std::numeric_limits<Double>::digits10,
         typename TimePoint>
    requires std::is_floating_point_v<Double>
          && Precision <= std::numeric_limits<Double>::digits10
inline std::string toString(const TimePoint& timePoint)
{
    auto seconds = Double(timePoint.time_since_epoch().count())
        * TimePoint::period::num / TimePoint::period::den;
    auto const zeconds = std::modf(seconds,&seconds);
    std::time_t tt(seconds);
    std::ostringstream oss;
    auto const tm = std::localtime(&tt);
    if (!tm) throw std::runtime_error(std::strerror(errno));
    oss << std::put_time(tm, "%Y-%b-%d %H:%M:")
        << std::setw(Precision+3) << std::setfill('0')
        << std::fixed << std::setprecision(Precision)
        << tm->tm_sec+zeconds;
    if (!oss) throw std::runtime_error("timepoint-to-string");
    return oss.str();
}

template<typename TimePoint>
TimePoint fromString(const std::string& str)
{
    std::istringstream iss{str};
    std::tm tm{};
    if (!(iss >> std::get_time(&tm, "%Y-%b-%d %H:%M:%S")))
        throw std::invalid_argument("get_time");
    TimePoint timePoint{std::chrono::seconds(std::mktime(&tm))};
    if (iss.eof())
        return timePoint;
    double zz;
    if (iss.peek() != '.' || !(iss >> zz))
        throw std::invalid_argument("decimal");
    using hr_clock = std::chrono::high_resolution_clock;
    std::size_t zeconds = zz * hr_clock::period::den / hr_clock::period::num;
    return timePoint += hr_clock::duration(zeconds);
}

int main()
{
    using std::chrono::system_clock;
    auto now = system_clock::now();
    std::clog << "==== " << toString(now) << std::endl;
    using DD = std::chrono::duration<std::size_t,std::ratio<2,3>>;
    using TP = std::chrono::time_point<std::chrono::system_clock,DD>;
    for (int i = 0;  i <= 3;  ++i)
        std::clog << "==== " << toString(TP(DD(i))) << std::endl;

    for (std::string s: { "2017-May-01 00:10:15", "2017-May-01 00:10:15.25",
                "2017-Mar-01", "1969-Dec-31 19:00:00.666666666666667",
                "2018", // underspecified - but succeeds as 2017-12-31
                "1752-May-5",   // out of range
                "not a date",
                })
    {
        try {
            std::clog << "---- "
                      << toString(fromString<system_clock::time_point>(s))
                      << std::endl;
        } catch (const std::exception& e) {
            std::cerr << e.what() << std::endl;
        }
    }
}


First of all, thanks for sharing your code, this is the best way to improve yourself!

The M in MVC

A Model in any MVC framework should provide an easy way to access a specific type of data. It allows you to stop worrying about database details and only access your specific type of data in a meaningful way. For a StackOverflow-like website, this means that your Controller can relax! Your controller doesn't want to know about INSERT INTO Questions(id, title, message, author) VALUES (9624, "Codeigniter Model Optimization", "...", "Shayan"). He just wants to do $questions->add("Codeigniter Model Optimization", "...", "Shayan") and know that all details (including security) are going to be handled by the Model.

The model should be in charge of ensuring everything goes well with the database, but that's not what you're doing here. You're creating a Leaky Abstraction, and this doesn't help you. Try coming up with a model that reduces the work the controller needs to do.

A few comments on the code itself.

You're repeating yourself a lot at the start of each function. One fix would be to put this in a function:
    $checks = $this->check($table, $conditionData);
    if ($checks !== FALSE) return $checks;
But the real fix is to remove those. $this->db->query() already removes FALSE when there's an issue. You should use it to check if there's an issue, and then decide what to do then. The handling of issues is what makes abstractions successful. Remember than "It's easier to ask for forgiveness than it is to get permission".
Please use query bindings (at then end of the page) which will avoid SQL injections. They're using PHP's prepared statements, which you should learn about if you want to write secure applications.


Product matcher refactoring regarding scopes and arrays

It is redundant to use self here.

def product_matcher(item)
  attribute_id = item.blank? ? token.id : item.id
  products.where(id: attribute_id).first
end


Automatically turn on Computer from Raspberry Pi (based on user presence in home)

1. Comments on your code

You make quite a lot of use here of os.system, which runs a command in a subshell. This can be a risky function to use, because the shell can do anything. For example, you write

os.system ("rm " + str(hometime_path))

but what if hometime_path were -rf *?

You're probably safe in this particular program because it's only for your own use and because the strings come from your own configuration file. But it's worth getting into the habit of doing this kind of thing properly, so that in situations which really are risky, you'll know what to do.

In the case of rm you can use os.unlink:

os.unlink(hometime_path)

But in the general case, use subprocess.call and use the -- argument (if necessary) to make sure that the arguments you pass cannot be misinterpreted as options. For example,

subprocess.call(['rm', '--', hometime_path])

In a case where you want to redirect standard output, like this:

os.system ("ping -w 1 " + str (ip_smartphone) + " >/dev/null")

you can use the stdout keyword argument to subprocess.call:

subprocess.call(['ping', '-w', '1', '--', ip_smartphone],
                stdout = open('/dev/null', 'w'))

Most of your calls to str are unnecessary: these configuration parameters ought to be strings already. (If they are not, I think it you'd prefer to get an exception so that you could fix the problem, rather than silently coercing the incorrect value to a string.)
You don't need to compare booleans explicitly to True and False. So instead of:

if os.path.exists(in_path) == True:

just write:

if os.path.exists(in_path):

and instead of:

if os.path.exists(hometime_path) == False:

just write:

if not os.path.exists(hometime_path):

In this code you remove a file only if it exists:

if os.path.exists(in_path) == True:
    os.system ("rm " + str(in_path))

But the rm command already has a option for this, so you could write instead:

subprocess.call(['rm', '-f', '--', in_path])

Or do it in pure Python:

try:
    os.unlink(in_path)
except OSError: # No such file or directory
    pass

(This is an example of how it is often better to ask for forgiveness than permission.)
Assuming that " > hometime" is a mistake for " > " + hometime_path (as suggested in another answer), then in this bit of code:

os.system ("rm " + str(hometime_path))
change_arrived=("echo " + str(check_presence) + " > hometime")
os.system (change_arrived)

you remove a file and then overwrite it with the value of check_presence. There's no need to remove the file first: the second command will overwrite it if it exists.

And in any case this is easy to do in pure Python:

with open(hometime_path, 'w') as f:
    f.write('{}\n'.format(check_presence))

You use the modification time of the file hometime_path to remember the last time that your ping command succeeded. Why not remember this time in a variable in Python and avoid having to create and delete and examine this file?
You use the existence of the file in_path to remember whether your smartphone is connected. Why not remember this fact in a variable in Python and avoid having to create and delete and examine this file?

2. Rewrite

Making the above improvements results in something like this (but this is untested, so beware):

import os, subprocess, time
from ConfigParser import SafeConfigParser
from datetime import datetime, timedelta

configfilename = "imhome.ini"
scriptpath = os.path.abspath(os.path.dirname(__file__))
configfile = os.path.join(scriptpath, configfilename)
parser = SafeConfigParser()
parser.read(configfile)
ip_smartphone = parser.get('imhome', 'ip_smartphone')
mac_address_pc = parser.get('imhome', 'mac_address_pc')
mp3_path = parser.get('imhome', 'mp3_path')
timeout = timedelta(seconds = int(parser.get('imhome', 'maximum_time_before_logout')))

devnull = open('/dev/null', 'wb')
connected = False
disconnect_time = None

while True:
    ping = subprocess.call(['ping', '-w', '1', '--', ip_smartphone],
                           stdout = devnull)
    if ping == 0:
        disconnect_time = datetime.now() + timeout
        if not connected:
            connected = True
            subprocess.call(['etherwake', mac_address_pc])
            subprocess.call(['mpg123', mp3_path], stdout = devnull)
    elif ping == 256 and connected and datetime.now() > disconnect_time:
        connected = False
    time.sleep(1)


Compile .tex and remove .div file from Haskell

When you are using packages, please make sure to say which ones. I guessed shellmate btw. As for the code, it's quite readable except for the handler definition which I've rewritten as follows:

handler :: S.FilePath -> IO ()
handler f = do
  (Right isfile) <- S.shell $ S.isFile f
  if      not isfile        then putStrLn "File not found."
  else if not $ isTeXFile f then putStrLn "Not a .tex file!"
  else compile f >>= either putStrLn return

Given that you are quickly dismissing the cases you are not interested in, I inspected not $ isTeXFile f and systematically written the if (...) then clauses on the same line. This avoids the crazy right-leaning nesting.

Using the either combinator of type (a -> c) -> (b -> c) -> Either a b -> c lets you rewrite the final case expression in a more concise fashion.

Finally, I don't think it's good practice to test a file's type based on its extension. Given that you are already running external tools, you may want to use ̀file for that job. It would look something like this:

isTeXFile :: S.FilePath -> IO Bool
isTeXFile fp = do
  (Right ans) <- S.shell $ S.run "file" [fp] ""
  return $ " LaTeX " `isInfixOf` ans

handler :: S.FilePath -> IO ()
handler f = do
  (Right isfile) <- S.shell $ S.isFile f
  if not isfile        then putStrLn "File not found."
  else do
  testTexFile    <- isTeXFile f
  if not $ testTexFile then putStrLn "Not a .tex file!"
  else compile f >>= either putStrLn return

The rest is pretty much perfect as far as I'm concerned (modulo some cosmetic preferences which I won't bore you with).


Printing 64-bit decimal numbers in freestanding environment

How can I print 64-bit decimal numbers in freestanding environment?
  suggests me some improvements...

Create test cases

Post lacks a good way to assess its correctness.  Since the goal is to print rather than form a string, that is later printed, (a better function IMO), we will do things the simply, but a bit the hard way and visually compare output.

Test case code

#include <inttypes.h>
#include <limits.h>
#include <stdint.h>
#include <stdio.h>

void print_uint64_dec(uint64_t u) {
  if (u >= 10) {
    uint64_t udiv10 = u/10;
    u %= 10;
    print_uint64_dec(udiv10);
  }
  putchar((int)u + '0');
}

void print_int64_dec(int64_t i) {
  uint64_t u = (uint64_t) i;
  if (i < 0) {
    putchar('-');
    u = -u;
  }
  print_uint64_dec(u);
}

int main(void) {
  int64_t ia[] = {INT64_MIN + 1, 0, 10, INT64_MAX/2, INT64_MAX - 1};
  for (size_t index = 0; index< sizeof ia/sizeof ia[0]; index++) {
    int64_t i = ia[index];
    print_int64_dec(i-1); putchar('\n');
    print_int64_dec(i+0); putchar('\n');
    print_int64_dec(i+1); putchar('\n');
  }
}

And its output:

-9223372036854775808
-9223372036854775807
-9223372036854775806
-1
0
1
9
10
11
4611686018427387902
4611686018427387903
4611686018427387904
9223372036854775805
9223372036854775806
9223372036854775807

OP code produced the same results.

Plan for the future

"processor doesn't have 64 bit division, and I can't rely on libgcc" --> accepting this as a given, this curious restriction could easily be removed later.  To that end, recommend to encapsulate this specialized code - and only the specialized part needed - the divide and mod of a int64_t, without the print part.

Something like

static unsigned mod10(uint64_t *u) {
  uint64_t dividend = *u;
  uint64_t quo = 0;
  uint64_t div = 0xA000000000000000; //largest shifted 10
  while (div >= 10) {
    quo <<= 1; // quo *= 2;
    if (dividend >= div) {
      dividend -= div;
      quo++;
    }
    div >>= 1;
  }
  *u = quo;
  return (unsigned) dividend;
}

void print_uint64_dec(uint64_t u) {
  if (u >= 10) {
    #if CURIOUS_CODE_NEEDED
      uint64_t udiv10 = u;
      u = mod10(&udiv10);
    #else
      uint64_t udiv10 = u/10;
      u %= 10;
    #endif
    print_uint64_dec(udiv10);
  }
  putchar((int)u + '0');
}

Simplify

I just had too much trouble following the "invented other way".  I recommend to  re-write to only replace the missing /10, mod 10 functionality in  a stand-alone function.  When a target platform lacks standard functionality, do not entangle your fill-in-the-gap code with the rest of user code.  Keep them separate.

Minor - Use consistent types

Code   converts intmax_t to uint64_t as if  intmax_t is always a 64-bit type.  (u)intmax_t is at least a 64-bit type.  Choose (u)intmax_t or (u)int64_t.

Minor - Avoid UB

intmax_t num ... -num is UB when num == INTMAX_MIN.  Simply enough to fix. Negate an unsigned type

// uint64_t n = num < 0 ? -num : +num;
uint64_t n = num;
if (num < 0) n = -n;
// OR
uint64_t n = num < 0 ? -(uintmax_t)num : num;
// Or various other approaches.

Minor - Missing  headers

I needed the below to compile your code.

#include <limits.h>
#include <stdint.h>


Check that file is fully downloaded by FTP

You definitely need more quoting of parameter expansions.  Notably, $FTP_PASSWORD may well contain characters that are meaningful to the shell:

FileSizeOnServer=$(curl --max-time 10 -u "$FTP_USER:$FTP_PASSWORD" \
                   --head "$FTP_Path" 2>&1 | grep "Content-Length:")

I'm not sure it's a good idea to redirect standard error there - you want errors to be visible, not piped into grep.

I'm not sure there's much value to the size comparison, though - curl should exit with non-zero status if it didn't transfer the whole file, so we should just use it directly:

if ! curl -u "$FTP_USER:$FTP_PASSWORD" "$FTP_Path"
then
    echo "Failed to download" >&2
    exit 1
fi

Or even simply

set -e
curl -u "$FTP_USER:$FTP_PASSWORD" "$FTP_Path"


You create a lot of TimeSpan objects which is unnecessary. Just create one timeout variable. Especially since it's used in multiple places. This makes changing the timeout later easier. Otherwise you are bound to forget one place.
Prefer TimeSpan.FromXYZ() methods. They makes it more obvious for what period you create a TimeSpan.
Consider moving the mail sending code into its own function which just accepts a single message and sends it.
It might make sense to iterate over the message queue directly instead of buffering them all up:

var timeout = TimeSpan.FromSeconds(1);
var queueIter = msgQueue.GetMessageEnumerator2();
while (queueIter.MoveNext(timeout))
{
    using (var message = msgQueue.ReceiveById(queueIter.Current.Id, timeout))
    {
        SendMessage(message);
    }
}

Instead of directly sending the message consider making an event available on the class like MessageReceived. Then other code can subscribe to it and do stuff (like sending it as mail or logging it or saving it somewhere, etc).
As mentioned in the comment you should wrap all objects you create which are IDisposable into using statements to make sure any allocated resources are cleaned up properly.


Find two missing elements from a sorted array in given range

You say the problem is to find missing values from a 'Range', but your method only takes a start value, not an end value.... is this intentional? The method comment says:

  Takes an input a sorted array with two variables that repeat in the range. and returns two variables that repeats

The method does nothing of the sort though... it takes one variable, and there's no indication the values repeat, and it returns missing values, not repeats.

Additionally, the method name is sortedConsecutiveTwoMissing but there's nothing in the implementation that suggests that the values have to be consecutive at all...

Also you suggest the array is sorted, but not whether it is unique... for example, your code may break on (missing is 3 and 5):

0 1 2 2 4 4 6 6 7 8 9

General / Code Style

Variables like a1 make me want to look for a2, a3, etc. Unless it's obvious, don't use numbered variables.
int high = start + (a1.length - 1) + 2; should have a comment .... the + 2 is not obvious, and magic numbers should either be very obvious, or documented. That line still makes no sense to me at all.... and high is not used for anything reasonable anyway.
calculatedX is not a calculated anything

At this point I don't believe the code does what you suggest it should, so I don't believe the code works... downvote time.

Edit the code, make it work....


Pretty print a tree from minimal data input

Nice solution, my suggestions:

Short variable names: variables like camt and cname can be extended to currentAmount and currentName. It's better to have longer names to improve readability. For example, I am not sure what stem stands for.

Types and input validation: there are a lot of casting in the methods which are not validated. Accepting an array of Object without any validation is a recipe for troubles. Using a class you can solve both problems, something like this:
class Node{
    private int depth;
    private String itemName;
    private int amount;
    public Node(int depth, String itemName, int amount) {
        // Input validation here
        this.depth = depth;
        this.itemName = itemName;
        this.amount = amount;
    }
    // Getters, etc.
}

So this code:
Object[] o = tree.get(i);
int cdepth = (int) o[0];
String cname = (String) o[1];
int camt = (int) o[2];

Can become:
Node node = tree.get(i);
int currentDepth = node.getDepth();
String currentItemName = node.getItemName();
int currentAmount = node.getAmount();

You can also make the properties of the class final to have an immutable node.

Constants: the strings \--- and +--- are repeated multiple times. Consider creating constants for such special strings so that they will be easier to change in the future.

Functionality: If the list is not properly built, the tree will not be printed correctly. For example:
The input:
1 a 1
2 b 1
3 c 1
4 d 1

Produces the correct output:
\---a x 1
   \---b x 1
      \---c x 1
         \---d x 1

But if we add one more node in the middle:
1 a 1
2 b 1
3 c 1
2 e 1
4 d 1

The output becomes:
\---a x 1
  +---b x 1
  |   \---c x 1
  \---e x 1
      \---d x 1

Now d changed its depth from 4 to 3 and e became its father.
Providing a well-formed list of nodes with corresponding depth is not a simple task if the tree grows in size. A solution might be to create a Tree class that knows how to add and remove nodes. Then the treePrint method will do a Pre-order scan of the tree and print the nodes on the way.


Not a big fan of case..when:

@user = User.find_first(params[:user_id]) if params[:user_id]
@user ||= User.find_by_custom_url(@url)

@url = params[:custom_url] || @user.custom_url


Find index of array item starting at a given location

To answer your immediate question: You can search in an array slice:

 guard let prime = numbers[start...].first(where: {$0 != nil}) else {break}

That works because array slices share their indices with the originating array.

There is a small bug in your program, as one can see here:

let sieve = Sieve(4)
print(sieve.primes) // [2, 3, 4]

The reason is that the

if lo < maxValue { ... }

loop does not include the last value. The test should be lo <= maxValue.

There are also some possible improvements:

        let lo = 2 * prime!

can be replaced by

        let lo = prime! * prime!

because all lower multiples have been “nilled” before. As a consequence, the outer loop

    while start <= maxValue { ... }

can be replaced by

    while start * start <= maxValue { ... }

Now instead of repeatedly searching for the next non-nil entry in the array you might as well iterate over the array. This allows also to get rid of the ugly forced unwrapping prime!:

    for i in (2..<numbers.count).prefix(while: { $0 * $0 <= maxValue }) {
        if numbers[i] != nil {
            for x in stride(from: i * i, to: numbers.count, by: i) {
                numbers[x] = nil
            }
        }
    }

At this point it becomes apparent that the information in the numbers array is redundant: Each element is equal to its index or nil. Therefore  a boolean array is sufficient instead of an array of optional integers, this reduces the required memory considerably.

I suggest that you first try to implement that yourself, otherwise have a look at func eratosthenesSieve() in Prime Number Generator & Efficiency.


Converting a boolean list to string, and vice versa

How about this:

To Save:

Settings.Default.blEnabled = string.Join(",", blenabled.Select(x=>x?"1":"0"));

To Load:

if(!string.IsNullOrWhitespace(Settings.Default.blEnabled))
  blenabled = Settings.Default.blEnabled
    .Split(',')
    .Select(x=>Convert.ToBoolean(int.Parse(x)))
    .ToList();

Is there some requirement that you save them as integers?  It could be further simplified by just using bool.ToString() and bool.Parse()...


Expanding a map into an infinite sequence

It really depends on your specific goals.  The code as it is is very
lazy, but also recomputes quite a lot by accessing the map on every
single step.

(iterate inc 0) can be more easily written as (range) as noted again
below and the definition of expand-map is partially repetitive
((lazy-seq (cons ...)) comes up twice, as does (rest indexes) -
generally it's better to keep the amount of duplicate code to a minimum.

The 'zero initial value is hardcoded, which is not that nice for a
general solution, but apart from that it looks okay.

I have two other rewritten options below with different degrees of
laziness and verboseness.

For both options I suggest a different way of iterating over the keys,
that is, getting and sorting the keys of the input map once, then
reusing it instead of looking up the current index that often.

Thus, option one, lazier then the other one, using repeat to create
the sub-list with the indicated value, then concatenating it with the
remainder.

Also, since it's not indicated what should happen on an empty map
(except the presented code defaulting to 'zero); that could be
indicated a bit nicer as well, by throwing a custom error perhaps.

(defn expand-map-2 [m]
  (letfn [(aux [indexes]
            (let [index (first indexes)
                  rest (next indexes)
                  value (m index)]
              (if rest
                (lazy-cat (repeat (- (first rest) index) value) (aux rest))
                (repeat value))))]
    (aux (sort (or (keys m) (throw (Exception. "No specification supplied.")))))))

The other way, less lazy, but IMO a bit nicer assuming your input map
isn't huge, is to precompute all lazy lists and concatenate them.  Also
uses the mapcat over two shifted maps.  The
(concat (rest keys) [nil]) seems necessary since mapcat terminates
early instead of till all the collections are exhausted.

(defn expand-map-3 [m]
  (let [keys (sort (or (keys m) (throw (Exception. "No specification supplied."))))]
    (mapcat (fn [first second]
              (let [value (m first)]
                (if second (repeat (- second first) value) (repeat value))))
            keys (concat (rest keys) [nil]))))

Since this post was migrated, there are actually a number of existing
solutions here.  I've already asked for one of them and got the go-ahead
to incorporate it with an explanation of the solution.

Courtesy of @amalloy:

(defn expand-map-4 [m]
  (rest (reductions (fn [prev idx]
                      (get m idx prev))
                    'zero
                    (range))))

Benchmarked this solution seems very similar to the above ones (and the
initial code), but is much more concise.  range will generate the the
infinite list instead of (iterate inc 0), so that is already nice.
reductions will return all intermediate results will reducing with the
provided function; since we start from 'zero here, this works
similarly to the code in the question (I'd rather replace this with
similar behaviour to what I posted above, since it doesn't rely on the
hard-coded 'zero though).  get is used instead of using the map
directly, but that's not actually necessary.  The first rest is used
to discard the spurious initial value (the supplied 'zero).

With those remarks in mind, I'd suggest this amended version:

(defn expand-map-5 [m]
  (let [keys (or (keys m)
                 (throw (Exception. "No specification supplied.")))]
    (rest (reductions (fn [prev idx]
                        (m idx prev))
                      (m (first (sort keys)))
                      (range)))))


DO NOT use GOTO. They have been criticised since 1960s.

Your indentation is broken for the first snippet. It is also inconsistent with your second snippet. Keep it consistent throughout a project. Try looking at some linters or follow a style guide.
Do not suppress your errors by using @. Let the function throw any and all errors it encounters. You should instead make use of try-catch blocks.
While you could replace the error lookups by error code to a switch-case block, I'd suggest that you use an associated array (or a hashtable) to keep a mapping from ERROR_CODE => "ERROR MESSAGE". This will go in a separate errors.php maybe, and referenced as needed.
Define the target image resolution as a constant, instead of placing magic numbers.
You could also have a client side javascript snippet for checking file size, so that users do not waste their bandwidth and time waiting for upload process.


If any image found and bigger than thumbnail settings, get that one

Let me make it clear for myself. You have an array of images, which sometimes can be empty. You start off by checking the first image, if it's valid for your needs you take it, and if not you keep on checking the next one, and the next one, and so on until you find the one which is valid. Is that right? If so, here are my few thoughts.

Firstly, I must say that Glenn has made good points, namely: 1) factor the common code in all cases out to a separate function, and 2) if you have nested conditionals, most times it's better and more readable to replace it with Guard Clauses.
However, personally I would prefer the following solution:

$theImg = null;
$i = 0;
while (!empty($matches[1][$i])) {
    $imgAtHand = $matches[1][$i];
    $dimensions = getimagesize($imgAtHand);
    if (($dimensions[0] > $width) && ($dimensions[1] > $height)) {
        $theImg = $imgAtHand;
        break;
    }
    $i++;
}

It has a couple of advantages over the "nested conditional" approach:

it eliminates code duplication;
it will work regardless of the array size.

One more thing. The following piece of code

isset($matches) && !empty($matches[1][0])

may well be replaced with

!empty($matches[1][0])

to make the code less verbose.


Calculate possible balances in piggy-bank by weight

Well, I don't have comments on the algorithm, but if you don't mind, I'd like to recommend a few improvements in the code. Just because it is a programming challenge, doesn't mean we shouldn't write good and clean code.

First major issue with the code is the excessive use of macro constants and function-like marcos. This is a deprecated practice in C++ since the language offers inline functions and typed constants. So all those shady 2-3 letter function-macros should really be actual functions.

Also, give them better names. It is pretty hard to tell just by looking at the code what a call to in() is. There's also an in2(), how's that different from in()? The only difference seems to be that the latter takes two parameters. Well, if you use functions, you don't need two names, since a single name can be overloaded.

#define inf 0x3f3f3f3f

What's the meaning of the constant (which should really be a const int)? It is not the largest value you can fit in a 32bit integer. So what's the story behind that? If you're not going to encode that info in the name, at least provide a comment with the reasons behind that choice. If you are just looking for a very large number, than perhaps use std::numeric_limits<int>::max().

int val[500], weight[500], dp[10001],n;

No need to make these variables global if they can be declared in the program stack and be passed as functions parameters, though the arrays are big. So perhaps they should be std::vectors.

int main()
{
    // your code goes here

Yep, I'd guess so ;)


Recursive spinlock for C using ASM, revision #1

gate_Leave has a superfluous compiler hint:

    : "eax"

Since gate_Leave returns an int and eax is often (always?) used to return values this is probably costing you extra instructions (although it might not as the function is inline, depending on how clever your compiler is).

Indentation and Labels

Labels are quite important in assembly.  I'd consider adding indentation so that they are easier to find, a lot like you would indent the contents of a while loop.

asm volatile (
    "jmp gate_Enter_check\n"
"gate_Enter_wait:\n"
    "pause\n"
"gate_Enter_check:\n"
    "cmp %[lock], %[pass]\n"     // Skip if pass >= lock
    "jge gate_Enter_skip\n"
    "mov %[lock], %%eax\n"       // Spinlock start
    "cmp %[gate], %%eax\n"       // Check if locked without lock cmd
    "je gate_Enter_wait\n"  // If locked, wait.
    "lock xchg %%eax, %[gate]\n" // Lock seems to be free, now we attempt to take it.
    "test %%eax, %%eax\n"
    "jnz gate_Enter_wait\n" // Spinlock end
"gate_Enter_skip:\n"
    "add %[lock], %[pass]\n"     // Checkin pass
    : [gate] "=m" (*gate), [pass] "=m" (*pass)
    : [lock] "r" (1)
    : "eax"
);

I'd consider minimising the contents of your spin section.  Some of the operations only need to be performed once (loading eax, checking pass).  I'm not sure you're really getting much benefit from the unlocked gate check, but without running tests I don't know either way:

asm volatile (
    "cmp %[lock], %[pass]\n" // We only need to check this once, if
                             // this changes while we are in the lock,
                             // some other thread is messing with it and
                             // we are in trouble anyway.
    "jge gate_Held\n"
    "mov %[lock], %%eax\n"   // Only need to load eax once, if it is ever
                             // changed, it's to 0 because we've just
                             // locked the gate

"gate_Enter_check:\n"
    "lock xchg %%eax, %[gate]\n" // Attempt to take it.
    "test %%eax, %%eax\n"
    "jz gate_Held\n"
    "pause\n"
    "jmp gate_Enter_check\n"

"gate_Held:\n"
    "add %[lock], %[pass]\n"
    : [gate] "=m" (*gate), [pass] "=m" (*pass)
    : [lock] "r" (1)
    : "eax"
);


Efficient numpy array manipulation to convert an identity matrix to a permutation matrix

Are there more efficient libraries than numpy for this?

Since permutation matrices are rather sparse, the scipy.sparse library is helpful.
Using its coo_matrix method we can build a matrix which contains given values at given indices.

From here it's just a matter of building the right lists of indices.

from itertools import chain
from scipy.sparse import coo_matrix

def permutation_matrix(n):
    # row and column indices - first even, then odd numbers in the latter
    I, J = range(n), list(chain(range(0, n, 2), range(1, n, 2)))
    # the following also works, if you are so inclined.
    # J = [m*2 + d for d, m in map(lambda k: divmod(k, n//2 + n % 2), range(n))]

    return coo_matrix(([1]*n, (I, J)))

If needed, we can use the .A property (short for .toarray()) to build a full matrix from this: e.g.
permutation_matrix(10).A.

Why bother with sparse matrices?

Multiplication with sparse matrices will be much faster: e.g. matrix-vector products can be computed in O(n) time instead of O(n^2).
Similarly, the memory requirements for storing these matrices in sparse format is O(n) instead of O(n^2).

  Is there an approach where I can shift the 1s without needing to
  create a separate zeros array in memory?

Sure, numpy.roll does circular shifting:

numpy.roll([1,0,0], 4) == numpy.array([0, 1, 0])

  Is there an Pythonic way to implement two different functions on two
  halves of the same array without splitting them up?

Not sure, but you can always cook something up.

from collections import deque
from itertools import chain

def apply_to_parts(part_selector, funs):

    def wrapper(vals):
        results = [deque() for _ in funs]

        for ix, val in enumerate(vals):
            part_ix = part_selector(ix, val)
            results[part_ix].append(funs[part_ix](val))

        return list(chain(*results))

    return wrapper

# multiply elements at even indices by 2
# divide   elements at odd  indices by 4
# return a list of elements in part 1 followed by elements in part 2
example = apply_to_parts(
    lambda ix, val: ix % 2,
    [lambda x:2*x, lambda y: y/4]
)

# should return [2, 6, 0.5, 1.0]
example([1,2,3,4])


Radio buttons already group together using the name attribute. I suggest throwing away the code.

<input type="radio" name="group1" value="male">Male

<input type="radio" name="group1" value="female">Female

<input type="radio" name="group2" value="1">Active

<input type="radio" name="group2" value="0">Inactive


I wanted to offer a different angle of better. This code could be more generic. Why is it tied to exactly std::string - what if I need to check palindromic nature of std::wstring or the contents of a std::vector<T>? How about std::list<T> or std::map<T> (if palindromic can even mean anything on a std::map)? Here's how you can handle all of those with a single function:

template <typename Sequence>
bool is_palindromic(const Sequence& seq)
{
    auto count = seq.size() / 2; // rounded down is fine, as a middle element matches itself
    auto i = seq.begin();        // prefer std::begin(seq) in C++14
    auto j = seq.rbegin();       // prefer std::rbegin(seq) in C++14

    for (Sequence::size_type c = 0; c < count; ++c, ++i, ++j)
    {
        if (*i != *j)
            return false;
    }
    return true; // considers sequences without mismatched characters to be palindromes
}

Note that I incorporated the other comments I agree with - in particular passing by const reference, and using the sequence's size_type. I'm not sure how to best support arrays, however; while std::[r]begin will handle arrays, I don't believe arrays have a .size() or ::size_type to use. I guess that means they need their own overload, or at least some overloaded helpers.


I am %100 sure that this is the correct answer,

I'm not so sure... I dumped your code into an online compiler*. I made very minor adjustments, moving target to a parameter and adding semicolons which aren't a big deal since you probably didn't have a compiler when writing it. I did not modify your code beyond that and treated it like a black-box.

import java.util.Arrays;

class Main {
  static boolean test(int[] arr, int target) {

    int start = 0;
    int end = 0;

    int total = 0;

    while (end < arr.length) {

      total += arr[end]; // 1 3 1 4 = 9

      while (total >= target) {

        total -= arr[start]; // 8

        start++;

        if (total == target) {
          return true;
        }

      }
      end++;
    }

    return false;
  }

  static class Input {
    int[] sequence;
    int target;

    Input(int[] sequence, int target) {
      this.sequence = sequence;
      this.target = target;
    }
  }

  public static void main(String[] args) {
    Input[] inputs = new Input[] {
      new Input(new int[]{1, 3, 1, 4, 23}, 8),
      new Input(new int[]{1, 3, 1, 4, 23}, 7),
      new Input(new int[] {}, 0),
      new Input(new int[] {}, 1),
      new Input(new int[] { 0 }, 0),
      new Input(new int[] { 0 }, 1),
      new Input(new int[] { 1 }, 1),
      new Input(new int[] { -1 }, -1),
      new Input(new int[] { Integer.MAX_VALUE }, Integer.MAX_VALUE),
      new Input(new int[] { 1, Integer.MAX_VALUE }, Integer.MAX_VALUE),
      new Input(new int[] { Integer.MIN_VALUE }, Integer.MIN_VALUE),
      new Input(new int[] { 1, 1, 1 }, 2),
      new Input(new int[] { 1, 1 }, 2),
      new Input(new int[] { 1, 0, 1 }, 2),
    };

    for (Input input : inputs) {
      System.out.print(String.format("%s, %d => ", Arrays.toString(input.sequence), input.target));
      try {

      System.out.println(
          test(input.sequence, input.target));
      } catch (Exception e) {
        System.out.println("Caught exception: " + e.getMessage() );
      }
    }
  }
}

That produced this output:

OpenJDK Runtime Environment (build 10.0.2+13-Ubuntu-1ubuntu0.18.04.4)
[1, 3, 1, 4, 23], 8 => true
[1, 3, 1, 4, 23], 7 => false
[], 0 => false
[], 1 => false
[0], 0 => true
[0], 1 => false
[1], 1 => false
[-1], -1 => Caught exception: Index 1 out of bounds for length 1
[2147483647], 2147483647 => false
[1, 2147483647], 2147483647 => false
[-2147483648], -2147483648 => Caught exception: Index 1 out of bounds for length 1
[1, 1, 1], 2 => false
[1, 1], 2 => false
[1, 0, 1], 2 => false

Your code was initially not wrapped into a method. Try to make it look like production quality code. That's ostensibly what the interview is looking at and writing all day.
Since it wasn't in a method, it implies you didn't consider writing tests.
Writing tests made it trivial to reveal cases that threw exceptions.
You didn't specify what should happen with an empty list which implies you didn't ask about that.
^^^ same with overflows. "Inputs that may cause overflows will cause undefined behavior" is a perfectly acceptable precondition in an interview IF you acknowledge that you have recognized this possibility, have a  notion of how to handle it, and the interviewer allows it.
It's also possible to yield incorrect answers with fairly trivial inputs, e.g. [1, 1]

*I do not recommend this online IDE, it felt very buggy. If someone has a better alternative I would be grateful.


if ($('.owl-item.active>.item.slide3').length>0) {
  $('#link3').addClass('hover');
} else if (jQuery('.owl-item.active>.item.slide4').length>0) {
  $('.link').removeClass('hover');
  $('#link4').addClass('hover');
} else {
  $('.link').removeClass('hover');
}

I notice the use of both $ and jQuery. Suggesting you use one or the other, but not both. While both are perfectly valid, it's best to keep it consistent.

Also, put a space on both sides of the > for readability. It's not immediately clear that there's actually 2 classes in the selector.

Comparing against 0 is redundant as the number can already double as a boolean. length is a number that's either 0 or a positive integer. Any non-zero number is truthy while 0 is falsy.

I would suggest you avoid IDs. IDs should be unique but nothing prevents you or other code from reusing the same ID. This will lead to problems. For instance, $('#selector') will only return the first of many elements with the same ID.

Without the accompanying HTML, we cannot make assumptions as to how the compare logic works. This is as far as the review goes.


As @l0b0 pointed out, you probably messed up your indents upon copying. Assuming they work:

First, looking at your question() functions, you can see a pattern, they prompt the user with a question. The user then has only two choices (binary like). If the user fails to enter a valid answer, they get prompted again. So why not create a function that gets passed the question and the binary answers? This also allows for easier expansion down the line like so:

def binary_question(question, answers):
    while True:
        print(question)
        Answer = input()
        if Answer in answers:
            print(answers[Answer])
            break
        else:
            print('try again...')

Questions = [
    '\nDo you get up and see what could be the source of this light? \nOr do you wait?',
    '\nThe light turns out to be a torch. Do you take this torch? enter y / n.',
]

Answers = [
    {
        'get up': 'You begin to walk towards the light.',
        'I get up': 'You begin to walk towards the light.',
        'wait': 'you wait, no one comes and you die...',
    },
    {
        'y': 'good choice, you pick up the torch and walk the out of the cave.',
        'n': 'well now your blind and dead...',
    },
]

game()
for que, ans in zip(Questions, Answers):
    binary_question(que, ans)

If you are not familiar with dictionaries or zip() look them up.

Second, you can allow for more choices by changing the user input strings to lower case and populating your Answers list to be only lower case. That way the user can enter "I get up" or "i get up", or "I GET UP", etc, and still get a valid response. Like so:

def binary_question(question, answers):
    while True:
        print(question)
        Answer = input()
        Answer = Answer.lower()
        if Answer in answers:
            print(answers[Answer])
            break
        else:
            print('try again...')

Questions = [
    '\nDo you get up and see what could be the source of this light? \nOr do you wait?',
    '\nThe light turns out to be a torch. Do you take this torch? enter y / n.',
]

Answers = [
    {
        'get up': 'You begin to walk towards the light.',
        'i get up': 'You begin to walk towards the light.',
        'wait': 'you wait, no one comes and you die...',
    },
    {
        'y': 'good choice, you pick up the torch and walk the out of the cave.',
        'n': 'well now your blind and dead...',
    },
]

game()
for que, ans in zip(Questions, Answers):
    binary_question(que, ans)

As you can see, we made use of str.lower() function and wrote lowercase only answers in our Answers dict.

Third, I just realized that if the player dies in question one, question two still gets asked. You need a return value to your main loop so you can break in case you are dead:

def binary_question(question, answers):
    while True:
        print(question)
        Answer = input()
        Answer = Answer.lower()
        if Answer in answers:
            print(answers[Answer][0])
            return answers[Answer][1]
        print('try again...')

Questions = [
    '\nDo you get up and see what could be the source of this light? \nOr do you wait?',
    '\nThe light turns out to be a torch. Do you take this torch? enter y / n.',
]

# can use named tuples here to make code more readable
# read about it if interested.
Answers = [
    {
        'get up': ('You begin to walk towards the light.', True),
        'i get up': ('You begin to walk towards the light.', True),
        'wait': ('you wait, no one comes and you die...', False),
    },
    {
        'y': ('good choice, you pick up the torch and walk the out of the cave.', True),
        'n': ('well now your blind and dead...', False),
    },
]

game()
for que, ans in zip(Questions, Answers):
    alive = binary_question(que, ans)
    if not alive:
        break

The new boolean values in Answers[] signify if that answer kills the player. In this case, True = alive and False = dead.


...        if len(args)>1:
...           for x in range(1, len(args)):
...              setattr(args[0], formalArgs[x], args[x])

You’re pretty much re-inventing zip here, use that instead. To extract out the first (self) parameter, you can use next (in Python 3) or slicing (in Python 2). To get a consistent behaviour accross Python versions, you can use itertools.izip in Python 2.

Something along the lines of:

arguments = zip(formalArgs, args)
_, self = next(arguments)
for name, value in arguments:
    setattr(self, name, value)

You can also define your wrapper as def wrapper(self, *args, **kwargs) to remove the need for next and already extract the value of self out of the args tuple. This will mean you’ll have to slice formalArgs though:

def wrapper(self, *args, **kwargs):
    formal_args = inspect.getargspec(func)[0][1:]
    for name, value in zip(formal_args, args):
        setattr(self, name, value)

You also don't need to inspect func at each call as, since you're using a decorator, you’re pretty much guaranteed that this object will never change during the lifetime of the program. Besides, it may be more readable to use the name, rather than the index, of the attribute you’re trying to extract out of the nametuple (since Python 2.6).

Lastly, getargspec has been deprecated since Python 3.0, so you'd better off using getfullargspec. But this function doesn't exist in Python 2, so you can try a conditional import:

from itertools import chain
from functools import wraps
try:
    # Python 3
    from inspect import getfullargspec as getargspec
except ImportError:
    # Python 2
    from inspect import getargspec
    from itertools import izip as zip

def store_attributes(method):
   arguments_names = getargspec(method).args[1:]

   @wraps(method)
   def wrapper(self, *args, **kwargs):
       for name, value in chain(zip(arguments_names, args), kwargs.items()):
           setattr(self, name, value)
       return method(self, *args, **kwargs)

   return wrapper

def class_store_attributes(cls):
    for name, value in vars(cls).items():
        if callable(value):
            setattr(cls, name, store_attributes(value))
    return cls

Usage being the same, even though I still don't get why you would use @class_store_attributes on the whole class rather than @store_attributes on a per-method basis.


Kotlin program to summarize git commits by regex match

I have never used Kotlin, so I can't give a comprehensive review or comment particularly on specific idioms.

I'm slightly bothered by this line, because null objects seems very much like a Java habit which Kotlin's paradigm generally tries to avoid.

var date: OffsetDateTime? = null,

It seems to me that Commit is the sort of thing whose values should be known at construction, so consider using the data class constructor.

I'm also a bit nervous about this line:

val gitDir = "C:\\dev\\git\\"

File(gitDir + repo)

I know you'll parameterise the list of repositories you want to use. When you do, it's worth thinking about things like cross platform usability. I can't give a specific recommendation, but it's generally better to use some sort of filesystem library rather than stitching together strings like that.

// string extensions
fun String.run(workingDir: File, targetFile: File = File("C:\\dev\\tmpFile")): File

Class extensions is a really cool capability, but it also feels like a dangerous use of that capabiltiy. As a rule of thumb, you wouldn't have a class method which isn't meaningful and legal to run for whatever instance of that class you have, and similarly be wary of adding extensions that don't make sense of most versions of a class. Since matchStr.run(...) wouldn't make any sense I'd be suspicious of extending String like this. I'd say either have a specific class for runnable strings, or just have a function that takes the string to run as a parameter.


Never ever use var. That's a deprecated form of public;
Avoid using public on your properties, you want to have controll about the value of every property in your class;
If you use protected or private doesn't make much sense. Protected means it can't be accessed from the outer scope, but it can be accessed from another class which extends this class. Private means it can only be accessed from the class where it is defined.

I like to have getters/setters for every property and never use $this->property directly inside my class, some other don't like that. See also this article by Fabien Potencier: "Pragmatism over Theory: Protected vs Private";
The :: operator, or T_PAAMAYIM_NEKUDOTAYIM, should only be used by accessing class constants and static vars/methods;
Avoid using static vars/methods;
Use $this->method() or $this->property to access properties from the inside of a class. It works just like you use it outside the class, except that you use the $this variable (which contains a reference to the current instance of the class).


Is there a better design pattern for a SDK?

I see this as a good design. As for now I would change only those two things and consider changing one more:

CommandAdapter seems to be unnecessary separation of logic here. I would just move it as instance method of Command (CommandAdapter is being removed),
Since Device represents low-level communication with hardware via RS232 - seems like something unmanaged going there and in fact SerialPort is IDisposable so - Device should be either:

public class Device : IDisposable
{
    private ushort deviceId;
    private SerialPort devicePort;
    public Device(string comPort)
    {
        devicePort = new SerialPort(comPort, 115200);
        // ...
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    public virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            devicePort.Dispose();
        }
    }

    //...
}

so now we have clear IDisposable semantics:

using (var device = new Device("COM1"))
{
    // ...
}

I am not sure whether Command is used somewhere else, but currently it seems to be a class that is created just to call ToArray on it. It may be inefficent, it depends how many times it is called etc. So consider reducing Command and pass byte[] representing command directly:

public class Command
{
    internal static byte[] Format(ushort deviceId, byte commandId, params byte[] data)
    {
        //build byte array to match format needed
        return new byte[] { };
    }
}

public static class CommandFactory
{
    public static byte[] GetDeviceId()
    {
        return Command.Format(0, GET_DEVICE_CMD_ID);
    }

    public static byte[] DoFooBar(ushort deviceId, byte mode, byte option)
    {
        return Command.Format(deviceId, FOOBAR_CMD_ID, mode, option);
    }

    // ...
}

public class Device : IDisposable
{
    // ...

    public byte[] FooBar()
    {
        byte mode = 1;
        byte option = 0x52;
        byte[] cmd = CommandFactory.DoFooBar(deviceId, mode, option);
        return TransceiveCommand(cmd);
    }

    private byte[] TransceiveCommand(byte[] cmd)
    {
        devicePort.Write(cmd, 0, cmd.Length);
        byte[] response = DeviceResponseParser.GetResponse(devicePort);
        return response;
    }
}

In this case you can of course merge Command.Format into CommandFactory. This makes much less sophisticated design but if Command do not any additional value - maybe worth consideration.


Find an unknown length using sohcahtoa (Trigonometry)

You know the equations, but fail to return them in your sohcahtoa dictionary.
Take 'soh':

\$\sin(\theta) = \frac{o}{a}\$
\$o = a\sin(\theta)\$
\$a = \frac{o}{\sin(\theta)}\$

From this you know all the equations, and you know they follow the form op(side, trig_fn(angle)). And so you should expand your sohcahtoa dictionary to contain this too.
I'd recommend you make an Enum for opposite, adjacent and hypotenuse, so that you get an actual error, rather than hidden errors, if you mis-spell them. (Yes you should be careful of this.)
It doesn't make sense to create sohcahtoa every time you call the function.

And so I'd change to:

from enum import Enum
import math
import operator

class TrigSides(Enum):
    OPPOSITE = 'opposite'
    ADJACENT = 'adjacent'
    HYPOTENUSE = 'hypotenuse'

SOHCAHTOA = {
    TrigSides.OPPOSITE: {
        TrigSides.HYPOTENUSE: (math.sin, operator.truediv),
        TrigSides.ADJACENT: (math.tan, operator.truediv)
    },
    TrigSides.HYPOTENUSE: {
        TrigSides.OPPOSITE: (math.sin, operator.mul),
        TrigSides.ADJACENT: (math.cos, operator.mul)
    },
    TrigSides.ADJACENT: {
        TrigSides.HYPOTENUSE: (math.cos, operator.truediv),
        TrigSides.OPPOSITE: (math.tan, operator.mul)
    }
}

def trigonometry(angle, side, known, unknown):
    trig_fn, op = SOHCAHTOA[known][unknown]
    return op(side, trig_fn(math.radians(angle)))


Change the title attribute of summary if details is open

detailsElem[i].ontoggle = function() {detailsToggle()};

It's better to use addEventListener. The problem is that doing it this way replaces anything assigned to ontoggle, potentially blowing away any handler put by other code.

var detailsElem = document.getElementsByTagName('details'),
summaryElem = document.getElementsByTagName('summary'),
summElemLen = summaryElem.length;
detlElemLen = detailsElem.length;

Personally recommending a var per variable. That way, you can easily add/remove lines without worrying about continuation. One such example is summElemLen ending with a ; and not a ,. This will cause detlElemLen to be defined on the global scope, and open to collision. This minor oversight can cause a lot of headache in the long term.

Also, using getElementsByTagName is very broad. Do you really want to take all elements? Or just a subset? If it's the latter, use a class name instead.

if (detailsElem[i].open === true) {

if statements expect a boolean. detailsElem[i].open is already a boolean. No need to do === true, it's redundant. true === true is always a true.

Lastly, one flaw in the code is that once you toggle one detail element, you toggle all summary titles regardless of whether they belong to the element you clicked.

The following is what I consider shorter, more explicit and takes advantage of the array API. We get all detail elements, loop through and attach a handler. Handler checks if a summary is present and only sets a title if there is one.

const slice = Array.prototype.slice

// querySelectorAll to select elements using a CSS selector.
// It returns an array-like structure (indexed, has length, no array API)
// To take advantage of array APIs, we use slice to convert to array.
const details = slice.call(document.querySelectorAll('.detail'))

// Use forEach to loop through each detail element found
details.forEach(detail => {

  // Add event handler when toggle is fired
  detail.addEventListener('toggle', event => {

    // Look for the summary with querySelector. It's like querySelectorAll
    // Except it returns either an element or null, instead of an array.
    const summary = detail.querySelector('summary')

    // No summary, do nothing.
    if(!summary) return;

    // Otherwise, assign title depending on detail state.
    summary.title = detail.open ? 'hide' : 'show'
  })
})


It looks like you want to create some helper functions as class methods.  If you do that, you probably want to use class variables (e.g. @@a) rather than instance variables.  I would like to suggest what I think may be a better way.

First, convert the instance variables you created with attr_accessor to class instance variables (not to be confused with class variables).  You can do that like this:

class CalendarDay
  class << self
    attr_accessor :from_month, :to_month, :year

    def line_of_day_numbers(month,year,start,offset)
      ...
      @sugar = 7
      x = 5
      @year = .....
      ...
    end
  end
end

Now you can use CalendarDay.from_month. CalendarDay.year = 2007, and so on.  Here class << self is opening CalendarDay's singleton class or metaclass.  (To be more precise, it sets self to that metaclass.)  You could add other class instance variables (@sugar), as well as local variables (x).  You can also add class instance methods, as I have done above.  You would invoke this method with:

CalendarDay.line_of_day_numbers(month,year,start,offset)

Notice that self. is not used in defining class instance methods.  That's because self is the class's metaclass when they are created.

Note that these are class instance variables and class instance methods, not class variables or instance variables or class methods or instance methods.  They are only available to the class object, CalendarDays.  If you were to create an instance of the class, cal_day = CalendarDay.new, you'd find cal_day would have no access to any of these class instance variables or class instance methods.

One of the nice things about doing it this way is that you can write your code between class << self and end in the same way you'd write code for a class instance.  All instance variables, local variables and instance methods are available to the class only.

For the record, there are a few (equivalent) alternatives to the class << self/end construct.  One is:

module CalendarDayModule
  attr_accessor :from_month, :to_month, :year

  def line_of_day_numbers(month,year,start,offset)
      ...
  end
end

class CalendarDay
  extend CalendarDayModule
end

I discussed that here.

Beyond this, I can make no suggestions for improving your code without seeing more of it, day_numbers() in particular.  BTW, within your line_of_day_numbers() class method, neither  first_line_padding() nor day_numbers() need be preceded by self..


Is there a condensed way of adding multiple event listeners each with different functions to the same group of elements?

Instead of iterating over the same array 3 times, iterate over it once:
topLevelDesktopNavDropdownItems.forEach((element) => {
  element.addEventListener('mouseenter', topLevelNavItemMouseOver);
  element.addEventListener('mouseleave', topLevelNavItemMouseOut);
  element.addEventListener('keydown', topLevelNavItemLinkKeyDown);
});

If you think that's too repetitive, you can put the listeners into an object and iterate over the object:
const handlers = {
  mouseenter: topLevelNavItemMouseOver,
  mouseleave: topLevelNavItemMouseOut,
  keydown: topLevelNavItemLinkKeyDown,
};
for (const element of topLevelDesktopNavDropdownItems) {
  for (const [event, handler] of Object.entries(handlers)) {
    element.addEventListener(event, handler);
  }
}

A couple suggestions regarding naming:

The mouseover event is not the same thing as the mouseenter event, Similarly, mouseleave is not exactly the same as mouseout. (One version propagates via bubbling/capturing, the other doesn't. If the elements have children, this makes a big difference.) For precision, consider naming the handlers exactly the same as the event they're listening for.

If you have lots of handlers like this, prefixing them all with topLevelNavItem may get undesirably verbose. To isolate their scope to hopefully make the prefixes less necessary, consider defining them inside a function:

const addDropdownListeners = () => {
  const mouseOverHandler = (event) => {
    // ...
  };
  // ...

Or define them inline with the object:
const dropdownHandlers = {
  mouseenter: (event) => {
    // ...
  }
  // ...


Well for starters maybe get rid of this with a few local variables and
give names to often used constants, e.g.

var pageNo = 'pageNo'+this.pageNumber;

or so.

The blocks with hasOwnProperty checks can be replaced with a
conditional:

this.clipCollection[this.category] = this.clipCollection[this.category] || {};

this.clipCollection.grandClipCount = (this.clipCollection.grandClipCount || 0) + 1;

And so on.


Move your code inside a function rather than doing things at module level to make it re-useable. Your function could accept a list of paths either through a function call or through command line arguments instead of a global list of paths.
Keep standard library, third party imports separate.
You could use itertools.chain.from_iterable instead of your flatten function. Also use glob.iglob to get an iterator instead of list of files to save memory.

for path in chain.from_iterable(glob.iglob(path) for path in PATHS):
    ...

For comparing types use isinstance instead of comparing types using is. is won't work in case of multiple-inheritance. Read: Differences between isinstance() and type() in python


I suggest hooking up the . button to a separate IBAction.  The decimal point isn't a digit, so the function name is confusing.  Furthermore, the code to handle a decimal point has little in common with the code to handle a digit.  There's no point in mashing the code together into the same function.

@IBAction func buttonDecimalPoint(sender: UIButton) {
    if !isTyping {
        display.text = "0."
    } else if !hasDecimal {
        display.text = display.text! + "."
    }
    isTyping = true
    hasDecimal = true
}

@IBAction func buttonDigit(sender: UIButton) {
    if !isTyping {
        display.text = ""
    }
    display.text = display.text! + sender.currentTitle!
    isTyping = true
}

Note that in buttonDecimalPoint, I test if !isTyping rather than if isTyping, so that I can write else if instead of nesting the conditionals like this:

@IBAction func buttonDecimalPoint(sender: UIButton) {
    if isTyping {
        if !hasDecimal {
            display.text = display.text! + "."
        }
    } else {
        display.text = "0."
    }
    isTyping = true
    hasDecimal = true
}

Another benefit is that the not-typing state can be thought of as the "initial" state, so it's more fitting that the code to handle it should come first.

Furthermore, I've moved the = true assignments to the end of each function to make the invariants obvious.  After pressing ., you know that isTyping and hasDecimal are both true.


Implementing a stack and using it to print alternate elements in reverse

Since you passed this may be a moot point,
but if this was an interview question,
when the spec says "implement an interface",
I would expect to see an interface:

public interface Stack<T> {

    void push(T item);

    T pop();
}

And an implementation:

public class StackImpl<T> implements Stack<T> {

    LinkedList<T> list = new LinkedList<>();

    @Override
    public void push(T item) {
        list.add(item);
    }

    @Override
    public T pop() {
        return list.removeLast();
    }
}

It's better to separate the interface, the implementation, and the runnable.
So the code of the main program,
and the retrieveAlternates method doesn't belong in a Stack class.

Also note that you don't need a stack at all to solve the problem.
You can just reference the elements of the input by the right indexes,
and you don't need to convert them to integers either:

static String retrieveAlternates(String[] input) {
    StringBuilder result = new StringBuilder();

    for (int i = 0; i < input.length; i++) {
        if ((i & 1) == 0) {
            result.append(' ').append(input[input.length - i - 1]);
        }
    }

    return result.substring(1);
}

I know this is cheating,
but actually,
you're already cheating when you implement a Stack interface using a LinkedList...
At an interview I would expect that you'd have to implement an array-backed stack or something,
without using the wonderful high level elements of the JDK.

Unit testing

Oddly, your unit tests have syntax errors: () missing from test1(),
and both tests call a method whose signature doesn't exist.
It's as if you've never run these tests,
just typed them up here because you know I would pick on not having any tests...

Also, test1 and test2 are not good names:
it's best when tests have descriptive names,
so that they are easier to understand,
both when reading the code later,
and when something fails and reading the error messages.

I would propose this naming style:

@Test
public void test_1_2_3_4_gives_4_2() {
    assertEquals("4 2", Solution.retrieveAlternates("1 2 3 4".split("\\s+")));
}

@Test
public void test_10_m2_3_4_gives_4_m2() {
    assertEquals("4 -2", Solution.retrieveAlternates("10 -2 3 4".split("\\s+")));
}

The splitting, necessitated by the method under test is tedious,
using new String[]{ ... } in each test case would also be tedious,
so I'd suggest to simplify using a helper method:

void assertAlternates(String expected, String input) {
    assertEquals(expected, Solution.retrieveAlternates(input.split("\\s+")));
}

@Test
public void test_1_2_3_4_gives_4_2() {
    assertAlternates("4 2", "1 2 3 4");
}

@Test
public void test_10_m2_3_4_gives_4_m2() {
    assertAlternates("4 -2", "10 -2 3 4");
}

And I suggest adding some more potential corner cases:

@Test
public void test_1_gives_1() {
    assertAlternates("1", "1");
}

@Test
public void test_1_2_gives_2() {
    assertAlternates("2", "1 2");
}

Note that I'm not following camelCase for test method naming.
I'm not aware of a standard for this,
and static code analysis tools like Sonar don't complain about this kind of naming,
even though I'm using the most strict rule set.

Keep in mind that unlike regular code,
it's acceptable (and even recommended) to use long names for test methods.
And these names tend to get long,
snake_case is far more readable (in my opinion) than camelCase.


ga('send', 'event', 'jserror', 'click', msg, {'transport': 'beacon'});

Yup, that's how I would do events in Google Analytics. However, the API also provides a special call for errors. It's found under Exception Tracking.

ga('send', 'exception', {
  'exDescription': msg,
  'exFatal': false
});

Another is that you're wrapping an addEventListener call into a try-catch. Not sure why this is required. The callback is fired asynchronously, thus the try-catch will make no sense (unless somehow, window or addEventListener doesn't exist)

if(typeof ga=="function") {

The snippet (and not the script that it loads) creates the global ga function for you, which means the global ga should be present when the snippet is present. It's seen in the snippet as this portion:

i[r]=i[r]||function(){...}

But I see that it's possible that you're not loading it when debugging. So this can be ignored I suppose.

Lastly, rename e to error. This makes the variable tell what it is more.


Composing and executing a customer search

Not sure if you know how dangerous omitting braces for if statements can be. Do you know what happens here :

if(!string.NullOrEmpty(searchData.StreetName)
    query.Include(c => c.Address);
    query.Where(c => c.Address.StreetName == searchData.StreetName);

no matter wether searchData.StreetName is null or not the query.Where(c => c.Address.StreetName == searchData.StreetName); will be executed nevertheless. I assume from the way you have formatted the code that you assume this will be only executed if the condition is true.

I would like to encourage you to always use braces {} although they might be optional. This helps you to structure your code which helps to make it more readable and by using them you make your code less error prone.


Returns an array of all inputs with specified name

The GiveElementsByName function is poorly indented.
And the variable declarations should not be only a single extremely long var line,
but each variable should be on its own line.
It's better like this:

function GiveElementsByName(name) {
    var finalOutput = [],
        times = document.getElementsByTagName('input').length,
        inOutput = 0,
        inAll = 0;
    while (times--) {
        if (document.getElementsByTagName('input')[inAll].name == name) {
            finalOutput[inOutput] = document.getElementsByTagName('input')[inAll];
            inOutput++;
        }
        inAll++;
    }
    return finalOutput;
}

It seems to me that there is an easier way to do this using document.querySelectorAll, which should be supported by modern browsers:

function GiveElementsByName(name) {
    return document.querySelectorAll('input[name=' + name + ']');
}


Eliminating repetitiveness in code to test hash functions

Your code does seem open to some improvement. Right now, you're not really getting much good out of using a pointer to a function. You could just about as well invoke each hash function directly in findLowHash as call it via a pointer in foundLow.

In this case, we have a number of functions that all have the same signature, so we can create an array of the pointers to functions. Of course, array should also set off alarm bells--you should almost always prefer std::array or std::vector. In this case, I'll use st::vector, but if you're using a compiler new enough to include it, std::array would be an excellent choice as well.

typedef unsigned int (*hash)(std::string const &key);

std::vector<hash> hashes{
    RSHash, JSHash, PJWHash, ELFHash, BKDRHash,
    SDBMHash, DJBHash, DEKHash, FNVHash, BPHash, APHash
};

Depending on the age of compiler you're using, it might not support the braced init-list like I've used above. At that point, it's open to argument that (under the circumstances) it would be easier to use an actual array instead.

In any case, once you have your pointers to functions in something you can index like array, you can use a loop to walk through the array of functions, and use each function in turn:

for (int h=0; h<hashes.size(); h++)
    for (int i=0; i<100000; i++) {
       incrStr(key);
       carryStr(key);
       if (hashes[h](key) < 10000) {
           std::cout << // ...
           break; // breaks inner loop, so goes to testing next hash function
       }
    }

Again, if you have a new enough compiler (C++11) available, you can make the outer loop a little prettier using a range-based for loop:

for (auto &&hash : hashes)
    // ...
    if (hash(key) < 10000)
        // ...

Once you've done that, there are a few more fairly obvious points, such as replacing the magic numbers like 100000 and 10000 with defined constants with more meaningful names.


First Occurrence of Number in Binary Search?

Not exactly a code review, but did you know that ruby 2 introduces binary search for arrays ?

See : Array#bsearch.

your problem could be solved like this:

myarray.each_with_index.to_a.bsearch{|(x,index)| x == n}
# => if found, returns an array containing the number and the index


Foreach loop to generate HTML table with title in first cell of each row in PHP

Is it critical that your product be the top row? It seems like you would benefit tremendously if your table was structured like this:

            Product
            Width
            Material

            50mm
            Plastic

because that way, you can just use a single foreach loop:

foreach ($rows as $row) {
    $similar_com .= "
";
    $similar_com .= "image_url' alt='$row->model_no' />
$row->name	";
    $similar_com .= "$row->width mm	";
    ...
}

You're doing a SELECT *. Avoid that; it's considered better to explicitly state the columns you're using.
I would rather rename your $rows variable to $products, but I notice that you already have a $product variable. I don't know what this variable is, but you should consider renaming some things... $similar_com is an especially useless name; I can't tell what it's supposed to mean.
I noticed you're using WordPress. The $wpdb->query(); $wpdb->last_result pattern is not as good as simply doing:

if ($rows = $wpdb->get_results($sql) {

If you have to keep your table structure the same, you could have separate variables for each row, then do it all in one foreach:

$widthRow = "
Width	";
$materialRow = "
Material	";
...
foreach ($rows as $row) {
    $widthRow .= "$row->width mm	";
    $materialRow .= "$row->material	";
    ...
}
$widthRow .= "
";
$materialRow .= "
";


NSAssert or NSLog in defaults switch case

Assertions are for declaring facts that you know to be true, not for conditions that you hope to be true.  If this method is only ever called by your own code, then it makes sense to assert.  On the other hand, if this is a public method, an assertion would not be an appropriate way to perform what is essentially parameter validation.


The good stuff

Your code looks neat and is pretty fast.

Remarks

I would second that the name Separator isn't chosen well and would like to suggest SpaceChar which is more obvious.

Review

The biggest problem I see is the missing null check for the parameter of the public method Compress. Throwing an ArgumentNullException instead of getting a NullReferenceException is better.

The Trim(string s) method doesn't buy you much. Saving some Ticks this way is a optimization which comes with less readable code. Just a call to string.Trim() is sufficient.

Initializing the StringBuilder like @Shelby115 suggested in his answer won't save you a lot but it is a good habit to do so. If you know how big the buffer of the StringBuilder can increase you should use that knowledge. With the default constructor the StringBuilder's internal buffer has a size of 16 which is doubled each time it is reached.

Instead of having this method in the TextCompressor class which implies that it compresses some text I would suggest making this an extension method.

I would like to suggest using a char [] instead of a StringBuilder and change the arrow code to something like this:

public static class StringExtensions
{
    public static string ReplaceMultipleWhiteSpaceWithSpace(this string str)
    {
        return str.ReplaceMultipleWhiteSpaceWithSeparator('\x20');
    }

    public static string ReplaceMultipleWhiteSpaceWithSeparator(this string str, char separator)
    {
        if (str == null) { throw new ArgumentNullException(str); }
        if (str.Length == 0) { return str; }

        int end = str.Length;
        int destinationOffset = 0;
        bool foundWhiteSpace = true;
        char current = separator;
        char[] destination = new char[end];

        for (int i = 0; i < end; i++)
        {
            if (Char.IsWhiteSpace(str[i]))
            {
                if (foundWhiteSpace) { continue; }

                foundWhiteSpace = true;
                current = separator;
            }
            else
            {
                foundWhiteSpace = false;
                current = str[i];
            }
            destination[destinationOffset] = current;
            destinationOffset++;
        }

        int newSize = foundWhiteSpace
            ? IndexOfLastNonWhithSpaceChar(destination, destinationOffset)
            : destinationOffset;

        Array.Resize(ref destination, newSize);

        return new string(destination);

    }
    private static int IndexOfLastNonWhithSpaceChar(char[] values, int startIndex)
    {
        if (startIndex >= values.Length) { startIndex = values.Length - 1; }
        for (int i = startIndex; i >= 0; i--)
        {
            if (!Char.IsWhiteSpace(values[i]) && values[i]!='\0')
            {
                return i +1;
            }
        }
        return startIndex;
    }
}

Some numbers

You mentioned in your question that you have measured the performance and provided some numbers, which are unfortunately missing a unit. I couldn't compare them to my numbers so I just measured your method and my method.

For both scenarios each benchmarked method first does a warm-up phase for 5000 ms and then it is called 10000 times and returns the average of StopWatch.ElapsedTicks which is then converted to milliseconds.

Passed in a string with Length of 7368 containing 4124 white space characters.

Yours: 0,0289723431498079 ms
Mine: 0,0308240396927017 ms
Other: 0,110759507042254 ms
Passed in a string with Length of 1591488 containing 890784 white space characters.

Yours: 6,70626021126761 ms
Mine: 7,66718351472471 ms
Other: 42,3948242637644 ms

So, what is Other? It is only taking 42 ms for the second scenario which is IMO fast enough for such a task. It's very simple:

string.Join(" ", str.Split().Where(s => s.Length > 0));


There are two things I think worth mentioning here:

use of random
magic numbers in enums

Random

Even though the java.util.Random class is thread-safe, it is not a great idea to use them in a multi-threaded context. As your class is an enum, it is likely that at some point it may be used in a threaded context (if it is not already). You should consider changing your code:

private static Random rnd = new Random();

to instead be (note also that this is 'final', and this is a java.util.concurrent.ThreadLocalRandom):

private static final ThreadLocalRandom rnd = ThreadLocalRandom.current();

This will give you better scalability in the future (or the present if you are already multi-threaded.

Enum Magic Numbers

Enums are a great concept in Java, and, it is one of those places where I believe magic numbers (special values with little apparent context or meaning) are really useful, and are OK.

You can embed 'magic' in with the enums and not worry too much about the readability... enums are supposed to be magic things.... So, I would consider code like the following:

import java.util.concurrent.ThreadLocalRandom;

public enum Direction {

    // use magic numbers to set the ordinal (used for rotation),
    // and the dx and dy of each direction.
    NORTH(0, 0, 1),
    EAST(1, 1, 0),
    SOUTH(2, 0, -1),
    WEST(3, -1, 0);

    private static final ThreadLocalRandom rnd = ThreadLocalRandom.current();

    static public Direction randomDirection() {
        return Direction.values()[rnd.nextInt(4)];
    }

    private final int r90index, r180index, r270index;
    private final boolean horizontal, vertical;
    private final int dx, dy;

    private Direction(int ordinal, int dx, int dy) {
        // from the ordinal, dx, and dy, we can calculate all the other constants.
        this.dx = dx;
        this.dy = dy;
        this.horizontal = dx != 0;
        this.vertical = !horizontal;
        this.r90index  = (ordinal + 1) % 4;
        this.r180index = (ordinal + 2) % 4;
        this.r270index = (ordinal + 3) % 4;
    }

    // Rotate 90 degrees clockwise
    public Direction rotate90() {
        return values()[r90index];
    }

    // Rotate 180 degrees
    public Direction rotate180() {
        return values()[r180index];
    }

    // Rotate 270 degrees clockwise (90 counterclockwise)
    public Direction rotate270() {
        return values()[r270index];
    }

    public Boolean isHorizontal() {
        return horizontal;
    }

    public Boolean isVertical() {
        return vertical;
    }

    public int dx(int steps) {
        return dx * steps;
    }

    public int dy(int steps) {
        return dy * steps;
    }

    public int forwards_x(int n) {
        return n + dx;
    }

    public int forwards_y(int n) {
        return n + dy;
    }

    public int backwards_x(int n) {
        return n - dx;
    }

    public int backwards_y(int n) {
        return n - dy;
    }

    public int left_x(int n) {
        // if we are E/W facing, our left/right 'x' co-ords are still 'x'
        // if we are N/S facing, our left/right 'x' is `-dy`
        return n - dy;
    }

    public int left_y(int n) {
        // see left_x comments for the idea
        return n + dx;
    }

    public int right_x(int n) {
        // see left_x comments for the idea
        return n + dy;
    }

    public int right_y(int n) {
        // see left_x comments for the idea
        return n - dx;
    }
}

The code above is very efficient. There are no conditionals in the methods, they will likely all be inlined in to the calling code. The 'smarts' are all contained within the enum, it 'just works'.


Matrix of checkboxes - only 1 allowed in a row

Assuming an unchecked starting condition you can eliminate a parameter and thus drop the conditional:

function switch_checkbox(id_pair)
{
    document.getElementById(id_pair).checked = false;
}

...

<input type="checkbox" name="group1[]" id="1-1" value="1-1" onChange="switch_checkbox('1-2');"/>


If I'm understanding things correctly, (x,y) is an anchor point of your object (say, bottom left), and you're iterating over every single point that could be an anchor point for an object that it's in collision with, then checking if it's an actual anchor point of an existing object.

My suggestion (assuming that your shapes are small and circle/box-like) would be to check for exclusion rather than inclusion. If you consider that each obj has a bounding rectangle around it, then do the following checks:

curr-x > test-x + test-width
curr-x + curr-width <= test-x
curr-y > test-y + test-height
curr-y + curr-height <= test-y

If any of these are true, then you're no longer interested.

So your function then becomes something like:

typedef std::multimap<Point2D, GameObj*> ObjectSpace;
void World::checkForCollisions()
{
    for (int i = 0; i < objectsVector; ++i) {
        GameObj* currObj = objectsVector[i];
        for ( ObjectSpace::iterator ito = objectsmap.begin(); ito != objectsMap.end(); ito++ ) {
            const GameObj* test = it->second;
            if ( test == currObj ) continue;
            if ( outsideBoundingRectangle( currObj, test ) ) continue;
            if ( checkCollision( currObj, test ) ) {
                    currObj->handleCollision( test );
            }
        }
    }
}

This may be enough for a reasonable speed.


Copying from a directory without using os.chdir()

shelve supports all methods that dictionarys do.

  Shelf objects support all methods supported by dictionaries. This eases the transition from dictionary based scripts to those requiring persistent storage.

And so you can use dict.setdefault, rather than your if-else.
Rather than using num += 1, you can use range(num, num + copies). Since num is defined in an outer scope, you can use it after the for loop too.
Rather than using string concatination, you can use f-strings in Python 3.6+ or format strings:

# yours
fName+'_'+str(num)+'.zip'
# f-string
f'{fName}_{num}.zip'
# string format
'{}_{}.zip'.format(fName, num)
'{fName}_{num}.zip'.format(fName=fName, num=num)

It's simpler to use with when handling content managers. And so you should use them on shelve.open and zipfile.ZipFile.

Not only does it make you not have to learn how to close all types of context managers. The context will be closed in the case of an error too.
Don't use CamelCase or camelCase, instead use snake_case.
Use _ as a 'throw away' variable. Some people, however, like to instead use __.
Put a space either side of your equal signs. a = b, not a= b.

This can become:

import os, shelve, zipfile

def backup_to_zip(folder, destination, copies=1):
    f_name= os.path.basename(folder)
    with shelve.open('names') as names:
        num = names.setdafault(f_name, 1)

        os.chdir(folder)
        for num in range(num, num + copies):
            zip_path = os.path.join(destination, f'{f_name}_{num}.zip')
            with zipfile.ZipFile(zip_path, 'w') as the_zip:
                for _, _, filenames in os.walk(folder):
                    for filename in filenames:
                        the_zip.write(filename)

        names[f_name] = num

You could also use pathlib rather than os.path. Which may allow you to use:

def backup_to_zip(folder, destination, copies=1):
    folder = Path(folder)

    with shelve.open('names') as names:
        num = names.setdefault(folder.name, 1)
        path = folder / Path(destination)
        for num in range(num, num + copies):
            with zipfile.ZipFile(path / f'{folder.name}_{num}.zip', 'w') as f:
                for file in folder.iterdir():
                    if file.is_file():
                        f.write(file.name)

        names[folder.name] = num


for(int i=1; i<=n; i++){
    findParent(dj, i);
}

for(int i=1; i<=n; i++){
    if(!map.containsKey(dj[i])){
       count++;
        map.put(dj[i], 1);
    }
}

This part is slow and unnecessary - you can count how many times you did union instead.

 int[] dj= new int[n+1];

With 10^9 limit for N, only that line requires 4GB of RAM, when limit for task is 1.5GB. Use HashMap instead and store only unioned ids - there will be at most 2*M of those.


This isn't really a bad workaround. In fact, I wouldn't even consider it a workaround. It is now part of the business logic of the application.

The only reason it feels like a workaround is because of your // 1 case and // 2 case comments. Remove those and this is no longer a workaround.

I see the following method:

protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
    var ticket = await EnsureCookieTicket();
    if (ticket == null)
        return AuthenticateResult.Fail("No ticket.");

    //...

    return AuthenticateResult.Success(new AuthenticationTicket(context.Principal, context.Properties, Options.AuthenticationScheme));
}

And can't help but wonder what the //... bit is because I see no reason for ticket to be a strong type. This entire method:

private Task<AuthenticationTicket> EnsureCookieTicket()
{
    var cookie = Options.CookieManager.GetRequestCookie(Context, Options.CookieName);
    if (String.IsNullOrEmpty(cookie))
        return null;

    var ticket = Options.TicketDataFormat.Unprotect(cookie, GetTlsTokenBinding());
    if (ticket == null)
        return null;

    var currentUtc = Options.SystemClock.UtcNow;
    var issuedUtc = ticket.Properties.IssuedUtc;
    var expiresUtc = ticket.Properties.ExpiresUtc;

    if (expiresUtc != null && expiresUtc.Value < currentUtc)
    {
        //...

        Context.Items.Add("IsExpired", true);
        return null;
    }
}

Never returns a non-null value either. So I'm guessing the bits you left out are substantially important to understanding why you chose the form you did.

Provided you don't need AuthenticationTicket in the HandleAuthenticateAsync() method, I would change the return result from Task<AuthenticationTicket> to Task<bool>. Then rename it to IsTicketValid().

if (expiresUtc != null && expiresUtc.Value < currentUtc)

You don't use .HasValue to check there, but you use it on Request.Path.HasValue, we should be consistent and do if (expiresUtc.HasValue && expiresUtc.Value < currentUtc).

I don't like any of these method names, and as a result the method actions themselves because it looks like each one of them has too many responsibilities. You omitted certain parts (so this should have been VTC'd probably) but I'd be willing to bet those parts do more than they should. You should try to find a way to break the flow up into smaller methods that are more maintainable.


Checking referential integrity of a database schema

This code does not work properly. Basically you build two enormous arrays containing all values of foreign keys in your database. That's probably a lot.

1: The $x and $test variables serve no purpose and should be removed.

2: The comparison of tablet A and B should be moved inside the while() loop.

I also suggest some unset's and closures of resources that are no longer needed.


There's a lot of design oddities in this, and I don't quite see the value of it.  The brevity it allows now will undoubtedly cause issues once you use this in a complex application.

Why is:

$core = new Core();
$core->init('User, Control');

$core->Control->test2();

echo "<br />";

$core->User->test();

Better than:

spl_autoload_register(...);

$control = new Control();
$control->test2();
$user = new User();
$user->test();

Autoloading is typically setup in some form of bootstrap.  It is usually done in the same place that DB connections are made, application-wide configuration is put into place, etc.

This mean that your main script content should never have to worry about autoloading since your bootstrapping will have already taken care of it.

(Note that a boostrap does not need to be a huge complex process.  Sometimes it can be as simple as include 'boostrap.php';)

Anyway, your class has a few design problems and a a few implementation problems:

Design:

What if you want more than 1 User object in the core?
What if you need to pass a parameter to a constructor
init() can make the state of the object unknown.

if you pass a Core instance to some other place of code, how does that code know what properties are valid on the object
This type of magic almost always ends badly since it hides state information

Implementation:

__get should check if the key exists in $extra before blindly accessing/returning
Unnecessary string processing: Why explode a string?  Just use an array.  It's cleaner and less error prone.
If you do keep this class (which I advise that you don't), I would consider making the init() part of the constructor.  I like to ensure that all of my instances are always in a stable, usable state.  What happens if you use a Core instance before calling init?
Setting up autoloading, storing objects and creating objects are three discrete responsibilities.  This means that the class is likely doing too much.

Once again, I recommend not using the class, but if you do:
Have the constructor take in an Autoloader instance and have that class handle loading
Have the class take in instances instead of names (this decouples creation from storing -- which is good since it means you have much more control of instantiation -- but it will kill the brevity of using your class)


If you use default parameters, you won't need to overload the function.

def punch(User user, User source, String latitude=null, String longitude=null)


Speed up lights-out variant solver in pure Python

You have a matrix of bits. You could represent each row by a single integer. (Remember that in Python the size of int is unlimited, so working with 255 bits is not a problem.)  Then you would be able to avoid the inner loop here

for row in xrange(pivotRow + 1, n):
    if toggle[row][col]:
        for i in xrange(len(toggle[row])):
            toggle[row][i] ^= toggle[nextFreeRow][i]

and do this instead

col_mask = 1 << col
for row in xrange(pivotRow + 1, n):
    if toggle[row] & col_mask:
        toggle[row] ^= toggle[nextFreeRow]


How can I reduce this .less call to one line per image

I don't see anything wrong with what you are doing but. it can be written shorter just as you asked.

.SBtnM(@selector, @urlprefix, @width, @height)
{
   .@{selector}
   {
       .toolbarbutton > &
       {
            @url: %("%s_normal.png", @urlprefix);
            width: @width;
            height: @height;
            background-image:url(@url);
       }
       .toolbarbutton:hover > &
       {
            @url:%("%s_rollover.png", @urlprefix);
            background-image:url(@url);
       }
       .toolbarbutton[checked="true"] > &
       {
             @url:%("%s_pressed.png", @urlprefix);
            background-image:url(@url);
       }
   }
}

.SBtnM(btnCSS1, 'chrome://xtoolbar/skin/img1', 42px, 24px);

For me this produces:

.toolbarbutton > .btnCSS1 {
  width: 42px;
  height: 24px;
  background-image: url("chrome://xtoolbar/skin/img1_normal.png");
}
.toolbarbutton > .btnCSS1 {
  background-image: url("chrome://xtoolbar/skin/img1_rollover.png");
}
.toolbarbutton[checked="true"] > .btnCSS1 {
  background-image: url("chrome://xtoolbar/skin/img1_pressed.png");
}

Works for LESS 1.3.1+ ONLY. For previous versions the syntax is slightly different.


Disclaimer: I am not an expert on cryptography or security, so please
take everything with respect to these topics with a grain (or more) of
salt. Note also that there are ready-made crypto libraries (such as
RNCryptor) so you might want
to use one of those.

I do not see the advantage of a default key – only the risk that you use
it for some critical task. I would suggest to remove the default value.

CCCrypt() in encryption mode can only fail if the provided buffer is
too small, or if padding is disabled. Both cases cannot occur in your
code. Therefore there is no need to make the return value of
the encryption method an optional:

func AES128EncryptedDataWithKey(key: String) -> NSData {
    return AES128Operation(CCOperation(kCCEncrypt), key: key)!
}

Your getCString() code is quite clear. There are various methods
to convert a C string to a byte buffer. Here are two alternatives
which don't require the address-of operator &:

var keyData = Array(key.utf8)
if keyData.count < kCCKeySizeAES128 {
    keyData += Repeat(count: kCCKeySizeAES128 - keyData.count, repeatedValue: 0)
}

or

let keyData = key.dataUsingEncoding(NSUTF8StringEncoding)!.mutableCopy() as! NSMutableData
if keyData.length < kCCKeySizeAES128 {
    keyData.length = kCCKeySizeAES128 // fills with zeros
}
// Use `keyData.bytes` to access the bytes.

(Note that these unwrappings/casts cannot fail.) Any of these methods
is fine, use whatever you feel most confident with.

The allocated buffer is "a bit" too large, the required size for
PKCS7 padding is the "next multiple" of the block size:

let bufferSize = (self.length/kCCBlockSizeAES128 + 1) * kCCBlockSizeAES128

The most reliable method is to determine the required buffer size by calling CCCrypt() with an empty buffer:

var bufferSize = 0
let status = CCCrypt(operation, CCAlgorithm(kCCAlgorithmAES128), CCOptions(kCCOptionPKCS7Padding), keyData, kCCBlockSizeAES128, nil, self.bytes, self.length, nil, 0, &bufferSize)
assert(status == CCCryptorStatus(kCCBufferTooSmall))

According to the CCCrypt documentation, this requires only a
"minimal runtime penalty."

Yes, you can use a Swift array instead of malloc():

var buffer = [UInt8](count:bufferSize, repeatedValue: 0)
// ...
return NSData(bytes: buffer, length: dataOutAvailable)

var numBytesEncrypted is misleading, it can be the number of
encrypted or decrypted bytes. CCCrypt() uses dataOutAvailable
for that parameter.

As I understand it from Wikipedia: AES,
AES 128/192/256 differ only in the size of the key, which means
that you have to replace kCCKeySizeAES128 by kCCKeySizeAES192
or kCCKeySizeAES256. (But as I said, I am not an expert on this
topic.)

You have chosen CBC (cipher block chaining) mode and not
ECB mode (as in the referenced Objective-C code) – which is good. But you should also
add an additional parameter to provide an
initialization vector., or the
possibility to generate a random one.
 Currently the corresponding parameter is
nil so that a block of zeros is used.
See – for example – Why use an Initialization Vector (IV)? for more information.


Toggling ActionBar visibility for SherlockFragmentActivity

Three points:

getSupportActionBar() is called four times within the same method. Store it as a local variable and use the variable four times instead, to improve code cleaniness and readability.
When catching exceptions, be as specific as possible. Catching Throwable is a horrible idea. Only catch the exceptions you need to catch (Which involves neither Errors or RuntimeExceptions. You shouldn't even wrap ((DilbertFragmentActivity) getSherlockActivity()).toggleActionBar(); inside a try-catch statement. If you think that something can go wrong (like a NullPointerException), make sure that it doesn't go wrong before you try to do it (by checking if something is not null for example).
If viewPager can be marked as private, it is good practice to also mark it as private.