To be honest: I fail to see how this class is particularly useful (at least yet).

You can immediately create a JsonReader from a URL, making your whole problematic convertStreamToString method (as well as readJsonFromString) superfluous. So far your class is equivalent to:

private JsonObject tryJsonFromUrl(String url) {
    try (InputStream is = new URL(url).openStream();
            JsonReader reader = Json.createReader(is);) {
        return reader.readObject();
    } catch (IOException e) {
        LOG.log(Level.SEVERE, e.toString(), e);
        return null;
    }
}

That being said, let me cover your specific questions and a few unspecific observations nonetheless, since you wanted all kinds of input.

Variable names

There is nothing wrong with your variable names IMHO.

Error handling

Your code may fail to close inputStream in case of an exception, leading to a potential resource leak. To prevent this, either put inputStream.close(); in a finally block or - even better - use try-with-resources as seen above.

Your code also throws a NullPointerException when urlString is null. You can add an explicit check or document that behaviour, but you should do one of them.

Error handling (2): Logging

When encountering an exception you usually want to log the stack trace as well to help with debugging. Your current logging will print something like that:

SEVERE: java.net.UnknownHostException: some-nonexisting.host.com

This may be enough for you now since you know that there is only one possible cause within your code. But think of someone else using your class or more complex scenarios, where it might be relevant to see from where your method was called: Your current logging output won't tell you anything about that.

On the other hand

LOG.log(Level.SEVERE, e.toString(), e);

will include the whole stacktrace, making it easier to trace back the error from the logging output alone (you won't be able to debug running production servers):

SEVERE: java.net.UnknownHostException: some-nonexisting.host.com
java.net.UnknownHostException: some-nonexisting.host.com
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:668)
    at sun.security.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:173)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:432)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:527)
    at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:264)
    at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:367)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:191)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1104)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:998)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:177)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1512)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1440)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
    at java.net.URL.openStream(URL.java:1038)
    at net.bounceme.dur.json.JsonOperations.tryJsonFromUrl(JsonOperations.java:32)
    at net.bounceme.dur.json.JsonOperations.main(JsonOperations.java:25)

Here you would see that the exception was thrown in line 32 of the JsonOperations class within the tryJsonFromUrl method and that this method was called from line 25 in the main method. That gives you already a first idea of what might have led to the exception.

convertStreamToString method

Scanner scanner = null;
scanner = new java.util.Scanner(is);

Can be shortened to

Scanner scanner = new Scanner(is);

(you are already importing java.util.Scanner)

Otherwise it doesn't look bad (see also this Stack Overflow answer).

Perhaps static methods?

If it's intended to be a pure utility class, I'd go with static methods. See this Stack Overflow question for a few details.

Assumption that the JSON will come in via URL

For a general purpose utility class that is almost certainly an erroneous assumption. You can either offer several entry methods, e.g.

public JsonObject tryJsonFromUrl(String urlString);
public JsonObject tryJsonFromUrl(URL url);
public JsonObject tryJsonFromString(String jsonString);

or a generic method, letting the caller handle the details:

public JsonObject tryJson(InputStream is);

The latter may be a bit more work for the caller, but in return offers more flexibility (it's also the option that has been chosen for javax.json.Json).

Custom exception? Or return a default empty JSON object?

Whether you throw an exception, return null or return an "empty" object is to some extent a matter of style. In your case I'd probably go without an exception as the method name ("try...") suggests that reading may fail (thus making it a non-exceptional case). And since I can't think of any general use for a default object, null would be fine as well.

If you decide to throw an exception, I'd prefer a custom one to a) make your api consistent and b) abstract from implementation details (e.g. reading JSON from a String won't throw an IOException).

General observations

"I find your lack of javadoc disturbing".

Especially when writing code for others, your class should describe what it does. In detail. See it as a contract: Your javadoc describes what behaviour a caller can (and cannot) expect. Oracles document on javadoc has a lot more details on that.

A library which handles URL -> JSON seamlessly

The default implementation, see above ;-)


UPenn CIS 194 Homework 4: Higher-order programming

hlint

hlint is a great tool for improving your mastery of Haskell idioms and syntax.

For example, here is one thing (of several) it found in your code:

input.hs:20:40: Warning: Avoid lambda
Found:
  \ x -> x > 1
Why not:
  (> 1)

I would study the output of hlint.

fun1'

Looks fine.

fun2'

Stylistically I like to avoid long inline expressions. Use let and where to define meaningful subexpressions. I find this more readable (also
combining the hlint suggestion):

fun2' = sum . filter even . takeWhile (> 1) . iterate collatz
  where collatz x = if (even x) then div x 2 else 3 * x + 1

collatz could even be a top-level function because it is generally useful.

makeTree

You are repeating the expressions makeTree a l and makeTree a r.
GHC might be able to detect the common sub-expression and unify the two
so that they are only evaluated once.

ghci doesn't do any CSE, so the same call will be executed twice.

In most cases it's best to use a where or let to ensure the expression
is only evaluated once:

| height l <= height r =
    let left = makeTree a l
    in  Node (height left + 1) left m r

More info on GHC and CSE: https://wiki.haskell.org/GHC/FAQ#Does_GHC_do_common_subexpression_elimination.3F

Also, height looks like it would be generally useful - why not expose it at the top level?

xor

Looks like it will work, but since you are not specifying a type for s
it will likely default to being an Integer.

But you don't need a whole Integer to keep track of the parity of a number. In fact, you can get by with simply a Bool.

As a extension to this exercise, try to write xor without using addition.

myFoldl

Try to write it without using reverse.

Hint: You have to build up a higher-order function.

Your answer will look like:

foldl f a xs =  (some big function) a

where (some big function) will be a foldr (\g x -> ...) g0 xs.

Another hint: With a fold like:

foldr h y xs

you know that y = foldr h y [], so use this to determine what g0 is.

Sundram

Stylistically I would use list comprehensions as much as possible - replacing map and filter.

Instead of:

sieveSundaram n = map (\x -> 2 * x + 1) (genSieve n)

I would write:

sieveSundaram n = [ 2*x+1 | x <- genSieve n]

and instead of:

genCrossed m = map (\(i, j) -> (i + j + 2 * i * j)) (filter valid (cartProd [1..m] [1..m]))

I would write:

genCrossed m = [ i+j+2*i*j | (i,j) <- cartProd [1..m] [1..m], valid (i,j) ]

Also, you are computing the expression i + j + 2 * i * j twice. Can you think of a way of organizing your code so that it is only computed once?

valid

The where clause in the valid function can be dropped if you define it this way:

valid (i,j) = ...

Given a value for m, how many pairs is valid examining? Can you think of a way to reduce that number by about half?


Argument confusion
If you were trying to replicate the java substring function, you should have had a start and end argument.  As it is, you have a start and length argument, but you didn't handle the length argument correctly.
Bug 1
This line doesn't correctly check for the case of copying off the end of the source string:

if (start > stringLength || len > stringLength || start < 0 || len < 0) {

It needs to be:
if (start + len > stringLength || start < 0 || len < 0) {

Edit: If you want to check for integer overflow, you can also throw in || start + len < 0, and use size_t everywhere instead of int.
Bug 2
This check is unnecessary and can return an error incorrectly:

if (start >= len) {
    fputs("start must be start < len", stderr);
    return -1;
}

For example, if the string has 10 bytes, start is 8 and len is 1, this check will return an error.
Bug 3
When you terminate the destination string, you use the wrong index.  It should be len, not stringLength.  Also, I'm not sure why you do a check before you write to it:

if (destination[stringLength] != '\x0') {
    destination[stringLength] = '\x0';
}

should be:
destination[len] = '\0';

Also, '\0' is the standard way to write the null character.  I've never seen it written as '\x0' before.
Unnecessary local variable
The variable substringLength is unnecessary because it is always the same as len.  You can just use len instead.
Return value
The java substring function returns the string.  Your function returns the length but I don't think that this will be useful to the caller.  The reason you might want to return a string is so you can chain calls like this:
strcat(substring(buf, path, dir_start, dir_length), basename);


Since you're asking for a readability review, here's my input:

Way too many comments. Comments should say why, not what - the code itself should describe what it's doing.
Use XML comments to describe methods. // regular comments only work if you're looking at the method's code. When you're using the code, XML comments are picked up by Visual Studio and you get tooltips to help you correctly use the method. For example:

/// <summary>
/// A recursive split merge method.
/// </summary>
/// <param name="A">The array to be sorted.</param>
/// <param name="iBegin">The lower bound index for the sub-array to be sorted.</param>
/// <param name="iEnd">The upper bound index for the sub-array to be sorted.</param>
private static void SplitMerge(int[] A, int iBegin, int iEnd)

Avoid Hungarian Notation. Prefixing i for int types is useless in .net, and hinders readability. iBegin and iEnd should simply be begin and end to be correct, startIndex and endIndex to be meaningful.
Use camelCase for parameters and locals. Parameter A should be a... but that's an awfully bad name. unsortedArray, or simply unsorted, would be much more descriptive.
Avoid snake_case. C# naming conventions don't encourage the use of an underscore (_) in the middle of an identifier's name. Use camelCase for parameters and locals, and PascalCase for types and public members (actually, exposed is more accurate, since internal and protected members should also be PascalCase).
Avoid Java-style curly braces. Not to start any flamewars, but C# conventions put the opening brace { on the next line.
Method names should start with a verb. Standard() isn't a good method name. Since it's a member of a class named MergeSort, Sort() would probably be best, and should take the array in as a parameter to be any useful...


Getting a min birth year and max death year from a list of years

What you really want to do is transpose the separate tuples into 2 tuples - one containing all the birth dates, and the other death dates.

Fortunately, python's zip function can do this easily for you, using the *x syntax:

years = [(1804, 1884), (1885,1997), (1902,1975), (1900,1989)]
births, deaths = zip(*years)
# births = (1804, 1885, 1902, 1900)
# deaths = (1884, 1997, 1975, 1989)
print(min(births), max(deaths))
# 1804 1997


Storing, fetching, and deleting battle simulation results

Stay away from globals. You will never need them. Never. Especially don't use globals in a class where they are completely unnecessary. They are an older technology that is full of security holes. Because $pdo is in the global scope, if I were of malicious intent I could hack into your database simply by using the already authenticated variable you gave me. This also makes it difficult to figure out where your variables are coming from. Without any kind of context it could become very easy to lose track of it. Instead of separating your connection logic from your class, just put it in the class constructor and use class properties to simulate a "global" state. Unlike Peter's example, this keeps the connection logic associated with the class instead of injecting it. The problem with dependency injection, in this case, is that it makes no sense unless you are reusing that same connection in another class at the same time. With the limited knowledge of this system I cannot know one way or the other and so DI seems a bit abstract.

private $pdo;//declare class property first

public function __construct() {
    try {
        $this->pdo = new PDO(//define class property
            'mysql:host=localhost;
            dbname=game;
            charset=utf8',

            'root'
        );
    } catch( PDOException $e ) {
        echo $e->getMessage();
    }
}

//to use class property
$this->pdo->prepare(/*etc...*/);

The reason we are using private in the above scenario is the same reason we aren't using globals. If the property were public it could be accessed outside of the class, which is not something we want to provide access to.

You have three more variables that could be made into properties. Properties are an essential part of OOP, they encapsulate the data needed to make the class work. They do this by allowing different methods to communicate with each other by storing and accessing properties within their class instead of returning and parsing parameters. Not to say methods can't have parameters, only that most become unnecessary. Without properties, you might as well be using regular functions. So, how do we apply this? The parameters you pass to your dataWarrior() method seem to be reused at different points in the class. The $battle parameter is used to determine the battle_id in every method, the $name parameter is used to get the warrior_name in two of the methods, and the $type parameter is used to get the type in two methods. So, instead of passing these values again and again, just assign them to a property and use that property whenever you would have used the passed parameter. This is most effective if done in the first method in which these parameters are all used. I would assume this is in createBattle()?

public function createBattle( $warrior ) {
    $this->battle = $warrior[ 'battle' ];
    $this->name = $warrior[ 'name' ];
    $this->type = $warrior[ 'type' ];

    //etc...
}

Don't forget to declare those properties at the top of your class. Declaring a property is equally as important as declaring your methods. If you don't declare a property or method it defaults to the public scope, but this wont always be the case. I have heard rumors of this being deprecated soon, which means no more default values and whole lot more warnings. So be prepared and code accordingly.

So, to answer your question: Not really, but a decent enough start. Just keep in mind the following principles: "Don't Repeat Yourself" (DRY), Single Responsibility, and, as Peter pointed out, SOLID, which is kind of the first two plus a few others all rolled into one. If your code follows these principles and utilizes the fundamental aspects of the OOP (Encapsulation, Inheritance, and Polymorphism), then you should be fine.

BTW: What tutorials are you using that is teaching you to use globals? I've become curious because this seems to be a growing trend recently, and if this is all coming from the same source I want to see what I can do about stopping it.


Prim's Algorithm - Minimum Spanning Tree

1. Keeping references to potentially dangling pointers

I can see a potential problem with the line

vertices[ver.first].parent = &vertices[curr_vertex];

if the std::vector<Vertex> vertices would be reorganised due to changes in length.
The address you take there isn't stable.

Maybe a better solution would be to keep a

std::vector<std::unique_ptr<Vertex>> vertices;

instead of keeping copies of the Vertex instances.

Then you can change

vertices[ver.first].parent = &vertices[curr_vertex];

to

vertices[ver.first].parent = vertices[curr_vertex].get();

Since all the vertices are in private scope of the Graph class the std::unique_ptr<Vertex> instances stored to the vertices vector will never invalidate, as long you guarantee to remove all child Vertex instances when a parent Vertex instane is removed from the graph (Well, that's not an operation in question here, but needs to be considered for production code).

2. Inconsistent error handling

Here

else
{
    std::cerr << "Negative weight\n";
}

you just use kind of errorneous input being reported to the console, while you throw exceptions for other cases.

For this condition you should rather do

throwing an exception
applying an assert() call in 1st place
clarify from the function signature

If Negative weight is erroneous input you should make that clear in 1st place:

  void Graph::add_edge(std::size_t src , std::size_t dest, unsigned weight)
                                                        // ^^^^^^^^

This way violations would be covered by the compiler, before runtime detects that flaw.

3. Storing unnecessary information

In your code example parent is never used besides storing the information. I am aware that you might have been simplified the actual usage of parent with this review question, but with the code context you give, that member variable doesn't make any sense.


Pass pointer data across multiple functions

Don't do your own memory management. Use the tools provided for you unless you have good reason to do otherwise.

This:

objMyMap.SetMapData((char*)ptrData);

causes undefined behavior. This is because when objMyMap is deleted you delete the pointer as a char pointer (it was created as an int pointer). Thus the runtime memory management will probably get the size of the block wrong.

If you ever use a C-Cast then you are probably doing something wrong. Always use C++ style casts. Then it is easy to spot when you are doing things wrong.

const_cast<>()          // Bad if you casting away constness.
reinterpret_cast<>()    // Bad unless used to interact with C libraries.
static_cast<>()         // Bad if used to cast pointers around
dynamic_cast<>()        // Safe but slow as it is a runtime cast.
                        // Note: Only useful for casting down class hierarchy
                        //       But it is also a sign of bad design.

Looking at the class.

class ObjMapData
{

There is no reason do your own memory management.

private:
char* itsMapData;

This should probably be a std::vector<char>. Once you do that the rest becomes irelavant and all memory management issues are solved.

........
public:
ObjMapData();

Don't bother to test for NULL. Just delete.

~ObjMapData(){if(itsMapData!= NULL) delete[] itsMapData;}
ClearMemory() {if(itsMapData!= NULL) {delete[] itsMapData; itsMapData= NULL}}
.......

This obviously leaks the memory that you had before.

void SetMapData(char* ptrData) { itsMapData = ptrData;} // or should I use int*&ptrData??

Sure. But only if you need to expose that data.
I would rather encapsolate the manipulation of the data inside the class so you don't need to expose it.

char* GetMapData() const { return itsMapData;}
}

You don't show it so I have to assume you are not following the "Rule of Three" (look it up).

I would have done this:

class ObjMapData
{
    private:
        std::vector<char> itsMapData;

    public:
        clearMemory() // lower case first letter of non type.
        {
            itsMapData.swap(std::vector<char>());
        }
        void setMapData(std::vector<char>& ptrData)
        {
             itsMapData.swap(ptrData);
        }
        char* getMapData() const { return &itsMapData[0];}
};

Addition based on comment:

  (could be INT8, UINT8, INT16, UINT16, UINT32, INT32)

// Note the above data is not correctly aligned on all systems.

// INT8   INT8      INT16            INT16

01234567  01234567  0123456701234567 0123456701234567  Not a 32 Bit Boundary
|         |         |       |        |       |         |
8/16/32 Boundary    8/16 Boundary    8/16/32 Boundary  8/16 Boundary
          8 Boundary        8 Boundary       8 Boundary

But lets assume you just made a typo and you know what you are doing.

// Need room for
// INT 8 | INT 8 | INT 16 | INT 32 | INT 32
std::vector<char>  data(96);
::read(fd, &data[0], 96);    // Wow look at that fits neatly.

INT8  d1 = *reinterpret_cast<INT8 *>(&data[ 0]);  // The reinterpret cast is required
INT8  d2 = *reinterpret_cast<INT8 *>(&data[ 8]);  // It also shows its really dangerious
INT16 d3 = *reinterpret_cast<INT16*>(&data[16]);
INT32 d4 = *reinterpret_cast<INT16*>(&data[32]);
INT32 d5 = *reinterpret_cast<INT32*>(&data[64]);


Unit testing needs only optional methods of protocol in Swift

There are plenty of approaches that can fix your problem. But the main issue is how you build your classes. So IMHO you should focus on that.

Recommendation 1:  You should build your classes with composition of protocols. Loggable, Runnable, Flyable etc. If you build your class with combination of many protocols, the problem would be solved. And since Swift enables default implementations for protocols you can write a shorter class that is build by protocols. In this case you can test these protocols and their implementations separately.

Recommendation 2: There is a code smell in this design. You say no need to test for most of the methods. But you still put them in the same interface. And inject a class that conforms to this interface. You should change the class structure or injection interface. As in first recommendation I offer you to separate those methods to several interfaces and inject each other separately.

let controller = Controller(service: ABCProtocolMock(), anotherService: XYZProtocolMock())

Recommendation 3: Code Complete 2nd Ed. offers classes should have no more than 7 methods. If a class has more methods they should be separated through many considerations including SOLID.

Recommendation 4: I don't support this solution, because its another hacky code smell. But as a lazy developer you can think about if only one method will be testable/replacable why do you inject a whole interface. You can just inject a small interface that provides that method only.

Recommendation 5: Using utility functions can be another hacky solution. Since you want to test just one method of the class and if this method's implementation can be abstracted from internals of your class. You can forward this method's implementation to a utility function and write unit tests for this utility function.

Recommendation 6: Another hacky solution is building your classes as NSObject childs, and using Method Swizzling for testing purposes

As I mentioned above I don't know what is your exact situation, but Recommendation 1-2-3 are the correct solutions for a solid rock architecture. Others are just hacks that can save your day, but through your situation you can prefer to choose one of them.

For this decision I can offer you to check; if this is a one-time issue you can use a hacky solution. But if this a common situation that effects your applications architecture you should definitely use Recommendation 1-2-3.


Django model to do accounting for a Litecoin miner pool

totalMachineHoursWorked should be a @classmethod.  It could be written more succinctly like this, using sum():

@classmethod
def totalMachineHoursWorked(cls, self):
    return sum(l3.indivMachineHoursWorked() for l3 in cls.objects.all())

However, I have doubts that any of the calculations should be done in Python.  totalMachineHoursWorked() needs to fetch the entire table.  I would recommend trying to find a way to do all of these calculations in SQL instead, because that's what SQL servers are designed to do: provide an efficient tool to let you extract aggregate reports by formulating your query intelligently.

In particular, if you need to calculate btcToHour() for multiple hosts, that would be horribly inefficient, since it would need to calculate totalMachineHoursWorked() multiple times, each of which involves fetching the entire table, and also performing a calculation on an individual row.


Count bits that differ between integers X and Y

Comments

Your current comments aren't all that helpful, as they are just repeating excactly what the code already told me.

To improve them, think about why you are doing what you are doing, and what the result represents. For example:

  var z = x ^ y;  //XOR x and y

Right, so ^ is bitwise xor. But why are you doing this? What is z after this operation?

var z = x ^ y;  // set bits in z that are different in x and y to 1.

This is a bit more helpful (but you can improve on the phrasing if you want).

Misc

Your indentation is off a bit.
remove debug statements

If you do this, your code might look like this:

function findNumberOfBits(x, y) {
    var bitCount = 0;
    var z = x ^ y;  // set bits in z that are different in x and y to 1.
    while (z !== 0) { // not all bits are 0
        bitCount += z & 1; //  add least significant bit
        z = z >> 1;  // iterate over z; set next bit as lsb
    }
    return bitCount;
}

The comments might be a bit much (you can remove some if you want), but they are not just repeating the code.

  Is this correct? My tests seem to say yes, but just to make sure.

Looks good to me.

  Is this the most efficient way to write it in JavaScript?

If your code should work platform-independent, probably. Otherwise, no. You need the xor, but to count the number of set bits in the result, there might be better approaches.

What you are calculating is called the hamming distance, and here you can see some efficient implementations for the hamming weight (the count of set bits).

See also this question about counting the number of set bits in an integer.


Postgres query to extract a JSON sub-object from a JSON field

I'd recommend (if it isn't already) converting to the type from json to jsonb and adding a GIN index. The documentation below lays it out pretty clear. Good luck!
 https://www.postgresql.org/docs/9.4/datatype-json.html

For my recommendation, reason for using jsonb as opposed to vanilla json is that regular json is stored as an exact copy in postgres and you cannot add an index to that column. Whereas jsonb has a smaller footprint and allows for indexing the specific column. I'd prefer to store it in a format that could be indexed to allow for queries to be more performant.


Notice how close the syntax of your compressed strings resemble that of a regular expression:

   aa2bb => aa.{2}bb
aa2bb4cc => aa.{2}bb.{4}cc
  aa10cc => aa.{10}cc

Therefore you can easily create a regexp from your compressed string and test the expanded string against it:

function isExp(exp, comp) {
  const regexp = RegExp(`^${comp.replace(/\d+/g, '.{$&}')}$`)
  return regexp.test(exp);
}


Before we move to the generation part, let's talk about your html...

        question

The correct answer was:

        good answer

    You had selected: bad answer

Your correct answer:

qwe

 can only nest phrasing content.
 and
 both belongs to flow content and palpable content. Therefore, you can't nested these 2 under
 element. For the definition of a phrasing content consult this answer.
Personally, I would prefer using
 to separate block of text, instead of using a
 to insert a line-break.

        question

The correct answer was:

        good answer

You had selected: bad answer

Your correct answer:

        the answer

As for html generation, I believe, it is better to use a templating engine, such as RazorEngine which allows you to  write C# code within the template itself :

review.cshtml :

@{
    var correctAnswer = Model.Answer.GetText();
    var userAnswer = Model.UserAnswer == null ? Model.UserAnswer.GetText() : string.Empty;
}

    @Model.Question.GetText()

@if (userAnswer == correctAnswer)
{

The correct answer was:

        @correctAnswer

You had selected: @userAnswer

}
else
{

Your correct answer:

        @correctAnswer

}

generation code :

public string GetReview(Quiz quiz)
{
    var path = Desktop.GetFile("review.cshtml"); // TODO: fix this path
    var template = File.ReadAllText(path);

    return Engine.Razor.RunCompile(template, path, typeof(Quiz), quiz);
}

EDIT: I noticed you used the null-propagation operator from c# 6. You can also use the new string interpolation to format the html :

public static string GetReview3(Quiz quiz)
{
    var builder = new StringBuilder();
    builder.Append($@"

            {quiz.Question.GetText()}

    ");

    string correctAnswer = quiz.Answer.GetText();
    string userAnswer = quiz.UserAnswer?.GetText() ?? string.Empty;
    if (correctAnswer == userAnswer)
    {
        builder.Append($@"

The correct answer was:

                {correctAnswer}

You had selected: {userAnswer}

        ");
    }
    else
    {
        builder.Append($@"

Your correct answer:

                {correctAnswer}

        ");
    }

    builder.Append(ForQuiz(quiz));

    return builder.ToString();
}


You should declare loop variables as close as possible to the loop

int flowersNeeded, numFriends, i;
// ... some code
for (i = 0; i < flowersNeeded; ++i)

The above code causes inefficiency and puts unecessary mental burden on the reader, you should use (in C99):

int flowersNeeded, numFriends;
// ... some code
for (int i = 0; i < flowersNeeded; ++i)

Avoid modifyng in place and assigning at the same time

multiplier = (++flowersBought / numFriends) + 1;

The above line is too much compact, usually you assign to a variable xor you increment a variable in place, I would explode it in two lines:

flowersBought++;
multiplier = (flowersBought / numFriends) + 1;

Sorry for being pedantic

The very same compiler you use to generate the binaries doubles as a code analysis tool:

gcc flowers.c -Wall -pedantic

Warns you about:

h.c: In function ‘main’:
h.c:15:5: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result [-Wunused-result]
     scanf("%d %d", &flowersNeeded, &numFriends);
     ^
h.c:21:9: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result [-Wunused-result]
         scanf("%d", &flowerCosts[i]);
         ^


I was looking at what you had coded here

var deleteRemovedSubcategories = @"
    DELETE FROM dbo.Subcategories
    WHERE CategoryId = @Id
        AND Id NOT IN @Ids";

and it took me a minute to figure out exactly what the Where clause was filtering, what finally gave it away was the name of the C# variable deleteRemovedSubcategories. If it were possible I would change some of these column names and/or T-SQL variables so that it is more clear what you are saying here.


Allocating memory for a matrix with a single malloc

I would use calloc instead of malloc since you're anyway clearing the matrix after allocation.

void* cmatrix = calloc(1, matsize);
...
//memset((void*) cmatrix, 0, matsize);  this is not needed anymore because of 'calloc'

Also I do not think there is any point in using char* here because. Looks like you're using char* only because it allows you to increment pointers by bytes. I think using float** here would be even more convinient:

float** cmatrix = (float**) calloc(1, matsize);
if (cmatrix == NULL) { ... }
float* datastart = (float*) (cmatrix + rows); // you don't need char pointers here
for (...) { ... }


There is a lot of weird stuff here.

It's strange to have no ns form for defining your namespace and requiring the libraries you need. Putting a bare use at the top is gross.
Don't use an entire namespace. Either require with an alias, like (:require [clojure.string :as s]) ... (s/join ...), or else require and refer the specific stuff you use: `(:require [clojure.string :refer [join trim]]).
The uppercase function names should be lowercase: poss-dupe, or even possible-duplicate, not Poss-Dupe
There should be a newline after the parameter definitions for most functions: (defn foo [x] \newline (...))
The eval is very suspicious, but I don't want to read your whole program and figure out what you should be doing instead. Probably ns-resolve or something.
(if (or (empty? x) f) nil y) is a bad way to write (when (and (seq x) f) y)
Usually calling keyword to look stuff up in a map suggests that you shouldn't be using keywords as keys, but in your case it looks fine-ish. However, instead of ((keyword whatever) m), it would be more readable to write (get m (keyword whatever)).


Python file with several function definitions

In case the number of arguments is really long then you can use **kwargs to avoid cluttering up arguments in function definition block. I would also avoid naming the function as "main" and replace it with something like "execute".

def execute(**kwargs):
  name = kwargs.get('name', 'Bill')
  # get other values
  pass

if __name__ = "__main__":
  execute(*sys.argv[1:])


Choosing a movement strategy based on the type of chess piece

The complexity of approach is too high, it can be reduced to the following:

PieceType pieceType = getPieceType();
contextMovement.setContext(pieceType.getMovement());
return contextMovement.executeMovement(from, to, board);

The PieceType enum (probably call it Piece?) can be extended with:

public enum Piece {

  PAWN() {
    @Override
    public Movement getMovement() {
      return new PawnMovement();
    }
  }, ... // other elements;

  public abstract Movement getMovement();

}


How can I make this userform timer faster?

Just formatting first:

Your code is missing indentation and has some extra newlines in it.

Your Do Until loop should be double indented because it is inside of a sub.
You should also get rid of the extraneous commented code. If you got it working, get rid of the junk.

Here is what the code should look like:

Dim StopTimer As Boolean
Dim Etime As Single
Dim Etime0 As Single
Dim LastEtime As Single
Dim goal As Single
Dim Etime1 As Single
Dim Etime2 As Single
Dim LastEtime2 As Single

Public Sub btnReset_Click()
    StopTimer = True
    Etime = 0
    Etime0 = 0
    LastEtime = 0
    Etime1 = 0
    Etime2 = 0
    LastEtime2 = 0
    lblTime.Caption = "00:00:00"
    lblExtra.Caption = "00:00:00"
End Sub

Public Sub btnStart_Click()
    goal = 86400 * (Sheets("Input").Range("C2"))    'goal time in seconds
    StopTimer = False
    Etime0 = Timer()
    Etime1 = Timer() + goal
    Do Until StopTimer
        If Etime < goal Then
            Etime = Int((Timer() - Etime0) * 100) / 100
            If Etime > LastEtime Then
                LastEtime = Etime
                lblTime.Caption = Format(Etime / 86400, "hh:mm:ss")
                DoEvents
            End If
        Else
            Etime2 = Int((Timer() - Etime1) * 100) / 100
            If Etime2 > LastEtime2 Then
                LastEtime2 = Etime2
                lblExtra.Caption = Format(Etime2 / 86400, "hh:mm:ss")
                DoEvents
            End If
        End If
    Loop
End Sub

Public Sub btnStop_Click()
    StopTimer = True
End Sub

Public Sub ComboBox1_Change()
    Dim cotime As Single
    Sheets("Input").Range("A2") = Me.ComboBox1.Value
    Me.AvgTime.Caption = Format(Sheets("Input").Range("C2"), "hh:mm:ss")
End Sub

Public Sub ComboBox2_Change()
    Sheets("Input").Range("B2") = Me.ComboBox2.Value
    Me.AvgTime.Caption = Format(Sheets("Input").Range("C2"), "hh:mm:ss")
End Sub

Private Sub UserForm_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
    Application.Visible = True
End Sub

Private Sub UserForm_Initialize()
    ComboBox2 = ""
    ComboBox1 = ""
End Sub

It is a lot easier to read this way as well.

Your naming should be "pascalCase" for everything.

Lose the Hungarian notation on the labels; name the labels appropriately, like timeOutput or something like that.

StopTimer -> stopTimer
Etime -> eTime
LastEtime -> lastETime


That method will only hit the DB once, with a query like SELECT COUNT(*) …. But if you try to enumerate the resulting IQueryable in any way (like calling ToArray() on it or using it in a foreach), it will make another DB query.

You should probably only return the IQueryable. If the consumer needs all the items, it will call ToArray() or similar, which will make one DB query and then look at the Length of the result (which of course won't make another query). If the consumer needs only part of the result (e.g. it will call Take(100)) and it also needs the total count, it will call Count() itself. This will mean there will be two queries, but I think it can't be done differently.

Also, you probably should not be returning a collection of an anonymous type from a method, because it's hard to use.


Finding out which user has made the most progress

The method's name can be improved. I like that you ended it with Async, it makes it compliant with the convention for async Task<T> methods - however there's another naming convention programmers use all the time: method names should start with a verb! FindUserWithMostProgressAsync might be a better name, unless that method is located in the User class itself (then it would be misplaced).

IList<SubmittedAnswer> answers = await GetAnswersInRange(timeRange);

This tells me GetAnswersInRange is an async function that isn't following the convention - should be GetAnswersInRangeAsync, but then it might be a better idea to just call it GetAnswersAsync and let overloading speak the "in range" part: parameterless returns all answers, overload taking an ITimeRange returns all answers within the specified time range - and that can be nicely documented with XML comments.

Now, returning an IList<SubmittedAnswer> when all you really need is to iterate the results, is bad communication: IEnumerable<SubmittedAnswer> would have worked better.

IEnumerable<IGrouping<int, SubmittedAnswer>> answersOfUsers = answers.GroupBy(a => a.UserId);

LINQ came with C# 3.5, and that version introduced a little wonder to avoid declaring obscure types such as an IEnumerable<IGrouping<int, SubmittedAnswer>> - implicit typing changes strictly nothing to how the code works, saves you a bunch of typing, and makes shorter, more readable code here:

var answersOfUsers = answers.GroupBy(a => a.UserId);

Explicit typing is actually quite annoying here:

foreach (IGrouping<int, SubmittedAnswer> answersOfUser in answersOfUsers)

Compare to:

foreach (var answersOfUser in answersOfUsers)

There's a typo there that becomes immediately apparent: the loop variable is named exactly the same thing at the collection that's being iterated - that code wouldn't compile... so I'll assume you meant to have this:

foreach (var answerOfUser in answersOfUsers)

Now now now... you have a grouping, and you're entering a foreach loop, only to filter some more - that foreach loop could be converted to a LINQ query.

So we have all the answers in the time range we're interested in:

var answers = await GetAnswersInRange(timeRange);

And what we're after, is the UserId for the user that has accumulated the most progress with these answers. Grouping by UserId was a good first step.

var userAnswers = answers.GroupBy(answer => answer.UserId);

Next, we want to know how much progress each user has - we can do this by projecting a selection into an anonymous type, with the Select method:

var userProgress = userAnswers.Select(userAnswer =>
    new { UserId = userAnswer.Key, Progress = userAnswer.Sum(answer => answer.Progress) });

And this is where var has a clear advantage over explicit typing - exactly what is the type of userProgress here? It's an IQueryable<T>, where T is an anonymous type with some int UserId and int Progress members: we don't need to care what the actual type is.

What's next? Well, what we have now could be visualized as a table with a UserId and a Progess column. The next step is to find out which user has the most progess, and we can sort the results to get that, in descending order so we have the top user, well, at the top:

var sortedUserProgress = userProgress.OrderByDescending(progress => progress.Progress);

And then, all we need to do is grab the first "row":

var topUserId = sortedUserProgress.First().UserId;

And then we can create the User object for the return value:

return new User { UserId = topUserId };

...That's all nice, but it's excessively verbose:

var answers = await GetAnswersInRange(timeRange);
var userAnswers = answers.GroupBy(answer => answer.UserId);
var userProgress = userAnswers.Select(userAnswer =>
    new { UserId = userAnswer.Key, Progress = userAnswer.Sum(answer => answer.Progress) });
var sortedUserProgress = userProgress.OrderByDescending(progress => progress.Progress);
var topUserId = sortedUserProgress.First().UserId;

The good news is that LINQ is awesome, and lets you chain all these methods, so you can actually do this:

var answers = await GetAnswersInRange(timeRange);
var userId = answers.GroupBy(answer => answer.UserId)
                    .Select(userAnswer => new
                        {
                            UserId = userAnswer.Key,
                            Progress = userAnswer.Sum(answer => answer.Progress)
                        })
                    .OrderByDescending(progress => progress.Progress)
                    .First().UserId;

Note that .First() will throw an exception if there is no element in the sorted results. You could use .FirstOrDefault() instead, but then the .UserId member call would have to go on a separate instruction, because FirstOrDefault() will return null when there's no "first element", which means you'd be calling .UserId on a null reference, which would obviously throw a NullReferenceException... and your current code returns a valid User object with UserId set to 0, which leads me to believe the rest of your code has checks that verify whether a UserId is zero or not... which is rather ugly. How about this instead?

var answers = await GetAnswersInRange(timeRange);
var result = answers.GroupBy(answer => answer.UserId)
                    .Select(userAnswer => new
                        {
                            UserId = userAnswer.Key,
                            Progress = userAnswer.Sum(answer => answer.Progress)
                        })
                    .OrderByDescending(progress => progress.Progress)
                    .FirstOrDefault();

return result == null
    ? null
    : new User { UserId = result.UserId };

Returning null when there's no data for the specified timeRange makes more sense to me than returning a User object with some meaningless default/hard-coded values.


Maximum product of word lengths in Python

My solution is quite different, let me explain it:

At first I define a small helper to check if two words have any letter in common, it may also be in-lined, but I like small functions.

def common(a, b):
    """
    >>> common("hello", "hi")
    {'h'}
    """
    return set(a) & set(b)

Then I define the relevant score function for the strings, as you see, after defining our criteria we are almost done.

def product_score(w1, w2):
    """
    >>> product_score("foo", "bar")
    9
    >>> product_score("foo", "fuu")
    0
    """
    return 0 if common(w1, w2) else len(w1) * len(w2)

The last step is very easy. We already know the criteria, so we can just map it over the combination of 2 of the input list and take the max:

def maxProduct(words):
    """
    Maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters.

    >>> maxProduct(["eae", "ea", "aaf", "bda", "fcf", "dc", "ac", "ce", "cefde", "dabae"])
    15
    """
    return max(product_score(w1, w2)
                   for (w1, w2) in itertools.combinations(words, 2))

I think my solution is more readable, mainly because it uses smaller functions and because it uses already existing wheels (standard library modules).


Checking if a string is a number with STL

I had to really look at your code and think about what it was doing before I figured it out.  That tells me that this code is not elegant by my definition of "elegant".  My definition of elegant is something like,

  Easy to understand, easy to maintain, efficient in execution, robust.

I would suggest something like this as a start:

if( m.empty() )
  return false;

string::iterator start = m.begin();
if( *start == '-' )
  ++start;

if( m.end() == find_if( start, m_end(), not1(ptr_fun(isdigit)) ))
  return true;
else
  return false;

Not much caring for the use of find_if, I'd refine it to:

if( m.empty() )
  return false;

string::size_type pos = 0;
if( m[0] == '-' )
  pos = 1;

if( m.find_first_not_of("0123456789", pos) == m.end() )
  return true;
else
  return false;

I find this to be much more elegant than the 1-liner you wrote.  It's more code, sure.  But it is exceedingly simple to understand and maintain.  You found a bug yourself just by brain-compiling it.  That's what code should look like.


You'll have to add a class to the divs to be able to select them all

Then, use $.each() (http://api.jquery.com/each/)

var sum = 0;
$( ".sumdiv" ).each(function( index ) {
    sum += $(this).outerHeight()
});


Simple animation method with requestAnimationFrame code structure

Firstly, the usage example at the end doesn't really make sense. You're passing 5 arguments to the function, but it seems to only take 1 options object.

Structurally, it seems overwrought to create the animation object. Everything can be handled with closures, as far as I can tell. Somewhat in the same vein, I see no reason for the $ and _ prefixes on half the stuff.

Speaking of naming, the x and y options should probably be called from and to or something. It took me a few moments to realize that's what they are - not coordinates or something similar.

Your setup also seems conflicted, or at any rate complicated. You're using frame count, FPS, and duration (time) to track things, though these may contradict each other. You can't really dictate FPS; FPS is a measured value. If the browser is busy, FPS will drop, meaning each iteration will take longer. But you're calculating animation progression based on _iteration versus duration (which has since been redefined as the target number of frames, not time).

So I can say "I want 600,000 FPS!" but I won't get that kind of performance (requestAnimationFrame aims for 30 to 60'ish FPS, usually). But I can also say I want a duration (time-wise) of 1 second, yet the animation will still run 600,000 iterations. However this will not complete in 1 second.

It makes slightly more sense if you want low FPS, since your function just skips some onProgress calls. But low FPS is usually not considered a thing to strive for, really. In case you do want it, it might be easier to use setTimeout instead of requestAnimationFrame and ignoring updates.

Typically, animations have a set duration (in time), and FPS is whatever it is. You can't control it anyway. And so counting frames usually isn't very useful. Instead you do:

animationProgress = (now - startTime) / totalDuration

And you clamp that to 0...1. That's the input to the easing function.

Lastly, there's no need to call cancelAnimationFrame unless you've already called requestAnimationFrame and want to undo that before the next repaint.

Here's a pretty basic implementation:

function animate(options) {
  options = options || {};

  // defaults
  var duration = options.duration || 1000,
      ease = options.easing || function (a) { return a }, // basic linear easing
      onProgress = options.onProgress || function () {},
      onComplete = options.onComplete || function () {},
      from = options.from || {},
      to = options.to || {};

  // runtime variables
  var startTime = Date.now();

  function update() {
    var deltaTime = Date.now() - startTime,
        progress = Math.min(deltaTime / duration, 1),
        factor = ease(progress),
        values = {},
        property;

    for(property in from) {
      if(from.hasOwnProperty(property) && to.hasOwnProperty(property)) {
        values[property] = from[property] + (to[property] - from[property]) * factor;
      }
    }

    onProgress(values);

    if(progress === 1) {
      onComplete(deltaTime);
    } else {
      requestAnimationFrame(update);
    }
  }

  requestAnimationFrame(update);
}

// ==============================

// Example
animate({
  from: { a: 0 },
  to:   { a: 100 },
  duration: 500,
  onProgress: function (values) {
    document.getElementsByTagName("pre")[0].innerHTML += values.a + "\n";
  },
  onComplete: function (actualDuration, averageFps) {
    document.getElementsByTagName("pre")[0].innerHTML += "Done in " + actualDuration + "ms";
  }
});

I've opted to pass the easing function as an option, rather than a name. Thus you can supply your own easing function on the fly, or pass in a predefined function.


Welcome to C++.

A few notes:

When working outside of a toy project, avoid using namespace std. For why, see here.
In addition, when working outside of a toy project, I encourage you to define your classes within the scope of a namespace. Only you can fight namespace pollution.
Your a header does not make use of the iostream, string, or stringstream headers. They need not be included in that header.
Your text header does not make use of the iostream or stringstream headers. They need not be included in that header.
Header includes are transitive. Because your main function includes your text header which in turn includes the string header, the main.cpp need not also include string.
Your main implementation file does not make use of the sstream headers. They need not be included in that file.
Your a class methods made no use of the class instance. That said, these methods could be declared as static.
Your text class methods made no use of the class instance. That said, these methods could also be declared as static.
When you write to the terminal, you probably want a next line character. You can do this either by appending a \n to the output or by calling to std::endl in the iostream header. For more on the distinction, please see this post.
return 0; is actually unnecessary to indicate successful execution of the main function as of C99. reference

Also, please do not return a constexpr char *. Assuming you haven't specified otherwise, your compiler is very likely compiling to the C++ 11 specification. In which case, your string methods will be subject to return value optimization outside of debug mode and no temporary variables or heap allocations will be made.


How would I name these types in a way that's accurate and not redundant?

Given that:

PlanCardPropsEnum is only referenced once, in the type definition of PlanCardProps
PlanCardPropsEnum is not exported
The exported object is absolutely constant (right?)
The exported object is not props, but a container for different possible props

I would refactor it to:

Rename the exported object to UPPER_SNAKE_CASE, which is acceptable for absolute constants/enums. Maybe call it AVAILABLE_PLAN_CARD_PROPS, since it's not props itself, but a container around multiple props. Or you could call it ALL_PLAN_CARD_PROPS.
Remove PlanCardPropsEnum completely. TypeScript can already automatically infer the type of the object to have values of { header: string; ctaText: string; };, and you probably shouldn't type as [key: string] because you only have "around six props each" - you'd want only those particular props to be referenceable on the object, and for any other property accesses to throw a TS error.
Then, PlanCardPropsType can be renamed to PlanCardProps:

export type PlanCardProps = {
  header: string;
  ctaText: string;
};

// This could also be called AvailablePlanCardProps
// now that its name doesn't collide with another's
export const AVAILABLE_PLAN_CARD_PROPS = {
  TrialPlan: {
    header: 'x',
    ctaText: 'click here'
  },
  NoPlan: {
    header: 'y',
    ctaText: 'cancel'
  }
};

It can often be good to avoid explicit typing - better to let TS automatically infer types. This cuts down on code that needs to be read.
It's unfortunate that props is plural; if it were singular, it would be easier to come up with a good name to distinguish the collection from the individual.
Note that "enum" is a keyword with a specific meaning in TS. Probably best only to refer to actual TS enums as "enum", else you may confuse people.
If you're worried about possibly making a typo and, for example, mis-typing headrr instead of header, you could define the object first (so that all the keys get included in the type, without repetition), then assign the object to another variable whose type is a Record of those keys and the PlanCardProps:
export type PlanCardProps = {
  header: string;
  ctaText: string;
};

// Ensure that the values of the exported object match PlanCardProps:
type Keys = keyof typeof AVAILABLE_PLAN_CARD_PROPS_INITIAL;
export const AVAILABLE_PLAN_CARD_PROPS: Record<Keys, PlanCardProps> = AVAILABLE_PLAN_CARD_PROPS_INITIAL;

This will throw a TS error if you make a typo.


Rendering three vertical dots using SCSS

What you're looking for is just &:

  div {
    position: relative;
    &, &:after, &:before {
      border-radius:100px;
      background-color:gray;
      width:.5rem;
      height:.5rem;
    }
    &:after, &:before {
      content: '';
      position: absolute;
      display: inline-block;
    }
    &:after {
      top: -1rem;
    }
    &:before {
      top: 1rem;
    }
  }


It was hard to understand, how your code works, so I started by changing variable names to more meaningful form, also unnecessary +1, -1 operation were fixed (i - 1, 1, len(key) + 1, etc):

class Solution:
    def findRotateSteps(self, ring, key):
        cumulative_lens = [[min(i, len(ring) - i) for i in range(len(ring))]]
        cumulative_lens.extend([[float('inf')] * len(ring) for _ in range(len(key))])

        for key_num in range(len(key)):
            for new_ring_pos in range(len(ring)):
                if ring[new_ring_pos] != key[key_num]:
                    continue

                min_sum_len = float('inf')

                for prev_ring_pos in range(len(ring)):
                    prev_ltr_sum_len = cumulative_lens[key_num][prev_ring_pos]

                    if prev_ltr_sum_len == float('inf'):
                        continue

                    clk_w_len = abs(prev_ring_pos - new_ring_pos)
                    a_clk_len = len(ring) - clk_w_len

                    new_sum_len = min(clk_w_len, a_clk_len) + prev_ltr_sum_len + 1
                    min_sum_len = min(min_sum_len, new_sum_len)

                cumulative_lens[key_num + 1][new_ring_pos] = min_sum_len

        return min(cumulative_lens[-1])

Now, it is possible to read the code like a story. The cause of low performance is how you store and search visited letter lens (cumulative_lens). You keep them in the list, thus you need to iterate through all items to find not inf ones for each key value:

for prev_ring_pos in range(len(ring)):
    prev_ltr_sum_len = cumulative_lens[key_num][prev_ring_pos]

    if prev_ltr_sum_len == float('inf'):
        continue

Example: you have 100 letters in the ring and 10 letters in the key. You found all possible lengths in the ring (there are 3 only) to the first key's letter and move to the second. It will be good to take just needed 3 in the next key's letter processing, not checking others 97 items, which are 'infs'. It can be done by storing ring letters in  the dictionary - the Python's hash table structure, like this:

letter_indexes = {
    'a' : [first a's index, second a's index],
    'c' : [first c's index, second c's index, third c's index],
    etc
}

In this case, we can get the list of the needed letter positions by doing letter_indexes[letter], not messing with the others. I wrote my own solution, see it in the end.

Also, I did some refactoring of your code:

changed multiple len(ring) calls to the ln_ring variable - no performance gain, but more readable.
changed

for key_num in range(len(key)):
    for new_ring_pos in range(len(ring)):
        if ring[new_ring_pos] != key[key_num]:

like constructions to more pythonic:

for key_num, key_ltr in enumerate(key):
    for new_ring_pos, ring_ltr in enumerate(ring):
        if key_ltr != ring_ltr:

Result:

class Solution:
    def findRotateSteps(self, ring, key):
        ln_ring = len(ring)

        cumulative_lens = [[min(i, ln_ring - i) for i in range(ln_ring)]]
        cumulative_lens.extend([[float('inf')] * ln_ring for _ in range(len(key))])

        for key_num, key_ltr in enumerate(key):
            for new_ring_pos, ring_ltr in enumerate(ring):
                if key_ltr != ring_ltr:
                    continue

                min_sum_len = float('inf')

                for prev_ring_pos, prev_ltr_sum_len in enumerate(cumulative_lens[key_num]):

                    if prev_ltr_sum_len == float('inf'):
                        continue

                    clk_w_len = abs(prev_ring_pos - new_ring_pos)
                    a_clk_len = ln_ring - clk_w_len

                    new_sum_len = min(clk_w_len, a_clk_len) + prev_ltr_sum_len + 1
                    min_sum_len = min(min_sum_len, new_sum_len)

                cumulative_lens[key_num + 1][new_ring_pos] = min_sum_len

        return min(cumulative_lens[-1])

My solution:

It works similar to your, but is much faster due to dictionary usage.

class Solution:
    def findRotateSteps(self, ring, key):
        # the 'prev_ltr' variable should have the start value in the
        # beginning, so the '#' character is choosed
        # It can be changed to any character different from key's content
        # In other words, it is like '-1' item with 0 index.
        ltr_indexes = {'#' : [0]}

        for idx, ltr in enumerate(ring):
            ltr_indexes.setdefault(ltr, []).append(idx)

        ln = len(ring)
        l_lens = [0] * ln

        prev_ltr = '#'
        for ltr in key:
            for pos in ltr_indexes[ltr]:
                all_variants = []

                for prev_pos in ltr_indexes[prev_ltr]:
                    clk_w = abs(prev_pos - pos)
                    a_clk = ln - clk_w
                    all_variants.append(min(clk_w, a_clk) + l_lens[prev_pos])

                l_lens[pos] = min(all_variants)

            prev_ltr = ltr

        return min(l_lens[pos] for pos in ltr_indexes[ltr]) + len(key)


Eager load additional data about some instructors

The query to the database wont't be executed by writing this linq statement

var viewModel = new InstructorIndexData
{
    Instructors = _db.Instructors
        .Include(i => i.OfficeAssignment)
        .Include(i => i.Courses.Select(c => c.Department))
        .OrderBy(i => i.LastName)
};

if the InstructorIndexData.Instructors property setter isn't executing any of the following actions

enumerating the elements by a for..each loop
calling ToArray(), ToDictionary() or ToList() on the IEnumerable
calling a linq operator like First(), Any

See: https://msdn.microsoft.com/en-us/data/jj573936.aspx

So, if you call ToList() on the enumerable shown above, only one call to the database will be made.

 var viewModel = new InstructorIndexData
 {
     Instructors = _db.Instructors
         .Include(i => i.OfficeAssignment)
         .Include(i => i.Courses.Select(c => c.Department))
         .OrderBy(i => i.LastName)
         .ToList()
 };

The call to

viewModel.Courses = viewModel.Instructors.Single(i => i.InstructorId == id.Value).Courses;

will then operate on the retrieved data and won't need a trip to the database anymore.


Programs for different language learning - Perl

What you did well

use strict;, use warnings;, and my scoping
qw(list of words) instead of ('list', 'of', 'words')
Generally straightforward, readable Perl.

Suggestions

There is a hard-coded correspondence between my $lang = 3 and the fact that there are three choices.  My suggestion:

my $choices = @choices;

In Perl, $choices and @choices are different variables: the former is a scalar, and the latter is a list.  The assignment above coerces the list into a scalar, and it does so by taking the number of elements in the list.  (You used this technique in @choices[rand @choices].
Parentheses are optional for subroutine calls, and they are typically omitted for well-known functions such as print.
For maintainability, terminate the last print with a semicolon, even if you aren't required to.
As @glennjackman already told you, say would be better than print, as it also outputs a trailing newline.
Avoid super-long string literals by using a here document.

    print <<"INTRO";
Welcome to the test script…
There are $choices languages to choose from.
@choices
INTRO

Your logic is rather trusting: any input other than "Ruby" or "Python" is treated as if it were "Perl".

A better way:

use feature qw(say);
…

chomp(my $choice = <STDIN>);
if ($choice eq 'Perl') {
    say "You're already writing in Perl!! Let me choose for you:";
    say @choices[rand @choices];
} elsif (grep { $choice eq $_ } @choices) {
    say "You have chosen $choice!";
}

A possible outcome is "You're already writing in Perl!! Let me choose… Perl".  I consider that to be a logic bug.


Add space between your functions, PEP8 suggests two spaces, but honestly any amount of space would be better than none.

There's not much of a difference between shuffle and shuffle_v2:

You've written a for loop as a while loop. Which doesn't make much sense as Pythons for loops are really clean and easy to use.
You use different bounds for your random.randint calls. shuffle is from the index to the end, for shuffle_v2 it's from the start to the index.

And so it's mostly asking which is better of the two different ranges.
Using the following, we can find which is better:

import random
from collections import defaultdict, Counter

def shuffle(cards):
    for write_index in range(len(cards)):
        read_index = random.randrange(write_index, len(cards))
        cards[read_index], cards[write_index] = cards[write_index], cards[read_index]

def shuffle_v2(cards):
    for i in range(1, len(cards)):
        index = random.randrange(0, i)
        cards[index], cards[i] = cards[i], cards[index]

if __name__ == "__main__":
    data = list(range(7))
    count = defaultdict(int)
    bound = 1000000
    for fn in [shuffle, shuffle_v2]:
        count = defaultdict(int)
        for _ in range(bound):
            d = list(data)
            fn(d)
            count[tuple(d)] += 1
        print(len(count), Counter(count.values()))

Which resulted in:

5040 {146: 1,   152: 1,   154: 2,   155: 1,   157: 1,   158: 3,   159: 4,   160: 3,
      161: 5,   162: 5,   163: 1,   164: 4,   165: 9,   166: 10,  167: 9,   168: 10,
      169: 20,  170: 27,  171: 19,  172: 17,  173: 31,  174: 37,  175: 33,  176: 30,
      177: 50,  178: 54,  179: 35,  180: 53,  181: 75,  182: 64,  183: 77,  184: 85,
      185: 90,  186: 112, 187: 104, 188: 102, 189: 128, 190: 126, 191: 131, 192: 126,
      193: 165, 194: 140, 195: 131, 196: 150, 197: 134, 198: 152, 199: 152, 200: 126,
      201: 143, 202: 140, 203: 156, 204: 134, 205: 117, 206: 118, 207: 117, 208: 112,
      209: 102, 210: 101, 211: 98,  212: 87,  213: 85,  214: 69,  215: 58,  216: 62,
      217: 45,  218: 48,  219: 48,  220: 54,  221: 35,  222: 35,  223: 34,  224: 22,
      225: 22,  226: 22,  227: 22,  228: 22,  229: 9,   230: 10,  231: 10,  232: 13,
      233: 9,   234: 3,   235: 5,   236: 7,   237: 4,   238: 5,   239: 2,   240: 1,
      241: 1,   243: 2,   244: 1,   245: 2,   248: 1,   250: 1,   253: 1}

720 {1238: 1,  1284: 1,  1287: 1,  1290: 1,  1296: 2,  1300: 1,  1305: 1,  1306: 1,
     1308: 1,  1309: 1,  1310: 1,  1311: 1,  1313: 1,  1314: 2,  1315: 1,  1316: 2,
     1317: 1,  1318: 5,  1320: 3,  1322: 2,  1323: 1,  1324: 1,  1325: 1,  1326: 2,
     1327: 2,  1328: 1,  1329: 2,  1330: 1,  1331: 6,  1332: 1,  1333: 3,  1334: 1,
     1335: 1,  1336: 9,  1337: 2,  1338: 5,  1339: 3,  1340: 3,  1341: 3,  1342: 2,
     1343: 3,  1345: 6,  1346: 4,  1347: 2,  1348: 2,  1349: 1,  1350: 8,  1351: 7,
     1352: 1,  1353: 4,  1354: 4,  1355: 3,  1356: 5,  1357: 7,  1358: 7,  1359: 8,
     1360: 4,  1361: 4,  1362: 9,  1363: 4,  1364: 4,  1365: 10, 1366: 6,  1367: 2,
     1368: 6,  1369: 9,  1370: 8,  1371: 6,  1372: 9,  1373: 9,  1374: 7,  1375: 8,
     1376: 8,  1377: 5,  1378: 10, 1379: 10, 1380: 5,  1381: 14, 1382: 8,  1383: 7,
     1384: 7,  1385: 4,  1386: 7,  1387: 10, 1388: 11, 1389: 6,  1390: 11, 1391: 2,
     1392: 7,  1393: 10, 1394: 4,  1395: 5,  1396: 12, 1397: 7,  1398: 10, 1399: 8,
     1400: 6,  1401: 8,  1402: 6,  1403: 5,  1404: 7,  1405: 7,  1406: 5,  1407: 14,
     1408: 8,  1409: 7,  1410: 5,  1411: 2,  1412: 2,  1413: 6,  1414: 6,  1415: 6,
     1416: 4,  1417: 10, 1418: 14, 1419: 8,  1420: 5,  1421: 4,  1422: 4,  1423: 3,
     1424: 6,  1425: 2,  1426: 9,  1427: 3,  1428: 6,  1429: 4,  1430: 4,  1431: 6,
     1432: 1,  1433: 4,  1434: 3,  1435: 2,  1436: 2,  1437: 1,  1438: 3,  1439: 1,
     1440: 2,  1441: 2,  1442: 2,  1443: 1,  1444: 4,  1445: 5,  1446: 2,  1447: 4,
     1448: 4,  1449: 3,  1450: 4,  1452: 2,  1453: 1,  1454: 1,  1455: 1,  1458: 1,
     1459: 3,  1460: 2,  1462: 1,  1463: 1,  1464: 1,  1465: 1,  1466: 2,  1467: 1,
     1468: 2,  1471: 2,  1472: 3,  1473: 1,  1476: 2,  1478: 1,  1483: 1,  1485: 1,
     1508: 1,  1531: 1}

This shows that the first algorithm not only had a more uniform distribution, it can actually shuffle into all 5040 different permutations. And so is the superior algorithm.


Calling stored procedure with a sqlCommand

You can use the ternary operator If():

sqlCommand.Parameters.Add(New SqlClient.SqlParameter("GroupID", SqlDbType.Decimal)).Value = If(groupID = 0, DBNull.Value, groupID)
sqlCommand.Parameters.Add(New SqlClient.SqlParameter("SiteID", SqlDbType.Decimal)).Value = If(siteId = 0, DBNull.Value, siteId)

Be aware that this can cause a compiler error if you have Option Strict turned on. The following is Option Strict compatible...

sqlCommand.Parameters.Add(New SqlClient.SqlParameter("GroupID", SqlDbType.Decimal)).Value = If(groupID = 0, DBNull.Value, CObj(groupID))
sqlCommand.Parameters.Add(New SqlClient.SqlParameter("SiteID", SqlDbType.Decimal)).Value = If(siteId = 0, DBNull.Value, CObj(groupID))

The If ternary operator was added in .Net 3.5/Visual Basic 2008. If you're using and older version you'll need to use the IIF function. The syntax is almost the same, just replace if with iif

sqlCommand.Parameters.Add(New SqlClient.SqlParameter("GroupID", SqlDbType.Decimal)).Value = IIF(groupID = 0, DBNull.Value, groupID)
sqlCommand.Parameters.Add(New SqlClient.SqlParameter("SiteID", SqlDbType.Decimal)).Value = IIF(siteId = 0, DBNull.Value, siteId)


Fixing starting times command by command and globally

Maintaining bidirectional relationships
Rather than this check:
    if not self._command.has_task(self):
        raise ValueError("orphaned task")

it would be better to mark the task as orphaned by nulling out its command. In other words,
def remove_task(self, task):
    """
    Remove the task from this command.  After calling this,
    the task is orphaned and the reference to the task should be discarded.
    """
    task.command = None
    self.tasks.remove(task)

Having command as a simple, "public", possibly-None member on Task is simpler. At most, I would give this a type hint of Optional[Command] in the constructor.
Types
Don't call date date; that's a commonly used class in a built-in library.
deadline should probably be of type datetime (not date), and duration should be of type timedelta, not int.


Drawing a word, with a box around one letter

You can get rid of the "unsafe bit casts", an CFArrayRef can
be bridged to [CTLine] (resp. [CTRun]) directly (tested with Swift 3 and Swift 4).

If you know for
sure that there is at least one line with at least one run then
it would be:

let lines = CTFrameGetLines(frame) as! [CTLine]
let line = lines.first!
let runs = CTLineGetGlyphRuns(line) as! [CTRun]
let run = runs.first!

Otherwise use optional binding with if let or guard let.
A most defensive version would be

guard let lines = CTFrameGetLines(frame) as? [CTLine],
    let line = lines.first,
    let runs = CTLineGetGlyphRuns(line) as? [CTRun],
    let run = runs.first else { return }


Below is your code with some minor tweaks and the comments moved into standard Haddock form.

module Bencode (readBencodedFile, BencodedValue(..), bencode, bencodeBS) where

import qualified Control.Monad as Mon
import Data.ByteString (ByteString)
import Data.ByteString.Char8 (pack)
import qualified Data.Map as M
import Text.Parsec.ByteString as ParseBS
import Text.Parsec.Char (anyChar, char, digit)
import Text.Parsec.Prim ((<|>), parserFail, runParser)
import Text.Parsec.Combinator (count, many1, option)
import qualified Text.Parsec.Error as PE

type BMapT = M.Map BencodedValue BencodedValue

data BencodedValue = Bint Integer
                   | Bstr String
                   | Blist [BencodedValue]
                   | Bmap BMapT
                   deriving (Eq, Ord, Show)

-- |Transform a 'BencodedValue' back to an encoded string
bencode :: BencodedValue -> String
bencode (Bint i)   = "i" ++ show i ++ "e"
bencode (Bstr s)   = (show . length) s ++ ":" ++ s
bencode (Blist bs) = 'l':concatMap bencode bs ++ "e"
bencode (Bmap bm)  = M.foldlWithKey (\a k b -> a ++ bencode k ++ bencode b) "d" bm  ++ "e"

-- |Return a 'BencodedValue' value to it original encoded 'ByteString' form.
bencodeBS :: BencodedValue -> ByteString
bencodeBS = pack . bencode

{-|
  'readBencodedFile' reads data from a torrent file and returns the parsed
  result as a dictionary in a 'BencodedValue'.
  The 'String' is the filename of the torrent to read.
 -}
readBencodedFile :: String -> IO (Either PE.ParseError BencodedValue)
readBencodedFile = parseFromFile bMap

------------------------
-- Internal functions --
------------------------

-- |Parse a Bencoded Integer
bInt :: ParseBS.Parser BencodedValue
bInt = do char 'i'
          neg  <- option ' ' (char '-')
          nums <- many1 digit
          char 'e'
          mkBint neg nums
  where
    mkBint ' ' ['0']    = return $ Bint 0
    mkBint '-' ('0':ns) = parserFail "Can't have a negative zero"
    mkBint _   ('0':ns) = parserFail "Invalid number with a leading zero"
    mkBint '-' nums     = return $ Bint $ read ('-':nums)
    mkBint _   nums     = return $ Bint $ read nums

-- |Parse a Bencoded String
bString :: ParseBS.Parser BencodedValue
bString = do nums <- many1 digit
             char ':'
             mkBstring (read nums)
  where
    mkBstring size = do cs <- count size anyChar
                        return $ Bstr cs

-- |Parse a Bencoded List
bList :: ParseBS.Parser BencodedValue
bList = do char 'l'
           ls <- many1 (bInt <|> bString <|> bList <|> bMap)
           char 'e'
           mkBlist ls
  where
    mkBlist = return . Blist

-- |Parse a Bencoded dictionary
bMap :: ParseBS.Parser BencodedValue
bMap = do char 'd'
          entries <- many1 dictEntry
          char 'e'
          mkBmap entries
  where
    mkBmap = return . Bmap . M.fromList

-- |Parse a Bencoded dictionary entry.
-- This is an internal function declared outside of 'bMap' to
-- facilitate testing.
dictEntry :: ParseBS.Parser (BencodedValue, BencodedValue)
dictEntry = do key <- bString
               value <- bString <|> bList <|> bInt <|> bMap
               return (key, value)

Answers to your questions.

Without getting REAL fancy there is no good way limit the BMap argument to a Bstr while it is an member of algebraic type.
Your analogy to repr from Python is a good one. Typically if there is a Haskell Show instance there is also a Read instance so show . read . show is valid. In your case the result of show needs to be parsed again and you do not expose a parse from string/bytestring. I added a bencode and bencodeBS which takes a BencodedValue and outputs a String or ByteString.
Look at where I simplified or renamed your items to see suggestions on idiomatic usage. On the whole you did pretty well. If I had more time I would have liked to transform your parser functions into Applicative style. By transitioning to the mkFoo functions I started that process for you if you like.
In the code you ask about why this is a String when the ByteString is the input. It is because the parsers are returning Strings parsed from the ByteString. If the performance really matters you could transition over to Attoparsec.


Attaching a click handler in a cross-browser way

The common thing in your code is the listener.

function massClickListener() {
    doMassClick( btnArray[index], nameArray[index]);
}

Then it is easier to use the ternary:

btnArray[index][ window.addEventListener ? 'addEventListener' : 'attachEvent'](window.addEventListener ? 'click' : 'onclick', massClickListener);

Personally however, I think this is better:

if (window.addEventListener) {
    btnArray[index].addEventListener('click', massClickListener);
} else {
    btnArray[index].attachEvent('onclick', massClickListener);
}

Using the conditional operator to choose different methods is not very readable.

Another option might be to use a framework that does these kinds of things for you.


jQuery slideshow with connected links and the ability to pause/resume when hovered

Objects
Your code is fairly spread out and not very portable. All your variables are living in the top scope (well, not the global scope, but in your first $ call).
It would be more beneficial to pack this code into an object/class which keeps the state contained in the object itself. You could perhaps create something like this:
function ImageCarousel(slides, links) {
    this.slides = slides;
    this.links = links;

    // Here, you can setup the state of the carousel.
    this.slideToActivate = 1;
    this.viewingLength = 2000;
    this.loop = null;
}

With this design, nothing is leaking out into outer scopes and you can keep all the logic and state together.

Expensiveness
$ is an expensive function. It traverses the whole DOM every time you call it (or most of it), and this is certainly no speedy task.
$("#carousel-nav")

and
$("#carousel-slides...")

pop up more times than they should. Are the returns of these functions changing at any point in the program? No. Therefore, the results should be stored in variables
var navLinks = $("#carousel-nav");
var slides = $("#carousel-slides...");

Then, you can just access these variables rather than calling the function every time.

Simplify operation
slideToActivate++
if (slideToActivate > slideCount) {
  slideToActivate = 1
}
changeCarouselSlide()

can be simplified to
slideToActivate = (slideToActive + 1) % slideCount;
changeCarouselSlide()

The remainder operator (%) wraps numbers back around to 0 if they pass the right hand value.

Necessarianess
// Deactivate everything.

Is this really necessary? You have (or you should have) all the information you need to turn off the exact slides/links that are activated. For setups where there are a lot of slides and links, your current solution can get slow.
Well, we know the current slide number and we have an array of slides and links...
slides[slideToActivate].hide();
navLinks[slideToActivate].css(...);

ID's
Your current system of ID's is a little strange.
<img id="1"...
<img id="2"...
<img id="3"...

These ID's aren't descriptive at all of what the slides are. Here are some possible things you can do:

Change the ids to something like "imagecarousel-slide-1".
Use a data property like imagecarousel-slide="1".
Assume the slides are in the order in which they will appear.

The last method is certainly the easiest to implement. If you do choose one of the two former methods though, make sure that when you stick them in the array I mentioned above (navLinks or slides) you order them based on the property you decided.


RegEx sentence-splitting madness. Mad genius?

Enlightenment.
Don't be impressed by a pattern. Format it to something readable:
[^.!?\s] [^.!?\n]*

(?:
    [.!?] (?! ['"]? \s | $ )
    [^.!?]*
)*

[.!?]? ['"]? (?= \s | $ )

There are three simple parts. No madness here, this pattern isn't complicated, but
before assuming parts are useless you have to fully understand what they do.

The first part [^.!?\s] [^.!?\n]* search a character that isn't a white-space or a punctuation mark, and then it consumes greedily all eventual following characters that aren't punctuation marks too or newlines.
Why newlines? This last point may seem surprising but is eventually related to the context: the way the text is formatted. In other words, sentences are perhaps on one line only.
Note that [^.!?\s] is the only thing that isn't optional in the pattern. Note also that since [^.!?\n]* is greedy, the next character after it can only be a punctuation mark, a newline or the end of the string.

The second part is an optional non-capturing group eventually repeated. Its goal is to accept punctuation marks that don't end the sentence, for instance things like:3.14, bestcatpics.maowmaow, bad enc?ding.
[.!?] should not be followed by a space or a "closing" quote and a space or the end of the string as the negative lookahead (?! ['"]? \s | $ ) expresses it. [^.!?]* will only reach the last position before the next punctuation mark (or the end of the string). Note that this time the newline isn't excluded: it's inconsistent with the first part.
The non-capturing group is repeated until there's no more "fake" punctuation mark.

The third and last part finishes the job consuming the punctuation mark that ends the sentence and the "closing" quote before a white-space or the end of the string. Punctuation mark and quote are optional.

Pattern Review.
From a technical point of view.
The pattern is well-designed to reduce the backtracking as possible: (A|B)* is unrolled to A* (BA*)*, where A is [^.!?] (with or without \n) and B is [.!?] with its lookahead assertion (?! ['"]? \s | $ ).
Writing ( [^.!?] | [.!?] (?! ['"]? \s | $ ) )* is shorter than [^.!?]* (?: [.!?] (?! ['"]? \s | $ ) [^.!?]* )* (about 9 chars) but is from far less efficient for a backtracking regex engine.
Other good point, all quantifiers are greedy and applied over restricted sets of characters, that is also more efficient than using reluctant quantifiers over permissive character classes (like the dot, [\s\S] or [^] in Javascript).
The only thing to deplore is the inconsistency between [^.!?\n] in the first part and [^.!?] in the second part. I really doubt there's a good reason behind. Also, (?=\s|$) is IMO better written like that: (?!\S) even if it looks less explicit.
About readability.
Most of regex engine provides a verbose mode that ignores white-spaces and inline comments in the pattern. Javascript doesn't have this feature yet, but for a long pattern like this one, nothing forbids to do that:
const pat = String.raw`
    [^.!?\s] [^.!?\n]* # start of the sentence

    (?: # "fake" punctuation mark
        [.!?] (?! ['"]? \s | $ )
        [^.!?]*
    )*

    [.!?]? ['"]? (?!\S) # end of the sentence`;

const re = RegExp.compile(pat.replace(/\s+|#.*/g, ''), 'g');

The approach.
This pattern may be the right solution in the specific context in which it is used. Nevertheless, and under no circumstances can it be considered a viable solution for isolating sentences from a plain text in natural language.
The analysis of natural language (NLP: Natural Language Processing) is a whole part of computing with these own tools like NLTK. While sentence breaking may seem like a basic task, it may require tools such as dictionaries, such as statistics (Machine Learning), and even, who would have thought, regex.


Header file that includes all standard C library headers

With this suggested usage:

#include "foo.h"
#include "std.h"

then any macros defined in "std.h" (and not used in the rest of the main) won't break the program.  Swapping these round:

#include "std.h"
#include "foo.h"

solves that problem, but then fails to diagnose missing includes in "foo.h".


Your leading whitespace is much smaller than is typical. Prefer 4 spaces for a level of indent.
In java we typically put the curly brace { on the same line. If you insist on doing it on a new line, do it consistently (main) and don't add a blank line of whitespace before the curly brace.
Variable names need to be clear and descriptive. str is meaningless - perhaps word? Likewise, firstVow is confusing, since nobody's getting married. Surely you mean firstVowel. Extra characters come at no charge, so if they make the variable name more descriptive, use them.
Closeable resources need to be closed always. Use either try-with-resources or a finally block to close open resources. Otherwise an exception in the middle of execution will prevent the resource from being closed.
Variables should be defined in the most constraining scope possible. All of your variables can and should be method variables, defined at the time of first need.
You repeat code to see if a character is a vowel. Using either a method so you're only writing the code once or a Set to hold all vowels would be better.
for loops would be easier to read than while loops, since you need all three statement anyway.
Your last block of work (word starts with a consonant) assumes there'll eventually be a vowel in the word.
It's generally preferable that methods return a value rather than performing direct IO themselves. If you don't follow that, the pattern you used for the first two blocks (multiple System.out.print calls) is much easier to read than the one big print with everything mushed together. If you do return a value, using a StringBuilder might be a better idea than using string concatenation.
In several places you store a character and use to that with an indexOf when the index is just i or 0. You should simplify that down.
In a couple of places you do if (condition) { } else if (!condition) { }. It's OK to just do if (condition) { } else { }


Removing duplicate code from basic collision detection implementation

It seems this is a job for a Parameter class.

public abstract class DeltaParameters{
  protected ? tileMap;
  protected int x, y;

  DeltaParameters(Point point, ? tileMap){
    this.x = point.x;
    this.y = point.y;
    this.tileMap = tileMap;
  }

  public int getX(){
    return x;
  }

  public int getY(){
    return y;
  }
  public abstract int getTileSideSize();
  public abstract int getMovingCoordinate();
  public abstract void offsetMovingCoordinate(int delta);
}

public class DeltaXParameters extends DeltaParameters{
  DeltaXParameters(Point point, ? tileMap){
    super(point, tileMap);
  }

  public int getTileSideSize(){
    return tileMap.getTileWidth();
  }
  public int getMovingCoordinate(){
    return x;
  }
  public void offsetMovingCoordinate(int delta){
    x += delta;
  }
}

I leave to you the job of guessing what would be DeltaYParameters :p

public int getMaxDelta(DeltaParameters dparams, int delta){
    if(delta>=dparams.getTileSideSize()) throw new IllegalArgumentException("This message is yet to be determined. It could be another method in DeltaParameters");
    if(delta==0) return delta;

    dparams.offsetMovingCoordinate(delta);
    if(isInsideTile(dparams.getX(), dparams.getY())){
        int map = dparams.getMovingCoordinate() /dparams.getTileSideSize() ;
        int offset = dparams.getMovingCoordinate() - (map * dparams.getTileSideSize() );
        int maxDelta = 0;

        if(delta < 0){
            maxDelta = delta + (dparams.getTileSideSize() - offset);
        }
        else if(delta > 0){
            maxDelta = delta - offset;
        }

        return maxDelta;
    }
    return delta;
}

Now you could call getMaxDelta just like this

getMaxDelta(new DeltaXParameters(new Point(0, 0), tileMap), 5);

What I have done here is to take the advantage of polymorphism over DeltaParameters class. Which could not be a so straigthforward method to refactor is now proven to be in a quite simple fashion imho.


Project Euler#61: Cyclical figurate numbers

boolean flag = false;//FLAG flag to use as a stepback conjugate
boolean stepback = false;
do {
    flag = false;//FLAG
    if (count < n - 2) {
        for (; i < 9999; i++) {
            if (isSpecialFigurate(i, low_lim, low_lim + (n - 1))) {
                if (count == -1 || (count >= 0 && i / 100 == a[count] % 100) && i > 1000) {
                    ++count;
                    a[count] = i;
                    break;
                } else {
                    figurateStack.pop();
                }
            }
        }
    } else {
        i = (i % 100) * 100 + a[0] / 100;
        if (isSpecialFigurate(i, low_lim, low_lim + (n - 1))) {
            ++count;
            a[count] = i;
            break;
        } else {
            stepback = true;
        }
    }
    if (i == 9999) {
        stepback = true;
    }
    if (stepback) {
        figurateStack.pop();
        i = a[count] + 1;
        --count;
        flag = true;//FLAG
        stepback = false;
    }
    if (count < n - 2 && !flag) {//FLAG
        i = 100 * (i % 100) + 10;
        flag = false;//FLAG
    }
} while (count < 6);
return a[0] + a[1] + a[2] + a[3] + a[4] + a[5];

You've got a flag variable in there. But from what I see, you don't need it. I've labeled all the usages with //FLAG.

The only line that sets flag to true is inside the if statement stepback. stepback is triggered by i == 9999 or some other condition earlier.

flag is set to false at the top of your do-while loop. So every iteration, it's set to false.

Because of this, the flag variable cannot be changed from false until the stepback if-statement.

So we can do this:

    if (stepback) {
        figurateStack.pop();
        i = a[count] + 1;
        --count;
        flag = true;//FLAG
        stepback = false;
    } else if (count < n - 2) {
        i = 100 * (i % 100) + 10;
        flag = false;//FLAG
    }

if stepback occured, flag is true, and the if statement thereafter becomes always false. So turn it into an else.

You don't make any other checks for flag, so now flag can be removed.

boolean stepback = false;
do {
    if (count < n - 2) {
        for (; i < 9999; i++) {
            if (isSpecialFigurate(i, low_lim, low_lim + (n - 1))) {
                if (count == -1 || (count >= 0 && i / 100 == a[count] % 100) && i > 1000) {
                    ++count;
                    a[count] = i;
                    break;
                } else {
                    figurateStack.pop();
                }
            }
        }
    } else {
        i = (i % 100) * 100 + a[0] / 100;
        if (isSpecialFigurate(i, low_lim, low_lim + (n - 1))) {
            ++count;
            a[count] = i;
            break;
        } else {
            stepback = true;
        }
    }
    if (i == 9999) {
        stepback = true;
    }
    if (stepback) {
        figurateStack.pop();
        i = a[count] + 1;
        --count;
        stepback = false;
    } else if (count < n - 2) {
        i = 100 * (i % 100) + 10;
    }
} while (count < 6);
return a[0] + a[1] + a[2] + a[3] + a[4] + a[5];

Next, we can collapse the if statement i == 9999 to be included in the stepback check:

Instead of

    if (i == 9999) {
        stepback = true;
    }
    if (stepback) {

We just do

    if (stepback || i == 9999) {

Because stepback disables itself, we don't need to worry about previous iterations of the while loop having stepback = true.

There's also an explicit else that we can make implicit...

        if (isSpecialFigurate(i, low_lim, low_lim + (n - 1))) {
            ++count;
            a[count] = i;
            break;
        } else {
            stepback = true;
        }

to

        if (isSpecialFigurate(i, low_lim, low_lim + (n - 1))) {
            ++count;
            a[count] = i;
            break;
        }
        stepback = true;

Making the total code

boolean stepback = false;
do {
    if (count < n - 2) {
        for (; i < 9999; i++) {
            if (isSpecialFigurate(i, low_lim, low_lim + (n - 1))) {
                if (count == -1 || (count >= 0 && i / 100 == a[count] % 100) && i > 1000) {
                    ++count;
                    a[count] = i;
                    break;
                } else {
                    figurateStack.pop();
                }
            }
        }
    } else {
        i = (i % 100) * 100 + a[0] / 100;
        if (isSpecialFigurate(i, low_lim, low_lim + (n - 1))) {
            ++count;
            a[count] = i;
            break;
        }
        stepback = true;
    }
    if (stepback || i == 9999) {
        figurateStack.pop();
        i = a[count] + 1;
        --count;
        stepback = false;
    } else if (count < n - 2) {
        i = 100 * (i % 100) + 10;
    }
} while (count < 6);
return a[0] + a[1] + a[2] + a[3] + a[4] + a[5];


How to make Print() method memory & CPU efficient?

First, observe that if you receive an out-of-sequence object, you have to potentially keep all the objects from the latest printed sequence number to the received number. Worst case, you receive the object in reverse order and have to keep them all in memory. There is no way around this. So, what you can optimize is first, when you are printing objects you can find them quickly, and second, you don't want to move them around, which will happen if you use a slice and grow it as necessary.
So, a sketch of an algorithm that will use CPU and memory better than what you have is as follows:
var nextInSequence=0 // The next item you are expecting in the sequence
var storedObjects=map[int]SomeStruct{}

func Print(seqNumber int, obj SomeStruct) {
   if seqNumber==nextInSequence {
     output obj
     nextInSequence++
   } else {
      storedObjects[seqNumber]=obj
   }
   for {
     if stored, ok:=storedObjects[nextInSequence] ; ok {
        output stored
        delete(storedObjects,nextInSequence)
        nextInSequence ++
     } else {
        break
     }
  }
}


One hash with params populate two objects

This could be refactored into a service object that does the manipulations. Your controller would still manipulate the Hash, but it would provide the service object the hash values it needs:

class BlogPostUpdateService
  def initialize(blog_post_params, blog_post_details_params)
    @blog_post_params = blog_post_params
    @blog_post_details_params = blog_post_details_params
  end

  def execute(blog_post)
    blog_post.update_attributes @blog_post_params
    blog_post.blog_post_details.update_attributes @blog_post_details_params
    update_blog_post_groups blog_post if @blog_post_params['group_ids']
    blog_post
  end

private
  def update_blog_post_groups(blog_post)
    # ...
  end
end

All of the logic for updating the blog post would be contained within the service object. Abstracting your internal architecture should be handled by the controller, which then delegates to the service for the actual modifications:

def update
  # ... abstract away your internal schema
  update_service = BlogPostUpdateService.new(blog_post_params, blog_post_details_params)
  update_service.execute @blog_post
  render :blog_post, status: 200
end

I'm also not clear why you are deleting 'post' and saving at as 'blog_post', but then later deleting 'blog_post' and saving it as 'blog_post_details'. This seems like you are jumping through a lot of hoops and I'm not sure what benefit it has, other than being really confusing.


Brainfuck interpreter (with emphasis on robustness)

Deficiencies? I don't really see any. Improvements? Maybe :)

You don't handle at all the return values of putchar, getchar and fflush. The Wikipedia article has some hints about how different implementations handle an EOF from the user input. Yours works as well, but is this really what you want?
In build_jump_table, the switch used to check whether *c is a [ or a ] seems a bit overkill. It would probably be easier to get away with a simple if .. else statement.
That's highly speculative, but I guess that if you replace the characters <, >, -, +, ., ,, [ and ] by values ranging from 0 to 7, or at least by contiguous values during the program load, it might help your compiler to generate a better jump table for your switch, which might help increasing the speed of the programs.

The assumption here is that your care more about the speed during the execution and that a little slowdown during the program load isn't a problem if it can otherwise improve performance.
I guess that you want your programs to be fast while they run and that a small slowdown when it terminates isn't one of your concerns if you can otherwise speed your program up. Therefore, if your compiler supports it (I guess it does), you could use __builtin_expect to influence branch prediction while the program runs:

switch (*ip) {
    case '<':
        if (__builtin_expect(--ptr < mem, false)) {
            return i + 1;
        }
        break;
    case '>':
        if (__builtin_expect(++ptr >= mem + sizeof mem, false)) {
            return i + 1;
        }
        break;
    // ...
}

It would however be a bad idea to influence branch prediction for the conditions in the cases of [ and ]. The results are too prone to change to risk a pessimization.

I would have some other small remarks but I will keep them for myself since they would be considered a matter of style and you know what you're doing anyway :)