Design

In modern standard libraries, std::string uses short string optimization, which allows to avoid heap allocations at all for string shorter then ~20 chars (on 64-bit machines). So you really want to measure performance, I am not readily convinced that your string offers performance improvement. Of course, for your specific use pattern it might, but you have to measure.

__dup function

This is the most problematic part of the code.

Apparently, you forgot to return value from __dup method (now fixed).
You must allocate one char more and fill it with zero. Or copy size+1 characters from the source.
Identifiers with leading double underscores or one leading underscore and a capital letter are reserved by the standard. You must not use such an identifier. It is enough that you already have put it into private section.

After the corrections, the function could look like this:

static char *dup(const char *s){
    auto size = strlen(s);
    char *copy = new char[size + 1];
    memcpy(copy, s, size + 1);
    return copy;
}

Safety

Functions do not check for null pointers. This code will cause illegal memory access:

String x;
String y{x};

Style

You don't need semicolons after the member function definitions
I would recommend not putting methods on a single line even if they have empty bodies.
You can use C++ style headers <cstring> and <cstdio> instead of C-style ones.
I would recommend to implement an operator<<(std::ostream &, const String &) so you could use your string together with iostreams.
For testing, it is better to use a testing framework. Like boost.test, gtest, Catch etc.


Functions are your friend

Even in Jython, functions are a valid construct. They allow for scope, so that you can better reason about temporary variables; give better stack traces when things go wrong; increase testability; etc. So you should move your code into some functions.

Invert your logic

This:

if len(laty) == 7 and len(longx) == 6:

should probably be inverted, and something done about it, i.e.

if len(laty) != 7 || len(longx) != 6:
    # throw, or at least print...
# continue on with the rest of the function

If you had requests...

then this:

url="http://something.com/arcgis/rest/services/something/Zones/MapServer/15/query?geometry=" + longx + "%2C" + laty + "&geometryType=esriGeometryPoint&spatialRel=esriSpatialRelIntersects&outFields=*&returnGeometry=false&f=pjson"

could be fairly reduced in insanity. The query params can be formed as a dictionary passed to the get method.

PEP8

Use any kind of linter or modern IDE, and it will give you suggestions on how to reformat this thing to follow Python formatting standards (PEP8). The most obvious thing it will notice is lack of spaces after commas.

Otherwise - perhaps you should provide some context about why this thing exists in Jython.

Suggested

I don't know whether this will work, because I don't have your setup; so you'll probably have to tweak it.

from psdi.mbo import MboConstants
from java.util import HashMap
from urllib import urlencode
from urlparse import urlunparse, ParseResult

def get_coords():
    """
    Get the y and x coordinates(UTM projection) from the WOSERVICEADDRESS table
    via the SERVICEADDRESS system relationship.
    The datatype of the LatitydeY and LongitudeX is decimal, i.e.
    1234567.8335815760, 123456.4075621164.
    """
    laty = mbo.getDouble("SERVICEADDRESS.LatitudeY")
    longx = mbo.getDouble("SERVICEADDRESS.LONGITUDEX")
    return laty, longx

def is_valid(laty, longx):
    """
    Verify if the numbers are legitimate UTM coordinates
    """
    return (0 <= laty <= 10e6 and
            167e3 <= longx <= 833e3)

def make_url(laty, longx):
    """
    Assemble the URL (including the longx and the laty). Note: The coordinates
    are flipped in the url
    """

    query = {
        'geometry': '%d,%d' % (laty, longx),
        'geometryType': 'esriGeometryPoint',
        'spatialRel': 'esriSpatialRelIntersects',
        'outFields': '*',  # You should narrow this if you only care about work zone.
        'returnGeometry': 'false',
        'f': 'pjson'
    }

    parts = ParseResult(scheme='http',
                        netloc='something.com',
                        path='/arcgis/rest/services/something/Zones/MapServer'
                             '/15/query',
                        query=urlencode(query),
                        fragment='')

    url = urlunparse(parts)
    return url

def fetch_waste_zone(url):
    # Get the JSON text from the feature service (the JSON text contains the
    # zone value)
    ctx = HashMap()
    ctx.put("url", url)
    service.invokeScript("LIB_HTTPCLIENT", ctx)
    json_text = str(ctx.get("response"))

    # Parse the zone value from the JSON text
    ctx = HashMap()
    ctx.put("json_text", json_text)
    service.invokeScript("LIB_PARSE_JSON", ctx)
    parsed_val = str(ctx.get("parsed_val"))

    return parsed_val

def main():
    laty, longx = get_coords()
    if not is_valid(laty, longx):
        print('Invalid coordinates')
        return

    url = make_url(laty, longx)
    waste_zone = fetch_waste_zone(url)

    # Enter the zone value into the zone field in the work order
    mbo.setValue("DESCRIPTION", "Waste Zone: " + waste_zone,
                 MboConstants.NOACCESSCHECK)

main()

Note:

There are functions
The functions contain """docstrings""" at the top
You should preserve the UTM coordinates as doubles until it's necessary to format them as integers in the URL string
UTM coordinates have real limits that you should use - not just string length
Even if you don't have requests, you can still do somewhat saner query string formation via dictionary
If the coordinates are invalid, do something - maybe print, definitely quit


In almost all methods for example in this one instead of

public void removeElement(T element)
{
    int index=searchElement(element);
    if(index>0)
    {
        removeElementAtIndex(index);
    }
}

should be

public void removeElement(T element)
{
    int index=searchElement(element);
    if(index >= 0)
    {
        removeElementAtIndex(index);
    }
}

Because otherwise the first element will get you an error.


Variable Names

You use a, b, c, d, e, f, and g to refer to important things. I started trying to keep track of what each one meant and then gave up. I have no idea. Give things meaningful names. Apparently d is the number with the longest sequence, whose length is e - which is certainly not obvious from the names!

Chaining

To find the length of the collatz chain for some number, n, involves also finding the length of the collatz chain for every other number in that chain. However, you don't store that information anywhere, so it's lost.

Furthermore, you calculate it TWICE:

if collatz_length(f)>e:
    d=f
    e=collatz_length(f)

So you're recalculating every chain every time twice. That's an enormous amount of extra work. Lastly, you're assuming that the largest starts halfway through. That isn't necessarily true, given that collatz(n) > n for odd n...

Saving State

You save some state in a, but that ends up with you having to do a linear search through a list... which will fail most of the time, but it'll take a long time to fail. At the very least, you could store things in a set(), which is O(1), but even then, you're storing the wrong state. You're storing numbers you've seen before, but what you should store is the chain lengths of the numbers you've seen before. That is...

Memoize

This is a problem that lends itself extremely naturally to memoization, so we can just do that:

@memoize
def collatz_length(n):
    if n == 1:
        return 1
    else:
        return 1 + collatz_length(collatz(n))

And then just stick that into max:

longest_num = max(range(1, 1000001), key=collatz_length)
print(longest_num)
print(collatz_length(longest_num))


Extending window.location give access to query string elements

For the most part this looks good to me - your code is easily understood and well formatted. However, there is still room for improvement.

Don't bother creating mapped, that logic could easily be integrated into the reduce function and avoids an extra loop over the array.

Don't assign to an object just to return it, instead of doing var obj = ... return obj just do return pairs.reduce(...

Parsing URLs is complicated. It's really easy to forget to encode / decode something when working with them. In this case, your code correctly decodes the query values, but fails to decode the query key - if my query is ?q%26=search, I would have to use document.location.query['q%26'] instead of the expected document.location.query['q&']. Is this likely to happen? Maybe not, but it should be handled.
What I mean to say is - don't reinvent the wheel. There is a build in URLSearchParams object which does the parsing for you.

What should happen if the URL is ?q=1&q=2? Should only the first value be kept? Only the last? What about ?q[]=1&q[]=2? Should this result in an array as PHP does or keep a single value? Ignoring these cases might be fine for your use case now, but if someone else uses your code, you should consider and document these edge cases.

Here's how I would implement this extension, ignoring the PHPism of converting keys using [] to arrays, and taking the last value if the same key is specified multiple times. I've defined it as a function for ease of testing, but it could just as well be dropped into your get() function.

function getQueryObject(query) {
  const result = {};
  const params = new URLSearchParams(query);
  for (const [key, value] of params) {
    result[key] = value;
  }
  return result;
}

;[
  '?q=1&q=2',
  '?q%26=URLUtils.searchParams&topic=api',
  '?q[]=a',
  '?q=with some spaces'
].forEach(query => {
  console.log(query, '-->', getQueryObject(query))
})


Translating Objective-C use of static and +(void)initialize to Swift

Some thoughts:

Make formatter a static stored property (which are guaranteed to be lazily initialized only once). This  allows to get rid of the backing property _formatter.
For more clarity, move the reinitialization code to a separate method, as in your Objective-C version.
Do not cache the other static properties. For example, returning formatter.shortStandaloneMonthSymbols is only one indirection more than returning _shortMonthNames, but is simpler and allows to get rid of the remaining backing properties.
A minor point: The notification closure does not access the (notification) argument, which can therefore be replaced by _.

Putting it together, we have the following implementation:

public struct DateInfo {

    private static func reinitialize() {
        formatter = DateFormatter()
    }

    private static var formatter: DateFormatter = {
        // This closure is executed exactly once, on the first accesss of the `formatter` property.
        NotificationCenter.default.addObserver(forName: NSLocale.currentLocaleDidChangeNotification, object: nil, queue: nil) { _ in
            reinitialize()
        }
        return DateFormatter()
    }()

    public static var shortMonthNames: [String] {
        return formatter.shortStandaloneMonthSymbols
    }

    public static var longMonthNames: [String] {
        return formatter.standaloneMonthSymbols
    }

    public static var numberOfMonths: Int {
        return shortMonthNames.count
    }
}

Another option would be to use the typical Singleton pattern:

public class DateInfo {
    static let shared = DateInfo()

    private var formatter: DateFormatter

    private init() {
        formatter = DateFormatter()
        NotificationCenter.default.addObserver(forName: NSLocale.currentLocaleDidChangeNotification, object: nil, queue: nil) { _ in
            self.formatter = DateFormatter()
        }
    }

    public var shortMonthNames: [String] {
        return formatter.shortStandaloneMonthSymbols
    }

    public var longMonthNames: [String] {
        return formatter.standaloneMonthSymbols
    }

    public var numberOfMonths: Int {
        return shortMonthNames.count
    }
}

The advantage is that all initialization is clearly done in the init method. A small disadvantage might be that more typing is needed to access the properties (e.g. DateInfo.shared.shortMonthNames).


Checking if file is within a directory for security

Nit-Picks

This exception-handling code should include the IOException as part of the SecurityException re-throw:

try {
    tested = new File(file).getCanonicalFile();
} catch (IOException e1) {
    // set the cause of the SecurityException so that users can potentially fix things
    throw new SecurityException(
            "The basedir resolution failed to resolve.", e1);
}

General

I believe the rest of the code supplies the required functionality. There are odd cases where, for example, on Linux you can remount a sub-directory at a different mount point. These two distinct file-systems may mirror each other, and a file/directory in one mount-point is identical to the other mount point.

This may produce false-positives in your code (where your code will claim the directory is not allowed, but it actually is...). False-positives in 'edge cases' in a security situation are better than false-negatives.

The intricacies of the new-in-Java-7 NIO2 Path class/interface may help with this. You could translate your File instances in to Path instances, and then use the isSameFile(...) method... which may, or may not help (reading the documentation it is unclear, and I do not have direct experience with that).

Update .... more Paths:

Using the Path and other NIO2 features, your code could probably be reduced to:

// basePath is already resolved as a Path.realPath from basedir
// classPath is already resolved as a Path.realPath from classDir
Path filePath = file.topath().realpath();
if (!filePath.startsWith(basePath) || !filePath.startsWith(classPath) {
    // illegal file access....
    throw new SecurityException(.....);
}


Iterating through a list to generate calendars

I'd like to know how I could condense this into only being called once, rather than in each function.

One option would be to make a method that accepted the calendar or type and called the associated method
methods:
    generateCalendar(type) {
        const generateMethod = `generate${type}Calendar`
        if (typeof this[generateMethod] === 'function')
          this[generateMethod]()
          this.addToCalendar()
        }
      }

Then pass the type:
<button @click="generateCalendar(calendar.type)">

If the only property being accessed in the loop was that type property then destructuring assignment would allow it to be simplified:

   <button @click="generateCalendar(type)">
      {{ calendar.type }}
    </button

Alternatively, with using the method above the generator properties of the calendars could be removed, and calendars could perhaps just be an array of strings.
Also, it seems that three of the four calendar methods are nearly identical other than the class of calendar object created: generateGoogleCalendar, generateOutlookCalendar and generateYahooCalendar. A generic method could be used to replace those three methods (and accept the calendar type as a parameter to be used to dynamically invoke a constructor) or create them dynamically in a loop.


You want "more efficient wordiness"??? I presume you're not asking for golfing, but for code that's more readable from conciseness.

@spec = map { $_ eq $module ? ($_, $_) : $_ } @spec;


Is there anything wrong with this double ternary?

Given your example I think that your double ternary operation should actually be a separate function. When you start getting complex one-liners like this, it is a sign that you need another function. Here's how I approached it:

function getStateName(state) {
  if(state is String) {
    return state as String;
  }

  // This will always return "null" if state.name does not exist.
  // I don't know about AS, but in JavaScript if something doesn't
  // exist it returns as undefined (not null), but you want the null
  // return. As far as I am aware, AS supports the || short-circuit and
  // truthy/falsey equivalence, like JavaScript.
  return state.name || null;
}

This could be used in your function like so;

public static function setStyleInState(styleName:String, value:*, state:*, target:UIComponent = null):void {
    var stateName:String = getStateName(state);

    if (!StateUtils.hasState(target, state)) {
        state = createState(stateName, null, target);
    }
    else if (!(state is State)) {
        state = getState(target, stateName);
    }
}

There's more to be said here; I think that exposing mutability like this on a static method (instead of on the instance of a state) is going to lead you into trouble later on down the road and you should probably re-evaluate your design.

Specifically, state in static methods is always a recipe for disaster when it comes to testability and debugging, especially when you branch into multiple threads.


You can try something like this, saving the names of the functions in a variable, and then accessing the variable with the name of the action, you can also save the reference of the functions of the variable in the properties and you would not have to use 'this'

_update: function(oHtml, oConfig) {
    var _this = this;
    var oParent;
    var actionsToExecute = {
      upd : '_updateAttr',
      new : '_insertAttr',
      del : '_removeAttr'
    }
    if (oConfig.attributes != null) {
        oConfig.attributes.forEach(function(oAttr) {
            //debugger;
            oParent = oHtml.find("#" + oAttr.id);
            _this[actionsToExecute[oAttr.action]](oParent,oAttr)
        });
        return oHtml;
    }
},


Test blank cell and out put phonetic (text)

Give your code a good name - not test - it doesn't tell me what it's doing.

At the same time, it's implicitly public so you might as well put that and always turn on Option Explicit. You can have it automatically by going to Tools -> Options in the VBE and checking the Require Variable Declaration option. This way if you have any variables not defined, the compiler will let you know.

You can use Do Until isEmpty but why not find the last cell and use a For loop? There is a standard way to find lastRow and lastColumn. That post explains why.

Technically you could eliminate If Cells(i, 2) <> vbNullString because the lastRow should determine that, but so would your Do Until isEmpty so it's already repetitive. You can also avoid assigning i an initial value and get rid of your messy (for VBA) iteration.

I would also eliminate the if block, personally.

Option Explicit

Public Sub GetPhonetic()
    Dim lastRow As Long
    lastRow = Cells(Rows.Count, 2).End(xlUp).Row
    Dim i As Long
    For i = 1 To lastRow
        If Cells(i, 6) <> vbNullString Then Cells(i, 6) = Cells(i, 2).Phonetic.Text
    Next i
End Sub

Also eliminate the commented code - if you aren't using it, it's just noise. I also eliminated the extra white space as you don't need it.

Re:

  I am also wondering if there is a way to set the starting point to be
  Column B (therefore, Cells(i,1)=B1) and possibility replace Cells(i,2)
  by dim as something(long?)?

I'm not sure what you mean here, you are already dim i as long and using that to determine your starting point; there's no need for it to be more complicated than cells(i,y).


Printing JUnit test results in file by changing and using the 'out' static variable of 'System' class

Looks good enough, but there's some improvements in the io API you're not using. Consider:

try (OutputStream outFile = Files.newOutputStream(Paths.get("result.txt"),
       StandardOpenOption.WRITE, StandardOpenOption.CREATE);
     PrintStream newSysOut = new PrintStream(outFile)) {
     System.setOut(newSysOut);
     Result result = JUnitCore.runClasses(TestSuite.class);
     printResults(result);
} catch (IOException ex) {
     // your code here
} finally {
     System.setOut(oldPrintStream);
}

This should give you more fine-grained Exceptions when your operations fail (not that I'm using it here).
Also you don't need to close the Resources you use yourself, because of the try-with-resources-block.

Small additional note: Your comments are extraneous for this example. I'd suggest removing them.


This query will return a random id from the DB with one simple SQL statement instead of using PHPs built in rand function.

MySQL:

$pdo->query('SELECT id FROM xxxxx ORDER BY RAND() LIMIT 1');

MS SQL:

$pdo->query('SELECT id FROM xxxxxx order by NEWID()');

I'm not entirely sure what database you're using, but this would eliminate a few lines of code.

Also, I'm not sure if you're using a database class to wrap around PHPs PDO class but I generally build an array and store my bound parameters in it then execute it. Looks a little neater.


Function that adds commas between groups of 3 digits in a string

Avoid using namespace std

The standard namespace isn't designed to be imported wholesale, and name collisions could later appear that silently change the meaning of your program (such as when you add an extra include, or move to a newer C++ standard).

std::string::insert moves content multiple times

We're not very efficient, because the later characters will be shuffled as many times as there are preceding commas inserted.  Worse, we don't even reserve() enough space to add the commas, so there could (theoretically at least) be multiple memory allocations.

Don't reinvent the wheel

It would be simpler and more flexible to use std::numpunct to perform the formatting.


Functions for setting cookies and outputting their IDs

First of all, let me tell you that I have zero experience with Codeigniter, but I suppose it is an MVC / OOP based framework, and I have plenty of experience with those. I am not trying to declare myself an expert or anything, just trying to be helpful and constructive. So here we go...

A few general words of advice:
 - try to avoid nesting control structures. Work with early returns in stead. You hardly ever need to nest an if inside an if, or even use an else. If you realy do, you are probably not following the principles of single responsibility
 - don't waste resources by storing stuff in variables and only using them once immediately after you stored them. Use the value you wanted to store directly.
 - Put comments inside your code. A lot of them! It may take a little bit longer now, but it will safe you time when you ever have to debug or alter your code!

With those hints in mind, I would write your first function as follows:

function setcookie() {
    // prepare the entry id
    $entry_id = $this->EE->TMPL->fetch_param('entry_id');

    // if cookie has not been set before
    if (! isset($_COOKIE['recently_viewed'])) {
        // write the current entry id to a cookie
        setcookie('recently_viewed', serialize(array($entry_id)), pow(2,31)-1, '/', '');
        // and we are done (return self for chaining)
        return $this;
    }

    // convert the cookie to an array
    $currentSession = unserialize($_COOKIE['recently_viewed']);

    // if the current entry id is already in the cookie
    if (in_array($entry_id, $currentSession)) {
        // we are done (return self for chaining)
        return $this;
    }

    // if there are already 5 entries
    if (count($currentSession) > 5) {
        // shift of the first entry
        // don't use an index here, cause there is no garantee the first element actualy has index 0
        array_shift($currentSession);
    }

    // push the current id onto the list
    $currentSession[] = $entry_id;
    // write it to a cookie
    setcookie('recently_viewed',serialize($currentSession), pow(2,31)-1, '/', '');
}

And the second function:

function recently_viewed() {
    // prepare the tagdata
    $tagdata = $this->EE->TMPL->tagdata;

    // if no recently_viewed cookie is present
    // (isset is supposed to be a little better in performance then array_key_exists)
    if (! isset($_COOKIE['recently_viewed']) ) {
        // do something and return the result
        return $this->EE->TMPL->parse_variables(
            $tagdata,
            array(
                array('entry_ids' => null)
            )
        );
    }

    // convert the recently viewed ids to a piped string
    // do something with it and return the result
    return $this->EE->TMPL->parse_variables(
        $tagdata,
        array(
            array(
                'entry_ids' => implode('|', unserialize($_COOKIE['recently_viewed']))
            )
        )
    );
}

You could even put that function into a single 'line' of code, which should be a bit more performant, but a lot less readable. And imo you should always take readable code over performant code when the difference is small. Just as an example though:

function recently_viewed() {
    return $this->EE->TMPL->parse_variables(
        $this->EE->TMPL->tagdata,
        array(
            array(
                'entry_ids' =>
                    isset($_COOKIE['recently_viewed'])
                    ? implode('|', unserialize($_COOKIE['recently_viewed']))
                    : null
            )
        )
    );
}


This would be a comment but I can't comment yet.

Why do you program the gravity yourself? Why not let the RB handle it? It has also a script-accessible value to change the gravity force. And the Direction of the Gravity is always -y. I think under the hood it could run smoother.


Nsum problem: find all n elements in an array whose sum equals a given value

def nsum(arr, n, val):

A documentation string here is important. The names of the variables are so vague that even knowing the task in advance is difficult to understand their meaning.

    if arr is None or len(arr) < n:
        return []

This check is non very useful. It does not decrease the algorithm complexity. In particular the check arr is None is wrong... you want the function to fail if the arr is not a list, otherwise you hide possible errors in the caller's code.

    # first sort the array by indice, so that we can search sequentially
    # with early stopping
    sorted_indice = sorted(xrange(len(arr)), key=lambda i: arr[i])
    size = len(arr)

invert the two lines above, so that you can use size in the previous line. Why to use xrange instead of range? The name of the variable sorted_indice is not very good for my taste: it is not "sorted" (maybe it is "sorting") and what does "indice" means? Maybe you mean "indices"?

    def nsum_recursive(arr, prev_indice, prev_sum, result):

Here the complexity is too much... we have four variables plus the three of the enclosing function: very difficult to keep track of all of them. arr is repeated. result should be the return value.

        ''' This is the main algorithm that is a recursive function.
        Think about the problem as tree search using depth-first search,
        Each node/state is determined by (prev_indice, prev_sum), where
        prev_indice is a list of currently explored indice, whose sum is
        prev_sum. When len(prev_indice)==n, we reach a leaf node. Then we
        can check whether the sum equals val.
        '''

The explanation is not very clear. You describe what are the nodes of the tree but what are the children of a node?

        # termination condition (leaf nodes)
        if len(prev_indice) == n:
            if prev_sum == val:
                result.append(tuple(sorted_indice[i] for i in prev_indice))
        else:

The two nested if are better replaced by a single if and the program should return at once, so that else is not required. This would reduce the indentation of your code. Also it seems that the check for equality and the check for early stopping are quite similar and could be done together.

            current_count = len(prev_indice)
            # depth-first search
            for idx in range(
                    0 if not prev_indice else prev_indice[-1]+1,
                    size-(n-current_count-1)):

here it is very difficult to understand if the range of numbers is correct.

                current_sum = prev_sum + arr[sorted_indice[idx]]
                # early stopping (pruning of branches)
                if current_sum>val and idx+1<size and arr[sorted_indice[idx+1]]>=0:
                    break

You can make the early stopping better (and maybe simpler) by checking that the current_sum plus the product of the remaining terms by the smallest term is larger that the target sum. You could also make the opposite check: if summing the larger possibile terms you cannot reach the target sum.

                nsum_recursive(arr, prev_indice+[idx],
                               current_sum, result)

    # start DFS from the root node
    result = []
    nsum_recursive(arr, [], 0, result)
    return result


Removing n elements from array starting from index

I believe that if the len < 0, it's better to adjust idx and len values. This will eliminate two branches of code.

Another suggestion is to use more readable variable names.
For instance, method arguments could be named startIndex and length respectively.

public static T[] RemoveAt<T>(this T[] array, int startIndex, int length)
{
    if (array == null)
        throw new ArgumentNullException("array");

    if (length < 0)
    {
        startIndex += 1 + length;
        length = -length;
    }

    if (startIndex < 0)
        throw new ArgumentOutOfRangeException("startIndex");
    if (startIndex + length > array.Length)
        throw new ArgumentOutOfRangeException("length");

    T[] newArray = new T[array.Length - length];

    Array.Copy(array, 0, newArray, 0, startIndex);
    Array.Copy(array, startIndex + length, newArray, startIndex, array.Length - startIndex - length);

    return newArray;
}


Query for stddev of number of stars per chatroom message

To answer your primary question directly, in certain SQL engines (for instance, Microsoft SQL Server and MySQL) you can declare query variables. Using plain SQL with Postgres, that is not possible.

You would either need to use plpgsql, which I'm pretty sure can't be done on 19B Data Explorer, or, using plain SQL, use WITH table expressions as you have.

Granted, it's not pretty, but otherwise works fine.

For a start, I would recommend to copy your query into a SQL formatter to format the code more appropriately; this makes it easier to then improve the code.

When using WITH tables, naming things goes a long way. I would first give this value a name (and remove the comment, please, or write a useful one):

WITH SE_Chat_ID_to_search
     AS (SELECT
        --Enter the user's SE chat user ID here:
        169713 AS id),

Which makes it easier to reference later and avoid doing SELECT * FROM SE_Chat_ID_to_search. I would also give a name such as uid to the value obtained within internal_id expression, for the same reason:

 internal_id
 AS (SELECT Max(id) AS uid
     FROM   "transcriptAnalyzer_user"
     WHERE  uid = (SELECT id
                   FROM   SE_Chat_ID_to_search)),

I would also carry that user ID into your other WITH table expressions, so that they can be joined properly (more on that in a moment), which will require the addition of a GROUP BY clause (or perhaps an aggregate function on it such as MAX(), same result though intention is less clear):

 stats
 AS (SELECT user_id,
            Avg(stars) AS mean,
            Count(*)   AS num_starred
     FROM   "transcriptAnalyzer_message"
     WHERE  user_id = (SELECT uid
                       FROM   internal_id)
        AND stars > 0
     GROUP  BY user_id),
 sum_diff_squared
 AS (SELECT user_id,
            Sum(Power((SELECT mean
                       FROM   stats) - stars, 2.)) AS sds
     FROM   "transcriptAnalyzer_message"
     WHERE  user_id = (SELECT uid
                       FROM   internal_id)
        AND stars > 0
     GROUP  BY user_id)

That brings us to the query which brings those tables together into the result set:

SELECT mean,
       power(sds / num_starred, 0.5) as stddev
from stats,
     sum_diff_squared

I mentioned joining tables properly. What you did above is an implicit join without a join condition, which effectively results in a Cartesian join (i.e. a Cartesian product of all rows of each table).

In your case, the impact was not felt because both tables return a single row; however, in reality, a Cartesian join is not only extremely slow, but more often also, unless done with careful intent, wrong.

There are 2 ways we can change this to a proper, non-Cartesian join. The first is by using the older (pre-ANSI92) implicit join syntax:

SELECT s.mean,
       Power(sds.sds / s.num_starred, 0.5) AS stddev
FROM   stats AS s,
       sum_diff_squared AS sds
WHERE  s.user_id = sds.user_id

Or by using the more modern explicit join syntax, which I always prefer due to its greater clarity:

SELECT s.mean,
       Power(sds.sds / s.num_starred, 0.5) AS stddev
FROM   stats AS s
JOIN   sum_diff_squared AS sds
       ON s.user_id = sds.user_id

The revised query returns identical results.


MultiThreaded TCP Server with high CPU usage

Big picture, you probably don't want to allocate and start a new thread to handle each incoming connection.  .Net has a very good ThreadPool implementation that scales up to as many threads as your machine can support without creating so many that performance suffers.

That said, it looks like your particular problem is that threads are never allowed to complete.  bClientConnected is the control variable for your main while loop, and it is never set to false, even if an exception is thrown.  You should always be suspicious of a catch that doesn't rethrow or at least exit the current function.


Applying a function to columns of two matrices producing their combinations

Your code is clear and concise, there is not much to complain about it, except for one small thing:

t = linspace(1, 2, 10)';

In MATLAB, ' is the complex conjugate transpose, whereas .' is the non-conjugate transpose, the simple re-ordering of dimensions. The array it is applied to here is real-valued, so there is no difference, but it is good practice to use .' always when the intention is to change the orientation of a vector. Bugs do appear at times because of the improper use of the ' operator.

As I've said before, loops are no longer slow in MATLAB, but often it's still possible to remove them ("vectorize the code") for a time gain. If the vectorization doesn't involve creating intermediate copies of the data, and doesn't involve complex indexing, then vectorization is still profitable.

In this particular case, vectorization involves calling a function one time vs calling it 10x10=100 times, and function calls still have a significant overhead in MATLAB. So cutting down on function calls will be beneficial.

Producing all possible combinations of two values can be accomplished with the bsxfun function in MATLAB. But in this case, we want to produce all combinations of two columns, and there is no function for that. However, you could use it to generate the product of all columns (the argument to trapz in your function ip). This requires a large intermediate matrix to be generated, but in this case (100 vectors of length 4), this is a very mild amount of data, and well worth the price if it means not calling a function 100 times.

Note that bsxfun is, since R2016b, no longer necessary. Everything you could previously do with bsxfun can now be done without it. For example, given x=1:10, you can do:

y = x .* x.';

to produce a 10x10 matrix with the product of all combinations of elements of x. This implicit singleton expansion happens automatically when the two arguments to any operator have compatible dimensions. That means that their sizes are identical along each dimension, or one of them has size 1 along a dimension (a singleton dimension). That singleton dimension gets repeated virtually to match the size of the other matrix.

Your function ip is written such that, given two input matrices x and y of compatible dimensions, it will compute your custom inner product along the first dimension, as long as that dimension has a size larger than 1. To make this function safer in use, you can explicitly tell trapz along which dimension to operate:

ip = @(x, y) trapz(x.*y, 1) / (size(x, 1)-1);

Now, ip(x,y) will compute many custom inner products at once, if x and y are matrices. However, ip(V, V) will compute the inner product of each column in V with itself, not all combinations of columns. For that, we need to do a little bit of reshaping of the inputs:

function V = cross_apply2(f, V1, V2)
s1 = size(V1, 2);
s2 = size(V2, 2);
V2 = reshape(V2, [], 1, s2);
V = f(V1, V2);
V = reshape(V, s1, s2);

What this code does is convert the second input matrix of size NxM to a matrix of size Nx1xM (this can be done without copying the data). Now the function f (really ip the way you call it) will use implicit singleton expansion to compute the custom inner product of each combination of columns of V1 and V2.

You can verify that cross_apply and cross_apply2 yield exactly the same result:

A = cross_apply(ip, V, V);
b = cross_apply(ip, V, f(t));

A2 = cross_apply2(ip, V, V);
assert(isequal(A,A2))
b2 = cross_apply2(ip, V, f(t));
assert(isequal(b,b2))

And we can also see what the time savings are for calling the function ip once instead of 100 times:

timeit(@()cross_apply(ip, V, V))
timeit(@()cross_apply2(ip, V, V))

On my computer this is 1.5016e-04 vs 2.9650e-05, a 5x speedup.

But cross_apply2 is not as general as cross_apply, as it imposes a requirement on the function to be applied to be vectorized.

trapz is a funny function. In your case, where it is called without an x input argument, it sets x to 1. The trapezoid rule now is simply the sum of the elements of the input vector, minus half the first and half the last element. I don't know what you application even is, but have you considered replacing this with the simple sum? Computing the true dot product is a lot faster.

You can do edit trapz to see how trapz is implemented. For the way you call it, it does:

z = sum((y(1:end-1,:) + y(2:end,:)), 1)/2;

This is the same, as I said before, as:

z = sum(y(:,:)) - y(1,:)/2 - y(end,:)/2;

But this second form is twice as fast for large arrays: The first form copies the data in y twice (minus one row), adds these results and sums them up, whereas the second form simply adds up all elements, then subtracts half of the first row and half the last row. For a random large array y:

y = rand(1000,100,100);
z1 = sum((y(1:end-1,:) + y(2:end,:)), 1)/2;
z2 = sum(y(:,:)) - y(1,:)/2 - y(end,:)/2;
max(abs(z1(:)-z2(:)))
timeit(@()sum((y(1:end-1,:) + y(2:end,:)), 1)/2)
timeit(@()sum(y(:,:)) - y(1,:)/2 - y(end,:)/2)

This shows that the largest difference between the two results is rounding errors (4.8317e-13), and the timings are 0.0778 vs 0.0341.


The problem is that a list made from the rows of a file with ~500M rows will have millions of entries, and that’s going to really hamper Python. As long as you’re using a list, I don’t think there’s any magic you can do here to magically fix that problem.

So you should ask: do I need a list? You may be able to make to do with a generator, which is much faster and more memory efficient (because it only computes one element at a time, not precomputing everything).

For a generator, I’m assuming that the customer IDs are monotonically increasing. If not, you really do have to go through the entire file to be sure you’ve got everything for each group. But your existing code seems to assume that, so I’ll assume I can as well.

Here’s a slight reworking of your code to use generators:

import csv

def sequencer(myfile):
    """
    Reads customer IDs and events from a CSV file.  Yields events for
    successive groups.
    """
    with open(myfile, 'rb') as csvfile:
        reader = csv.reader(csvfile, delimiter='|', quotechar='"')
        next(reader) ## skip header

        current_cust_id = 1
        seq = []
        for row in reader:
            cust_id, event = row

            if ('word' in event) or ('say' in event):
                continue

            while int(cust_id) != current_cust_id:
                yield seq
                seq = []
                current_cust_id += 1
            seq.append(event)

        yield seq

I’ve done away with the massive list (sequence), and we just yield the list of per-customer events whenever the customer ID changes.

A few other comments on your code:

Put your imports at the top of your file; don’t hide them inside a function.
There isn’t much in the way of documentation. Your function should at least have a docstring, and some more comments would be nice. For example, tell me why we’re skipping lines with “Say” or “Word”. I can read that the code is doing it, but I can’t read your mind to find out why.
You were assuming that customer IDs increase by 1 every time, and that there’s never going to be a gap. What happens if you run your code against:

"CustID"|"Event"
1|Alpha
1|Beta
1|AlphaWord
1|Delta
2|Beta
2|Charlie
2|CharlieSay
5|Echo
5|Delta

Maybe you know that will be the case; I wasn’t sure, so my code is defensive against this possibility.
Rather than doing seq.extend([row[1]]), it’s much cleaner to do seq.append(row[1]). It saves you creating an additional list.


Sandwich shop interface using the Decorator pattern

No:

An object "Sub" and a decorator "Topping" implement the same interface.
In addition a decorator takes an item (of the same interface) that it is decorating.
This is not quite what you have done.

What if I want extra cheese and meat?

You need something more like this:

class Price
{
    public:
       virtual     ~Price()   = 0;
       virtual int getPrice() = 0;
};

class Sub: public Price
{
    public:
        int getPrice() override {return 375;}
};

class ExtraCheese: public Price
{
    std::unique_ptr<Price>   item
    public:
        ExtraCheese(std::unique_ptr<Price>&& item)
             : item(std::move(item))
        {}
         int getPrice() override {return item->getPrice() + 25;}
};

int main()
{
    std::unique_ptr<Price>   sub(new Sub);
    std::unique_ptr<Price>   subCheese(new ExtraCheese(sub));
    std::unique_ptr<Price>   subCheeseMeat(new ExtraMeat(subCheese));

    std::cout << subCheeseMeat->getPrice();
}


Date and time columns conversion to Time(WithZone)

Nope. That's about as clean as it'll get, though like Flambino said, you can skip the last .seconds call. It's a bit clunky, but that's just how it works out.


First the nitty picky stuff

Every container has a empty() method. I would consider it bad practice to use  size() > 0 rather than !empty(), as it can have really performance implictations for lists and maps.
Please post complete code. You are missing any headers and also the dubious using namespace std; That one you should really ommit in your code and start using proper namespaces.

So now to the problem at hand. I think your data structure is indeed badly choosen. The first thing to note is what is important.

a. The type of instruction
b. The number of remaining instructions
c. The time until a certain instruction is ready.

You are missing the third point, which complicates the code more than it should. So lets start with a data structure that fits the problem

struct Instruction {
    Instruction(const char id)
        : Identifier(id)
    {}

    const char Identifier;
    size_t remainingUses = 1;
    size_t nextPossibleTime = 0;
}

So I named it next possible time, because the current time since start is the same for every instruction. Now given a current time we can schedule an instruction

char scheduleInstruction(const size_t currentTime, const size_t coolDown) {
    --remainingUses;
    nextPossibleTime = currentTime + coolDown + 1;
    return Identifier;
}

So when we schedule an instruction we decrement the number of remaining uses and set the next possible instruction time until the current time + the cool down period. Obviously we can put currentTime+coolDown+1 in the caller but that is a question of personal preference.

Now to check whether an Instruction can be scheduled we only have to compare currentTime with nextPossibleTime for the instruction.

So now we have scheduled an instruction how do we move it withine a queue? Quite easy there are only 2 relevant quantities

1. nextPossibleTime
2. remainingUses

So lets define a comparison operator for that task as you did

inline bool
operator< (Instruction const& b) const {
    return std::tie(nextPossibleTime, remainingUses) <
           std::tie(b.nextPossibleTime, b.remainingUses);
}

By using std::tie we automatically get the correct comparison of the two fields. Now consider a given container and we have scheduled an instruction, then we swap the elements until our scheduled instruction is not smaller than
another given instruction.

void rescheduleInstructions() {
    auto lastInstruction = myInstructions.rbegin();
    auto nextInstruction = std::next(lastInstruction, 1);

    while(nextInstruction != myInstructions.rend() && (*lastInstruction< *nextInstruction) {
        std::iter_swap(nextInstruction , lastInstruction);
        ++nextInstruction;
        ++lastInstruction;
    }
}

EDIT:

So I made a mistake here. The problem becomes obvious when looking at the simple sequence
AAABC n=2

The A Instruction will be scheduled after B and C with the old code, leading to the sequence

A->B->C->A->Idle->A

However the optial sequence would be

A->B->A->C->A

The reason for the error is, that we only need go back at max coolDown steps as after that point any instruction will be ready and we can sort from there with simply after the remainingUses, which ensures that we always schedule the most important instruction first.

void rescheduleInstructions() {
    auto lastInstruction = myInstructions.rbegin();
    auto nextInstruction = std::next(lastInstruction, 1);

    for (size_t step = 0; step  < coolDown; ++step ) {
        if (nextInstruction == myInstructions.rend()) {
            break;
        }
        if (*nextInstruction < *lastInstruction) {
            break;
        }
        std::iter_swap(nextInstruction , lastInstruction);
        ++nextInstruction;
        ++lastInstruction;
    }
}

So lets wrap this up by creating a class for the instruction set

class InstructionSet {
    InstructionSet (const std::string instructions, const size_t cooldown)
        :coolDown(cooldown)
    {
        for (const char& instruction : instructions) {
            auto pos = std::find(myInstructions.begin(), myInstructions.end(), [&instruction](const Instruction& i) {return i.Identifier == instruction; });
            if (pos != myInstructions.end()) {
                pos->AddInstruction();
            } else {
                myInstructions.emplace_back(instruction);
            }
        }
        std::sort(myInstructions.rbegin(), myInstructions.rend());
    }

    std::string findOptimalSchedule();

private:
    void rescheduleInstructions();

    std::container<Instruction> myInstructions;
    size_t currentTime = 1;
    const size_t coolDown;
}

You could also go for sorted insertion into the vector, however i felt that it complicates the matter of finding and in my experience just inserting and sorting at the end is more performant.

Now for the optimal schedule we have to start with the last element and then go from there. If currentTime is not less than nextPossibleTime of the final instruction we can schedule it. Otherwise due to the ordering we know that there is no possible instruction and we have to go idle (I choose "1" for that). After an instruction has been scheduled, we check whether there are remaining uses and either remove it or reschedule.

    std::string findOptimalSchedule() {
        std::string schedule;
        while(!myInstructions.empty()) {
            auto nextInstruction = myInstructions.rbegin();
            if(currentTime >= nextInstruction->nextPossibleTime) {
                schedule.push_back(nextInstruction->scheduleInstruction(currentTime, coolDown));
                if (nextInstruction->remainingUses == 0) {
                    myInstructions.erase(nextInstruction);
                } else {
                    rescheduleInstructions();
                }
            } else {
                schedule.push_back("1");
            }
            ++currentTime;
        }
        return schedule;
    }

Edit

To put all the code together and remove the unnecessary occurence of std::string although it

#include <algorithm>
#include <vector>

struct Instruction {
    Instruction(const char id)
        : Identifier(id)
    {}

    inline bool
    operator< (Instruction const& b) const {
        return std::tie(nextPossibleTime, remainingUses) <
               std::tie(b.nextPossibleTime, b.remainingUses);
    }

    char scheduleInstruction(const size_t currentTime, const size_t coolDown) {
        --remainingUses;
        nextPossibleTime = currentTime + coolDown + 1;
        return Identifier;
    }

    const char Identifier;
    size_t remainingUses = 1;
    size_t nextPossibleTime = 0;
}

    class InstructionSet {
    InstructionSet (const std::vector<char> instructions, const size_t cooldown)
        :coolDown(cooldown)
    {
        for (const char& instruction : instructions) {
            auto pos = std::find(myInstructions.begin(), myInstructions.end(), [&instruction](const Instruction& i) {return i.Identifier == instruction; });
            if (pos != myInstructions.end()) {
                pos->AddInstruction();
            } else {
                myInstructions.emplace_back(instruction);
            }
        }
        std::sort(myInstructions.rbegin(), myInstructions.rend());
    }

    int findOptimalSchedule() {
        std::vector<char> schedule;
        while(!myInstructions.empty()) {
            auto nextInstruction = myInstructions.rbegin();
            if(currentTime >= nextInstruction->nextPossibleTime) {
                schedule.push_back(nextInstruction->scheduleInstruction(currentTime, coolDown));
                if (nextInstruction->remainingUses == 0) {
                    myInstructions.erase(nextInstruction);
                } else {
                    rescheduleInstructions();
                }
            } else {
                schedule.push_back('1');
            }
            ++currentTime;
        }
        return static_cast<int>(schedule.size());
    }

private:
    void rescheduleInstructions() {
        auto lastInstruction = myInstructions.rbegin();
        auto nextInstruction = std::next(lastInstruction, 1);

        for (size_t step = 0; step  < coolDown; ++step ) {
            if (nextInstruction == myInstructions.rend()) {
                break;
            }
            if (*nextInstruction < *lastInstruction) {
                break;
            }
            std::iter_swap(nextInstruction , lastInstruction);
            ++nextInstruction;
            ++lastInstruction;
        }
    }

    std::vector<Instruction> myInstructions;
    size_t currentTime = 1;
    const size_t coolDown;
}


Handle data sent back over serial by Arduino

Nobody wants an explicit setTimeout in their async code; you want data as soon as possible.

So I'd wrap the Arduino interface in an object that is an EventEmitter. Have that object listen to any and all incoming data, and dispatch it as temperature events, leverPulled events, and whatever else, based on content.

For extra points, make the Arduino object's data detection extensible, so it can, by itself, be dumb. It might just parse any given line as JSON, and then look through its registered data detection/classification methods, to see what kind of packet it got. Then it'll dispatch an event with that name to whomever listens.

So something like:

// in arduino.js or whatever you want to call it
var serialport = require('serialport'),
    ports = require('./ports'),
    port = ports.arduino;

var machine = new serialport(port, {
  baudRate: 9600,
  parser: serialport.parsers.readline("\n")
});

var wrapper = new require('events'); // i.e. new EventEmitter

var classifiers = {};

machine.on('data', function (string) {
  try {
    var json = JSON.parse(string);
    for (var type in classifiers) {
      if (!classifiers.hasOwnProperty(type)) continue;

      // classifiers are just function that return true
      // if they recognize the json they're given
      if (classifiers[type](json)) {
        wrapper.emit(type, json);
        break;
      }
    }
  } catch (e) {
    wrapper.emit('error', e); // might want to be more elaborate
  }
});

wrapper.addClassifier = function (type, callback) {
  // might want throw an error if the type already exists
  classifiers[type] = callback;
};

wrapper.send = function (string) {
  machine.send(string);
};

module.exports = wrapper;

Usage would be something like:

var arduino = require('./arduino');

// give the arduino wrapper a way to recognize temperature packets
arduino.addClassifier('temperature', function (json) {
  return ('temperature' in json);
});

module.exports.getTemperature = function (callback) {
  // listen for the next incoming temperature reading
  // and send it straight to the callback
  arduino.once('temperature', callback);

  arduino.send('9');
};

And if you want to check for errors, then you can add a timeout - if the temperature event hasn't fired in, say 500ms from sending the '9' command, something's probably wrong (and you'll want to remove the listener). You'll also want to give getTemperature a callback with the Node-typical err, data parameters, so you can send an error back:

module.exports.getTemperature = function (callback) {
  var timeout = null;

  var listener = function (json) {
    clearTimeout(timeout);
    callback(null, json);
  };

  arduino.once('temperature', listener);

  arduino.send('9');

  setTimeout(function () {
    // if we're here, we didn't hear back from the arduino in time
    arduino.removeListener('temperature', listener);
    callback(new Error('Timed out'), null);
  }, 500);
};


Can I further optimize this solution for HackerRank's “Making Candies”?

Unlearn bad behavior taught by competitive coding sites
Competitive coding sites unfortunately teach some bad coding habits. You did not include your whole program, the #includes are missing for example. If you did #include <bits/stdc++.h>, don't.
The call to std::ios::sync_with_stdio() is only useful if your program is I/O bound, and it won't make a difference if you are just writing the final result to std::cout.
Use of integer types
__int128 is not a standard C++ type, and I don't think it is necessary at all to use it. The problem states that n is limited to \$10^{12}\$, so you only need 64-bit variables and some care to avoid values wrapping around.
A long is only guaranteed to be at least 32-bits in size. So reading in the initial values is already broken since they might be larger than that. Also, none of the values should ever become negative, so the appropriate type to use here is std::uint64_t.
Speeding up the algorithm
Yes, you can optimize your solution further. Consider the case where the desired number of candies n = 1000000000000, the cost is so high you can never buy/hire (p = n), and you start with m = 1 and w = 1. Then your loop will just do n iterations, adding 1 to candies each time.
What you should do is calculate how many iterations it would take to get enough money to buy/hire something new, and then advance that many iterations in one step. So:
const auto passes_needed_to_buy = candies < p ? (p - candies) / production : 0;

Of course, if this value is more than passes_needed, then you know you will never be able to buy anything before you produced enough candy.


Print file out 1 character at a time in the terminal - Python

I would recommend just using the built in functionality of print to do the flushing. Though I am an advocate for breaking things out into classes and functions, you should use built in functionality when you can.

Making code complex for no reason results in two things:

1) More bugs.
2) More programmers who want to wring your neck down the road because they have to maintain or fix your software.

So you can simplify your code like this:

from time import sleep

BLINK = 0.2

print("\n\tSTART PRINTING\n")

with open('example.txt') as f:
    for line in f:
        for char in line:
            print(char, flush=True, end='')
            sleep(BLINK)

print("\n\tEND PRINTING\n")

If you want to make this into a function (to make it easier to import/export) then I would do following:

from time import sleep

def time_print_file(filename, print_rate, **print_kwargs):
    """
    INPUT:
        filename: The path to the file to be printing
        print_rate: The delay used to print each character
        print_kwargs: keyword arguments accepted by pythons
           print statement. (Except `end` and `flush`)
    """
    print_kwargs.pop('flush', None) # We don't allow the flush print-keyword
    print_kwargs.pop('end', None) # We don't allow the end print-keyword
    with open(filename) as f:
        for line in f:
            for char in line:
                print(char, flush=True, end='', **print_kwargs)
                sleep(print_rate)

if __name__ == '__main__':
    print("\n\tSTART PRINTING\n")
    time_print_file(filename='example.txt', print_rate=0.2)
    print("\n\tEND PRINTING\n")


Dynamically creating elements with an object constructor

I am going to answer the questions in reverse order and share some design thoughts at the end.

  Can the function call be integrated either into the constructor function (and called when a new object is created) or called from the new object parameter? (It somehow feels wrong to place on a separate line after every new object creator.

Yes; it can.

The constructor function is just that; a function. In fact, it doesn't even need to be: if you move the logic from Photo.create into the constructor (which seems like a valid decision), then there is no point in this being it's own class.

To move the Photo.create logic into the constructor, just move it up a scope:

function Photo(name, src) {
    this.name = name;
    this.src = src;
    var container = document.getElementById('thumbs_container');
    var img = document.createElement('img');
    img.src = this.src;
    img.alt = this.name;
    img.className = 'thumb';
    img.style.width = '200px';
    container.appendChild(img);
}

However, as I stated above, this doesn't really need to be a class anymore; it's just one function.

  Is the code valid and are there any main reasons not to use this technique?

No, the way you are doing this is just fine. However, as stated above, it does not need to be object-oriented for the implementation you have provided.

If your code is going to specific to what you have shown where you paint the picture as soon as you create, then this ought to be a function.

However, there is still a way that this can be improved. If you are familiar with regexes, then you know that there is such thing as compiling a regex before you actually use it. The reason for this is because compiling regexes can be a time and resource consuming process, so it's best to get it out of the way so it does not slow the the code in the middle of it.

You can do something similar here: if, in the constructor function, you..

Create the element
Define the container
Define the class
And define the width

then, you can just store this information for when you want to put the image on the DOM.

To use this, you would create a new Photo instance which would do the above in advance. Then, later in your code when you are ready to paint, you can specify (or re-specify) the source and name.

The constructor would look like this:

function Photo(name, src) {
    this.name = name || "";
    this.src = src || "";

    var container = document.getElementById('thumbs_container');
    var img = document.createElement('img');
    img.src = this.src;
    img.alt = this.name;
    img.className = 'thumb';
    img.style.width = '200px';

    // no painting yet

    this.create = function() {
        container.appendChild(img);
    }
}

Note how this code looks almost identical to the first code snippet in this answer. The only difference here is that you are preparing the system resources ahead of time; just like regexes. This will provide a speed boost in your code if used correctly.

var photo = new Photo(); // prepare resources for image

/* bunch of code all up until when it is needed to draw */

photo.create(); // put image/resources in DOM


Allow users to customize your TimeSink class

We achieve this by making it a template class:

template <typename TimeUnit, typename Clock>
class time_sink;

This will allow your class to be used in different scenarios; it removes restrictions.

Since the TimeUnit template parameter is the one most likely to be changed, we can provide a default argument for Clock:

template <typename TimeUnit, typename Clock = std::chrono::steady_clock>
class time_sink;

Your destructor can be simplified

Instead of doing...

time_point end = std::chrono::steady_clock::now();
auto elapsed = end-start;
auto remaining_time_to_sleep = min_duration - elapsed;
if (remaining_time_to_sleep > epsilon)
{
    std::this_thread::sleep_for(remaining_time_to_sleep);
}

...we can do:

auto time_spent = Clock::now() - begin;
if ( time_spent < min_duration )
{
    std::this_thread::sleep_for( min_duration - time_spent );
}

I find this clearer and easier to understand.

Consider using std::chrono::high_resolution_clock as your default clock type

This stack overflow question should tell you why that's the preferred clock type for timing function execution.

template <typename TimeUnit, typename Clock = std::chrono::high_resolution_clock>
class time_sink;

Concise usage with the std::chrono_literals namespace and a template function

This would simply make the code shorter. Note that there is a repetition, as we must define time_sink's time unit type.

using namespace std::chrono_literals;
using time_sink = time_sink<std::chrono::milliseconds>;
time_sink{ 500ms };

In order to make usage fully concise (avoid repetition), we can use a template function and implement the idea proposed by 5gon12eder, in this comment which simply creates the time_sink object and uses template function type deduction to fill in the details.

template <typename TimeUnit, typename Clock = std::chrono::high_resolution_clock>
time_sink<TimeUnit, Clock> make_time_sink( TimeUnit const minimum_duration )
{
    return time_sink<TimeUnit, Clock>{ minimum_duration };
}

This allows us to create a time_sink in a short and clear way:

using namespace std::chrono_literals;
make_time_sink( 500ms );
// rest of function code, etc.

The improved code

Here's what the final code could look like:

#include <chrono>
#include <thread>

template <typename TimeUnit, typename Clock = std::chrono::high_resolution_clock>
class time_sink
{
public:
    time_sink( TimeUnit const minimum_duration ) :
        min_duration{ minimum_duration },
        begin{ Clock::now() }
    {}

    ~time_sink()
    {
        auto time_spent = Clock::now() - begin;
        if ( time_spent < min_duration )
        {
            std::this_thread::sleep_for( min_duration - time_spent );
        }
    }

private:
    TimeUnit min_duration;
    std::chrono::time_point<Clock> begin;
};

template <typename TimeUnit, typename Clock = std::chrono::high_resolution_clock>
time_sink<TimeUnit, Clock> make_time_sink( TimeUnit const minimum_duration )
{
    return time_sink<TimeUnit, Clock>{ minimum_duration };
}

Sample usage

As 5gon12eder points out, you must also ensure that you keep the return of make_time_sink in order to prevent time_sink's destructor from running early, since destructors are called at the "end of the full expression, for nameless temporaries" (source).

void f()
{
    using namespace std::chrono_literals;

    // we keep the return of make_time_sink in order to prevent
    // time_sink's destructor from executing before the end of the function
    auto ts = make_time_sink( 500ms );
    // ... do work ...
}

int main()
{
    f();
}


Elegantly avoid columns containing NaNs?

You can use d2[:, dnan] to select the wanted columns. (I'm assuming you want to process all rows unlike your current code)

def dosomething(d2):
    dnan = ~numpy.isnan(d2.sum(axis=0))
    validcols = d2[:, dnan]
    normalized = numpy.transpose((d2.T - numpy.mean(validcols, axis=1)) / numpy.std(validcols, axis=1))
    l = nanmean(normalized, axis=0)
    return l


Improved RandomGenerator with nextPrime() method

I'll concentrate on the syntactical issues in this review since the others have already commented on the other parts of the code.

import acm.program.*;
import acm.util.RandomGenerator;

public class exercise4 extends Program {
public int nextPrime(int n){                                          //sieve of Eratosthenes
        final RandomGenerator rgen = RandomGenerator.getInstance();
        boolean[] array = new boolean[n];

Your code is difficult to read for an experienced Java programmer because you violate all kinds of conventions:

Class names start with an uppercase letter, yours (exercise4) doesn't.
After every opening {, the code is written one more level to the right. So the line that declares nextPrime should be more to the right. Ideally you let your IDE format the code for you. For Eclipse, press Ctrl+Shift+F, for IntelliJ press Ctrl+Alt+L, for Netbeans Alt+Shift+F.
rgen is a final variable, but array isn't. That's inconsistent. Either both or none should be final.

Continuing:

        for (int i=2; i<n;i++) {

You should leave some space around the operators, so write for (int i = 2; i < n; i++) {.

            array[i]=true;
        }
        int i=2;
        while (i<Math.sqrt(n)) {
            if (array[i]==true) {

You can leave out the == true.

                int m=i*i;
                int j=0;
                while (m+j*i<n) {

You should never call this code with an n that is close to Integer.MAX_VALUE. Otherwise the expression m + j * i will overflow and become negative, and something negative is surely smaller than a large n.

                    array[m+j*i]=false;
                    j++;
                };
            };
            i++;
        };
        int random;
        do {
            random=rgen.nextInt(n);
        } while(array[random]==false);
        return random;
    }
    public void run(){
        //long start = System.currentTimeMillis();
        println(nextPrime(2_000_000));
        //long elapsedTimeMillis = System.currentTimeMillis()-start;
        //float elapsedTimeSec = elapsedTimeMillis/1000F;
        //println("Completed in: "+elapsedTimeSec+" seconds.");
    }
}


The problem that you observe with this program is speed, so let's look at that.

Running the program, I immediately noticed that the get_permutations section was slow, and the dictionary_check section was many times faster. That immediately tells me that it's not worth looking for faster ways to do the dictionary_check until get_permutations is much faster. After all, even if we could make dictionary_check take no time at all, the program would take almost as long to run!

Of course, I've been a bit naughty there. I went with my internal clock, when what I should do is use a tool. This is the result of running cprofile.

python -m cProfile -s cumtime boggle.py

             116983186 function calls (93930898 primitive calls) in 32.455 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000   32.455   32.455 {built-in method builtins.exec}
        1    0.052    0.052   32.455   32.455 boggle.py:1(<module>)
        1    0.009    0.009   32.403   32.403 boggle.py:62(find_words)
        1    0.085    0.085   31.945   31.945 boggle.py:34(get_permutations)
5763088/16    4.231    0.000   31.726    1.983 boggle.py:15(words_from)
15128064/720384   12.915    0.000   27.119    0.000 copy.py:132(deepcopy)
3601920/720384    5.565    0.000   25.605    0.000 copy.py:210(_deepcopy_list)
 30256128    3.207    0.000    3.207    0.000 {method 'get' of 'dict' objects}
  3601920    1.764    0.000    2.288    0.000 copy.py:252(_keep_alive)
 23052288    1.619    0.000    1.619    0.000 {built-in method builtins.id}
 18009500    1.261    0.000    1.261    0.000 {method 'append' of 'list' objects}
 11526144    0.840    0.000    0.840    0.000 copy.py:190(_deepcopy_atomic)
        1    0.289    0.289    0.448    0.448 boggle.py:50(dictionary_check)
  4431757    0.324    0.000    0.324    0.000 {built-in method builtins.len}
   720284    0.131    0.000    0.131    0.000 {method 'add' of 'set' objects}
      173    0.076    0.000    0.076    0.000 {built-in method builtins.print}
   712738    0.067    0.000    0.067    0.000 {method 'lower' of 'str' objects}
   178691    0.017    0.000    0.017    0.000 {method 'strip' of 'str' objects}
      240    0.000    0.000    0.003    0.000 cp1252.py:22(decode)
      240    0.003    0.000    0.003    0.000 {built-in method _codecs.charmap_decode}
        1    0.000    0.000    0.000    0.000 {built-in method io.open}
        1    0.000    0.000    0.000    0.000 _bootlocale.py:11(getpreferredencoding)
        1    0.000    0.000    0.000    0.000 {built-in method _locale._getdefaultlocale}
        1    0.000    0.000    0.000    0.000 boggle.py:5(check_board)
        1    0.000    0.000    0.000    0.000 codecs.py:259(__init__)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

The first few lines are just the call sequence in: for example there's a lot of time (cumtime) spent in find_words but almost all of it is in functions that it's calling and very little in the function directly (tottime). That's not where you want to cut down.

Instead, a huge amount of time is spent within deepcopy: 27 of 32 seconds. That is genuine time expenditure, and a good place to start hitting. Two options occur to me: either look for a simpler board representation that is cheaper and easier to copy, or try to avoid the copies.

For option 1, the obvious simpler thing is a flat list or tuple with sixteen elements, which you then index into as [row * 4 + column]. The data would be the same, but you'd avoid the overhead of copying all the extra lists.

For option 2, you'd want to use one board and keep track of what you're changing (and, depending on your implementation, perhaps exactly one copy of the board you never change). When you use a letter you'd stub it out; when you come back up the tree you'd replace the stub symbol with the original letter.

I haven't done it myself and it's always dangerous guessing at performance, but I would be optimistic about getting four to five times faster with that second change.

The above is trying for efficiency gains with minimal changes to the underlying algorithm. If you want to get much faster, however, you'll need to change your approach to the problem. The first rule of getting a job done faster is "The fastest work is the work you don't do."

Although I said earlier and stand by that you don't need to start optimising dictionary_check, there may be some opportunities to benefit from knowing your word list while you explore the grid. For example, there are no words that start with "plt". If, then, your running_string is "plt" then all future strings you find are guaranteed to get filtered out at the end. One option would be to read your word list at the start, and prepare a dictionary of all the prefixes that appear. As you recursively call words_from, if the running_string is not in the prefix dictionary, return immediately. That would probably offer enough gains that you could remove your limit to length 8 words.

I notice that the question and code have been editted several times since I started this answer. I'm just going to post it as is, and hope that except in the most fiddly details it is still helpful.


JavaScript function to generate tree object from flat object

Here is what I'd do. I'd split it into two actions - adding a single property and assigning them all.

Adding a single property is just adding a function if it's something like "a", and it's adding a property to a sub-object if it's something like "a....". So let's use recursion and break it up into those two use cases:

If it's at length one , create the function (but keep all the keys for the third example).
If it's more, call it recursively and create a property.

This translates to the following JS:

function walkTheChain(arr, val, obj){
  if(arr.length === 1) return obj[arr[0]] = Object.assign(() => val, obj[arr[0]]);
  if(!(arr[0] in obj)) obj[arr[0]] = {};
  walkTheChain(arr.slice(1), val, obj[arr[0]]);
}

Now, creating the whole object is just a matter of applying it to all the keys passed in:

function createMessages(map){
  var obj = {};
  for(var key in map) walkTheChain(key.split("."), map[key], obj);
  return obj;
}


Converting between backend object and object suitable for JSON

I would move the construction of the JSON objects into factory methods like this:

public class BundledProductOfferingJsonDto
{
    ....
    public static BundledProductOfferingJsonDto fromDto(BundledProductOfferingDto dto, Set<ProductOfferingJsonDto> productOfferings)
    {
        return new BundledProductOfferingJsonDto(dto.getId(), dto.getName(), dto.getDescription(), dto.getStatus(),
                dto.getBrand(), dto.getValidFor(),
                productOfferings,
                dto.getDescriptorId(), dto.getTags(), dto.getProductOfferingPrice());
    }
}

Similar for SimpleProductOfferingJsonDto

Also, is there a reason why your are using the while loops with the iterators instead of for example for (ProductOfferingDto piter : tmp)?

The method could then read something like this:

public Set<ProductOfferingJsonDto> getJsonProductOfferings() {
    Set<ProductOfferingJsonDto> set = new HashSet<ProductOfferingJsonDto>();
    ProductOfferingJsonDto pjson = null;
    for (ProductOfferingDto pdto : productOfferings) {
        if (pdto instanceof BundledProductOfferingDto) {
            Set<ProductOfferingDto> tmp = ((BundledProductOfferingDto) pdto).getProductOfferings();
            Set<ProductOfferingJsonDto> tmpset = new HashSet<ProductOfferingJsonDto>();
            for (ProductOfferingDto piter : tmp) {
                SimpleProductOfferingDto piterdto = (SimpleProductOfferingDto)piter;
                tmpset.add(SimpleProductOfferingJsonDto.fromDto(piterdto));
            }
            BundledProductOfferingDto bpod = (BundledProductOfferingDto) pdto;
            BundledProductOfferingJsonDto pjson = BundledProductOfferingJsonDto.fromDto(bpod, tmpset));
            set.add(pjson);
        }
    }
    return set;
}


Password Attacker (Google apac test problem)

This kind of problem can be solved with dynamic programming. The key points are :

you care about the number of combinations and not the list of them
assuming you know how to compute it for some values, you can go forward and compute it for even more values.

Here is how it could go (not verified whatsoever).

Given the length n (n > 0) and the number of distinct characters m (m > 0), you know that :

nb_comb(n, 1) = 1 which corresponds to strings with a single character.
nb_comb(n, m) = 0 if 1 <= n < m which corresponds to the fact that the string is too short to use all characters
nb_comb(n, m) = m * nb_comb(n-1, m-1) + m * nb_comb(n-1, m) if 1 < m < n which corresponds to the fact that to build a string of n characters, you can consider that you have to build a string of length n-1 and to add one at the end. Basically, you can either :

consider strings containing m-1 distinct characters and add the missing character : you have nb_comb(n-1, m-1) such strings for each of the m distinct characters. This contributes to m * nb_comb(n-1, m-1) combinations.
consider string containing all m characters and add any of the already added character : you have nb_comb(n-1, m) such strings and m ways to add an already existing character at the end. This contributes to m * nb_comb(n-1, m) new combinations.

(You can check that strings have not been counted twice (either the last character is a duplicate from another or it is not a duplicate).)

Without knowing it corresponds to Stirling numbers, I managed to deduce the same equations as the one in that stackoverflow question.

Python recursive solution to check it works :

import itertools

def nb(n, m):
    #print(n, m, "?")
    assert n>0
    assert m>0
    if m == 1:
        res = 1
    elif n == 1:
        res = 0
    else:
        res = m * (nb(n-1, m-1) + nb(n-1, m))
    if False: # check results
        slow_res = sum(1 for p in itertools.product(range(m), repeat=n) if len(set(p)) == m)
        assert slow_res == res
    return res

tests = [
    (1, 1, 1),
    (2, 2, 2),
    (3, 3, 6),
    (4, 3, 36),
    (5, 5, 120),
    (15, 15, 674358851),
]
for n, m, r in tests:
    nb_ = nb(n, m) % (1000000007)
    assert nb_ == r, "(%s,%s,%s != %s)" % (n, m, r, nb_)

This still gets way too slow for bigger solutions. Having a look at the functions calls for the case 15-15, for instance, adding a call to print at the beginning of the fonction and running python my_script | sort -n | uniq -c | sort -n, you get :

   ...
   1001 (1, 11)
   1001 (1, 5)
   1287 (2, 10)
   1287 (2, 7)
   1716 (2, 8)
   1716 (2, 9)
   2002 (1, 10)
   2002 (1, 6)
   3003 (1, 7)
   3003 (1, 9)
   3432 (1, 8)

showing that the fonction gets called with the same arguments thousands of times.

A solution would be memoization but a better one is to go the other way, generating the different values.

A way to do so is :

def nb2(n, m):
    # nb(i, j) is in results[i-1][j-1]
    results = [[None for j in range(m)] for i in range(n)]
    for j in range(m):
        results[0][j] = 0
    for i in range(n):
        results[i][0] = 1
    for i in range(1, n):
        for j in range(1, m):
            results[i][j] = (j+1) * (results[i-1][j-1] + results[i-1][j])
    return results[n-1][m-1]


First Dockerfile, I would appreciate critique

I would set the execute permissions on the entrypoint.sh before building the docker image - RUN, COPY and ADD create layers - COPY preserves the file permissions so you can remove the RUN chmod +x /entrypoint.sh (a layer from your final image).

FROM alpine:3.10

ARG BUILD_DATE

LABEL maintainer="MyNameGoesHere" \
      org.label-schema.schema-version="1.0" \
      org.label-schema.name="postfixrelay" \
      org.label-schema.build-date=$BUILD_DATE

EXPOSE 25

VOLUME [ "/var/spool/postfix" ]

COPY ./entrypoint.sh /

RUN apk add --no-cache --update \
        bash \
        ca-certificates \
        cyrus-sasl-login \
        postfix \
        rsyslog \
        tzdata && \
    rm -rf /var/cache/apk/*

ENTRYPOINT ["/entrypoint.sh"]

... moved the EXPOSE, VOLUME and COPY instructions above the RUN - the VOLUME and EXPOSE are not likely to change and the build cache for the COPY will only be invalidated if the contents of the file changes as explained in the ADD or COPY best practices. Finally, split the packages being added on multiple lines to make it clearer at a glance in i.e. a git diff when something changes.

Concerning the entrypoint.sh I'd suggest taking a look at the Exec form ENTRYPOINT example to ensure that your process is receiving the Unix signals.

For the docker-compose I'd pass the PASS environment variable from the hosts environment and name the default network explicitly:

version: '3'
services:
  postfixrelay:
    container_name: postfixrelay
    restart: unless-stopped
    environment:
      ...
      - PASS=${PASS}
...
networks:
  default:
    name: postfixrelay
...

If you want to docker-compose up --scale postfixrelay=3 you'd need to stop using container_name, trying to start multiple containers with the same name will conflict. You'd also need to stop publishing the ports to the host, will have port conflicts - would need to set up a tcp load balancer (i.e. nginx, traefik, ...) and proxy the connections to your upstream services.

Then there is docker swarm and kubernetes (or other) as proper orchestration managers for your service(s).


You don't need to terminate the list of candidate factors.  Haskell, being a lazy language, deals with infinite lists just fine.

In Haskell, it is common to use pattern matching instead of if … then … else.

There is not much advantage to having your go helper take an Integer (Integer, Integer) rather than three Integers.

You are repeating the isDiv test in fullyDiv and go.  Instead of a fullyDiv function, you can just fold the retry logic into go itself.

The names x, y, and o are hard to follow.  I suggest maxPrime instead of x, and w instead of y (the mnemonic being the first character of wheel).

isDiv :: Integer -> Integer -> Bool
n `isDiv` k = n `mod` k == 0

maxPrimeFact :: Integer -> Integer
maxPrimeFact n = go n 1 (2 : [3, 5..])
  where
    go 1 maxPrime _ = maxPrime
    go n maxPrime wheel@(w:ws)
      | n `isDiv` w = go (n `div` w) w wheel
      | otherwise   = go n maxPrime ws

But you should be able to rewrite it further by taking advantage of divMod.

maxPrimeFact :: Integer -> Integer
maxPrimeFact n
  | n < 2     = error ("Invalid n=" ++ (show n))
  | otherwise = go n 1 wheel
  where
    wheel = 2 : [3, 5..]
    go 1 largestPrimeFactor _ = largestPrimeFactor
    go n largestPrimeFactor (w:ws)
      | n `isDiv` w = go (n `div` w) w (w:ws)
      | otherwise   = go n largestPrimeFactor ws


There is one error in your implementation: The test
if rand <= range must be if rand < range, otherwise the returned
values are not correctly distributed according to the given weights.
You can check that with the input list

[("Red", 1), ("Blue", 1)]

which returns only "Red" without this fix.

Apart from that, your code looks correct, but there are some
possible improvements.

The final return "" is never reached unless you made a programming
error. Instead of returning some value (in order to satisfy the compiler), replace it by

fatalError("This should never be reached")

This will stop the program execution immediately, and
fatalError() has the @noreturn attribute, so the compiler won't
complain about a missing return value.
Replace for tuple in input { } by for (color, weight) in input,
that allows you to get rid of the non-descriptive tuple.0 and tuple.1
in the loop body.
Add the current weight to the sum before testing against rand,
that makes the range variable obsolete.

The function does then look like this:

func weightedColor(input: [(String, Int)]) -> String {

    let total = UInt32(input.map { $0.1 }.reduce(0, combine: +))
    let rand = Int(arc4random_uniform(total))

    var sum = 0
    for (color, weight) in input {
        sum += weight
        if rand < sum {
            return color
        }
    }

    fatalError("This should never be reached")
}

The next step is to make the function generic.
There is nothing which is special to colors or strings,
so you can simply replace String by a generic type T:

func weightedRandomElement<T>(items: [(T, Int)]) -> T {

    let total = UInt32(items.map { $0.1 }.reduce(0, combine: +))
    let rand = Int(arc4random_uniform(total))

    var sum = 0
    for (element, weight) in items {
        sum += weight
        if rand < sum {
            return element
        }
    }

    fatalError("This should never be reached")
}

Then the same function can be used to get a random color:

let colors = [("Red", 20), ("Blue", 50), ("Green", 70)]
let color = weightedRandomElement(colors)

or a random number:

let numbers = [(3.1415, 20), (2.71827, 50)]
let number = weightedRandomElement(numbers)

or anything else.

Update: As @hashemi correctly said, the fatalError() point would
also be reached if the function is called with an empty array.
Actually that would also happen if the function is called with a non-empty array but the sum of the given weights is zero. These
situations could be considered as a programming error on the caller's side and can be checked with a  precondition().

@hashemi also suggested to use UInt instead of Int as data type
for the weights. This is more natural because the weights must not
be negative (and unexpected results would happen for negative input).

Then the function looks like this:

func weightedRandomElement<T>(items: [(T, UInt)]) -> T {

    let total = items.map { $0.1 }.reduce(0, combine: +)
    precondition(total > 0, "The sum of the weights must be positive")

    let rand = UInt(arc4random_uniform(UInt32(total)))

    var sum = UInt(0)
    for (element, weight) in items {
        sum += weight
        if rand < sum {
            return element
        }
    }

    fatalError("This should never be reached")
}

and is called like

let colors : [(String, UInt)] = [("Red", 20), ("Blue", 50), ("Green", 70)]
let color = weightedRandomElement(colors)


Using LINQ or Lambda instead of nested and multiple foreach statements

By using an IEqualityComparer<Person> which only compares the Value property like

public class PersonValueComparer : IEqualityComparer<Person>
{
    public bool Equals(Person x, Person y)
    {
        if (x == null && y == null) { return true; }
        if (x == null || y == null) { return false; }

        return x.Value == y.Value;
    }

    public int GetHashCode(Person obj)
    {
        if (obj == null || obj.Value == null) {return 0;}
        return obj.Value.GetHashCode();
    }
}

you can by using linq methods replace the loops by

        PersonValueComparer valueComparer = new PersonValueComparer();
        initialList = secondList.Where(p => initialList.Contains(p, valueComparer))
            .Concat(initialList.Where(p => !secondList.Contains(p, valueComparer))).ToList();

We are first using the Where() method to filter the secondList for items which are in the initialList . Then we use Concat() to add the Person''s which are not in thesecondList`.

Based on the naming guidelines properties should be named using PascalCase casing.

You should always use meaningful and descriptive names for naming methods, variables, properties and classes so Sam the Maintainer sees at first glance what it is about.

Shortening variable names doesn't add any value but instead reduces readability which Sam the Maintainer doesn't like.


Refactoring 3 level depth for loops in JavaScript

This may not actually be any better as far as performance goes, but I believe it is equivalent to your code (and possibly more readable?).

http://jsfiddle.net/Jq8sk/1/

var arr = ['n0', 'n1', 'n2'];

$('.trs').each(function(){
   var $row = $(this);

    for(var i=0;i<arr.length;i++){

        if($row.children(".tds." + arr[i]).length === 0){
            // td doesn't exist, see if any later rows have it

            var $tds = $row.nextAll(".trs").children(".tds." + arr[i]);

            if($tds.length > 0){
               $row.append($tds[0]);
            }
        }
    }
});


knockout binding handler for custom components

I like your approach much better than using separate values.

The code reads really well, I only have 1 minor suggestion.

If you had a helper function like this:

function unwrapOrDefault( gift , defaultValue )
{
    return gift === undefined ? defaultValue : ko.unwrap( gift ),
}

then you could have

        min: unwrapOrDefault(value.min, -5),
        max: unwrapOrDefault(value.max, 5 );
        scale: unwrapOrDefault(value.scale, 2);
        step: unwrapOrDefault(value.step, 0.1);
        bigStep: unwrapOrDefault(value.bigStep, 0.5);


Check if a JavaScript variable exists and checking its value

First off, your code really breaks down to this logic and I find it helpful to write it out the longer version to full understand the logic flow before trying to shorten it:

var header_cookie, cookie_check, city_profile, state_profile;
if (typeof header_check !== "undefined") {
    header_cookie = 'user_profile';
    cookie_check = true;
    city_profile = 'userCity';
    state_profile = 'userState';
} else {
    header_cookie = 'admin_profile';
    cookie_check = false;
    city_profile = 'city';
    state_profile = 'state;
}

FYI, I also find this a LOT easier to follow what's actually happening than the code you have.  It also saves several comparisons on the cookie_check value.

There are some ways to shorten this, but it's not entirely clear that any are "better" where the definition of better includes readability by someone who has never seen this code before, but you can decide what you think of that issue for the alternatives:

Since you really only have two states, you could predefine each state and then just pick which one to use and access the properties off a single state object:

var userState = {
    header_cookie: 'user_profile', city_profile: 'userCity', state_profile: 'userState';
};
var adminState = {
    header_cookie: 'admin_profile', city_profile: 'city', state_profile: 'state';
};
var state = typeof header_check !== "undefined" ? userState: adminState;

Done this way, you'd access state.header_cookie, state.city_profile and state.state_profile rather than your standalone variables.

Or, if you wanted to keep the individual variables, you could do this:

var states = {
    header_cookie: ['user_profile', 'admin_profile'],
    city_profile: ['userCity', 'city'],
    state_profile: 'userState', 'state'];
};

var stateIndex = typeof header_check !== "undefined" ? 0 : 1;
var header_cookie = states.header_cookie[stateIndex];
var city_profile = states.city_profile[stateIndex];
var state_profile = state.state_profile[stateIndex];


Cube root in Python 3 using Bisection Search: Numbers in -1 to 0

There are some problems with your code, the algorithm being (too complicated, it is also) wrong.

In addition to that, you haven't made any functions, which you should strongly consider doing.

The better way of writing this script is to write two (or more) functions, one function being the actual cuberoot function which accepts one (or two) argument, namely the number you want to find the cube root for.  It should return one number, the cube root.

Writing functionality in function, or perhaps encapsulating functionality in functions allows you to more easily test the function.  Having all functionality in functions, also allows you to import cuberoot from a different file.  This is essential when building more complex applications and libraries later.

I have attached one example of how you can modularize your code so that it is both easy to test and easy to import, and not least of all, it's easy to read and thus understand.

As you can see in the while loop, it is quite close to your example, but a bit simplified.

I have also added an assert statetment in the main function to easily verify that the result is correct.  Adding automatic tests are now quite easy as well.

The bottommost __main__ part is there to ensure that the main function is called only if we call the file as a script:

$ python cuberoot.py -0.5
-0.7936859130859375

Here is the refactored code:

def cuberoot(cube, epsilon=0.0001):
    """Compute cube root of n using binary search.

    We yield the result when |result**3-n|<epsilon.
    """
    high = 2 + abs(cube)
    low = -high
    while True:
        guess = (low + high) / 2.0
        err = abs(cube - guess ** 3)
        if err < epsilon:
            return guess
        if guess ** 3 > cube:
            high = guess
        else:
            low = guess

def main():
    """Read one number from command line and print its cube root."""
    from sys import argv

    try:
        cube = float(argv[1])
    except ValueError:
        exit("Usage: cuberoot n [n must be a number]")
    except IndexError:
        exit("Usage: cuberoot n")

    cr = cuberoot(cube)
    assert abs(cr ** 3 - cube) < 0.0001  # verify the result
    print(cr)

if __name__ == "__main__":
    main()


How to good code for multiple if conditions?

One trick that improves readability of if's called early return: idea is to return from method as soon as you know what will be returned.
public static String getRepoType(String repoPath) {
    boolean gitRepo = new File(repoPath, Constants.GIT_FOLDER).exists();
    if (gitRepo) {
        return Constants.GIT;
    }
    boolean svnRepo = new File(repoPath, Constants.SVN_FOLDER).exists();
    if (svnRepo) {
        return Constants.SVN;
    }

    // New type, need to be handled
}

Take a look at this good question about similar stuff.


Sequential Thread Execution using wait() and notifyAll()

the first issue I see is that i++; is not thread safe. Instead use an AtomicInteger

second is that the thread gets into a spin lock when it is awake and it's not its turn. the solution to this is to do:

while(!Thread.currentThread().getName().equalsIgnoreCase(turn)) {
    waitNotifySignal.doWait();
}

but this has a race condition (turn changed after the test but before the wait->the changing thread has already called doNotifyAll() and deadlock occurs. (This is the reason why wait and notify have to be in the synchronized blocks)

This means that you need to synchronize the testing and the changing of turn, but if we do this then we don't need a special WaitNotifySignal class but a normal Object will suffice:

class SignalThread implements Runnable {

    final AtomicInteger index = new AtomicInteger(1);

    String turn = "1"; // synchronization will take care of visibility

    Map<String, String> sequence = new HashMap<String, String>();

    Object waitNotifySignal;

    public SignalThread(Object waitNotifySignal) {
        this.waitNotifySignal = waitNotifySignal;
    }

    @Override
    public void run() {
        int i = index.get();
        while (i <= 10) {
            synchronized(waitNotifySignal){
                while(!Thread.currentThread().getName().equalsIgnoreCase(turn)) {
                    try{
                        waitNotifySignal.wait();
                    }catch(InterruptedException e){
                        return;//interrupted means that the thread should stop
                    }
                }
            }

            System.out.println("Thread: "
                    + Thread.currentThread().getName() + " --- " + i);
            i = index.incrementAndGet();

            synchronized(waitNotifySignal){
                turn = getNextTurn(turn);
                waitNotifySignal.notifyAll();
            }
        }
    }

    //...
}

besides that your doNotifyAll() didn't. only one thread ever got out of the synchonized block in doWait, which means that deadlock would occur if more than one thread was waiting and the wrong thread got notified.


I see two problems with your loops.

In terms of style, calling file.next() and catching StopIteration is highly unconventional.  The normal way to iterate is:

for line in fileinput.input(options.file):
    …

In terms of functionality, I would personally consider the grepper to be buggy because it will fail to find a log message where the filter keyword that you are seeking appears on a continuation line.

To solve both problems, I would decompose the problem into two parts: reconstructing the logical messages (somewhat ugly) and searching (relatively straightforward).

import fileinput
import re

def log_messages(lines):
    """
    Given an iterator of log lines, generate pairs of
    (level, message), where message is a logical log message.
    possibly multi-line.
    """
    log_level_re = re.compile(r'\b(TRACE|DEBUG|WARN|ERROR|CRITICAL)\b')
    message = None
    for line in lines:
        match = log_level_re.search(line)
        if match:                               # First line
            if message is not None:
                yield level, message
            level, message = match.group(), line
        elif message is not None:               # Continuation line
            message += line
    if message is not None:                     # End of file
        yield level, message

for level, message in log_messages(fileinput.input(options.file)):
    if filter in message:
        sys.stdout.write(message)

Note that I've used a regular expression to look for TRACE, DEBUG, etc.  The \b anchors ensure that we don't mistake words like "INTRACELLULAR" for a TRACE message.


Let the operators and the numbers have some space to breathe. Looking at

double tempNumber = number2*100/number1;

it is hard to see that the variable is called number2. So by adding some horizontal space will increase the readability like so

double tempNumber = number2 * 100 / number1;

The if condition here

if ((number2 >= number1) && number1 > 0 && number2 > 0)

can be simplified by removing the check for number2 > 0. If number2 is greater than or equal to number1 and  number1 is greater than 0 then for sure number2 is also greater than 0.

The same is true for

if ((number1 >= number2) && number1 > 0 && number2 > 0)

    if (number1 < 0 && number2 < 0)
    {
        number1 = Math.Abs(number1);
        number2 = Math.Abs(number2);

        if ((number1 >= number2))
        {
            double tempNumber = number2 * 100 / number1;
            Math.Abs(percentageDifference = 100 - tempNumber);
        }
        if ((number2 >= number1))
        {
            double tempNumber = number1 * 100 / number2;
            Math.Abs(percentageDifference = 100 - tempNumber);
        }
    }

In this construct you are calculating the percentageDifference two times if number1 and number2 are both < 0 and are the same. Using an else if would skip this.

If you would declare tempNumber, which by the way is named sub optimal,  instead of percentageDifference outside of the if's you could remove a lot of code duplication by calling Math.Abs(percentageDifference = 100 - tempNumber); at the end of thr method. In addition why do you use it like this and not like

percentageDifference = Math.Abs(100 - tempNumber);

which would be more readable.