I have a suggestion.  Basically I'm not sure why you are adding so much to the HTML to handle the the parent and child checkboxes.  Isn't the hierarchy of the HTML enough to go on?  From the HTML you can already determine the parent and child relationships.  In additon why trigger more events.  Just handle the event as it bubbles up though the DOM.

Below is an example of some code that I believe to be far more reusable and much easier to implement.  In addition, I have modified this to work with future checkboxes added to the DOM.  It may be necessary to load some of the children via AJAX and/or appending to the DOM therefore your method would require you to bind your function on each append to the DOM, where as mine would handle it though delegation of events.

$.fn.nestedCheckboxes = function (stopPropogation) {
    this.addClass('nestedCheckboxes');
    this.click(nestedCheckboxHandler);
    this.delegate(':has( > input:checkbox)', 'click', nestedCheckboxHandler);
    function nestedCheckboxHandler (evt) {
        if ($(evt.target).is("input:checkbox")) {
            var parentContainer = $(this);
            var checkbox = parentContainer
                            .find(' > input:checkbox:eq(0)');
            var parentCheckbox = parentContainer
                                    .parent()
                                    .closest(':has( > input:checkbox)')
                                    .children('input:checkbox');

            if (evt.target == checkbox[0]) {
                $('input:checkbox', parentContainer)
                    .prop("checked", checkbox.prop("checked"));
            }
            var parentCheckboxValue = !parentCheckbox
                                        .parent()
                                        .find("input:checkbox")
                                        .not(parentCheckbox[0])
                                        .is("input:checkbox:not(:checked)");

            parentCheckbox.prop("checked",parentCheckboxValue);
        } else if (stopPropogation) {
            evt.stopPropagation();
        }
    };
};

$(function () {
    $('div').nestedCheckboxes();  //this is how you would use the function

    $('#addChildren').click(function () {
       $(this).after('

<input type="checkbox" />Child 2 SubChild 1

<input type="checkbox" />Child 2 SubChild2

');
       return false;
    });

});

In addition I have added an option for the nestedCheckboxes to stopPropogation if an element other than a checkbox is clicked.  By default this if set to false.

Finally have a look at the fiddle I created and play around.  You will see that the HTML Markup is far more simplistic.

http://jsfiddle.net/jfhartsock/WwtJr/


Calculate admission prices of different days

Several things that come to mind:

Don't use using namespace std; as it leads to namespace pollution (e.g. name collision)
Don't use std::endl unless you need to flush the buffer
As you already noticed there is a lot of duplicate code and just like DRY states we don't want to repeat ourselves

Going for a simple rewrite while keeping mostly to your original code we could do the following:

#include <iostream>

int main()
{
    unsigned int kids, adults;
    char day;

    std::cout << "Enter the number of Adults attending? ";
    std::cin >> adults;

    std::cout << "Enter the number of Children attending? ";
    std::cin >> kids;

    std::cout << "What is the day of the week? ";
    std::cin >> day;
    std::cout << "The day entered is: " << day << "\n";

    switch (day)
    {
        case 'u': case 'U':
            std::cout << "Total price is: " << adults * 12 << "\n";
            break;

        case 't': case 'T':
            std::cout << "Total price is: " << adults * 8 + kids * 6 << "\n";
            break;

        case 'm': case 'M':
        case 'w': case 'W':
        case 'r': case 'R':
        case 'f': case 'F':
        case 's': case 'S':
            std::cout << "Total price is: " << adults * 12 + kids * 6 << "\n";
            break;

        default:
            std::cout << "Not a valid day" << "\n";
    }
}

This makes use of Fall through cases in the switch construct thus simplifying your code without overengineering it.


FizzBuzz example in Python for game manual

Nicely done! The great thing about this implementation that it's easy to extend (for example if you want to add (7, "jazz"). I have only some minor nitpicks.

Tuples are immutable, as opposed to lists.
Since the list of fizz-buzz-jazz definitions don't change during the run of the program,
the divs list can be a tuple.
Tuples are faster than lists.

divs = (
    (3, "fizz"),
    (5, "buzz"),
)

The parentheses are unnecessary around (divisor, name):

ndivs = ''.join(name for (divisor, name) in divs
                if n % divisor == 0)

This may be a matter of taste,
but I'd find this line more readable on a single line:

ndivs = ''.join(name for divisor, name in divs if n % divisor == 0)


Can MD5ing all the files in a table cause a memory leak?

In Java you have to do so much hard work to leak memory (someone will say not closing stream, but that's another story).

I think you have a C programming background. So you are thinking of memory leak. Forget it there is JVM for you.

And use enhanced for loop in Java as much as you can...

for(File file : directory) {
    System.out.println(MD5.asHex(MD5.getHash(file)));
}


Saves files and attachments regardless of errors in the model

Uploaded files are a tricky thing. You really don't want to move the files into their final resting spot until the other stuff is saved. Ideally, you want:

Commit to database
Move files to permanent storage
(Optionally) One more commit to the database to update file paths or names

Validation errors, of course, throw this all out of whack. From a UI perspective you solve this by switching your form from "create mode" to "edit mode" -- don't show the "upload" field. Show the files in the UI as if you were editing something that already existed in file storage, except you are referencing a temp file on the server instead of a file in permanent storage.

So now the process becomes:

Run validations (they fail...)
Update a temporary copy of you model with the temp file paths

This is where a "view model" can be useful, so the object used to render things on screen does not have to adhere to the same constraints as your Active Record classes

Re-render the page so the user can correct the errors
User corrects errors
User submits form, including references to temp files
Commit to database
Move files to permanent storage
(Optionally) One more commit to the database to update file paths or names


SQL Injection and php performance checking

You are using prepared SQL statements, but not using parameterised queries in them, so you're still wide open to SQL injections. This is how you should be doing it:

$gid = $_GET['gid'];
$queryr = $pdo->prepare('SELECT test3.name FROM test1, test2, test3 WHERE test1.id = test2.groupid AND test3.id = test2.peopleid AND test1.id = :gid ORDER BY test3.name ASC');
$queryr->bindParam(':gid', $gid, PDO::PARAM_STR);
$queryr->execute();

Assuming that your $gid is supposed to be numeric, you should probably extract it this way too:

if(is_numeric($_GET['gid'])) {
  $gid = (int)$_GET['gid'];
  // ...
  $queryr->bindParam(':gid', $gid, PDO::PARAM_INT);

The same applies to your later queries that are being generated from $_POST.

This segment also seems to be missing a set of braces. If it works, then it's likely only a coincidence. if without braces is hard enough to read in just PHP, but if you drop out of PHP, I honestly have no idea how PHP will react.

  <?php foreach ($queryl as $i => $rowl) { ?>

   <?php if ($i)?>
  <input name="checkbox_del[]" id="test_<?php echo $i ?>" type="checkbox" value="<? echo $rowl['id']; ?>"/>
  <label for="test_<?php echo $i ?>">
   <a href="test1.php?gid=<?php echo $rowl['id']; ?>"><?php echo $rowl['name']; ?>

  <?php } ?>

There is a larger problem with this script in general. Mixing logic with the output can cause design problems. Ideally you would load all your data at the top, then generate your page all at once. I don't know how big a system this is, but in general it's much easier to manage the system as a whole if you structure your pages this way. What happens if you want to conditionally show something at the top of the page, but the condition isn't generated till later when you are processing data?

Eg, you might end up with something like the following:

<?php
include("db_con1.php");
$queryl = $pdo->prepare('SELECT id, name FROM test1 ORDER BY name ASC');
$queryl->execute();

$lists = array();
while (($rowl = $queryl->fetch(PDO::FETCH_ASSOC)) !== false) {
  $lists[] = $rowl;
}

// And so on for all the data you need to load
?>

It seems your right bar and left bar aren't associated directly, but if they were then you could put more in that while loop to load stuff into $rowl before adding it to $lists. You can then just iterate over this array in your code. All your SQL is at the top of the file and easy to change, all your presentation is at the bottom of the file and will read a lot nicer too, with just some loops and some echo's.


There are a number of things going on here, but it boils down to Amdahl's Law.

I am going to take a stab at some guessing here, but I expect my numbers to be in the right ballparks. Your code does:

Collection groupNames = people.getPublicGroups(userID);
For each Group:

you connect to flickr
you download the data
you parse it
you write-to-file.

Here are things that you are doing slower than necessary:

you are parsing the same URL many times (as many times as you have groups to process), as the URL does not change inside the loop. If you process it once outside the loop, you will get the same results.
Is you file output buffered?
Do you need to doc.getDocumentElement().normalize(); ?

Now, as for the real application of Amdahl's law, and, assuming the URL is wrong that you are processing (and that there should be 1 URL per group), you should: run things in parallel.

Consider something like:

ExecutorService service = Executors.newFixedThreadPool(....);
....
LinkedList<Future<String>> futureops = new LinkedList<>();

while (...) {
    futureops.add(service.submit(new Callable<Integer>() {
        public String call() throws IOException {
            // ****** Will need to probably do this as a separate class to get  *****
            // ****** it to compile right, or use `final` judiciously.          *****
            DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
            DocumentBuilder b = f.newDocumentBuilder();
            Document doc = b.parse(urlString);

            doc.getDocumentElement().normalize();
            NodeList items = doc.getElementsByTagName("group");
            Node n = items.item(poolCounter);
            Element e = (Element) n;

            //get total photos in group
            String numberOfPhotos = e.getAttribute("pool_count");
            //get members in the group
            int numberOfMembers = gInfo.getMembers();
            return "\t" + name + " " + numberOfPhotos + " photos" + ", " + numberOfMembers + " members";
        }
    });

    while (!futureops.isEmpty()) {
        String result = futureops.removeFirst();
        file.writeFile(result);
        System.out.println(result);
        poolCounter++;
    }
}


class WeakBoundMethod:

I suggest making it a new-style class by inheriting from object.

    assert (hasattr(meth, '__func__') and hasattr(meth, '__self__')),\
           'Object is not a bound method.'

Don't do this. Just let the invalid parameter types raise attribute errors when you try to fetch the __func__ and __self__. You don't gain anything by checking them beforehand.

assert self.alive(), 'Bound method called on deleted object.'

Raising an Assertion here is a bad choice. Assertions are for thing that should never happen, but having the underlying self object cleaned up doesn't really count. Raise an exception like weakref.ReferenceError. That way a caller can reasonably catch the error.

The documentation is very clear, well done.

EDIT

    try:
        return self._func(self._self(), *args, **kw)
    except Exception as e:
        raise e

Why are you catching an exception only to rethrow it? That's really pointless.

I'd write the whole function as:

def __call__(self, *args, **kw):
    _self = self._self()
    if _self is None:
        raise weakref.ReferenceError()

    return self._func(_self, *args, **kw)


Creating an instance of an unit of work (NHibernate)

In some camps it is not advised to tightly couple your code to framework specific dependencies like IConfiguration.

Based on the shown constructor it looks like the UnitOfWorkV really needs the connection string and not the configuration. That late bound constructor dependency will only be realized when the class is being resolved.

Refactor the  class to depend on what is actually needed.

public UnitOfWorkV(string connectionString) {
    _sessionFactory = Fluently.Configure()
        .Database(MsSqlConfiguration.MsSql2008.ConnectionString(connectionString)
        .ExposeConfiguration(ConfigureNhibernateValidator)
        .Mappings(m => {
            m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly());
            m.HbmMappings.AddFromAssemblyOf<JobQueue>();
        })
        .BuildSessionFactory();
    Session = _sessionFactory.OpenSession();
    Session.FlushMode = FlushMode.Auto;
}

And get the connection string at start up,

var connectionString = Configuration.GetConnectionString("ConexionV");

injecting it explicitly into the class.

if(connectionString == null) //Fail early
    throw new Exception("Missing connection string");

services.AddScoped<IUnitOfWork, UnitOfWorkV>(_ => new UnitOfWorkV(connectionString));

That way, any validation can be done immediately at startup instead of deferring to when resolving the actually class


Is my 4x4 matrix multiplication on a 1D float array correct?

My final code is:

public float[] multiplicate(float[] factor){
    int a = 0;
    int b = 0;
    float[] result = new float[factor.length];
    for (int i = 0; i < factor.length; i++){
        a = (i/4)*4;
        b = (i%4);
        result[i] = (mat4f[a] * factor[b]) + (mat4f[a+1] * factor[b+4]) + (mat4f[a+2] * factor[b+8]) + (mat4f[a+3] * factor[b+12]);
    }
    return result;
}

I'll keeping using 1D float array because I'll need to use a FloatBuffer to send it to OpenGL (using LWJGL). So i'll get less overhead by calling one FloatBuffer.put(myArrFloatVar) then FloatBuffer.put(new float[]{r00, r01...r33} or event calling FloatBuffer.put(r00) 16 times.


Recode C -> C++ trampoline function macros using templates

Surprisingly (to me at any rate) there is a template solution.

It appears that it is possible to do:

template<FuncSignature funcPointer>
myFunc(){...}

And later:

x = myFunc<&MyClass::MyMethod>

You can pick up the trail here: https://stackoverflow.com/questions/26934036/coding-static-to-instance-method-trampoline-function-with-templates


Refactoring fixed static adding items to new List

Well, we can cut the boilerplate down a little bit with some helpers and changes to your original classes like this:

using System.Collections.Generic;

using static AdPosition;
using static AdType;

public class AdItem
{
    public AdType Type { get; set; }

    public string Container { get; set; }

    public SizeList Sizes { get; set; }

    public PositionList Position { get; set; }
}

public sealed class AdItemList : List<AdItem>
{
    public void Add(AdType type, string container, SizeList sizes, PositionList position)
    {
        this.Add(new AdItem { Type = type, Container = container, Sizes = sizes, Position = position });
    }
}

public sealed class SizeList : List<List<int>>
{
    public void Add(params int[] values)
    {
        var intList = new List<int>(values.Length);

        foreach (var value in values)
        {
            intList.Add(value);
        }

        this.Add(intList);
    }
}

public sealed class PositionList : List<Position>
{
    public void Add(string id, string value)
    {
        this.Add(new Position { Id = id, Value = value });
    }
}

then your method shrinks up like so:

private static AdItemList GetAdSlotItems()
{
    var s = "";
    return new AdItemList
    {
         { LeftSky, "div-ad-skyscraper-l", new SizeList { { 120, 600 }, { 160, 600 } }, new PositionList { { LeftSky.ToString(), left.ToString() } } },
         { RightSky, "div-ad-skyscraper-r", new SizeList { { 120, 600 }, { 160, 600 } }, new PositionList { { RightSky.ToString(), right.ToString() } } },
         { LeaderBoard, "div-ad-leaderboard", new SizeList { { 300, 250 } }, new PositionList { { inline.ToString(), inline.ToString() } } },
         { BillBoard, "div-ad-billboard", new SizeList { { 728, 90 }, { 970, 250 }, { 300, 50 } }, new PositionList() },
         { MPU1, "div-ad-rectangle-e1", new SizeList { { 300, 250 }, { 300, 600 } }, new PositionList { { MPU1.ToString(),mpu1.ToString() } } },
         { MPU1, "div-ad-rectangle-e2", new SizeList { { 300, 250 }, { 300, 600 } }, new PositionList { { MPU2.ToString(),mpu2.ToString() } } },
         { MPU1, "div-ad-rectangle-e3", new SizeList { { 300, 250 }, { 300, 600 } }, new PositionList { { MPU3.ToString(),mpu3.ToString() } } },
         { WallPaper, "div-ad-wallpaper", new SizeList { { 1, 1 } }, new PositionList() }
    };
}


Using Python to get data from a Star Wars API

You should never compose URLs using this technique!

search = sys.argv[1]
url = 'https://swapi.co/api/people/?search={0}'.format(search)      #need to divide url to make search process more dynamic
r = requests.get(url)

Query string parameters need to be percent-encoded.  The Python Requests library provides a correct way to do it:

search = sys.argv[1]
url = 'https://swapi.co/api/people/'
r = requests.get(url, params={'search': search})

Going further, I would caution you to never concatenate any user-supplied string to form another string that will be interpreted by some computer system.  You must first considering the escaping mechanism.  SQL injections, cross-site scripting, LDAP injection, etc. — they're all vulnerabilities that result from this same kind of carelessness.


Random permutation with defined order of last occurrences

I want to make it more efficient. Currently its time complexity is O(n*m), n being the number of distinct characters and m the average number repetitions.

There are two important errors there. Firstly, the time complexity of the given code is worse than stated. Secondly, the stated complexity is optimal.

Taking those in reverse order: the stated complexity is optimal because the number of items which must be inserted into chr_list is \$\Theta(mn)\$, and no matter how you arrange things each insertion will take \$\Omega(1)\$ time.

However, the given code does insertions at random, and an insertion into a random position in a list takes \$\Theta(\textrm{len})\$ time, so the overall complexity of the given code should be \$\Theta(m^2 n^2)\$.

How to achieve optimal asymptotic performance? You need to arrange for the insertions to be done in order. I think that probably requires some additional datastructures. The simplest approach conceptually is to have an array (or a list in Python terms) to store the characters in their final positions and a datastructure of unassigned indexes which allows fast selection of the maximum element and a random element. In Pythonesque pseudocode:

tmpList = [None] * sum(chr_counts)
unassigned = new Datastructure(sum(chr_counts))
for c in reverse(chr_list):
  tmpList[unassigned.removeMax()] = c
  for i in 1 to chr_counts[c] - 1:
    tmpList[unassigned.removeRandom()] = c
copy tmpList to chr_list

The best implementation I've thought of so far for the datastructure of unassigned indexes combines a linked list for fast implementation of max with an array for fast implementation of random. I'm not familiar with Python's OO syntax, so this is again pseudocode:

class LinkedListNode:
  LinkedListNode prev
  LinkedListNode next
  int arrayIdx
  int value

class Datastructure:
  LinkedListNode[] array
  LinkedListNode sentinel = new LinkedListNode

  init(len):
    array = []
    for i in range(len):
      array[i] = new LinkedListNode { arrayIdx = i, value = i }
    for i in range(len-1):
      array[i].next = array[i+1]
      array[i+1].prev = array[i-1]
    sentinel.next = array[0]
    sentinel.prev = array[len-1]
    sentinel.next.prev = sentinel
    sentinel.prev.next = sentinel

  removeMax():
    return removeNode(sentinel.prev)

  removeRandom(rnd):
    randIdx = rnd.randint(0, len(array))
    return removeNode(array[randIdx])

  removeNode(node):
    # Remove from linked list
    node.next.prev = node.prev
    node.prev.next = node.next
    # Remove from array
    array[node.arrayIdx] = array[-1]
    array[node.arrayIdx].arrayIdx = node.arrayIdx
    del array[-1]

    return node.value

Note: I don't really think Datastructure is a good name, but it's not an easy class to name so I'm using it as a placeholder instead of Foo.


Length limited listagg for muliple m:n relations in a view

Oracle regular Character types are limited to 4000 bytes. Really, Oracle should find a way to extend that, but until they do, using CLOB is the only real option.

On the other hand, Oracle has a rich infrastructure available for creating user defined functions. You are already creating the view, you may as well extend that to include the function.

There are a number of articles out there that can help:

http://www.oracle-base.com/articles/misc/string-aggregation-techniques.php
http://www.oracle-developer.net/display.php?id=306
and others....

The one that is missing from those is the use of XML functions.... It is a relatively commonly used 'hack', to use the XML-processing functions in Oracle (and other databases) to reformat the data in a more convenient way, and then to extract from that XML just the parts you want.

So, ideally you should create a user-defined function for your problem, but, you can accomplish the same thing, perhaps faster, with a hack of XML....

Consider swapping the nested select:

     SELECT inner.MAIL_ID,
            LISTAGG(inner.CUSTOMER_NAME, '; ')
              WITHIN GROUP (ORDER BY inner.CUSTOMER_NAME) AS CUSTOMERS
       FROM (
            SELECT rel.MAIL_ID,
                   cust.CUSTOMER_NAME,
                   ROW_NUMBER() OVER
                     (PARTITION BY rel.MAIL_ID ORDER BY cust.CUST_ID) AS RN
              FROM CUSTOMERS_MAILS rel INNER JOIN
                   CUSTOMERS cust ON (cust.CUST_ID = rel.CUST_ID)
            ) inner
      WHERE inner.RN <= 50
      GROUP BY inner.MAIL_ID

with:

Select CM.MAIL_ID,
  substr(xmlcast(
    xmlagg(
      xmlelement(E, '; ' || C.CUSTOMER_NAME)
      ORDER BY C.CUSTOMER_NAME
    ) AS CLOB -- or AS VARCHAR2(4000)
  ), 3
) as CUSTOMERS
from CUSTOMERS C, CUSTOMER_MAIL CM
where C.CUST_ID = CM.CUST_ID
group by CM.MAIL_ID

I have put together a simple SQLFiddle that shows this select in action. It assumes two sets of users, (some male names, some female names), and it puts the different users in to different MAIL_ID's.

Once you have swapped out these nested statements, it will significantly shorten your query.... Your handling code though will have to change. Getting a CLOB back from the view is a big change.... and it is best to handle that in a different way....

Edit: About this operation as a general problem

At an academic level, the problem you are experiencing is because you are doing a non-relational operation in a relational database. Data in a relational database is treated using set arithmetic. You have sets of data that you can intersect, union, filter, and otherwise manipulate. The problem you are tying to solve in this question is the conversion of a set of values in to a single merged value (with internal consistency requirements). This type of operation is not well defined in set theory.

The standard/recommended mechanism for solving this problem is to export the data set in to an external application, and process the data from there. Any system you use in an SQL query to remove the set-like nature of the data is a 'hack', and that is why you are unsatisfied with the result you are seeing. The right solution is to not use SQL.


More simplified way of creating page links dynamically?

This:

$count = 1;
for($i = 1; $i <= $num; $i++) {
    if(($i%$npp) === 0) {
        $count++;
    }
}

is equivalent to

$count = floor($num / $npp) + 1;

As for the paging, I'd do it like this:

$from = $page - $half;
if ($from <= 2) $from = 2;
$to = $page + $half;
if ($to >= $count - 1) $to = $count - 1;

$extra = $query . $by;
$links = $this->pageLink(1, $extra);
if ($from > 2) $links .= "...";
for ($i = $from; $i <= $to; $i++)
    $links .= $this->pageLink($i, $extra);
if ($i < $count) $links .= "..."; // I use $i instead of $to because $i == $to + 1, so I save one addition
$links = $this->pageLink($count, $extra);

Here, you also need:

private function pageLink($num, $extra) {
    return '' . $num . '';
}

This was written by heart, so be weary of the possible bugs.


I want to talk about your View while I'm on mobile and thinking about it. Just like regular C# code we should definitely define structure for our Razor code. The first thing that rubs me wrong is that @using statement. I really don't like it because you only need it for the @model declaration at the top of the file. I would just get rid of it and explicitly specify the model full type.

Next, I really don't like the @{ } block with the foreach and such in it. Generally I just prefer to prefix each code block with @whatever instead. This helps create a more consistent convention throughout. (Right now you mix code and @code in your view which is generally bad.)

As far as the HTML itself, we've started leaning more on CSS to do the styling for things, so elements like strong and i should be span class="title" then in your CSS .title would have font-weight: bold;.

Let's talk about your serialization:

private T Deserialize<T>(string filePath)
{
    var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
    var data = System.IO.File.ReadAllText(filePath);
    return jss.Deserialize<T>(data);
}

You always call it as Deserialize<T>(Server.MapPath(...)), so let's encapsulate that:

private T DeserializeAppData<T>(string file) =>
    Deserialize<T>(Server.MapPath($"~/App_Data/{file}.json"));

Then call it as DeserializeAppData<T>("Reports"). Much simpler, straightforward and to the point. You still have the other Deserialize<T> method, in case you need it for other things.


Sorting an array of strings using pointers (followup)

Advice 1

I suggest that you add the { and } to loop/conditional block even in the case it's a one-liner. The reason is if someone maintains your code and need to add a statement or a couple, they do not need to type those.

Advice 2

The display may print a more friendly text:

void display(char *s[], int n)
{
    int i;
    printf("\n\n[");
    char* separator = "";
    for (i = 0; i < n; i++) {
        printf("%s%s", separator, s[i]);
        separator = ", ";
    }
    printf("]\n\n");
}

For example: [abc, bb, def].

Advice 3

If you need to sort large array of strings, there are more efficient algorithms especially for sorting strings. See this. Also, I believe radix sort would perform good as well.

Hope that helps.


Wordpress single post content class customization with if-else function

The third
 appears to be the same in all three cases, so that can be abstracted out of the cases.
The outermost
 appears to have class pt-4 applied only if is_page_template( 'landingpage.php' ) returns a value that evaluates to FALSE and is_single() returns a value that evaluates to TRUE.
And the first nested (i.e. second)
 has class container-fluid if either of those functions return a value that evaluates to TRUE.
This logic could be rewritten as below. I know it strays away from the familiar wordpress style of using the Alternative syntax for control structures and uses the shortcut syntax (i.e. <?=) of echo but it does add some separation of the logic from the markup
<?php
// default class names
$contentClass = 'site-content';
$containerClass = 'container-fluid';
if (!is_page_template( 'landingpage.php' )) {
    if (is_single()) {
        $contentClass .= ' pt-4';
    }
    else {
        $containerClass = 'container';
    }
}
?>
    <div id="content" class="<?= $contentClass; ?>">
        <div class="<?= $containerClass; ?>">

It could be simplified using ternary operators but some may argue that would detract from readability.

Is this shorter?
yes, only by two lines

is this more elegant?
Well, that is subjective. The code above should be simpler to read. Consider the scenario where the code is updated by multiple people, including programmers and designers. The programmers can have designers update the markup without affecting the business logic. For more on this topic, refer to Mixing PHP and HTML.


Mapping square objects to specific cells in a TableLayoutPanel in WindowsForms game

The problem of your code is that you use separate conditions for each particular row and for each particular column.
But it can be easily aggregated into one - check if the row number is odd. A rest of the desired functionality can be reached using arithmetics.

Please try this code:

private static void MapSquareNumToScreenRowAndColumn(int squareNumber, out int rowNumber, out int columnNumber)
{
    const int Rows = 7;
    const int Cols = 6;

    // Calculate the rowNumber and the columnNumber at once.
    // See Math.DivRem for details: http://msdn.microsoft.com/en-us/library/yda5c8dx(v=vs.110).aspx
    rowNumber = Rows - 1 - Math.DivRem(squareNumber, Cols, out columnNumber);

    // If the rowNumber is odd:
    if ((rowNumber & 1) != 0)  // (rowNumber & 1) is the same as (rowNumber % 2)
        columnNumber = Cols - 1 - columnNumber;  // Invert the columnNumber
}


HackerRank Ransom Note, solved using Data.Map as a hash table

This will be a list of "don't"s, since your code is very readable, but contains some code smells. It doesn't actually solve the puzzle, but more on that later.

Data.Map.Map is not a hashtable

I just want to get something out of the way first: Data.Map isn't a hash table. A hash table needs a function \$\text{hash}: A \to I\$, where \$I\$ is some finite, bounded and integral set with \$|A|\gg|I|\$. An efficient hash map/table uses buckets and provides a best case \$\mathcal O(1)\$ access if implemented correctly. Data.Map only provides \$\mathcal O(\log k)\$ access, since it's implemented as a tree. That's why you need the Ord constraint on almost all functions in Data.Map.

However, it's still a nice data structure for this problem.

Python's dictionaries on the other hand are based on hashable functions.

Don't give names to things you won't use

  [a,b] <- readInts

You don't actually use a or b. You don't actually use that line at all. That line is meant for languages like C, where you need to manage memory yourself, e.g.

int ok = scanf("%d %d",&a,&b);
ptr_t words = malloc(...);
ptr_t words = malloc(...);

You get it. However, since you never use them, just ignore that line, e.g.

main = do
  _ <- getLine -- ignore first line
  ms <- ...

Don't repeat yourself

The first thing one notices immediately is duplicate code:

  -- create magazine words table
  let mss = zip ms (repeat 1)
  let mms = M.fromListWith (+) mss

  -- create note words table
  let lss = zip ls (repeat 1)
  let lms = M.fromListWith (+) lss

That should be a function, e.g.

count :: Ord a => [a] -> Map a Int
count xs = M.fromListWith (+) (zip xs (repeat 1))

An intersection isn't what you want

Let's think about the following magazine and words:

> let ms = words "this stranger was giving a code review. the next thing will blow your mind"
> let ws = words "we have your daughter"

Lets use count on bothmsandwsand thenintersectionWith`:

> intersectionWith (-) (count ms) (count ws)
fromList [("your",0)]

Huh. That's strange. Could we actually form that ransom note? No. We're missing "we", "have", and "daughter". So what can we conclude?

intersectionWith isn't correct, since there might be elements in the ransom note that aren't in the magazine.
Hackerrank is missing edge cases.

What should we do instead? Well, we can flip the sign on the words map and then use the union:

subtractMap :: (Ord k, Num a) => Map k a -> Map k a -> Map k a
subtractMap a b = M.unionWith (+) a (fmap negate b)

Why is it important to negate, and not simply unionWith (-)? Because the operation will only take effect if there are elements with the same key in both maps.

Put it all together

So, you've used Data.Map correctly, except for the intersectionWith, which didn't come up because the test cases were borked. Otherwise, everything was fine, except for the things mentioned above.

Here's the code that implements all the suggestions above. Note that type signatures on top-level functions are very recommended:

import Control.Applicative
import           Data.Map (Map)
import qualified Data.Map as M

count :: Ord a => [a] -> Map a Int
count xs = M.fromListWith (+) (zip xs (repeat 1))

subtractMap :: (Ord k, Num a) => Map k a -> Map k a -> Map k a
subtractMap a b = unionWith (+) a (fmap negate b)

main :: IO ()
main = do
  _ <- getLine -- ignore first line
  mss <- (count . words) <$> getLine
  lss <- (count . words) <$> getLine

  -- subtract occurrences in the words from the magazine
  let dm = subtractMap mms lss

  -- see if any words need more than it avaliablity
  let a = M.filter (<0) dm

  -- print answer
  putStrLn $ if M.null a then "Yes" else "No"

You could also put words into count, if you want to get the duplication even more down, or you could write

solve :: String -> String -> Bool
solve ms ws = M.null (M.filter (<0) (subtractMap (count ms) (count ws)))

main = do
   getLine
   a <- solve <$> getLine <*> getLine

   putStrLn $ if a then "Yes" else "No"

But at that point the code get's rather terse and unreadable, and that's up to personal preference.


Function names in F# are usually written in camelCase. (Though members that are not private should use PascalCase, to adhere to general .Net naming conventions.)
SubArrayBegin is not recursive, so it doesn't need to be rec.
List implements Seq, so you don't need that Seq.ofList.
Collection manipulation functions usually have that collection as the last parameter, so that you can use them with |>.
Your implementation of SubArrayEnd is pretty complicated and inefficient. Instead, you could write it for example like this:

let rec subArrayEnd n list =
    match (n, list) with
    | 0, _ | _, [] -> list
    | _ -> subArrayEnd (n-1) (List.tail list)

There is no reason why your innerInsertSort has to follow the normal imperative version of insert sort so closely and operate on a single list (and use List.nth). Instead, you could have two collections: one where you take from using pattern matching and one where you insert using List.partition and @.
Alternatively, you could use ImmutableList from Microsoft.Bcl.Immutable instead of List for the collection you're inserting into. With that, you can insert into the middle in O(log n) and you can also find the index to insert to in O(log n) using binary search. So it will make your code simpler and also much faster.


It looks really good! Here are a few points;

I don't like the arguments in your setLimit and init functions, especially because some of them are optional.

I would prefer an Object argument in this case.

function setLimit(limits) {
  finalLimit = limits.final;
  warnLimit = limits.warn;
  errorLimit = limits.error;
}

this.setLimit({
  final: 10,
  warn: 5,
  error: 8
});

This makes it obvious at call time which argument is which.

Your var declarations are inconsistent here:

var finalLimit = null,
  warnLimit = null,
  errorLimit = null;
var max = 59;
var interval = null;

Pick either to comma separate them or not. Not both.

In a couple of places you use == instead of ===. Generally we stick to === for reasons.

You CSS selectors are very generic. This is generally a bad thing as they will easily collide with other styles the moment you integrate it into a real page.

I favour BEM syntax, which would make it look something like this;

      00
    : 00
    : 00

  <button class="timer__btn js-start-timer">Start</button>
  <button class="timer__btn js-end-timer">Stop</button>
  <button class="timer__btn js-reset-timer">Reset</button>

Note I've also removed your onclick handlers in favour of interaction specific classes. I prefix my classnames with js- if they are used solely for JavaScript selectors. This helps decouple the CSS and JavaScript.

In your code you then attach the handlers;

document.querySelectorAll('.js-start-timer')[0]
  .addEventListener('click', startTimer);


For starters, they will take all your files based on a pattern and "compile" them down to a single file - no more adding lots of script references.  That's just the tip of iceberg.

I happen to prefer Gulp.  Take a look at the npm packages for gulp.  For what you're trying to achieve, start with gulp-concat and gulp-livereload.

Follow the instructions here to get you started.

Here's an example that uses a watch to keep an eye on file changes, and, when detected, initiates a 'build' tasks, which will the livereload your page (requires the livereload plugin in chrome/firefox/whatever).

You will then only need a reference to the ./public/js/app.js file in your index.html file.

Note the build task uses two different globs, this is to ensure, in the case of AngularJS, that the module definition file is always the first thing in the concatenated file.

var gulp = require('gulp');
var concat = require('gulp-concat');
var livereload = require('gulp-livereload');

gulp.task('build', function() {
 return gulp.src(['src/**/*.module.js', 'src/**/*.js'])
  .pipe(concat('app.js'))
  .pipe(gulp.dest('./public/js'))
  .pipe(livereload());
});

gulp.task('default', ['build'], function() {
 livereload.listen({
    start: true
  });

  gulp.watch('src/**/*.js', ['build']);
});

Like a said, this is just the tip of the iceberg.  There are tons of examples of very powerful workflows using Gulp and Grunt out there.


There are a few potential issues here, speed and accuracy in particular.
Speed
The cache is often faster than querying a value directly because of computation - you need to input, process, calculate, and output values.  For example, when you search the web, the servers return results based on cached data so they don't have to literally scan every website, read keywords, process data, etc.  Reading from the cache is as simple as getting the final value with no computation involved.
Accuracy
Querying a cache can return obsolete data.  Let's say you have a product priced at $X, and change the price for a sale.  If you don't update the cache, you will return outdated prices to your customers.  Querying the original data bypasses the intermediate value, always ensuring the value is correct.


Finding consecutive days in an array of dates

Never use 86,400 seconds as the duration of a day. "Most" days have 24 hours,
but in regions with daylight saving time, a day can have 23 or 25 hours (when the
clock is adjusted one hour forward or back).

Another problem is that you compare the difference in seconds between two days
in order to decide if they are on the same day. Then for example
"April 3, 10:00" and "April 4, 09:00" will be considered the same day.

There is also a bug in your final loop: The loop is exited if two dates are more
than one day apart, instead of continuing to search for a longer sequence of
consecutive days.

I would start by computing the difference in days to some reference date first:

dates.sort() // Short form for: dates.sort(by: < )
let referenceDate = calendar.startOfDay(for: dates.first!)

let dayDiffs = dates.map { (date) -> Int in
    calendar.dateComponents([.day], from: referenceDate, to: date).day!
}

Now we have an array of (non-decreasing) integers, in your example
that would be

print(dayDiffs)
// [0, 1, 1, 1, 2, 3, 3, 3, 4, 5]

It remains to find the longest
sequence of consecutive numbers (ignoring duplicates) in that array, i.e. no date/calendar calculations
are needed from this point on.

This should be done in a separate function, which could look like this:

/// Find maximal length of a subsequence of consecutive numbers in the array.
/// It is assumed that the array is sorted in non-decreasing order.
/// Consecutive equal elements are ignored.

func maximalConsecutiveNumbers(in array: [Int]) -> Int {
    var longest = 0 // length of longest subsequence of consecutive numbers
    var current = 1 // length of current subsequence of consecutive numbers

    for (prev, next) in zip(array, array.dropFirst()) {
        if next > prev + 1 {
            // Numbers are not consecutive, start a new subsequence.
            current = 1
        } else if next == prev + 1 {
            // Numbers are consecutive, increase current length
            current += 1
        }
        if current > longest {
            longest = current
        }
    }
    return longest
}

The approach is actually similar as in your last loop, only that

we only have to compare integers,
we continue to search for longer subsequences if one consecutive sequence ends,
consecutive equal numbers are simply ignored, so that it is no longer necessary
to remove duplicates in advance,
zip() + dropFirst() is used to iterate over all pairs of adjacent array elements, that saves a look of bookkeeping (dateIndex,
nextDateIndex).

You should add unit tests to verify that the function works correctly.
This is easier for an array of integers than for an array of dates.

With these preparations, the number of consecutive days is simply obtained as

let consecutiveDaysCount = maximalConsecutiveNumbers(in: dayDiffs)


This is one case where using the preprocessor may be worthwhile (despite the lack of namespace awareness).  In the code below, ss[] not only gets an appropriate size without any effort on your part, it's actually populated with the concatenated text at compile time.

#define S1 "string1"
#define S2 "string2"

// optionally, create real character arrays so you can modify them etc.
char s1[] = S1;
char s2[] = S2;

// now the magic - automatic concatenation of adjacent string literals
char ss[] = S1 S2;


Tracking the number of string elements using std::unordered_map

void insert(const std::string &name)
{
    auto it = data.find(name);
    if (it == data.end())
    {
        data[name] = 1;
        return;
    }
    data[name]++;
}

If it is available, you should prefer taking std::string_view parameters over std::string const&. You see, every time you do:

table.insert("Orange");
table.remove("Orange");

a string has to be constructed for "Orange". Especially when all you're doing is removing or getting the count, that's very wasteful. std::string_view is very lightweight, and automatically converts from both C-strings and std::string. Even in the case of insert(), because your inserts are conditional, it's worthwhile.

Now your insert() can be simplified quite a bit because when you do data[???] with an unordered_map, and ??? is not in the map, it automatically gets inserted with a default value. For int, the default value is 0.

So all you need is:

void insert(std::string_view name)
{
    ++data[name];
}

remove() works, but it's not very efficient. The problem is that after you find the element and have the iterator... you throw that information away! Then you use data[name] which has to do another search.

Instead, use what you've got. When you have the iterator, use it.

void remove(std::string_view name)
{
    auto const it = data.find(name);
    if (it != data.end())
    {
        if (--it->second == 0)
            data.erase(it);
    }
}

count() has bit of a bug, and it's one the compiler would have informed you about if you'd made the function const.

The bug is that, as with remove(), after finding the element and getting an iterator to it, you throw that information away and use operator[]... but in this case, operator[] is non-const, meaning it might modify the map. That's not something you want happening if you're just getting a count.

Once again, the solution is to simply not throw the iterator away, but to use it:

int count(std::string_view name) const noexcept
{
    auto const it = data.find(name);
    if (it == data.end())
        return 0;
    return it->second;
}


Converting the weight of a potato into a letter grade

You are very much correct that switch statements cannot take boolean operators like that: switch statements are used to build jump tables, and can only use constants to do so. However, you can easily come up with a fairly robust solution to your problem using a Dictionary and some LINQ.

Since you tagged your question beginner I'll be gentle with the explanation.

The first thing we'll do is make a Dictionary<int, string> which represents the lowest value associated with each grade.

var gradeMap = new Dictionary<int, string>
{
    [0] = "X",
    [201] = "A",
    [401] = "B",
    [801] = "Z",
};

So, this means if the value is >= 801, then it's Z, and so on.

Next, we'll simply one-line this entire operation in LINQ:

gradeMap.OrderByDescending(x => x.Key).FirstOrDefault(x => x.Key <= testWeight).Value

What's happening here? LINQ is Language Integrated Query, if you've ever worked with SQL you might recognize the Query bit, essentially, LINQ allows you to build code which looks and act's like a query against an IEnumerable object (which Dictionary is).

So if we take this step-by-step, we can start with our dictionary as follows:

0: X
201: A
401: B
801: Z

The gradeMap.OrderByDescending(x => x.Key) bit will first take the entire gradeMap dictionary, and order it by the key value in highest-to-lowest order:

801: Z
401: B
201: A
0: X

Next, we do a FirstOrDefault(x => x.Key <= testWeight), which will loop through all the elements (in the backwards order we have them) that are in the dictionary, and find the first one that matches our expression (x.Key <= testWeight). The x.Key is the reference to the key of the dictionary (our int values):

801: Z (Skipped)
401: B (Skipped)
201: A (Matched)

So, now we have the 201: A item from the dictionary, the last part is to get .Value on it which returns the string portion of it:

A

And viola, we have our value. :)

We can combine this together and get:

var testWeight = 205;
var grade = gradeMap.OrderByDescending(x => x.Key).FirstOrDefault(x => x.Key <= testWeight).Value;

So, the final thing we have to do is combine it with your original programme:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static int GetIntNumber(int min, int max, string prompt, string inputPrompt)
    {
        int number;

        Console.Write(prompt);
        do  //loops as long as input is not between min and max
        {
            while (!int.TryParse(Console.ReadLine(), out number)) //loops as long as the input is not an integer
            {
                Console.Write("\nYou must enter an integer number!: ");
            }
            if (number < min || number > max) Console.Write(inputPrompt); //<--| write input prompt if number out of range
        } while (number < min || number > max);

        return number;
    }

    static void printGrade(string grade)
    {
        Console.WriteLine("\nYour potato is grade " + grade);
    }

    static void Main()
    {
        do
        {
            var gradeMap = new Dictionary<int, string>
            {
                [0] = "X",
                [201] = "A",
                [401] = "B",
                [801] = "Z",
            };

            int weight = GetIntNumber(0, 1500, "\nEnter the weight of the potato in grams: ", "\nEnter an integer between 0 and 1500: ");

            printGrade(gradeMap.OrderByDescending(x => x.Key).FirstOrDefault(x => x.Key <= weight).Value);

            Console.WriteLine("\nPress any key to check the grade of another potato.");
        } while (Console.ReadKey(true).Key != ConsoleKey.Escape );

        Console.Read();
    }
}

The next best thing would be to extract the LINQ logic into a new method:

public string GetGrade(int weight)
{
    var gradeMap = new Dictionary<int, string>
    {
        [0] = "X",
        [201] = "A",
        [401] = "B",
        [801] = "Z",
    };

    return gradeMap.OrderByDescending(x => x.Key).FirstOrDefault(x => x.Key <= weight).Value;
}

Then our Main method becomes:

static void Main()
{
    do
    {
        int weight = GetIntNumber(0, 1500, "\nEnter the weight of the potato in grams: ", "\nEnter an integer between 0 and 1500: ");

        printGrade(GetGrade(weight));

        Console.WriteLine("\nPress any key to check the grade of another potato.");
    } while (Console.ReadKey(true).Key != ConsoleKey.Escape );

    Console.Read();
}

Now if you need to add a new grade, for whatever reason, it's trivial.

Also: if you're not using C#6.0, you will have to replace var gradeMap with the following:

var gradeMap = new Dictionary<int, string>
{
    {0, "X"},
    {201, "A"},
    {401, "B"},
    {801, "Z"}
};

Good work so far, hopefully you continue improving and learn more regarding C# and the paradigms it holds. :)

The answer by t3chb0t is also very good, I recommend reading it thoroughly as well (especially the bit about method overloading).


Show/hide checkbox div on change and load

It could be done with:

$(document).ready(function() {
    $("input").change(function() {
        var index = $(this).closest("li").index();
        $(".metabox").eq(index)[this.checked ? "show" : "hide"]();
    }).change();
});

http://jsfiddle.net/bK8EC/118/

Remember to add proper qualifiers in your real code, for example add id="something" to your ul and then do $("#something input:checkbox") instead of just binding this event to every input on the page. The .metabox is also pretty fragile if a container isn't added.


Mark a radio element as selected on page load and when clicked

As @elclanrs says, function () { StyleSelectedPlan(); } is redundant — you can just write StyleSelectedPath.

Since you're using jQuery, you should use $(document).ready(handler), or better yet, $(handler), to call the handler function when the page loads.

$(StyleSelectedPlan).on('click', '.select-plan', StyleSelectedPlan);

function StyleSelectedPlan() {
    $('.radio-wrapper').removeClass('selected');
    $('.select-plan:checked').closest('.radio-wrapper').addClass('selected');
}
.radio-wrapper.selected { color: green; }

<input name="name" type="radio" class="select-plan" id="one">one

<input name="name" type="radio" class="select-plan" id="two">two

<input name="name" type="radio" class="select-plan" id="three" checked>three (preselected)


I love your program’s entry point. Nearly all of my F# CLIs have an entrypoint that look nearly identical. However, Rust will automatically convert a Result into an exit code for you.

You can get rid of your run_app and wrapper by inclining it and modifying main’s signature.

fn main() -> Result<(), Box<dyn Error>> {
   // contents of `run_app` method
}

I believe this will even automatically print out the error.


SquareRoot(int)

returns half if the integer is not a perfect square. A very dubious decision. I'd consider returning a best integer approximation, or throwing an exception.
uses a linear search. A binary search would be quite faster. A Newton-Raphson (yes it works with integers) would be even factor.

An error approximation is better done as Math.abs(number - Math.pow(candidate_square_root, 2))


var count = 0;
var lastPercentage = 0d;

var nextBatch = new Func<bool>(() => ++count % batchSize == 0);

It was a clever usage of context capture but I think it ended up playing against you.

Your method has way too much responsibility. You should had at least another method to resolve the batching problem. Because you mixed the two things(batch + db stuff) you ended up by having this:

var enumerator = items.GetEnumerator();
while (enumerator.MoveNext())
{
    //...
    do{
       //...
    } while (!nextBatch() && enumerator.MoveNext());
}

And the first thing that I thought about was: "Why the hell is he advancing the enumerator twice? Why couldn't he use foreach instead?" And than I realized, without even parsing the code too much: "Ah it must be because of the batching stuff...".

It doesn't really matter if I got that right or not, I had to spend time to think about it, asking this kind questions is very useful actually. I would strongly suggest you next time you see yourself using enumerator.MoveNextto ask the same thing. Why aren't you using foreach?

Anyway, as I said you should separate those two concerns. A batch implementation would become like this:

public IEnumerable<IEnumerable<int>> Batch(int total, int batchSize){
    for(int i = 0; i < total; i += batchSize){
        var currentBatchSize = Math.Min(batchSize, total - i);
        yield return Enumerable.Range(i * batchSize, currentBatchSize);
    }
}

A similar thing could be said about reportProgress. You ended up by creating abstraction over a simple calculation that is to calculate the report progress(with a simple mathematical formula). It didn't really contribute in any positive way to the readability/maintainability of your code.

Putting that all into a new implementation would look like this:

public static IEnumerable<IEnumerable<int>> GetBatches(int total, int batchSize){
    for(int i = 0; i < total; i += batchSize){
        var currentBatchSize = Math.Min(batchSize, total - i);
        yield return Enumerable.Range(i, currentBatchSize);
    }
}

public static void BatchSave<T, TContext>(
    this IList<T> items,
    int batchSize,
    Func<TContext> createContext,
    IProgress<double> progress
)
    where T : class
    where TContext : DbContext
{
    var batches = GetBatches(items.Count, batchSize).ToList();
    int currentBatch = 0;
    foreach(var batch in batches){
        using (var context = createContext())
        {
            context.Configuration.AutoDetectChangesEnabled = false;
            context.Configuration.ValidateOnSaveEnabled = false;

            foreach(var i in batch){
                Console.WriteLine("Add " + items[i]);
            }
            //context.SaveChanges();
            progress.Report(++currentBatch * 100.0 / batches.Count);
            Console.WriteLine("Save batch = " + currentBatch);
        }
    }

    progress.Report(100);
}

This alternative might yet lack something. For example, if you are really a neat freak, maybe you would try to change the return result of GetBatches in someway to be more useful. One thing that could be useful is to know which batch is the current batch. Should the return be IEnumerable<IEnumerable<Tuple<int, int>>>(where tuple can be another classes with two integers if you want...). Would it be more useful to turn it to GetBatches<T>? with IEnumerable<IEnumerable<T>> return? Well I will leave that for you to decide, at least I am providing the foundations for it.

One another thing that might be worth pointing is that there isn't really a reason to createContext() multiple times, you can create it just one time, and just call SaveChanges per each batch. Or maybe there is an efficiency reason, that I am not aware of... but you have to prove it by measuring.


Review

You don't need to calculate the difference from two temporary values GetUTCDate and GETDATE.

SELECT @DifferenceInHoursBetween = DATEDIFF(HH,GetUTCDate(), GETDATE())

Proposed Solution

Instead, you could apply the local time zone offset to the specified datetime.

SELECT
    USER_ID,
    CreateDate AS [DateTime IN UTC],
    CONVERT(datetime,
        SWITCHOFFSET(CONVERT(datetimeoffset, CreateDate),
            DATENAME(TzOffset, SYSDATETIMEOFFSET()))) AS [LocalDateTime]
FROM EVENTLOG(nolock);

Fiddle: SQL Server 2017

Daylight Savings Time

Both methods, OP and solution don't take into account DST. And unfortunately, SQL Server does not come with a built-in conversion from DST. You'd have to make a function yourself. More about DST in SQL Server


Porting ProcMonDebugOutput from C# to VBA

That's some pretty intense Win32 API stuff you got here, it's nice to see pointers and API calls in a VBA question, it's quite a change from the typical "speed up my Excel macro" question -- kudos!

One thing worries me though:

Dim Buffer As String
'Create a string buffer
Buffer = Space(200)
FormatMessage FORMAT_MESSAGE_FROM_SYSTEM, ByVal 0&, Err.LastDllError, LANG_NEUTRAL, Buffer, 200, ByVal 0&
Err.Raise Buffer

The first argument of Err.Raise should be an error number. If FormatMessage fills up buffer with a string that starts with an error number, then that's the error you're raising, and the rest of the message goes to oblivion. If the string does not start with a number, by VBA's implicit coversion rules you're raising error 0, which is a non-error... and that can't be right.

This instruction is redundant at first sight:

ProcMonDebugOutput = False

...but then, the function doesn't return a Boolean, but a LongPtr - why the Boolean assignment then? False would be implicitly converted to 0, which is the same value that would be returned if you didn't make that confusing assignment. I'd just remove it.

Same kind of issue here:

Dim outLen As Long
outLen = 0

outLen is already initialized with a value of 0, the assignment is redundant... and unless I missed something, the variable is assigned, but isn't used at all. I'd remove these two lines too.

I'll admit I didn't know you could specify ByVal at the call site to force a parameter to be passed by value (I wonder if it breaks the rubberduck parser... but that's my problem ;-) - I like it more than the parentheses-wrapping of the parameter to force ByVal for: it's more readable and less confusing - well done!

I can't seem to get a call-site ByVal to compile... will confirm in a few days when I'm on my laptop. Phone doesn't run VBA ;-)


Implementing `components(separatedBy:)` method in Swift

Coding style

This is of course a matter of personal taste, but would split multiple statements like

var currentIndex = 0; var stringBuffer = ""; var separatedStrings:[String] = []

into separate lines

var currentIndex = 0
var stringBuffer = ""
var separatedStrings:[String] = []

I would also start new lines for nested code blocks, i.e.

if currentIndex == lastIndex { separatedStrings.append(stringBuffer) }

becomes

if currentIndex == lastIndex {
    separatedStrings.append(stringBuffer)
}

Correctness

Your function takes a separator of type string (protocol) as an argument, but actually works only for separators consisting of a single character. Example:

let sampleString = "Do not be sorry. Be better."
print(sampleString.components(separatedBy: ". "))
// ["Do not be sorry. Be better."]

The reason is that here

if String(character) == separatorString

a single character of the source string is compared with the separator.

Your method also behaves differently from the standard library version when called with an empty string,

"".components(separatedBy: ".")

returns an empty array [] instead of a single-element array [""]. The reason is that the check

if currentIndex == lastIndex { separatedStrings.append(stringBuffer) }

is never done for an empty input string. (Checking for the last iteration inside a loop always makes me suspicious.)

Simplifications

Instead of converting a character to a string for appending

stringBuffer += .init(character)

you can append it directly:

stringBuffer.append(character)

Keeping track of the current character position can be done with
enumerated()

for (currentIndex, character) in self.enumerated() {
    // ...
}

instead of incrementing var currentIndex.

Efficiency

The main bottleneck is the

var lastIndex:Int

extension method. For Strings (and other collections which are not random accessible) determining self.count is a O(N) operation (N = number of characters). It requires traversing the entire string.

This method is called for each character in the source string, so that this contributes O(N^2) to the execution time.

It would also be more efficient to locate the next occurrence of the separator and append an entire substring to the result array, instead of appending single characters repeatedly.

Alternative implementation

Here is an alternative implementation, considering the above suggestions:

func components<T>(separatedBy separatorString: T) -> [String]
    where T: StringProtocol, Index == String.Index {
        var separatedStrings: [String] = []
        var pos = startIndex
        while let range = self[pos...].range(of: separatorString) {
            separatedStrings.append(String(self[pos..<range.lowerBound]))
            pos = range.upperBound
        }
        separatedStrings.append(String(self[pos...]))
        return separatedStrings
}


Pagination should be done by the database server where applicable.  There is really no point pushing data down the wire if it is not being used, so what you should think about doing, is passing in your page number and count variables to the query or preferable a stored procedure, and use SQL to select the subset of data you want. There are SQL constructs in most SQL language variants to do this.

Here is an example using MySql:

SELECT `field1`, `field2` from `mycatalog` LIMIT start, (start + cnt)

And something similar with Sql Server:

WITH #set AS (SELECT [Field1], [Field2], ROW_NUMER() OVER (ORDER BY [Field1]) AS [Index] FROM [MyDatabase])
SELECT [Field1], [Field2] FROM #set WHERE [INDEX] BETWEEN @start AND (@start + @count)


Small app to show variables declared in a bash script

The difference between $* and $@

warn() { printf '%s\n' "$*" >&2; }

This is equivalent to the simpler:

warn() { echo "$*" >&2; }

The printf version is useful if you want to produce one line per parameter,
and in that case you must use "$@" instead of "$*".
Also in callers of warn.

Use -r for raw output of jq

Instead of jq "..." | tr -d '"' a better way is jq -r "...".

An alternative to printf and a sub-shell

Instead of this:

  # shellcheck disable=SC2046
  printf '  %s\n' $(shfmt -tojson < "$filename" | jq "$jq_query" | tr -d '"')

I recommend this way (and no need to disable shellcheck):

shfmt -tojson < "$filename" | jq -r "$jq_query" | sed -e 's/^/  /'

Use a bit more double-quotes

You did a good job of double-quoting the most important things.
I would double-quote here too:

command_exists $r || die This script depends on $r and it is not found.

To train good habits:

command_exists "$r" || die "This script depends on $r and it is not found."

"$@" is the default list for for

Instead of for f in "$@"; do, you can simply write for f; do.

The shebang

In some systems Bash is not in /bin/bash.
For that reason I prefer to use #!/usr/bin/env bash as the shebang, it makes the script more portable.

Simplify the readable file check?

  [[ -f $filename ]] || die "$filename is not a file or does not exist."
  [[ -r $filename ]] || die "$filename is not readable."

The -r implies -f. I would simplify this to one line:

[[ -r $filename ]] || die "$filename is not a readable file."

Use echo when it's good enough

Instead of printf '\n%s:\n' "$f" I would write:

echo
echo "$f:"

Here-documents

EOH is an unusual symbol for the here-document marker.
That's not a problem, but I think the less surprising elements in a script,
the better.
I don't see a good reason to not call this EOF as usual.

Your questions

  Some possible areas for improvement:

  Can the jq query be improved?
  Are there other entries in the json output of shfmt that I can look for variable assignments.

Unfortunately I'm not able to answer these.
You might want to wait for another reviewer who can!


Data model for tracking currency in a safe

One concern I have is tracking non-US currency. Not a requirement currently, but maybe in the future.

You're right to be concerned about the flexibility of your approach: what would Twos return in a currency that doesn't have toonies?
Taking future considerations into account, I think you need to re-think your model.

CurrencySet

By modeling the CurrencySet entity the way you have, you've pretty much hard-coded the currency paper's nominal values:

class CurrencySet
{
    public int CurrencySetId { get; set; }

    public int Ones { get; set; }
    public int Twos { get; set; }
    public int Fives { get; set; }
    public int Tens { get; set; }
    public int Twenties { get; set; }
    public int Fifties { get; set; }
    public int Hundreds { get; set; }
}

I'd suggest something like this:
public class Currency
{
    public int Id { get; set; }
    public string Code { get; set; }
    public string CultureName { get; set; } // for number formats

    public virtual ICollection<CurrencyExchangeRate> CurrencyExchangeRates { get; set; }
    public virtual ICollection<CurrencyPaper> CurrencyPapers { get; set; }
}

public class CurrencyExchangeRate
{
    public int Id { get; set; }
    public int CurrencyId { get; set; }
    public int ReferenceCurrencyId { get; set; }

    public decimal Rate { get; set; }

    public virtual Currency Currency { get; set; }
    public virtual Currency ReferenceCurrency { get; set; }
}

public class CurrencyPaper
{
    public int Id { get; set; }
    public int CurrencyId { get; set; }

    public decimal NominalValue { get; set; }
    public string SerialNumber { get; set; }
    public string Issuer { get; set; }
    public int YearIssued { get; set; }

    public virtual Currency Currency { get; set; }
}

Now you can detect currency paper with consecutive serial numbers if you want, and your Safe can contain papers in many currencies, and calculate the total value in $USD, CDN$, €EUR or ¥YEN, given the exchange rate for $USD as a reference currency.
Granted, me putting SerialNumber, Issuer and YearIssued in there is pushing it, but it makes a point: this model is much closer to the actual real-world objects - an approach with its own pros and cons.

Safe

Doing this turns your Safe into an actual safe that literally contains money - it also means the calculating the Totals is a method that has nothing to do in the data itself:
public class Safe
{
    int Id { get; set }

    //...

    public virtual ICollection<CurrencyPaper> CurrencyPapers { get; set; }
    public virtual ICollection<TransactionLog> TransactionLogs { get; set; }
}

SafeTransaction

It's really a log entry more than the transaction itself: I think I'd call it TransactionLog though.
Now what your code is doing, is logging the number of individual CurrencyPaper instances that were involved in a transaction. To do this with the approach I'm suggesting, you might want to break the transaction logs in two tables for full details: one with "header", another with "details" (enabling tracking of individual CurrencyPaper instances) - but that's certainly overkill. You could also just track the total amount deposited/withdrawn, given a Currency.

Navigation properties should be virtual
Be consistent about FK properties - your SafeTransaction doesn't have them.
Naming is ok - although I prefer the entity key to be called Id.


Don't use NULL unless you have to

Some IDEs will refuse to compile your code unless you include <cstdlib> so that NULL is available. If you compile using a C++ compiler using latest standards, you could use nullptr instead, since it is a language construct in those versions and does not require including anything.

Minor improvements

//bool Stack::isEmpty()
//{
//    if(top == NULL)
//        return true;
//    else
//        return false;
//}

bool Stack::isEmpty()
{
    return top == nullptr;
}

and

//Node * Stack::pop()
//{
//
//    if (isEmpty())
//        return NULL;
//    else
//    {
//        Node * copy = new Node(*top);
//        ll.deleteFirst();
//        top = ll.getHead();
//        return copy;
//    }
//}

Node * Stack::pop()
{
    if (isEmpty())
    {
        return nullptr;
    }

    Node * copy = new Node(*top);
    ll.deleteFirst();
    top = ll.getHead();
    return copy;
}

Alternative implementation

It's not difficult to devise a generic stack:

my_stack.h

#ifndef MY_STACK_H
#define MY_STACK_H

#include <iostream>
#include <stdexcept>
#include <vector>

template<typename T>
class MyStack {

    std::vector<T> storage;
    void check_not_empty()
    {
        if (storage.empty())
        {
            throw std::runtime_error{"Peeking from an empty stack."};
        }
    }

public:
    void push(const T& element)
    {
        storage.push_back(element);
    }

    void pop()
    {
        check_not_empty();
        storage.pop_back();
    }

    const T& peek() const
    {
        check_not_empty();
        return storage[storage.size() - 1];
    }

    size_t size()
    {
        return storage.size();
    }

    bool is_empty()
    {
        return storage.empty();
    }

    friend std::ostream& operator<<(std::ostream& os, const MyStack<T>& stack)
    {
        os << "[";
        std::string separator = "";

        for (size_t i = 0; i != stack.storage.size(); ++i)
        {
            os << separator << stack.storage[i];
            separator = ", ";
        }

        return os << "]";
    }
};

#endif

main.cpp

#include "my_stack.h"
#include <iostream>

using namespace std;

int main()
{
    MyStack<int> stack;

    cout << stack << endl;

    for (int i = 1; i <= 5; ++i)
    {
        stack.push(i);
        cout << stack << endl;
    }

    while (!stack.is_empty())
    {
        stack.pop();
        cout << stack << endl;
    }
}


Determine whether one vector is a prefix of the other

For a prefix search, you can use std::mismatch() in <algorithm>.

bool isPrefix(const std::vector<int>& v1, const std::vector<int>& v2) {
    if (v1.size() > v2.size()) {
        return v2.end() == std::mismatch(v2.begin(), v2.end(), v1.begin()).first;
    }
    return v1.end() == std::mismatch(v1.begin(), v1.end(), v2.begin()).first;
}


Simple Ruby directory navigator functions

Your two code samples are not exactly equivalent.  The second one has nicer formatting (fixed-width numbering) and attempts to parameterize the glob pattern (but fails in that regard — full_directory_navigator should accept a pattern parameter and pass it to both Dir.glob and list_directory_entries).

I'm not convinced that splitting up the select_file function into six functions makes it any better.  It's not any more readable or extensible than the original.  The parameter passing just gets in the way.  (If you had defined a class, there might be some advantage, in that a subclass could customize the behaviour by overriding one of the methods.)

With more effective string formatting, the code is simple enough to fit in one function.

To repeat a character, use string multiplication.
The ternary conditional could just be an if-qualified expression, since one of the outcomes is nil.
To make a fixed-width column of numbers, use '%-8d' % number.

def select_file(glob='*', glob_flags=File::FNM_DOTMATCH)
  entries = Dir.glob(glob, glob_flags)

  # Header
  puts '-' * 79,
       "Listing entries in #{File.basename(Dir.pwd)}#{
                               " matching \"#{glob}\"" if glob != '*'
                           }",
       '',
       '%-8s   %s' % ['Index', 'Entry'],
       '-' * 79

  # Listing
  entries.each_with_index { |entry, i| puts '%-8d - %s' % [i + 1, entry] }

  # Prompt
  print 'Select File/Folder: '
  entries[gets.to_i - 1]
end

selection = select_file()
puts "Selected: #{selection}"

Note that you haven't done any validation on the input.  If the input doesn't look like a number, then gets.to_i - 1 becomes 0 - 1, which refers to the last item in the array.


Proper way of deallocating memory in SLL?

Answers to your questions

Am I causing any memory leaks, and is there a better, safer way to do things?

Yes, see for example your second question. A safer way is to use something like std::unique_ptr to manage pointers for you.

In remove_front(), should I set head to nullptr, or should I delete it instead?

You should delete it of course. If you just set head to nullptr, the memory for the head node is still allocated.
Avoid using names that start with an underscore
Names that start with underscores are reserved for the standard library. There are some more specific rules, but in general it is best to avoid them completely. You can safely append an underscore to the end of a name though.
On the other hand, while you have _length, head is written without an underscore. If you are not consistent in marking private variables with an underscore, there is not much point to it at all.
Flawed logic in remove(int index)
There is an issue with the for-loop in remove(int index): you are moving the head pointer instead of node_ptr. In fact you are not using node_ptr at all after initializing it. The compiler should have given you a warning about this (be sure to enable compiler warnings and fix them).
To make this work correctly, even when removing the head node, you should use an extra layer of redirection: you want a pointer to the pointer you need to update, like so:
Node **node_ptr = &head;           // node_ptr is pointing to the variable `head`
for (int a = 0; a < index - 1; ++a)
    node_ptr = &(*node_ptr)->next; // node_ptr is updated to point to some node's `next` variable

Node* temp = *node_ptr;            // get the actual Node pointer to
*node_ptr = (*node_ptr)->next;     // update `head` or a `next` to skip one Node
delete temp;                       // delete the target Node

Once you grasp this you've become a two-star programmer!
Unnecessary code duplication
You have three different functions for removing an element, but they all do mostly the same. In fact, the first one, remove(int index), does everything you need. You don't need to treat index == 0 as a special case, the code will work correctly anyway. You can make remove_front() and remove_back() call the generic remove() function:
void remove(int index)
{
    if (index < 0 || index >= _length)
        throw "index is out of range";

    Node **node_ptr = &head;
    for (int a = 0; a < index - 1; ++a)
        node_ptr = &(*node_ptr)->next;

    Node* temp = *node_ptr;
    *node_ptr = (*node_ptr)->next;
    delete temp;

    _length -= 1;
}

void remove_front()
{
    remove(0);
}

void remove_back()
{
    remove(_length - 1);
}


Computing six dot products involving one common input vector

There is a common mathematical operation involving many dot products: it's called matrix multiplication.

$$ \left[\begin{matrix}v_1 & v_2 & v_3 & v_4\end{matrix}\right]
\left[\begin{matrix}
a_1 & b_1 & c_1 \\
a_2 & b_2 & c_2 \\
a_3 & b_3 & c_3 \\
a_4 & b_4 & c_4
\end{matrix}\right] =
\left[\begin{matrix}(\vec{v}\cdot\vec{a}) & (\vec{v}\cdot\vec{b}) & (\vec{v}\cdot\vec{c})\end{matrix}\right]
$$

So, I recommend that you concatenate vectors \$\color{lightgreen}1\$ to \$\color{lightgreen}6\$ into a matrix and perform matrix multiplication.

You can also transpose and swap the matrices:

$$
\left[\begin{matrix}
a_1 & a_2 & a_3 & a_4 \\
b_1 & b_2 & b_3 & b_4 \\
c_1 & c_2 & c_3 & c_4 \\
\end{matrix}\right]
\left[\begin{matrix}v_1 \\ v_2 \\ v_3 \\ v_4\end{matrix}\right]
 =
\left[\begin{matrix}\vec{a}\cdot\vec{v} \\ \vec{b}\cdot\vec{v} \\ \vec{c}\cdot\vec{v}\end{matrix}\right]
$$


Beginner's LINQ exercise to print the odd numbers in descending order

People will commonly create an Extension method for IEnumerable to add a map method that behaves much like the IList<T>.ForEach method.

public static class IEnumerableExtensions {
    public static void ForEach<T>(this IEnumerable<T> source, Action<T> action) {
        foreach(item in source) action(item);
    }
}

With this in hand, you can go all out on your filter & map.

class Program
{
    public static void Main(string[] args)
    {
        int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

        numbers.Where(IsOdd)
                .OrderByDescending(x => x)
                .ForEach(Console.WriteLine);
     }

     private static bool IsOdd(int x) => x % 2 == 1;
}

Note that I did extract a method so we could name the filter. It makes it a bit more readable (and as an added bonus, reusable).

You may be asking yourself why naming the predicate is better than using a variable. Other than reuse, the benefit is that there's no need to store any state. At its heart, Linq is a functional way to program, so it's good to embrace it.


List.append is an expensive O(d) operation, making your addTwoNumbers O(d2).  To reverse the list, you would be better off calling List.rev once at the end.  (By the way, List.append c [r] would be better written as c @ [r].)

The loop helper function could use a better name.  My suggestions are either add or addTwoNumbers'.  I don't like the name c either, as it is somewhat mnemonically similar to carry.

Put the base cases first, followed by the recursive cases.

One of the cases can be simplified by taking advantage of commutativity.

When adding two numbers, carry should never be greater than 1.

let addTwoNumbers (a: int list) (b: int list) =
    let rec add (a: int list) (b: int list) (sum: int list) (carry: int) =
        match a, b, carry with
        | [], [], 0 ->
            sum
        | [], [], 1 ->
            1 :: sum
        | [], _, _ ->
            add b a sum carry
        | (h1::t1), [], _ ->
            let c, s = Math.DivRem(h1 + carry, 10)
            add t1 [] (s :: sum) c
        | (h1::t1), (h2::t2), _ ->
            let c, s = Math.DivRem(h1 + h2 + carry, 10)
            add t1 t2 (s :: sum) c
    add a b [] 0 |> List.rev


Safe, fully standards-following integer abs in C

This kind of code relies on careful reading of the standard, so if it were me I would add cross-references to the sections of the standard that I was relying on, for example I might write:

/* This relies on the following facts from the C99 standard:
 *
 * §6.2.5.9 The range of nonnegative values of a signed integer
 * type is a subrange of the corresponding unsigned integer type.
 * It follows from this and §7.18.2.5 that UINTMAX_MAX >=
 * INTMAX_MAX.
 *
 * §6.2.6.2.2 Signed integers are represented as sign-and-
 * magnitude, two's complement, or one's complement. It follows
 * that INTMAX_MIN is either -INTMAX_MAX (in sign-and-magnitude or
 * one's complement) or -INTMAX_MAX-1 (in two's complement).
 */

I don't like writing code that can't be tested on any platform that I have access to. Although the code looks good in this case, if you pursued this approach on a bigger scale, then it would be very surprising if all the untested code were correct. I would prefer to write something like:

#if UINTMAX_MAX == INTMAX_MAX && INTMAX_MIN < -INTMAX_MAX
#error "Two's complement with UINTMAX_MAX == INTMAX_MAX is not supported."
#endif

so that untested platforms get a compiler error instead of compiling and executing untested code. In the unlikely event that you discover such a platform, you can add the code and test it at that point.


Terminology

In your hull function, you use the name origin to indicate the chosen point with the minimum y coordinate.  That's confusing, as the term usually means the point (0, 0) in the Cartesian plane.  For the rest of this review, I'm going to refer to the chosen point as the pivot instead.

Wrong result

The test result that you quoted in your own question shows that the algorithm is incorrect!

Furthermore, when I ran your code with the suggested test case, I got a totally different result than what you claimed, which makes it hard for me to explain exactly what went wrong.  (The code produces results in clockwise order, contrary to your claimed answer which lists them in counterclockwise order.  I seriously doubt that you posted the question correctly.)  I can, however, point to four issues:

(drop 1 list) was responsible for removing (-4, 1) from consideration.
A correct traversal involves backtracking whenever a right turn occurs.  Therefore, you must filter the candidate points while you traverse the list.  You cannot simply traverse the list and keep just the vertices where a left turn occurred, since a left turn that occurs at an interior point doesn't mean that it is a vertex of the convex hull.
Reporting points that lie collinearly on the convex hull (but not at a vertex) is a difficult task with this algorithm, since it is hard to determine in advance the order in which to consider such points such that they will be guaranteed to be part of a left-turn-only tour.
Degenerate cases are poorly handled.  hull of a single point lists that point twice.  hull of a triangle can also list the pivot twice.

Implementation

Stuff like this is hard to follow:

angle :: Point -> Point -> Point -> Float
angle a b c = - (bax * bcx + bay * bcy) /
              (sqrt ((bax * bax + bay * bay) * (bcx * bcx + bcy * bcy)))
    -- more efficient than acos for the algorithm and is the same for sorting
    where
      bax = x a - x b
      bay = y a - y b -- coordinates of b->a
      bcx = x c - x b
      bcy = y c - y b -- coordinates of b->c

A remedy is to use a vector package to allow you to think at a more abstract level.

angle a b c :: Vector2 -> Vector2 -> Vector2 -> Double
angle a b c = (ab `vdot` bc) / ((vmag ab) * (vmag bc))
  where
    ab = b - a
    bc = c - b

In the implementation below, I've rewritten the function further, restricting it to only compare a single vector against \$\mathbf{\hat{x}}\$, and renaming it to cosAngleX to be more honest.

You don't really need to define the argmin function.  argmin y pts could just be written as minimumBy (comparing y) pts, using support from Data.List.

Suggested solution

import Data.List (minimumBy, sortBy)
import Data.Ord (comparing)

-- https://hackage.haskell.org/package/AC-Vector
import Data.Vector.Class (vdot, vmag)
import Data.Vector.V2 (Vector2(..), v2x, v2y)
import Data.Vector.V3 (Vector3(..), v3z, vcross)

data Direction = TurnLeft
               | TurnRight
               | StraightLine
                 deriving (Show, Eq)

-- Direction of the turn when travelling from a to b to c
turn :: Vector2 -> Vector2 -> Vector2 -> Direction
turn a b c
  | z > 0     = TurnLeft
  | z < 0     = TurnRight
  | otherwise = StraightLine
  where
    ba = a - b
    bc = c - b
    promote23 (Vector2 x y) = Vector3 x y 0
    z = v3z ((promote23 bc) `vcross` (promote23 ba))

-- Cosine of the angle that a vector forms with the X axis.
-- We can sort by this instead of sorting by the angle as long as all vectors
-- have a nonnegative y coordinate (which is the case, since we picked a point
-- with the minimum y coordinate as the pivot).
-- For (Vector2 0 0), the result is Infinity
cosAngleX :: Vector2 -> Double
cosAngleX v
  | norm == 0  = 1/0
  | otherwise  = (v `vdot` xHat) / norm
  where
    xHat = Vector2 1 0
    norm = vmag v

giftWrap :: [Vector2] -> [Vector2]
giftWrap vs = result
  where
    -- Decides whether to keep or reject vertex b.
    -- Vertex b is provisionally kept if a left turn occurs there; the result
    -- is finalized only when a closed left-turn-only tour is completed.
    giftWrap' (a:b:c:vs)
      | vs == [] && dir == TurnLeft  = (True, [b, c])
      | vs == []                     = (False, [c])
      | dir == TurnLeft && final     = (True, (b:gw))
      | dir == TurnLeft              = giftWrap' (a:gw)
      | otherwise                    = (False, (a : c : vs))
      where
        dir = turn a b c
        (final, gw) = giftWrap' (b:c:vs)
    (_, result) = giftWrap' (vs ++ [head vs])

-- Chooses the point with the smallest y coordinate (breaking ties by smallest
-- x coordinate), then presents the points by the angle between the x axis,
-- the pivot, and each point.  The pivot will be the last element of the
-- resulting list.
chain :: [Vector2] -> [Vector2]
chain pts = sortBy (comparing byAngleX) pts
  where
    comparing2 primaryKey secondaryKey a b
      | firstCmp == EQ  = comparing secondaryKey a b
      | otherwise       = firstCmp
      where firstCmp = comparing primaryKey a b
    pivot      = minimumBy (comparing2 v2y v2x) pts
    byAngleX v = -cosAngleX (v - pivot)

-- Convex hull in some counter-clockwise order
hull :: [Vector2] -> [Vector2]
hull (a:[])    = [a]
hull (a:b:[])  = [a, b]
hull vs        = giftWrap $ chain vs

The test case:

*Main> hull [(Vector2 (-3)   1),  (Vector2 (-4) 1),   (Vector2 (-1)  4),
             (Vector2   0    0),  (Vector2   2  2),   (Vector2 (-1)  3),
             (Vector2 (-1)   2),  (Vector2   1  0),   (Vector2   3 (-1)),
             (Vector2 (-1) (-1))]
[Vector2 {v2x = 3.0, v2y = -1.0}, Vector2 {v2x = 2.0, v2y = 2.0},
 Vector2 {v2x = -1.0, v2y = 4.0}, Vector2 {v2x = -4.0, v2y = 1.0},
 Vector2 {v2x = -1.0, v2y = -1.0}]


The main performance problem of your code is that you check for duplicate digits only in the innermost loop, although a collision between e.g. a and b can be detected already in the second loop.

This way you generate 387420489 digit combinations and throw away 99.9% of them (it's only 362880 permutations of 9 digits). Moving the duplicates checks to the outermost place possible can potentially speed up your program by a factor of 1000.

And there might be better algorithms, but on Code Review we concentrate on improving your original code instead of inventing something new.


I found this answer helpful; I also like using the shoulda matchers to clean things up.

Yes, I think you should test your assignments. If you use the shoulda matchers, this becomes much less painful, for example:

describe "POST 'update'" do

  context "when invalid" do
    before(:each) do
      project.stubs(:update_attributes).returns(false)
      post 'update', id: project.id
    end

    it { should render_template('edit') }
    it { should assign_to(:project).with(project) }
  end
end

I usually stub where it's relevant rather than at a global level, but I don't have a good argument as to why besides that it's easier for me to understand when I'm reading it.

It's fine to test in isolation as long as you're testing your full stack somewhere like with cucumber or integration tests.


I will try to point out things that can be improved in your code:

1. Removing complexity by using return:

    if (data > 100) {
        System.out.println("Only Enter Numbers Between 0-100");
        Start();
        return;
    }

    if (data == random) {
        System.out.println("Wow, you guessed it!!");
        scanInput.close();
        return;
    }

    if (data < random) {
        go ++;
        if (go == attempt) {
            System.out.println("You have guessed the wrong number " + go + " times, sorry but you'll have to try again! :(");
            scanInput.close();
            System.exit(0);
            return;
        }
        System.out.println("Higher");
        Start();
        return;
    }

    if (data > random) {
       // ...
    }

2. Try to avoid recursion, if it is not needed - your code can be easily converted not to use recursion:

public static void Start() throws IOException {

while (true) {

    if (go == attempt) {
        System.out.println("You have guessed the wrong number " + go + " times, sorry but you'll have to try again! :(");
        scanInput.close();
        System.exit(0);
        return;
    }

    Scanner scanInput = new Scanner(System.in);
    data = scanInput.nextInt();

    if (data > 100) {
        System.out.println("Only Enter Numbers Between 0-100");
        continue;
    }

    if (data == random) {
        System.out.println("Wow, you guessed it!!");
        scanInput.close();
        break;
    }

    if (data < random) {
        go ++;
        if (go == attempt) {
            System.out.println("You have guessed the wrong number " + go + " times, sorry but you'll have to try again! :(");
        continue;
    }
}

3. return value instead of System.exit(0);

In order to make your function more reusable, you can have it return a boolean specifying if the number was guessed or not. The caller can decide what to do with the information (maybe this should be integrated in some guessing Web service and those exits are not ok).

Also, it would make sense to allow the user to abort guessing.

// true if guesses, otherwise false
public static boolean Start( throws IOException {
    go = 0;

    while (true) {
        if (go == attempt) {
            System.out.println("You have guessed the wrong number " + go + " times, sorry but you'll have to try again! :(");
            scanInput.close();
            return false;
        }

        Scanner scanInput = new Scanner(System.in);
        data = scanInput.nextInt();

        // define an abort constant and inform the user what value abort the guessing process
        if (data == AbortNumber) {
            System.out.println("Guessing aborted by user");
            return false;
        }

        if (data > 100) {
            System.out.println("Only Enter Numbers Between 0-100");
            continue;
        }

        if (data == random) {
            System.out.println("Wow, you guessed it!!");
            scanInput.close();
            break;
        }

        if (data < random) {
            go ++;
            if (go == attempt) {
                System.out.println("You have guessed the wrong number " + go + " times, sorry but you'll have to try again! :(");
            continue;
        }
}

4. Variable initializations - go is initialized with 0, but it is better to put it explicitly. It is particularly useful, when your guessing instance is reused, as go is changed during the guessing process.

5. Proper names for variables - it is recommended to provide meaningful names for your variables. E.g.:

data -> userGuess
go -> step
attempt -> maxAttempts

6. Avoid repetition - use a constant for maximum number range and use it across your code:

const int MaxNumber = 100;
// ...
static int random = (int) (Math.random() * MaxNumber + 1);
// ...
if (data > MaxNumber)
// ...
System.out.println("Only Enter Numbers Between 0-" + MaxNumber);
// ...

7. Testing for maximum attempts - == should do the work, but >= is safer: if (go >= attempt). It sounds a little paranoiac, but in complex programs and especially when dealing with multi-threading, it is possible that the variable passes over the threshold and the cycle never ends.

Final code

By merging some parts of code in a separate function, your final code could look like (not tested and no renames performed):

private static const int MaxNumber = 100;
private static int random = (int) (Math.random() * MaxNumber + 1);
private static int data;
private static int go;
private static int attempt = 10;

private static void endGuess(String message, Scanner scanInput) {
   System.out.println(message);
   scanInput.close();
}

public static boolean StartGuess() throws IOException {
    go = 0;

    while (true) {
       Scanner scanInput = new Scanner(System.in);
       data = scanInput.nextInt();

       if (go >= attempt) {
          endGuess("You have guessed the wrong number " + go + " times, sorry but you'll have to try again! :(", scanInput);
          return false;
       }

       if (data > MaxNumber ) {
          endGuess("Only Enter Numbers Between 0-" + MaxNumber, scanInput);
          continue;
       }

       if (data == random) {
          endGuess("Wow, you guessed it!!", scanInput);
          return true;
       }

       go ++;

       if (data < random)
          endGuess("Higher", scanInput);
       else // data > random
          endGuess("Lower", scanInput);
    }
}

public static void main(String[] args) throws IOException {
    System.out.println("Guess A Number Between 0-" + MaxNumber + " Within " + attempt + " Goes");
    bool guessed = StartGuess();

    // use guessed in this context, maybe set exit code if not guessed
}


You seem to assume that there is a root between a and b. If it is not the case, bisect will never terminate. Assuming that f is well-behaving, it would be prudent to test that f(a) and f(b) have different signs before proceeding.
Also, consider the case f(a) > 0 && f(b) < 0

bisect doesn't find the approximation of the root. It finds an argument at which f is reasonably small. It could be quite far from the root. A prudent termination condition is b - a < e.

a + b may overflow, and then all bets are off. Consider mid = a + (b - a)/2.


I feel that rofl pretty well covered how this could be done differently, but I want to point out what I feel to be an issue.

You really shouldn't be formatting the decimal results as a string. Formatting should be done in whatever application consumes the data you're sending it. As a user, I would be pretty upset to receive a "percentage" that I couldn't do any mathematical analysis on without first splitting out the "%" character, dividing by 100, and then formatting it as a percentage natively.

Select CONVERT(decimal(5,0), 1.0 * SUM([SalesCount]) / [Total Leads])


Length of a C string, capped to some maximum

All three versions can be improved.

The first function has the problem that strlen(s) is likely to be called twice.  strlen() is an expensive operation, as it walks along the entire string until it finds the NUL terminator.

The second version (the macro) has the same issue, with the additional caveat that it breaks if s is an expression with a side-effect, such as an assignment.  For example, MAX_SIZE_OF(str++) would expand to

(strlen(str++) > M_MAX_SIZE ? M_MAX_SIZE : strlen(str++))

and possibly lead to str being incremented twice.  (Even if you decide that the ALL_CAPS_NAME alerts programmers to the fact it is a macro and thus susceptible to this kind of thing, it's still a trap that is better avoided altogether.)

The last version is better, in that it avoids both the second call to strlen() and the double-argument-expansion problem.  However, I still have two objections.

First, I think that you would be better off decomposing the problem into two parts, like MIN(M_MAX_SIZE, strlen(s)).  The MIN() macro, although not in the C standard, is frequently reimplemented, and widely understood.  On the other hand, it is less obvious what your maxSizeOf() is supposed to do.  I'm not sure that it's even worth the brain power to keep track of the existence of this function.

Second, if the string that is passed to the function is much longer than M_MAX_SIZE, it still needs to walk all the way to the end of the string — even if M_MAX_SIZE is 5 and the string is a gigabyte long.  To avoid that problem, I think that you may be better off walking down s yourself.  And if you do hunt for the NUL terminator yourself, then it is suddenly worthwhile to have this function again.

More importantly, worrying about the efficiency of the function compared to the macro is a false optimization.  The operation that could potentially take a long time and scale poorly is strlen().  That's the performance problem that would bite you — not the function-vs.-macro stuff that you are worrying about.


I guess you'd be better off using Class.getRessource() to access your files. I assume they are packaged with your application.

This method would not be restricted to the view layer (where it actually not belongs). And you won't be concerned with servlet container details.


How to Avoid Conditional Check Duplication

In my opinion, there are not other good ways that I see to avoid this kind of logic; you can attenuate the arrow code by inverting the first condition and returning early.
if (!altPhoneExist && !altEmailExist) {
   return;
}

// Here we know it's either one of them

if (altPhoneExist) {
   contact.setPhoneNumber(contact.getAlternativePhoneNumber());
}

if (altEmailExist) {
   contact.setEmail(contact.getAlternativeEmail());
}

rqType.getContactInfoList().add(CraneFactory.createContactPerson(contact));


Anything wrong with my typical module pattern?

I would suggest using a constructor and prototypes (as well as the module pattern) if you want to learn OOP in JavaScript. This is typically how libraries like jQuery and Zepto are built:

var App = (function($) {

  'use strict';

  // Gallery

  var Gallery = (function() {

    // Constructor
    function Gallery(images, container) {
      this.images = images;
      this.$container = $(container);

      // Create elements we need first,
      // and cache them in variables to use them
      // in prototype methods
      this.$nav = $('');
      this.$next = $('
Next
');
      this.$prev = $('
Prev
');

      // Initialization
      this._init();
      this._events();
    }

    // Methods that start with underscore are
    // meant for internal use, even though they are still public
    // it is a well known convention
    Gallery.prototype._init = function() {
      this.addImages(this.images);
      this.$nav.append(this.$next, this.$prev);
      this.$container.append(this.$nav);
    };

    Gallery.prototype._events = function() {
      this.$prev.click(function() {
        //...
      });
      this.$next.click(function() {
        //...
      });
    };

    // Public method
    Gallery.prototype.addImages = function(imgs) {
      // Append all images at once for best performance
      this.$container.append(imgs.map(render).join(''));
    };

    // Helpers

    // This function is available in the code above
    // because function declarations get hoisted to the top
    // of the scope, as opposed to function expressions, ie:
    // "var render = function(){}"
    function render(path) {
      return '';
    }

    // Return a wrapper that will let us call "Gallery"
    // without using the "new" keyword
    return function(x, y) {
      return new Gallery(x, y);
    };
  }());

  // App

  function init() {
    // app init
  }

  return {
    Gallery: Gallery,
    init: init,
  };

})(Zepto);

(function($) {

  App.init();

  var imgs = ['image1.jpg', 'image2.jpg', 'image3.jpg'];

  // short for document.ready(fn)
  $(function() {
    // We get back an instance of "Gallery"
    // without using the "new" keyword
    var gallery = App.Gallery(imgs, '#gallery'); // you can pass a selector

    // Add more images using public method
    gallery.addImages(['a.jpg', 'b.png']);
  });

})(Zepto);

Once you feel more comfortable with prototypes and inheritance in JavaScript, I would probably consider making a jQuery/Zepto plugin for your gallery, so you'd be able to call it on your elements like $('#gallery').myGalleryPlugin(images).