Polymorphic customer classes for employees and affiliates

JavaDoc

Your whitespaces are all messed up, sometimes there are spaces, sometimes not, sometimes there's a new line after a function declaration, sometimes not. Be consistent, even better, use a code formatter.

abstract class Customer {
    String cid;
    String customer_name;
    double fare;

Why is everything package-private? That class should most likely be public and the variables private or protected.

String cid;
String customer_name;

Both names are not very good:

The first one is abbreviated, the second isn't, be consistent.
The customer prefix is superfluous, as it is a field in the class Customer.

double fare;

You're representing money with a double, this is dangerous! Use a BigDecimal or a similar class instead.

protected String getCid() {
protected String getCustomer_name() {
protected abstract double getFare();
protected abstract void printDetails();

Why are all these methods protected, shouldn't they be public?

CustomerAffiliated(String cid,String customer_name,double fare){

    super();
    this.cid=cid;
    this.customer_name=customer_name;
    this.fare=fare;
}

There should be a consutructor in the Customer class which accepts these values. This makes sure that less knowledge is used when extending the class, additionally you could transform the values in the original constructor.

@Override
protected void printDetails() {
    System.out.println(this.getCid());
    System.out.println(this.getCustomer_name());
    System.out.println(this.getFare());
}

Printing directly to stdout is bad, you should return a String so that the system which invokes the method can decide where the output goes to. Ideally you could remove this function favor of overriding toString.

Customer c;
c=new CustomerAffiliated("1","a",100);
c.printDetails();

Why assigning it on the next line if you could do it on the same line? Why abbreviating the name of the class? It makes the code only unnecessary hard to read, imagine the following, exaggerated, example:

for (Customer c : l) {
    double f = c.getFare();

    if (f > 0) {
        a.add(c);
    }
}

Not exactly easy to read, is it? You can't take one line and take a guess what's going on. Let's try that again with long names:

for (Customer customer : customers) {
    double customerFare = customer.getFare();

    if (customerFare > 0) {
        customersWithFare.add(customer);
    }
}

Your structure makes somewhat sense, depending on what you're trying to achieve. It's hard to say if this is the best approach without knowing anything about the rest of the system. But as a more generic approach having a Customer class with a discount and type field would be more efficient in the real world (as most of the time the data for customers comes from a database which has now idea about some class structure).

public class Customer
    public String getId()
    public String getName()
    public BigDecimal getFare()
    public BigDecimal getDiscount()
    public CustomerType getType()

public enum CustomerType
    NORMAL
    AFFILIATED

This is not without drawbacks itself, but reduces the need to know about and create different classes. Technically you could also hardcode the discount value into the enum, always depending on what you're trying to achieve.


Is this a good approach for creating pages for multiple content typs with GatsbyJS?

There's definitely a lot of duplicate code in those 2 ifs. I'd extract it into function and pass different things as parameters.

Then code would look let's say:

//not sure about name of function and parameters
function nodeFieldPerType(filePath, getNodePath) {
  if (
    node.internal.type === "Mdx" &&
    node.fileAbsolutePath.includes(filePath)
  ) {
    const value = createFilePath({ node, getNode })
    createNodeField({
      name: "slug",
      node,
      value: getNodePath(value),
    })
  }
}

Then you call it like like:

nodeFieldPerType(`content/posts`, value => `/blog${value}`);
nodeFieldPerType(`content/projects`, value => `/project${value}`);

This cleans it up a bit. If you keep adding more possible branches, you may need to add more parameters. You can go further to make this as a static configuration and put this into configuration structure, that you fill in advance. Then in your code you just pick the one you need and call it.
Ex:

config = {
`content/posts`: { getNodePath:  value => `/blog${value}` }, //object on purpose so that you can add more parameters later
`content/projects`: { getNodePath: value => `/project${value}` },
}

And then instead of your ifs you check if filePath exists in this config and if it does, you call function with parameters in config.


Converting an integer to a hexadecimal string representation in Java

inLeadingZeros I find dubious; wrong name probably
0x00_00_03_44 would be output as "344" whereas conventional would be a two-fold "0344" (or even interspaced as "03 44"). The reason that from left-to-right one can create a byte by two chars.
The exceptional case probably can be dealt with in front.
Error if (digit != 0) { should be if (digit != '0') { or something else is meant.
toHexChar still expects an int digit 0..10. So probably a semantic clash.
a as parameter name is unfortunate especially in English; num or n is more clear.

I am uncertain whether your code is correct by just reading it, due to the variable & if.
/**
 * Converts the given integer into its textual hexadecimal representation.
 *
 * @param num the integer to convert.
 * @return the string representing {@code num} in hexadecimal notation.
 */
public static String intToHexString(int num ) {
    if (num == 0) {
        return "00";
    }

    StringBuilder stringBuilder = new StringBuilder(Integer.BYTES * 2);
    while (num != 0) {
        char digit = toHexChar(num & 0xf);
        num >>>= 4;
        stringBuilder.append(digit);

        digit = toHexChar(num & 0xf);
        num >>>= 4;
        stringBuilder.append(digit);
    }
    return stringBuilder.reverse().toString();
}

// Converts the integer digit to its textual hexadecimal representation:
private static char toHexChar(int digit) {
    return 0 <= digit && digit < 10 ?
            (char)(digit + '0') :
            (char)(digit - 10 + 'a');
}


There are 4 ways to a solve this:

Solution 1:

You can define a fixed width STD_LOGIC_VECTOR (SLV), which can be used to construct other vectors (let's call them STD_LOGIC_VECTOR_VECTORs (SLVV).

subtype T_SLV_8  is STD_LOGIC_VECTOR(7 downto 0);        -- define a Byte
type    T_SLVV_8 is array(NATURAL range <>) of T_SLV_8;  -- define a new unconstrained vector of Bytes.

Now you can define your entity as follows:

entity mux_slvv_8 is
  generic (
    PORTS  : POSITIVE  := 4
  );
  port (
    sel  : in  STD_LOGIC_VECTOR(log2ceilnz(PORTS) - 1 downto 0);
    X    : in  T_SLVV_8(PORTS - 1 downto 0);
    Y    : out T_SLV_8
  );
end;

The internal logic can be reduced to:

architecture rtl of mux_slvv_8 is
begin
  Y <= X(to_integer(unsigned(sel)));
end;

This can be improved by extracting to_integer(unsigned(..)) into a function called to_index.

Solution 2:

The next step would be, to be also flexible in how many bits are multiplexed at once. So let's introduce a generic BITS to specify the data bits. VHDL has a problem to define array of unconstrained arrays (this is solved with VHDL-2008, but not all vendors support this feature).

So solution 2 uses a flat vector to pass all bits to the mux.

entity mux_flat is
  generic (
    PORTS  : POSITIVE  := 4;
    BITS   : POSITIVE  := 8
  );
  port (
    sel  : in  STD_LOGIC_VECTOR(log2ceilnz(PORTS) - 1 downto 0);
    X    : in  STD_LOGIC_VECTOR((BITS * PORTS) - 1 downto 0);
    Y    : out STD_LOGIC_VECTOR(BITS - 1 downto 0)
  );
end;

architecture rtl of mux_flat is
  type T_SLVV is array(NATURAL range <>) of STD_LOGIC_VECTOR(BITS - 1 downto 0);
  signal mux_in : T_SLVV(PORTS - 1 downto 0)
begin
  gen : for i in 0 to PORTS - 1 generate
    -- convert flat vector to slvv
    mux_in(i) <= X(((i + 1) * BITS) - 1 downto (i * BITS));
  end generate;
  Y <= mux_in(to_integer(unsigned(sel)));
end;

Solution 3:

Being flexible in PORTS and BITS can also be done by using a real 2-dimensional array -> STD_LOGIC_MATRIX (SLM).

type T_SLM is array(NATURAL range <>, NATURAL range <>) of STD_LOGIC;

This would be the entity declaration:

entity mux_slm is
  generic (
    PORTS  : POSITIVE  := 4;
    BITS   : POSITIVE  := 8
  );
  port (
    sel  : in  STD_LOGIC_VECTOR(log2ceilnz(PORTS) - 1 downto 0);
    X    : in  T_SLM(PORTS - 1 downto 0, BITS - 1 downto 0);
    Y    : out STD_LOGIC_VECTOR(BITS - 1 downto 0)
  );
end;

You could also write a generate loop to do some wiring or you can define some functions to do that.

-- get a matrix row
function get_row(slm : T_SLM; RowIndex : NATURAL) return STD_LOGIC_VECTOR is
  variable slv : STD_LOGIC_VECTOR(slm'high(2) downto slm'low(2)); -- Xilinx iSIM work-around, because 'range(2) = 'range(1); tested with ISE/iSIM 14.2
begin
  for i in slv'range loop
    slv(i) := slm(RowIndex, i);
  end loop;
  return slv;
end function;

And thats the corresponding architecture:

architecture rtl of mux_slm is
begin
  Y <= get_Row(X, to_integer(unsigned(sel)));
end;

Solution 4:

If your tool supports VHDL-2008 and arrays of unconstrained vectors, then you can use this type:

type T_SLVV is array(NATURAL range <>) of STD_LOGIC_VECTOR;

Type Conversion:

The following images illustrates all possible type conversions regarding: SL, SLV, SLVV and SLM.

If you are interested in more, I could upload my complete collection of vector, vector-vector and matrix types, functions and procedures. Please give me a hint.

Edit:

Here is the package PoC.common.vectors. It's included in my PicoBlaze Library which is currently in beta state. The release of PoC is also planned, but not so progressed. So I included some necessary packages and modules into this library. The source code license is 'Apache License 2.0'.


There is no identifiable difference between your table's column names and your preferred keys, but if you want to alter the keys, just build that into your SELECT clause -- this is what "aliases" are for.

Suppose you wanted to capitalize each column name, here's how that could look:

$stmt = $conn->prepare("SELECT name AS Name,
                               company AS Company,
                               email AS Email,
                               phone AS Phone,
                               address AS Address
                        FROM tickets_info
                        WHERE ticket = ?");
$stmt->execute([$_POST['ticket']]);
$ticket = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];

Note, I am not using a loop.  Your snippet is overwriting itself in the loop, so I am interpreting that to mean that ticket is a PRIMARY/UNIQUE column.

If you want to extract all columns from your table and use the column names as keys, you don't need to change your original query.

$stmt = $conn->prepare("SELECT * FROM tickets_info WHERE ticket = ?");
$stmt->execute([$_POST['ticket']]);
$ticket = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];


Replacing IUnitOfWork with a Factory Pattern

Bad idea...?

Generally, I belong to the camp thinking generic repositories are a bad idea:

The abstraction will be leaky at best.
If you really need a repository per type, why not let the client new it up directly?
Except from basic CRUD, there is no generic functionality, so a generic interface will reduce your options.

The abstractions doesn't seem right. I know it follows the usual conventions and examples given on EF, but do you want the database to dictate the shape of your domain objects?

If you split the responsibilities between domain logic and persistence, it may be clearer what to do. A split like that will also open new possibilities on how to implement and optimize.

Here are some ideas:

Handle different responsibilities in different places

Given an imaginary customer and two use cases:

Upgrade to gold customer.
Get a list of gold customers.

Those are different responsibilities which can be expressed like:

public class Responsibilities
{
    public void UpdateCustomer()
    {
        var repository = new Repository();
        var customer = repository.GetCustomerById(42);

        customer.UpgradeToGold();

        repository.Save(customer);
    }

    public void QueryGoldCustomers()
    {
        var query = new CustomerQuery();
        var goldCustomers = query.GetGoldCustomers();
    }
}

Repository and state management

This is a naive implementation; it will only work with customers already stored in the database, plus it generates multiple calls to the database. But the implementation is separated from everything else, so we are free to optimize the database access when it starts to be a problem.

I haven't used EF in a while, so the Save method may be way off.

public class Repository
{
    readonly Database context = new Database();

    public Customer GetCustomerById(int id)
    {
        var state = context.CustomerState.Single(x => x.Id == id);
        var address = context.Addresses.Single(x => x.Id == state.AddressId);
        var snapshot = new Customer.Snapshot
            {
                State = state,
                Address = address
            };

        return new Customer(snapshot);
    }

    public void Save(Customer customer)
    {
        var provider = (IProvideSnapshot<Customer.Snapshot>) customer;
        var snapshot = provider.GetSnapshot();

        context.Addresses.Attach(snapshot.Address);
        context.CustomerState.Attach(snapshot.State);
        context.SaveChanges();
    }
}

Isolated queries

Same thing here; there are better ways to implement the query. Note that this query is only meaningful inside of the domain boundary, like when you want to send special offers to all gold customers.

UI views, reports and such would probably benefit from using dtos and not the domain object directly.

If it turns out to be hard to generate efficient queries with EF, we are free to select other tools, even inline SQL.

public class CustomerQuery
{
    readonly Database context = new Database();

    public IEnumerable<Customer> GetGoldCustomers()
    {
        var states = context.CustomerState.Where(state => state.IsGold);
        var addressIds = states.Select(state => state.AddressId);
        var addresses = context.Addresses.Where(address => addressIds.Contains(address.Id));

        return states
            .Select(state => new Customer.Snapshot
                {
                    State = state,
                    Address = addresses.Single(address => address.Id == state.AddressId)
                })
            .Select(snapshot => new Customer(snapshot))
            .ToList();
    }
}

Other classes for completeness

In this example, the shape of the domain class, the Customer, is not dictated by the database.

The shape of the Snapshot is, though. But that could be a good thing, because the object-to-database impedance mismatch is lower.

public class Customer : IProvideSnapshot<Customer.Snapshot>
{
    readonly Snapshot snapshot;

    public Customer(Snapshot snapshot)
    {
        this.snapshot = snapshot;
    }

    public void UpgradeToGold()
    {
        snapshot.State.IsGold = true;
    }

    Snapshot IProvideSnapshot<Snapshot>.GetSnapshot()
    {
        return snapshot;
    }

    public class Snapshot
    {
        public CustomerState State { get; set; }
        public Address Address { get; set; }
    }
}

public interface IProvideSnapshot<out T>
{
    T GetSnapshot();
}

public class Database : DbContext
{
    public DbSet<CustomerState> CustomerState { get; set; }
    public DbSet<Address> Addresses { get; set; }
}

public class CustomerState
{
    public int Id { get; set; }
    public int AddressId { get; set; }
    public bool IsGold { get; set; }
}

public class Address
{
    public int Id { get; set; }
}


"How can I make this SEDE query better?" (bad title finder)

Your query is well structured, and consistent, but there is one issue you have failed to incorporate.... not all bad questions have a user. When questions are migrated, or there's a user deleted, the question may have no link back to the Users table.

This requires an Outer Join to Users.

Additionally, I have found that CTE expressions are fantastic for aliasing column names. For example, both Posts and Users tables have an ID column, and you need to have Posts.ID and Users.ID in different places. Both also have a CreatedDate. When these aliases become long, and complicated, it bogs down the readability of the query.

Oh, about the readability, the case statement is dead code. Don't use code that serves no purpose, or, alternatively, "debug code" should be removed before deployment. If you cannot trust yourself to have the right conditions on the query, then you cannot trust yourself to have the right debug code either.

So, if you alias these values in a CTE, and use the CTE to make the Outer join neat, you can reduce your query to:

SELECT PostID as [Post Link],
       Score,
       PostDate,
       UserID as [User Link],
       Reputation
FROM BadTitles
LEFT OUTER JOIN Users on UserId = Id
ORDER BY Score ASC, PostDate DESC

OK, that's a cheat, because BadTitles is a CTE, but, the full query, using your expanded comments, is:

DECLARE @Question INT = (SELECT Id FROM PostTypes WHERE Name = 'Question');
DECLARE @Answer INT = (SELECT Id FROM PostTypes WHERE Name = 'Answer');

with BadTitles as (
    SELECT Id as PostId,
           OwnerUserId as UserId,
           Score,
           CreationDate as PostDate
    FROM Posts
    WHERE
      /* Filter out non-question posts */
          Posts.PostTypeId = @Question

      /* Post not closed yet */
      AND Posts.ClosedDate IS NULL

      /* Generic title */
      AND (
            Posts.Title LIKE '%please%'
        OR  Posts.Title LIKE '%review%'
        OR  Posts.Title LIKE '%improve%'
        OR  Posts.Title LIKE '%better%'
        OR  Posts.Title LIKE '%how to%'
        OR  Posts.Title LIKE '%how can i%'
        OR  Posts.Title LIKE '%how do i%'
        )
)
SELECT PostID as [Post Link],
       Score,
       PostDate,
       UserID as [User Link],
       Reputation
FROM BadTitles
LEFT OUTER JOIN Users on UserId = Id
WHERE (Reputation IS NULL OR Reputation <= 500)
ORDER BY

  /* Lowest scores first - Change to DESC if you want Highest first */
  Score ASC,

  /* Newest first - Change to ASC if you want oldest first */
  PostDate DESC

Note that this produces an addition hundred or so questions from migrations, etc.


Beating built-in timsort with own count sort function

I did some benchmarks using the timeit module and this test data:

random.seed(1)
data = [random.randint(0,10000) for _ in xrange(1000000)]

Original version clocks in at 411 ms, and the builtin sorted at 512 ms.

Using counts = defaultdict(int) that allows unconditional counts[num] += 1 takes it to 330 ms.

Using sorted_list.extend(counts[num] * [num]) instead of the inner loop improves to 250 ms, or 246 ms when also omitting the second if.

Using min(counts), max(counts) instead of min(unsorted_list), max(unsorted_list) improves further to 197 ms.

Using chain and repeat from itertools to construct the result takes 182 ms (though repeat does not make much difference).

Code looks like this after the changes:

from collections import defaultdict
from itertools import chain, repeat

def countsort(unsorted_list):
    counts = defaultdict(int)
    for num in unsorted_list:
        counts[num] += 1

    return list(
            chain.from_iterable(
                repeat(num, counts[num])
                for num in xrange(min(counts), max(counts) + 1)))


Well your provided example data can't be real, because I never ever saw an int? which could take 1.1 as value.

I will apply to the posted code the standard C# naming convention, meaning that properties are named using PascalCase casing.

That being said, lets take a look at the Tree class

public class Tree
{
    public int? id { get; set; }
    public string text { get; set; }
    public List<Tree> children { get; set; }
}

which seems to be just a TreeNode with children and without a parent. IMO this is too much. Just add your TreeNode to a List<TreeNode> Children property and you won't need the Tree class anymore.

By initializing the Children property at creation of the object, you will waste some space (memory) but you won't need to check if Children == null anymore.
If the root node (parent == null) won't be the first node in the collection then your method will fail.
Omitting braces although they might be optional is dangerous because this can lead to hidden and therefore hard to find bugs.

I would like to encourage you to always use them.
Using recursion to tackle this problem is a good idea.

Another approach

which assumes the TreeNode looks like so

public class TreeNode
{
    public int? Id { get; set; }
    public string Text { get; set; }
    public int? Parent { get; set; }
    public List<TreeNode> Children { get; set; }

    public TreeNode()
    {
        Children = new List<TreeNode>();
    }
}

where I would usually make the setters private and fill the properties at constructor level, but I will leave this for you to do.

By using FirstOrDefault() we can get the root node very easily and should remove it from the nodes collection. Let us introduce a method to do this

private static TreeNode RemoveRootNode(this List<TreeNode> nodes)
{
    if (nodes == null)
    {
        throw new NullReferenceException("nodes");
    }

    var root = nodes.FirstOrDefault(n => !n.Parent.HasValue);
    if (root != null)
    {
        nodes.Remove(root);
    }

    return root;
}

Now we don't need the root node to be the first item in the collection anymore.

Next we need the "main"  method which takes a List<TreeNode> as a parameter and returns a TreeNode which is the root node like so

public static TreeNode BuildTree(this List<TreeNode> nodes)
{
    var root = nodes.RemoveRootNode();
    if (root == null) { throw new ArgumentOutOfRangeException("nodes"); }
    return root.BuildTree(nodes);
}

Edit

Based on the changed example data, we now can have multiple TreeNode with Parent == null which makes the RemoveRootNode() method superfluous and will result in TreeNode buildTree(this List<TreeNode>) like so

public static TreeNode BuildTree(this List<TreeNode> nodes)
{
    if (nodes == null)
    {
        throw new ArgumentNullException("nodes");
    }
    return new TreeNode().BuildTree(nodes);
}

As we see there should be a BuildTree(this TreeNode, List<TreeNode>) method which will look like:

private static TreeNode BuildTree(this TreeNode root, List<TreeNode> nodes)
{
    if (nodes.Count == 0) { return root; }

    var children = root.FetchChildren(nodes).ToList();
    root.Children.AddRange(children);
    root.RemoveChildren(nodes);

    for (int i = 0; i < children.Count; i++)
    {
        children[i] = children[i].BuildTree(nodes);
        if (nodes.Count == 0) { break; }
    }

    return root;
}

which is self-explanatory. It fetches the children by using

public static IEnumerable<TreeNode> FetchChildren(this TreeNode root, List<TreeNode> nodes)
{
    return nodes.Where(n => n.Parent == root.Id);
}

and add them to the Children property of the root node and removes them from the nodes by

public static void RemoveChildren(this TreeNode root, List<TreeNode> nodes)
{
    foreach (var node in root.Children)
    {
        nodes.Remove(node);
    }
}

Then it iterates over the the children and calls itself recursively.


Never use OOP just because people say it's cool. If you do not know how to apply it, that means you just do not need it in this task. That's it. Forget about OOP. Involving it without much need only makes code worse and unreadable.


A "C" shape of 7 boxes that turn green on click

This has "interview question" all over it :D Anyways.

First, I'd avoid inline styles. The most common issue with inline styles is that they are hard to override. Only !important can override them from a stylesheet, aside from changing the inline style values themselves. If you carry over the habit to building large apps, CSS maintenance becomes a hell lot worse.

Additionally, styles in JS is hard to maintain. In a large code base, looking for which JS changed some style is hard. You don't know where it happened and the debugger won't tell you immediately without putting DOM breakpoints, which is annoying when a lot of changes take place.

As an alternative, I suggest you define CSS classes corresponding to the state of the box and programmatically add/remove classes. I would suggest reading about BEM, especially modifiers (the "M"). We can use modifiers as "state".

// Base box style
.c-box__box{
  color: transparent
}

// During the "selected" state, you add this class.
.c-box__box--selected{
  color: green
}

// During the "unselected" state, add this class.
.c-box__box--unselected{
  color: red
}

In the sample CSS above, a box would initially be transparent. Clicking the box, you make the box turn to a "selected" state. Thus you add .c-box__box--selected. When you unselect, you make the box turn to an "unselected" state. You remove the .c-box__box--selected and add .c-box__box--unselected. Since styles are defined accordingly in CSS, it will color the box appropriately. Now JS has no idea of styling, only classes pertaining the state of the boxes.

e.stopPropagation() stops the bubbling process, and prevents the event from going up the ancestors and firing events that are attached there. In this case, you don't need it as you are not interested in stopping some event handler in some ancestor from firing.

In your code, you're manually counting your elements (I see a hard 7 there). An alternative would be to use querySelectorAll to get each box and attach a handler. When they get clicked, they get stored in another array. When that array's length matches the length from querySelectorAll, then  you can say all your boxes have been selected and you can start your unwinding process. A reverse operation would simply be a pop of the array of selected boxes. This way, you can add an arbitrary amount of boxes without worrying about a hard-coded limit.

Also, instead of a recursive setTimeout, you can use a more loop-like setInterval. When you reach empty, you simply stop the interval from running. Also note that timers are async. One can easily do something between the unwinding process, like say click on a red box. I suggest you put a flag to tell the handler to not proceed while it's unwinding.

Here's a demo (warning: I wrote it using SCSS and ES6): http://codepen.io/anon/pen/JGRzVe

var boxesNodeList = document.querySelectorAll(".c-box__box");
var boxesArray = Array.prototype.slice.call(boxesNodeList);
var selectedBoxes = [];
var isUnwinding = false;

boxesArray.forEach(function(box) {

  box.addEventListener('click', function() {
    if (isUnwinding) return;

    box.classList.remove('c-box__box--unselected');
    box.classList.add('c-box__box--selected');
    selectedBoxes.push(this);

    if (selectedBoxes.length === boxesArray.length) {
      isUnwinding = true;
      var timer = setInterval(function() {
        var box = selectedBoxes.pop();
        box.classList.remove('c-box__box--selected');
        box.classList.add('c-box__box--unselected');
        if (!selectedBoxes.length) {
          clearInterval(timer);
          isUnwinding = false;
        }
      }, 500);
    }
  });
});
.c-box {
  display: table;
  border: 1px solid blue;
  padding: 100px;
  overflow: hidden;
}
// Base box style
.c-box__box {
  float: left;
  border: 1px solid #000;
  width: 50px;
  height: 50px;
  margin: 2px;
  // Every 3n+1, break to a new line
  &: nth-child(3n + 1) {
    clear: both;
  }
}
// Just a transparent box
.c-box__spacer {
  display: inline-block;
  border: transparent;
  width: 50px;
  height: 50px;
  margin: 2px;
}
// Selected state style
.c-box__box--selected {
  background: green;
}
// Unselected state style
.c-box__box--unselected {
  background: red;
}


List of all possible monetary totals from a set of cash

1. Review

The data structure cash is a map from denomination to the count of the bills in that denomination. This is a representation of a multiset, and it's a good idea here to use the built-in collections.Counter:

from collections import Counter
cash = Counter({1: 1, 5: 3, 10: 2})

Now you can replace this line:

cash_list = [i for i in sorted(cash) for j in range(cash[i])]

with a call to the Counter.elements method:

cash_list = list(cash.elements())

The code is not organized into functions. This makes it hard to test and hard to measure the performance. It would be better to write something like this:

from collections import Counter
from itertools import combinations

def change(cash):
    """Given a map from denomination to the count of bills in that
    denomination, return the set of values that can be made using a
    subset of the bills.

    """
    totals = set() # Set of possible totals
    cash_list = list(Counter(cash).elements()) # List of all bills
    for r in range(len(cash_list)+1):
        for subset in combinations(cash_list, r):
            totals.add(sum(subset))
    return totals

Now we can easily test it:

>>> change({1:1, 2:1, 4:1, 8:1}) == set(range(16))
True

and measure its performance:

>>> from timeit import timeit
>>> timeit(lambda:change({1:20}), number=1)
0.6443959611933678

2. Performance

The algorithm loops over all subsets of bills. But this doesn't take advantage of the fact that bills of the same denomination are indistinguishable. For example, we know that

change({1:25}) == set(range(26))

since if you have twenty-five $1 bills, you can make change for all dollar amounts from $0 to $25. But this calculation, that should be trivial, takes a very long time:

>>> timeit(lambda:change({1:25}), number=1)
22.855976961087435

And good luck waiting for, say, change({1:100}) to finish running. So we can improve the performance in these cases by taking advantage of the fact that if have \$n\$ bills of denomination \$d\$, the possible values are \$0, d, 2d, \ldots, nd\$, that is, range(0, (n + 1) * d, d). Using itertools.product we can write it like this:

from collections import Counter
from itertools import product

def change2(cash):
    """Given a map from denomination to the count of bills in that
    denomination, return the set of values that can be made using a
    subset of the bills.

    """
    ranges = [range(0, (n + 1) * d, d) for d, n in Counter(cash).items()]
    return set(map(sum, product(*ranges)))

This is slightly slower than the original code in cases where all the denominations are different:

>>> timeit(lambda:change({2**i:1 for i in range(20)}), number=1)
0.9978475249372423
>>> timeit(lambda:change2({2**i:1 for i in range(20)}), number=1)
1.0107885741163045

but it is massively faster in cases where there are many bills of a denomination:

>>> timeit(lambda:change2({1:25}), number=1)
0.000085500068962574


For each line in a file, read two integers and output the minimum

There are a few methods that will make the task easier for you:

File.ReadLines to read the file line-by-line (see also File.ReadAllLines)
Enumerable.Skip to skip the first line
Enumerable.Select to map the the lines to the minimum of the two numbers
string.Join for formatting the output

You might also consider taking the input and output file paths from the args parameter. Putting it all together (without error checking) could look like this:

public static void Main(string[] args)
{
    var minimums = File.ReadLines(args[0]).Skip(1).Select(GetMinimum);
    File.WriteAllText(args[1], string.Join(" ", minimums));
}

private static int GetMinimum(string line)
{
    var numbers = line.Split(' ').Select(int.Parse).ToArray();
    return Math.Min(numbers[0], numbers[1]);
}

I've been lazy here with error checking -- it would be a good exercise to add that to the code. It's also good practice to specify the file encoding when reading and writing files, which again I haven't shown here.


Is the following divide and conquer recursive algorithm for the exponentiation more efficient than the iterative one for large numbers?

I think your analysis is correct if multiplication of k-digit and ℓ-digit numbers takes Θ(kℓ) time, but more efficient multiplication algorithms are known. The most efficient algorithm in wide use (implemented in GMP) is Schönhage-Strassen, which is O(k log k log log k) for numbers of equal length. I don't know the complexity for unequal lengths, but I suspect it's O(ℓ log k log log k) for k < ℓ. Using that algorithm, or any sub-kℓ algorithm, you should find that the divide-and-conquer approach is faster.


Find kth element from tail of singly linked list in one pass

Trust... it's all about trust.

Trust your length is accurate (if it is not, you have other problems).

Then, your code becomes a simple loop:

// length has the size of the list
int kthPos = length - kthElem;

if (kthPos < 0) {
    return null;
}

Node<T> node = head;
while (kthPos-- > 0) {
    node = node.getNext();
}
return node;


Finding all neighbours of a node sliding tile

Your code is really hard to read. I suggest the following:

Have four methods slideUp, slideDown, slideLeft, slideRight, each copying the this and applying the slide operation.
In the neighbour generation routine just check all the four, and whichever of them return a non-null result add to the list; finally, return the list.
Cache the index of the zero tile.

I had this in mind:

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Scanner;

public class SlidingTilePuzzleNode {

    private int[] state = new int[9];

    private int zeroTileIndex;

    public SlidingTilePuzzleNode() {
        for (int i = 0; i < state.length - 1; ++i) {
            state[i] = i + 1;
        }

        zeroTileIndex = state.length - 1;
    }

    private SlidingTilePuzzleNode(int[] state, int zeroTileIndex) {
        this.state = state.clone();
        this.zeroTileIndex = zeroTileIndex;
    }

    public SlidingTilePuzzleNode slideUp() {
        int x = getX(zeroTileIndex);
        int y = getY(zeroTileIndex);

        if (y == 0) {
            return null;
        }

        int nextx = x;
        int nexty = y - 1;
        int nextIndex = xyToIndex(nextx, nexty);
        SlidingTilePuzzleNode node = new SlidingTilePuzzleNode(state,
                                                               nextIndex);
        int tmp = node.state[nextIndex];
        node.state[nextIndex] = node.state[zeroTileIndex];
        node.state[zeroTileIndex] = tmp;
        return node;
    }

    public SlidingTilePuzzleNode slideDown() {
        int x = getX(zeroTileIndex);
        int y = getY(zeroTileIndex);

        if (y == 2) {
            return null;
        }

        int nextx = x;
        int nexty = y + 1;
        int nextIndex = xyToIndex(nextx, nexty);
        SlidingTilePuzzleNode node = new SlidingTilePuzzleNode(state,
                                                               nextIndex);
        int tmp = node.state[nextIndex];
        node.state[nextIndex] = node.state[zeroTileIndex];
        node.state[zeroTileIndex] = tmp;
        return node;
    }

    public SlidingTilePuzzleNode slideLeft() {
        int x = getX(zeroTileIndex);
        int y = getY(zeroTileIndex);

        if (x == 0) {
            return null;
        }

        int nextx = x - 1;
        int nexty = y;
        int nextIndex = xyToIndex(nextx, nexty);
        SlidingTilePuzzleNode node = new SlidingTilePuzzleNode(state,
                                                               nextIndex);
        int tmp = node.state[nextIndex];
        node.state[nextIndex] = node.state[zeroTileIndex];
        node.state[zeroTileIndex] = tmp;
        return node;
    }

    public SlidingTilePuzzleNode slideRight() {
        int x = getX(zeroTileIndex);
        int y = getY(zeroTileIndex);

        if (x == 2) {
            return null;
        }

        int nextx = x + 1;
        int nexty = y;
        int nextIndex = xyToIndex(nextx, nexty);
        SlidingTilePuzzleNode node = new SlidingTilePuzzleNode(state,
                                                               nextIndex);
        int tmp = node.state[nextIndex];
        node.state[nextIndex] = node.state[zeroTileIndex];
        node.state[zeroTileIndex] = tmp;
        return node;
    }

    public Collection<SlidingTilePuzzleNode> getNeighbors() {
        List<SlidingTilePuzzleNode> neighborList = new ArrayList<>(4);
        SlidingTilePuzzleNode node = slideUp();

        if (node != null) {
            neighborList.add(node);
        }

        node = slideDown();

        if (node != null) {
            neighborList.add(node);
        }

        node = slideLeft();

        if (node != null) {
            neighborList.add(node);
        }

        node = slideRight();

        if (node != null) {
            neighborList.add(node);
        }

        return neighborList;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        int index = 0;

        for (int y = 0; y < 3; ++y) {
            for (int x = 0; x < 3; ++x) {
                sb.append(state[index++]);
            }
            sb.append("\n");
        }

        return sb.toString();
    }

    private static int getX(int index) {
        return index % 3;
    }

    private static int getY(int index) {
        return index / 3;
    }

    private static int xyToIndex(int x, int y) {
        return y * 3 + x;
    }

    public static void main(String[] args) {
        SlidingTilePuzzleNode node = new SlidingTilePuzzleNode();
        SlidingTilePuzzleNode tmpNode;
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.println(node);

            String cmd = scanner.nextLine().trim().toLowerCase();

            switch (cmd) {
                case "quit":
                case "exit":
                    System.exit(0);

                case "up":
                    tmpNode = node.slideUp();

                    if (tmpNode != null) {
                        node = tmpNode;
                    }

                    break;

                case "down":
                    tmpNode = node.slideDown();

                    if (tmpNode != null) {
                        node = tmpNode;
                    }

                    break;

                case "left":
                    tmpNode = node.slideLeft();

                    if (tmpNode != null) {
                        node = tmpNode;
                    }

                    break;

                case "right":
                    tmpNode = node.slideRight();

                    if (tmpNode != null) {
                        node = tmpNode;
                    }

                    break;
            }
        }
    }
}

Hope that helps.


Good Practices

✔ I like the fact you don't rotate if the array's length is a multiplication of K.
✔ As you stated in the comments, the second array B gets created too early, since in some occasions it would be created in vain.

Review

The challenge is clearly written for Java:class Solution { public int[] solution(int[] A, int K); }. The provided signature deserves its own review (casing conventions, static members, meaningful member names). However, if you 'cannot' change the signature given to you, I would be consistent and use N instead of len for the array's length.
You sometimes return the provided array and sometimes create a new one. I would make this very clear in the specification. A consumer should know whether or when a copy is returned. This affects further usage of the object.
You should guard against the source array being null.
How would you handle a negative value of K? If you think about it, a left rotation is just the inverse of a right rotation.
Nested statements could have been prevented by inverting the if-statement and exiting early. Less nested statements generally increase readability.
For bigger arrays you should check Buffer.BlockCopy to optimize copying sections of an array to another array. You could see a rotation as copying 2 sections from one array to another given a pivot. Check out this article about the subject.
If you can change the signature, make a static class with static method, use a meaningful method name RotateRight with arguments array and count and make it clear whether in-place rotation is performed or a new array is created.


Adapter class displaying characters' info

I think this method is not that long that you really need to refactor it, but you could do something like

public View getView(int index, View view, ViewGroup viewGroup) {
    view = createViewIfNeeded(view)
    final ViewHolder characterProfile = (ViewHolder) view.getTag();
    Character character =  mLeBluetoothLightsList.get(index);
    characterProfile.imgIconState.setImageResource(mIconStateRrs[character.getIconStatus()]);
    characterProfile.imgCharacterStatus.setImageResource(character.isAlive() ? R.drawable.alive : R.drawable.dead);
    characterProfile.txtName.setText(character.getCharacterName());
    logIfDebug(index, character);
    return view;
}

private static void logIfDebug(int index, Character character){
    if (Config.IS_DEBUG) {
        Log.i(mClassName, "getView - Index: " + index
                + "| Icon status: " + character.getIconStatusForLog()
                + "| Character status: " + character.isAliveForLog()
                + "| Name: " + character.getCharacterName());
    }
}

// You could extract createAndInitCharacterProfile from this method if you want
private View createViewIfNeeded(View view){
    if (view == null) {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.character_item, null);
        ViewHolder characterProfile = new ViewHolder();
        characterProfile.imgIconState = (ImageView) view.findViewById(R.id.icon_state);
        characterProfile.imgCharacterStatus = (ImageView) view.findViewById(R.id.character_state);
        characterProfile.txtName = (TextView) view.findViewById(R.id.name);
        view.setTag(characterProfile);
   }
   return view;
}


SICP - exercise 2.5 - representing pairs of nonnegative integers using only numbers and arithmetic operations

Well this is going to be inefficient no matter what, it's just that way. So we aren't going to improve the built-in expt, so that leaves repeat-divide for improvement. Let call it de-factor.

So first I thought something like

(define (de-factor p n)
 (let* ((max-expt (ceiling (/ (log p) (log n))))
             ;;log of p in base n
        (gcd-of (gcd p (expt n max-expt)))
        (res (/ (log gcd-of) (log n))))
   res))

which works so long as log internal is accurate enough to return the closest integer.It runs into significant rounding errors for some x and y less than a hundred.  If you built a very large log table you could solve in log time so long as you could accurately cast from your log table to the input x and y. (gcd runs in log time) Of course in such case the memory overhead of such a table or map would be huge, so not really that great of an optimization.

(define (de-factor p n)
 (let* ((rough-max-expt (let loop ((x 1))
                           (if (>= (expt n x) p)
                               x
                               (loop (* 2 x)))))
             ;;can't use log trick, returns inexact math
        (gcd-of (gcd p (expt n rough-max-expt))))
    (x-to-what-y n gcd-of)))

(define (x-to-what-y x n) ;return y such that (= n (expt x y)) is #t
 (if (= n 1)
     0
    (let loop ((y 1) (step 1) (acc x) (narrow? #f))
      (cond ((= acc n) y)
            ((< step 1) (error x step acc narrow?))
            (else (let ((next (* acc (expt x step))))
                     (if (<= next n)
                         (loop (+ y step)
                               (if narrow? (/ step 2) (* step 2))
                               next
                               narrow?)
                         (loop y
                               (/ step 2)
                               acc
                               #t))))))))

Minimal changes to the rest

(define (cons x y)
    (* (expt 2 x) (expt 3 y)))

(define (car p) (de-factor p 2))

(define (cdr p) (de-factor p 3))

As far as performance it's still less than linear because of the exact bignum math. (cdr (cons 12345 54321)) returns 12345 in a few seconds, but (cdr (cons 123456 654321)) in about a minute and a half.

When I tried your (cdr (car 12345 54321)) it ran out of memory, with a basic tail-recursion optimization, it took about 10 seconds. (cdr (cons 123456 654321)) is about a half hour. So my code is an optimization, but really just the nature of that big of numbers is they are very inefficient to do a lot of math on, and even more so the bigger they get. You would never do something this weird in production code.

Tail optimization for benchmarking

(define (repeat-divide x y)
  (let loop ((acc 0) (x x))
    (if (> (remainder x y) 0)
        acc
        (loop (+ 1 acc) (/ x y)))))


Using % for string formatting is deprecated. You should be using str.format() instead. Here's how one would use str.format(): print "Hello {0}.".format("world"). str.format() also supports using keyword arguments. Here's an example of that: print "Hello {word}.".format(word="world").
Near the end of the function deploy, underneath the if block with the condition os.path.isfile(local_file), you have comments above every line. These are unnecessary and can be removed.
Finally, I'm not sure why you have square brackets, [], around the value of the variable env.key_filename. If these aren't needed, they can be removed.


Results Reporting / Checking with Multiple Results in For Loop

In case there is any chance to use a template engine, then you should prepare your data first

$obj = drupal_json_decode($result);
$output = [];
foreach($obj as $row){
    if(!$value["IsArchived"] && !preg_match("/^123 ABC/", $value["ProjectName"])){
        $row['CommentStart'] = _abc_date($value["CommentStart"]);
        $row['CommentEnd'] = _abc_date($value["CommentEnd"]);
        $output[] = $row;
    }
}

and then output it (an exampe is using Twig template engine but the logic would be the same even with raw PHP)

{% for value in output %}

        {{ value["ProjectName"]}}
        ({{ value["CommentStart"] }} - {{ value["CommentEnd"] }})
        {% if lrnmore %}
            |
                 {{ lrnmore }}

        {% endif %}
        |
            View Comments

 {{ value["Description"] }}

{% endfor %}
{% if not output %}

No Records to Display

{% endif %}

this way you will have a clear separation between the business logic and display logic and as a bonus you will have HTML which is readable and maintainable.


If complexity is getting to high for a method it's usually a good idea to split out helper methods. If you end up to pass in the same parameters to each of these methods, it could also be a good idea to extract a class.
Some solution could be
def check_for_next_section(line, current_section)
  ZoneCheck.new(line, current_section).run
end

class ZoneCheck
  SECTION_HEADERS = {
    hawaii_1: '"[2] For Hawaii, the following Postal Codes are Zone 44 for Ground',
    hawaii_2: '"For Hawaii, the following Postal Codes are Zone 46 for Ground',
    alaska_1: '"[3] For Alaska, the following Postal Codes are Zone 44 for Ground',
    alaska_2: '"For Alaska, the following Postal Codes are Zone 46 for Ground'
  }.freeze

  def initialize(line, current_section)
    @line = line
    @current_section = current_section
  end

  def run
    if zones?
      :zones
    elsif hawaii_1?
      :hawaii_1
    elsif hawaii_2?
      :hawaii_2
    elsif alaska_1?
      :alaska_1
    elsif alaska_2?
      :alaska_2
    else
      current_section
    end
  end

  private

  attr_reader :line, :current_section

  def zones?
    current_section == :preamble &&
      line.starts_with?('Dest. ZIP')
  end

  def hawaii_1?
    current_section == :zones &&
      !line.blank? &&
      line.starts_with?(SECTION_HEADERS[:hawaii_1])
  end

  def hawaii_2?
    current_section == :hawaii_1 &&
      line.starts_with?(SECTION_HEADERS[:hawaii_2])
  end

  def alaska_1?
    current_section == :hawaii_2 &&
      line.starts_with?(SECTION_HEADERS[:alaska_1])
  end

  def alaska_2?
    current_section == :alaska_1 &&
      line.starts_with?(SECTION_HEADERS[:alaska_2])
  end
end


Things that just pop up in my mind when seeing the code (more of the architecture and robustness rather than language constructs):

1) Harcoding path to ini file

The path might have a meaning in your development environment, but it will mean nothing in a test or production environment. I would set it in an included file and use it from there. Something like:

$defaultConfigFilePath = "C:\Users\ashle\Miracle\config\config.ini";

in loadConfiguration
    $configFile = !isset($configFile) ? $defaultConfigFilePath : $configFile;

Hopefully, they will introduce a coalesce operator soon to simply write:

$configFile = $configFile ?? $defaultConfigFilePath;

2) Error handling

loadConfiguration function does not handle any incorrect formatting. Any line which is not in the format name=value will not be imported correctly.

You can explode into an $lineArray and check if elements are defined and exactly two.

3) A more powerful config reader

This is a good exercise, but ini files have a more complex format that seems to be handled by parse_ini_file function.


A slightly better option that takes a little more effort up front but saves a lot of time in the long run, and makes the code more readable (and the obfuscated word harder to crack) would be to follow this pattern...

First, create an NSString class category and fill that category with a readonly property for every character.

@interface NSString (Obfuscater)

@property (readonly) NSString *a;
@property (readonly) NSString *b;
@property (readonly) NSString *c;
// etc...

@end

Now, we write the accessor method, which will follow this pattern:

- (NSString *)a {
    return [self stringByAppendingString:@"a"];
}

And how does this work?

NSString *password = @"".p.a.s.s.w.o.r.d;

This is about the same as nesting stringByAppendingString: several times, with the inner most call being:

[@"" stringByAppendingString:@"p"];

We start with an empty string and append the first character, etc.

Now, this version, compared to the one proposed in the question, is slower, and becomes noticeably more slower with exceptionally long strings, but the obfuscation is better and the working code is more readable.


std::string/std::wstring template wrapper for Win32 API

I have not completed this but want to make my own template library for wrapping the Win32 API to make it compatible with std::string/std::wstring...
Is this a good idea?

If you have the time to do that as an exercise, probably (there should be a lot of effort involved).
If you want to create a library for future use with an intentional name clash, probably no.

Is it acceptable to undefine Windows API macros (e.g. #undef GetWindowText)?

Not really. If you are careful about it, you can make it work, but these macros can change, their implementation can change depending on where MS wants to take their API in the future and what is behind them may change. You are better off writing your library so that there are no name clashes with MS's macro names.

Is there perhaps a better way to do this besides changing the name scheme (e.g. getWindowText or GetWindowString as opposded to GetWindowText)? I prefer not to change the names.

No. You are better off using new names. Seeing the old names in code would make me (as a client of your lib) assume they have the same semantics, parameters and behavior as the WinAPI defines (macros and all). I would assume the names belong to WinAPI and look automatically to MSDN documentation if I had questions (as in, not in your library's documentation).
Using the same name would create confusion for other people using your code, for you as a developer (consider what happens when you have an error due to a macro name accidentally included where you define your API: you'd have errors caused by name clash in macro expansion, when you don't want the macro defined. For you it would be (almost) easy to fix, as you know the problem. Consider what happens though, when a client of your code writes:
#include <yourcode.h> // undefines macros and defines your interface
#include <windows.h>  // redefines macros and causes errors

This is an error that is easy to make for client code (especially for someone not familiar with the implementation details/constraints of your library) and it is something that you cannot enforce in your library code (you actually could, if you issue #error directives in your includes but that is as brittle as the whole concept - MS changes some implementation details and you have to update your code).
Also consider that your library would have to be complete from the start - if you only implement wrappers for what you need and discover you need a new API, you'd have to define a wrapper to use it - you will be unable to simply include the WinAPI headers and using it from there (as doing so would cause macro expansion clashes).

I prefer to deal directly with the Windows API; I just want to make it easier to work with std::basic_string.

Nothing is stopping you from wrapping the calls. Just don't undefine WinAPI function access macros and replace them with functions (using undefined macro names). You'd introduce a naming/include limitation in client code that would be hard to get around to in specific cases, and would only work with ugly workarounds in client code or by requiring modifications to your library).


Character class with name, gender, and inventory list

This is a very straightforward implementation. Not much to improve.

Especially copying the list passed in from the caller is a good safety measure, as it makes sure that, if the caller later modifies his list, this doesn't affect the Character's inventory. It's always a good idea that changing an instance's state is done by using its methods (so it can adjust itself appropriately, e.g. drop some items if the inventory becomes too heavy).

A few ideas to think about:

Similarly to the constructor, you can make the getInventory() method safe against a caller's attempts to modify the list, by encapsulating it in a read-only wrapper:

return Collections.unmodifiableList(inventory);

Then the caller can read the list, but not change it.

You might want to implement some more inventory methods to add, remove or find inventory items.

There also is a programming style where you wouldn't implement add, remove or find methods for the inventory, and have the getInventory() method return the internal list, allowing the caller to directly modify that list. But that breaks encapsulation and generally leads to quality problems, so don't do it that way.

Probably, the ordering of items in the inventory doesn't matter, so you could use a Set instead of a List (but then you can't have multiple instances of the same item).

And you could change the constructor parameter inventory from List to Collection, allowing the caller to pass the items as List or Set, whatever suits him better.

Maybe, when your project evolves, you'll find that inventory items could have their own properties and behaviour, so you might want to change from List<String> to List<InventoryItem> early.


Structure and style looks fine, although I have some general notes:

Prefer the strong (in)equality operators (!== and ===) whenever possible
Always use braces, even for one-line "blocks". It's nice to save a few keystrokes, but personally I prefer the consistency of always using braces
You could skip the defaults for the beforeSend, complete, etc. callbacks and leave them undefined. Defining them as empty functions is fine, but not necessary with the checks you're doing.

In terms of features/behavior:

I'd highly suggest simply modifying the user's settings, and then passing them to $.ajax(), rather than declare a new object. That way, users can set whatever extra ajax options they want, and not see them ignored. In other words, let your plugin fill in the blanks in the settings the user passes in, not the other way around.

Besides that:

You may want to skip elements that aren't actually forms
It'd probably be wise to use $form.data("dataType") instead of $form.attr() in case the data type was set using .data() and isn't a real attribute.
Speaking of data type, you should check if it's a string specifically, since that's the only thing jQuery wants anyway.
Lastly about the data type: I don't think your plugin should define a "json" default. Better to let the be defined explicitly by whomever is using the plugin, or leave it at jQuery's default.

Most importantly: Please forward any and all arguments to the callbacks. For instance, the regular beforeSend receives the XHR object and its settings, but if I specify a beforeSend using this plugin, I won't get those. Since the name's the same, I'd expect it to receive the same arguments. I like to use beforeSend to grab the XHR so I can use it as a Deferred/Promise object, but I can't do that here.

By the way, it'd be in the spirit of jQuery to invoke the callbacks in the element's context, not in the context of the jQuery wrapper around the element. But if you follow my suggestion of modifying the settings rather than replacing them, be sure to note in your documentation that this context-switching only applies to those four callbacks. E.g. if I declare a dynamic 201 callback to handle the 201 Created status code, it won't be called in the element's context (and I can think of a clean way to make it happen).

You may also want to get some of the form's attributes using .prop() instead of .attr(). For instance, a method attribute is not required (it'll default to "GET" in that case). Also, the accept attribute is worth checking and carrying over to the ajax options, if present.

Here's what I came up with (untested)

(function ($) {
  $.fn.ajaxForm = function (options) {
    options = $.extend({}, $.fn.ajaxForm.defaults, options);

    // A simple helper function
    function callHandler(name, form, args) {
      if(typeof options[name] === "function") {
        options[name].apply(form, [].slice.call(args, 0));
      }
    }

    return this.each(function () {
      var settings,
          form = this;

      settings = $.extend({}, {
        action:   $form.prop("action"),
        method:   $form.prop("method"),
        accepts:  $form.attr("accept"),
        dataType: $form.data("dataType")
      }, options);

      settings.beforeSend = function () {
        $form.addClass("ajaxForm-loading");
        callHandler("beforeSend", form, arguments);
      };

      settings.complete = function () {
        $form.removeClass("ajaxForm-loading");
        callHandler("complete", form, arguments);
      };

      settings.success = function () {
        callHandler("success", form, arguments);
      };

      settings.error = function () {
        callHandler("error", form, arguments);
      };

      $(this).on("submit", function (event) {
        event.preventDefault();
        $.ajax(settings);
      });
    });
  };

  $.fn.ajaxForm.defaults = {};

})(jQuery);


Problem 1: Monoid

One subtle problem here:

instance Monoid PigLatin where
  mempty :: PigLatin
  mempty = PigLatin ""

  mappend :: PigLatin -> PigLatin -> PigLatin
  mappend (PigLatin a) (PigLatin b) = PigLatin $ a ++ " " ++ b

While it may not seem it, this is in fact an invalid Monoid instance. When we write Monoid instances we want certain laws to hold true so we can reason about them more easily. One such law: mappend mempty x = x = mappend x mempty. We want mempty to act as an "identity element" (like adding zero to or multiplying one by an integer). The extra space character makes this impossible. If the Monoid instance had been lawful, we could have replaced foldl mappend mempty with mconcat.

So the first thing I would do is to excise this Monoid instance and instead use unwords, as we'll detail below. This approach has the advantage of letting us delete safeTail.

Problem 2: Slicing and dicing newtypes

The other thing we want to tackle is the problem of lifting String operations into our newtypes. We really want to lift unwords :: [String] -> String to unwords :: [PigLatin] -> [PigLatin]; that would obviate the need for the fold and the Monoid instance altogether. We also want to lift String -> String to PigLatin -> PigLatin, as evidenced by our plMap function. There's a similar problem with englishWords: we have a function String -> [String] but we want English -> [English] Haskell programmers are extraordinarily lazy and so we ask ourselves, how can we do this in the least amount of code possible?.

A common trick is to add a type variable:

newtype PigLatin a = PigLatin a
  deriving (Functor)

newtype English a = English a
  deriving (Eq, Functor, Foldable, Traversable)

This lets us derive instances for Functor, Foldable, and Traversable. It even admits an Applicative instance:

instance Applicative PigLatin where
  pure =
    PigLatin
  (<*>) (PigLatin a2b) (PigLatin a) =
    PigLatin (a2b a)

But why? Let's break down these typeclasses one by one.

Functor

One of our best friends. With Functor, plMap = fmap. The compiler automatically knows how to lift functions of type String -> String to PigLatin String -> PigLatin String. Not having to write any code is the best code there is. In fact, the compiler can even lift any type a -> a to PigLatin a -> PigLatin a even if in the end we only want to deal with PigLatin String values.

Foldable and Traversable

Having these two instances around permits the almight traverse. This humbly named function does something very very useful as it has type (a -> [b]) -> English a -> [English b], which is exactly what we need to lift words up through our English newtype. When we choose to equip English with a Foldable and a Traversable instance we are granted the keys to this wonderful kingdom. The end result is this function

englishWords :: English String -> [English String]
englishWords =
  traverse words

Which is hardly long enough to worth defining!

Applicative

I fibbed earlier as it turns out that traverse actually has type

(Applicative f, Traversable t) => (a -> f b) -> t a -> f (t b)

This unwieldy amalgam of variables and arrows can be broken down thusly. You can choose any types f, t and as long as there's an Applicative f and a Traversable t instance the compiler will do what you please.

Up above we chose f ~ [] (the list type) and t ~ English. What if instead we were to choose f ~ PigLatin and t ~ []? Well then we would have a very interesting function of type (a -> PigLatin b) -> [a] -> PigLatin [b].

Notice that wordToPig has type English String -> PigLatin String, which means traverse wordToPig would have type [English String] -> PigLatin [String], which is exactly what we want. Why?

sentenceToPig :: English String -> PigLatin String
sentenceToPig =
  fmap (capitalize . unwords) . traverse wordToPig . traverse words

Because that allows us to reach for our old friend fmap. capitalize . unwords takes [String] to String, which means when we lift it up with fmap we get a function PigLatin [String] -> PigLatin String. Exactly what we need.

Coercible, the hidden typeclass

One thing you may not be aware of is that GHC generates a Coercible instance for all newtypes. What this means is a little too complicated to go into detail here, but the end result is that you can type coerce (PigLatin "hello") :: String and get back "hello" :: String. Both the "hello" :: String and the PigLatin "hello" :: PigLatin String have the same in-memory representation, as guaranteed by the newtype keyword, and thus this poses no problem for the runtime. I like to use it for short scripts and it's especially handing for printing out newtypes. I noticed you defined a Show instance, and I think that's OK too. But I thought I'd bring it up since it's often overlooked.

Altogether now

{-# LANGUAGE DeriveFunctor     #-}
{-# LANGUAGE DeriveTraversable #-}

import Control.Monad (when)
import Data.Coerce (coerce)
import Data.Char (toLower, toUpper)
import System.IO (hFlush, stdout)

newtype PigLatin a = PigLatin a
  deriving (Functor)

newtype English a = English a
  deriving (Eq, Functor, Foldable, Traversable)

instance Applicative PigLatin where
  pure = PigLatin
  (<*>) (PigLatin a2b) (PigLatin a) = PigLatin (a2b a)

quitCommand :: English String
quitCommand = English "\\q"

wordToPig :: English String -> PigLatin String
wordToPig (English word@(x:_)) =
  PigLatin $ if isVowel x
             then word ++ "yay"
             else rearrangedWord ++ "ay"
  where
    rearrangedWord =
      drop (length initialConsonants) word ++ initialConsonants
    initialConsonants =
      takeWhile isConsonant word
    isConsonant =
      not . isVowel
wordToPig (English "") =
  PigLatin ""

isVowel :: Char -> Bool
isVowel letter = letter `elem` "aeiou"

sentenceToPig :: English String -> PigLatin String
sentenceToPig =
  fmap (capitalize . unwords) . traverse wordToPig . traverse words

capitalize :: String -> String
capitalize (x:xs) = toUpper x : map toLower xs
capitalize [] = ""

putStrNow :: String -> IO ()
putStrNow message = do
  putStr message
  hFlush stdout

prompt :: String -> IO (English String)
prompt promptInput = do
  putStrNow promptInput
  input <- getLine
  return $ English input

main :: IO ()
main = do
  input <- prompt "> "
  when (input /= quitCommand) $ do
    putStrLn . coerce $ sentenceToPig input
    main


First of all, that's not how hangman is usually implimented, but I won't question it, I'll only review your code.

1. Make sure your code actually works

You currently have an endless while loop. Your hangman() function does not do what it's supposed to, it does not update the value of i. Remove the 'i' variable entirely and change the main loop to "while(hangman()) { ... }". You should also remove the hangman() call at the end of your while loop (in the 'else' block), because it's not needed after this adjustment.

(note: that's the least  you should do. I'd suggest avoiding global variables entirely (you'll still have a global variable 'faults'), but changing that would require redesigning the whole code. You should at least change 'faults' to 'g_faults' to indicate that it's a global variable)

2. Adjust the output of your program

This is sort of a minor nitpick, but your output looks ugly. A space before user input and a newline char after 'correct!' should fix it.

3. Properly indent your code

Your code as it currently is is hard to read and understand, because it does not follow the common identation rules. I'll post your code with proper indentation later.

4. Don't use the NULL macro

Especialy in this situation, there is no need for it (correct me if I'm wrong). Simply write 'time(0)'.

5. Name your variables properly

The name of your variable should make clear what the varable does. Thus, your 'word' string should be 'current_word' or at least 'cWord', the 'checkAnswer' char should be 'currentLetter' or 'missingLetter' ect.

Sorta fixed code

#include <iostream>
#include <string>
#include <algorithm>
#include <time.h>

int faults = 0;
int hangman();

// No need for 'i' variable

int main(){
    // No need for NULL macro
    srand(time(0));

    // If you declare words[] inside the while loop, it gets created and destroyed every time the loop
    // executes. There is no need for that, thus you should declare the array outside of the loop
    std::string words[7]{"Alpha", "Cornwall", "Crepuscular", "Blind", "Steroid", "Plunder", "Talisman"};

    while (hangman()){
        std::string word = words[rand() % 7];

        // No need to separately declare and initialize the 'n' variable
        int n = rand() % word.length();
        char checkAnswer = word.at(n);

        // No need for an underscore variable, because you only use it once in your code.
        // One could argue that you should still keep the variable in case you wanted to change the
        // symbol, but your variable name indicates that it equals to '_', so you wouldn't use it
        // for that.(What I meant is if you wanted to change "A_pha" to, let's say, "A*pha")
        word.at(n) = '_';

        std::cout << word << ' ';
        char answer;
        std::cin >> answer;

        if (answer == checkAnswer){
            std::cout << "Correct!\n";
        }
        else{
            // Prefer ++a to a++. It doesn't matter in this case, but it's a good practice
            ++faults;
        }
    }
}

int hangman(){
    // Switch statement may have been more fitting here, but I'm too lazy to rewrite
    // your code, so do it yourself if you want to :P
    if (faults == 0){
    std::cout << "|----------------------" << std::endl;
    std::cout << "|                      |" << std::endl;
    std::cout << "|" << std::endl;
    std::cout << "|" << std::endl;
    std::cout << "|" << std::endl;
    return 1;
    }
    else if (faults == 1){
        std::cout << "|----------------------" << std::endl;
        std::cout << "|                      |" << std::endl;
        std::cout << "|                      O" << std::endl;
        std::cout << "|" << std::endl;
        std::cout<<"|" << std::endl;
        return 1;
    }
    else if (faults == 2){
        std::cout << "|----------------------" << std::endl;
        std::cout << "|                      |"<<std::endl;
        std::cout << "|                      O" << std::endl;
        std::cout << "|                      |" << std::endl;
        std::cout << "|" << std::endl;
            ;
        return 1;
    }

    else if (faults == 3){
        std::cout << "|----------------------" << std::endl;
        std::cout << "|                      |" << std::endl;
        std::cout << "|                      O" << std::endl;
        std::cout << "|                      |" << std::endl;
        std::cout << "|                     /" << std::endl;
            ;
        return 1;
    }
    else if (faults == 4){
        std::cout << "|----------------------" << std::endl;
        std::cout << "|                      |" << std::endl;
        std::cout << "|                      O" << std::endl;
        std::cout << "|                      |" << std::endl;
        std::cout << "|                      X" << std::endl;
        return 1;
    }
    else if (faults == 5){
        std::cout << "|----------------------" << std::endl;
            std::cout << "|                      |" << std::endl;
            std::cout << "|                      O" << std::endl;
            std::cout << "|                      |" << std::endl;
            std::cout << "|                      X" << std::endl;
            std::cout << "                       -" << std::endl;
        return 1;
    }
    else if (faults == 6){
        std::cout << "|----------------------" << std::endl;
        std::cout << "|                      |" << std::endl;
        std::cout << "|                      O" << std::endl;
        std::cout << "|                      |" << std::endl;
        std::cout << "|                      X" << std::endl;
        std::cout << "                      - -" << std::endl;
        return 1;
    }
    else if (faults == 7){
        std::cout << "|----------------------" << std::endl;
        std::cout << "|                      |" << std::endl;
        std::cout << "|                      O" << std::endl;
        std::cout << "|                      |" << std::endl;
        std::cout << "|                      X" << std::endl;
        std::cout << "                      - -" << std::endl;
        std::cout << "Dead.Dead.The hangman is dead!You lose!" << std::endl;
        return 0;
    }
    // Again, just a design nitpick, but your images of hangman with 6 and 7 faults are identical.
    // Shouldn't the hangman be dead after 6 faults then?
}


First of all, the Conversation class does not provide any events for chances, so nobody has a chance to get to know if something changes. This is already be implemented within an (Sorted)Observable collection, but unfortunately you publish this private field as IList<Message> by the Message method. So the notification abilities of this collection can not be used. Furthermore methods should always be connected with a action, so GetMessages() would be a more suitable name. But the best way is to make it a property.

using SoftConsept.Collections;

public class Conversation : INotifyPropertyChanged
{
    readonly SortedObservableCollection<Message> messages;

    public event PropertyChangedEventHandler PropertyChanged;

    public Conversation ()
    {
        messages = new SortedObservableCollection<Message> ();
    }

    private DateTime _updateTime = DateTime.Now;
    public DateTime UpdateTime{
       get{ return _updateTime;}
       private set{
           UpdateTime = value;
           OnPropertyChanged("UpdateTime");
       }
    }

    private void OnPropertyChanged(string propertyName){
       var handler = PropertyChanged;
       if(handler==null) return;
       handler(this, new PropertyChangedEventArgs(propertyName));
    }

    public void Add (Message message)
    {
        messages.Add (message);
        UpdateTime = DateTime.Now;
        message.PropertyChanged += OnMessagePropertyChanged;
    }

    private void OnMessagePropertyChanged(object sender, PropertyChangedEventArgs args)
    {
        UpdateTime = DateTime.Now;
    }

    public void Remove (Message message)
    {
        messages.Remove (message);
        UpdateTime = DateTime.Now;
        message.PropertyChanged -= OnMessagePropertyChanged;
    }

    public ObservableCollection<Message> Messages
    {
        get{
            //I assume that SortedObservableCollection is subtype of ObservableCollection
            return messages;
        }
    }
}

public class Message : INotifyPropertyChanged {}

So now some observer might register for changes in Messages (add, delete) and also for changes in the single Message instances.

For more info, look at Microsoft documentation:


Enforcing Paired Statements Using ScriptBlock

To be honest I feel this might be overcomplicating things.

I use Push-Location/Pop-Location in try/finally blocks when needed (like when loading the SQLPS module), but that's almost never.

For the most part I think one should avoid changing the current location and instead reference the desired path (either relative or absolute). So something like:

$p = $BasePath | Join-Path -ChildPath 'subfolder'
Get-ChildItem -Path $p

rather than:

$p = $BasePath | Join-Path -ChildPath 'subfolder'
Push-Location $p
try {
    Get-ChildItem
} finally {
    Pop-Location
}

As you've seen, there are also some issues with using scriptblocks in that way. You might have scope issues with variables, and call stack/execution context will be a bit different. This might get complicated further when you consider pipelines.

So in summary I'd rather avoid changing the working directory and then not obfuscate the process when I do so it's clear what's going on.


To me the code is a little hard to read in that you have an initialization function, metadata around events to be bound, the binding function, and the callbacks all at the same level in your events object.  How is this any better than just defining all the event bindings within a typical document.ready() block?  At least there, all your code for each binding is kept all in one place, rather than spread out across the different properties in this event object.

To me, something like the following is simply clearer (and would actually be more concise in terms of total characters needed to implement the functionality):

$(document).ready(function() {
    $('.js-settingsCollapse').on('click', function() {
        ...
    });

    $('.js-settingTrigger').on('click', function() {
       ...
    });

    ...
}

I also don't see how your framework will handle event delegation so as to allow for this approach to work with dynamically added elements.

Also, since you are really not using any functionality in jQuery which is not available in regular javascript, you might want to consider dropping the jQuery dependency.


Your terran is randomly generated, you may use a "transition" map like this:

transitions = {Tiles.land: [Tiles.sand] +
               [Tiles.tree] * 2 +
               [Tiles.land] * 5,
               Tiles.sand: [Tiles.water, Tiles.sand],
               Tiles.tree: [Tiles.tree, Tiles.land],
               Tiles.water: [Tiles.water] * 10
               }

It read "When you're near a land, you have a chance to peek sand, two to pick tree, and 5 to pick another land".

Then you may want to code something like this to pick a tile according to the neighbors:

def pick_tile_for(world, x, y):
    surrounding = []
    if x > 0:
        surrounding.append(world[x - 1][y])
    if y < len(world) - 1:
        surrounding.append(world[x][y + 1])
    if y > 0:
        surrounding.append(world[x][y - 1])
    if x < len(world) - 1:
        surrounding.append(world[x + 1][y])
    surrounding = [tile for tile in surrounding if tile is not None]
    if len(surrounding) == 0:
        return None
    excluded = set(surrounding[0])
    for tile in surrounding:
        excluded = excluded - set(transitions[tile])
    next = list(chain(*[[t for t in transitions[tile] if t not in excluded]
                        for tile in surrounding]))
    return choice(next)

Finally you may want to use this "not so random" tile picker:

def generate(world_size):
    system('cls' if name == 'nt' else 'clear')
    world = []
    for x in range(world_size):
        world.append([None for _ in range(world_size)])
    world[choice(range(world_size))][choice(range(world_size))] = Tiles.land
    for x in range(world_size):
        for y in range(world_size):
            if world[x][y] is None:
                world[x][y] = pick_tile_for(world, x, y)
    for x in range(world_size - 1, -1, -1):
        for y in range(world_size - 1, -1, -1):
            if world[x][y] is None:
                world[x][y] = pick_tile_for(world, x, y)
    for line in world:
        print ''.join(line)

Note that I'm iterating the world twice, one in reverse, because my "first land" is randomly placed, I do not start from a corner, the world is built around the first randomly placed land.

I think there may be a lot of better ways to do this, but it was fun to do. You also may try to read about "flood fill".

Ceveat: I'll never build rivers with this kind of algorithm.


DRY - don't repeat yourself - basically means that you should extract repeated logic into methods.

In this case you're repeating

checking validity
creating Date instances (if they're valid, you should just create them, and then compare them; it's madness to create them for the comparison only to re-create them a few lines later)
... and for each of those, you're extracting 3 specific values from a params hash

So you could for instance do this instead:

# Returns a Date, or nil if the input isn't valid
def params_to_date(params = {})
  args = %w(year month day).map { |k| params[k] }
  Date.new(*args) if Date.valid_date?(*args)
end

# ...

def some_controller_action
  from_date = params_to_date(params[:from])
  to_date = params_to_date(params[:to])

  if from_date && to_date && from_date < to_date
    run_report(from_date, to_date)
  else
    redirect_to :back, alert: "Please provide valid date values."
  end
end


First off, your formatting is not very good.  It makes it difficult to read.  I would suggest looking at your IDE's menu options and use the format command.

It seems like you're trying to reinvent the wheel here. The <ios> header contains that option already.  To write the vector to a file as base 16 numbers, you can do that directly in the writeFile function:

void writeFile(std::string_view str, std::vector<unsigned char> const & v)
{

    assert(str.data() != nullptr);
    std::ofstream f(str.data(), std::ios::binary);
    for(auto c : v)
    {
        if(f.is_open())
        {
            f << std::hex << (int)c;
        }
    }
    f.close();
}

If creating the string is more to the point than writing to the file, you can use a stringstream and do the same thing:

#include <sstream>

std::string hexify(std::vector<unsigned char> const & v)
{
    std::stringstream ss;
    for(auto c : v)
    {
        ss << std::hex << (int)c;
    }
    return ss.str();
}

If characters with single digit character codes are to be used and the leading 0 is required, it's simply a matter of adding a couple of functions from the <iomanip> header:

<< std::setw(2) << std::setfill('0') << std::hex << (int)c

If reinventing the wheel is the point, first there's a tag for that.

When you have a need for literal (magic) use a constant variable. It gives meaning to anonymous values.

Generally speaking when you're using iterators in a loop, since end() is past the last element, it's better to use not equals(!=) instead of less than.


Converting Roman numerals to integers and vice versa

def int_to_roman (integer):

    returnstring=''
    table=[['M',1000],['CM',900],['D',500],['CD',400],['C',100],['XC',90],['L',50],['XL',40],['X',10],['IX',9],['V',5],['IV',4],['I',1]]

The element in your list should really be tuples not lists. It should also be a global constant so that you can reuse across both functions.

    for pair in table:

Use for letter, value in table: rather then indexing the tuples.

        while integer-pair[1]>=0:

I think the code looks better with spacing around binary operators. Also why this instead of: while integer >= pair[1]:?

            integer-=pair[1]
            returnstring+=pair[0]

It'll probably be better to create and append to list and then join the list elements together at the end.

    return returnstring

def rom_to_int(string):

    table=[['M',1000],['CM',900],['D',500],['CD',400],['C',100],['XC',90],['L',50],['XL',40],['X',10],['IX',9],['V',5],['IV',4],['I',1]]
    returnint=0
    for pair in table:

        continueyes=True

Whenever I use a logical flag like this, I think: it should be removed. I figure that flags like this only serve to confuse the logic of what you are doing. i think a break is clearer then setting a flag.

        while continueyes:
            if len(string)>=len(pair[0]):

                if string[0:len(pair[0])]==pair[0]:

strings have a funciton: startswith that does this. You should use it here. There is also need to check the length. If you take a slice past the end of a string in python, you just get a shorter string.

                    returnint+=pair[1]
                    string=string[len(pair[0]):]

                else: continueyes=False
            else: continueyes=False

    return returnint

My version of your code:

def int_to_roman (integer):
    parts = []
    for letter, value in TABLE:
        while value <= integer:
            integer -= value
            parts.append(letter)
    return ''.join(parts)

def rom_to_int(string):
    result = 0
    for letter, value in table:
        while string.startswith(letter):
            result += value
            string = string[len(pairs[0]):]
    return result

One last thought. Your rom_to_int doesn't handle the case where an invalid string is passed. You might want to consider having it throw an exception or something in that case.


I think your main problem is that you're using iterate where partitioning and mapping would work just fine.

I would create a simple helper function that splits the input line-seq into cases. Normally you could use partition for this, but since the number of lines can vary from case to case, you would have to use loop/recur. (See my split-cases function below. Also, note that we don't really care about the number of cases on the first line; we completely ignore it via destructuring.)

Now, believe it or not, all you have to do is map your parse-grid function over the result of (split-cases ...) and you'll end up with a list of sets of coordinates, one for each case.

I think your parse-grid function is very nice. It's concise and it makes good use of map-indexed and destructuring. The only thing I would tweak is that I would leverage the built-in :when syntax of Clojure's for macro to filter out the coordinates of the non-# characters. Then you can take out the filter identity part because there are no longer any nil values to remove.

So, here is how I would revise your code:

(defn split-cases [[_ & lines]]
  "Returns a seq of cases, each of which is a seq of #/. lines."
  (loop [result []
         [number-of-lines & lines] lines]
    (if (seq lines)
      (recur (conj result (take number-of-lines lines))
             (drop number-of-lines lines))
      result)))

(defn parse-grid [grid]
  "Parses a text grid of .s and #s and returns a set of coord
   pairs for each # element"
  (set (for [[row line] (map-indexed vector grid)
             [col c]    (map-indexed vector line)]
             :when (= c \#)]
         [row col])))

(defn read-stdin []
  (line-seq (java.io.BufferedReader. *in*)))

(defn parse-cases-stdin []
  (map parse-grid (split-cases (read-stdin))))


//if I don't write this loop, the 0s get printed as 3452816845....Why???

Because malloc doesn't initialize an allocated memory. It contains garbage. You may avoid the explicit loop by using calloc.

As a side note, prefer sizeof(variable) to sizeof(type), e.g.

board[i] = malloc(sizeof(*board[i]) * sizeOfBoard);

This way, if you ever change the type of board squares, this line wouldn't change. No double maintenance.
The code adds queens into the rows sequentially. There is no need to test lower diagonals: there are no queens there yet.
Working with the entire 2-dimensional board is an overkill. A one-dimensional array of queen files suffices. Besides, testing for placement safety becomes much simpler:

bool is_safe(int * queens, long long row, long long col, long long dim) {
    for (long long rank = 0; rank < row; rank++) {
        if (queens[rank] == col) {
            // Another queen is at this column already
            return false;
        if ((row - rank) == abs(queens[rank] - col)) {
            // A square is under diagonal attack
            return false;
        }
    return true;
}

A for having all the solutions, do not break the loop when retVal == 1, and

if (row_index == boardSize) {
    do_something();
    return 1;
}

where do_something() may print the board, or save the board in a global state, or whatever suites your needs.


Refactor code to solve the 'Line is too long' error in rubocop

I'd just write the call with one line per key/value:

Method.create(
  domain_id: domain.id,
  type_notification: type,
  message: title,
  url: url,
  owner_id: user.id
)

Note that the explicit reference to self in method calls is not idiomatic (check the unofficial Ruby style guide for this and other useful tips).

Also, since Method is a class name already in the core, is not a good idea to have a model what that name.


Project Euler #8 - "largest product in a series"

This is probably not a good idea:

while (ifs.good()) {
  string line;
  getline(ifs, line);
  series += line;
}

You should be checking the stream itself, not the current state of the stream.  This can be done by putting the stream read (getline() in this case) inside the loop statement.

Also, as getline() (which uses line) will be moved out of scope after this change, you'll need to initialize line before the loop.

string line;

while (getline(ifs, line)) {
    series += line;
}

This will both attempt the read and determine if it was successful.  If it wasn't, specifically if the end of the file has been reached, then it will fail, and the loop will terminate.  See this answer for more info.
Your compiler should've warned you about this type-mismatch:

for (size_t i = 0; i < DIGITS_IN_PRODUCT; i++)

The loop counter type should be an int to match the constant's type.


Linking input/output states and conditions in an input file

Your main questions

  The script works, although I do not have large data to test against.

You don't necessarily need a large dataset.
It's better to think of all possible corner cases.
For example, your sample data demonstrates failures of OUTCOND but not of INCOND.
Also, although there is an example of more than one outgoing links,
but there is no example of more than one incoming links.
There are not too many interesting cases,
if you add examples for all them,
then you can be fairly confident in your solution.

  The script will break if some cond has the character delim in the name

If you want to be really safe, you could add a sanity check for that, and raise an error when such name is found, for example by calling exit with a non-zero value.

  The script might break (and/or return false positives) if a line is inserted twice or if two lines have the same jname.

Ditto.

Simplify

Many things can be simplified in this code.

The conds[""]=0; is unnecessary, you can simply delete that line.

Instead of this:

icnd_size = split($2, incond_list, " ");

for (i=1; i<=icnd_size; ++i) {
conds[incond_list[i] delim $1]++;
}

You don't really need the return value of split,
because instead of a counting loop,
you can use a more idiomatic for-each loop:

split($2, inconds, " ");

for (i in inconds) {
    conds[inconds[i] delim $1]++;
}

The same goes for outconds as well.

Mutually exclusive if statements

These if statements cannot be both true at the same time:

if (conds[i] == 1) {
    # ...
}

if (conds[i] == -1) {
    # ...
}

So they should be chained together with an else if.

Formatting

Instead of this:

for (i=1; i<=ocnd_size; ++i) {
conds[$1 delim outcond_list[i]]--;
}

It would be better to write like this:

for (i = 1; i <= ocnd_size; ++i) {
    conds[$1 delim outcond_list[i]]--;
}

Naming

Some of the names are not so great.
For example sz, i, j, c in the END block.
sz is actually unnecessary,
and I would rename the others to pair, job, and cond,
respectively.

Putting it together

Consider this alternative implementation:

#!/usr/bin/awk -f

BEGIN {
    FS = " *; *";
    delim = "-";
}

{
    split($2, inconds, " ");

    for (i in inconds) {
        conds[inconds[i] delim $1]++;
    }

    split($3, outconds, " ");

    for (i in outconds) {
        conds[$1 delim outconds[i]]--;
    }
}

END {
    oformat = "Invalid %s %s on job %s\n";
    for (pair in conds) {
        split(pair, parts, delim);

        if (conds[pair] == 1) {
            job = parts[2];
            cond = parts[1];
            inorout = "INCOND";
        } else if (conds[pair] == -1) {
            job = parts[1];
            cond = parts[2];
            inorout = "OUTCOND";
        }
        if (conds[pair] != 0) print "Invalid", inorout, cond, "on job", job;
    }
}


Name Spaces
A most common practice is to preface types and functions supplied by the
Standard Template Library, sometimes known as the Standard Library with
std:: rather than ignoring names spaces by the statement

using namespace std;

This will become quite helpful as the problems and code become more complex
and you need to include other name spaces. Some languages such as C don't
support namespaces, however, C++ does and it is quite a useful feature.
More complex programs may use multiple name spaces and each one of these
name spaces can contain a definition for functions such as sort() or
find_if(), or overrides on operators such as <<. You may even need to
write your own sort() or find(). Using std::sort allows you not to
create your own name space when you write your own sort() with the same
arguments.

Initialization of Empty Containers
There is no need for the empty braces on this line:

    vector<int> indices = {};

The vector container class has a constructor that will initialize an empty
vector properly.

    vector<int> indices;

Use the Features of the Container Classes and the Standard Template Library
You may find this website useful for learning all of the features a
particular container class or the standard library.

There are definitely some functions you could be using, such as
std::find(), std::find_if(), std::count_if() and std::string::substr() that could definitely shorten the code.

It might be wise to investigate std::map as well for counting words.

GOTO
There are almost always ways to avoid using goto in C++. In rare cases
goto may be appropriate for error handling, more so in C than in
C++ because C++ has try{}/catch{} and exceptions.

In the following code there is really no reason to use a goto:

vector<string> deleteNumbers(const vector<string>& data) {
    vector<string> tr = {};
    for (unsigned int i = 0; i < data.size(); i++) {
        for (char c: data[i]) {
            if (string("0123456789").find(c) == -1) continue;
            else goto mainLoop;
        }
        tr.push_back(data[i]);
        mainLoop: continue;
    }
    return tr;
}


N rotations of an array, either left or right, and then printing the result

There are two basic ways to solve this type of problem.  One is having to do the rotation in place, where you can't allocate additional storage for a copy of the array.  This uses less memory but takes longer, since the rotations have to go by small increments (usually 1, since that is easiest to implement).  The other way is to do the rotation into a copy.  This has the advantage of being faster but can take additional memory.  Your implementation is a hybrid of both.

Don't write using namespace std;.

You're passing all your vectors by value, which will result in copies being made.  Since you're making a new vector to store the rotated vector in, you can pass them by const &.  For example,

std::vector<int> rotate(const std::vector<int> &myVector, int direction);

print can take advantage of range based for loops:

void print(const vector<int> &rotatedVector) {
    for (int v: rotatedVector){
        std::cout << v << '\n';
    }
}

This also avoids using endl, since that will do a flush which can greatly slow the rate output is displayed.

Your two parameter rotate function can rotate by more than one element at a time.  You can combine the two rotate functions into one, with an offset of -direction * count instead of -direction.  (With appropriate code to precalculate that value and a check so that the result is not larger than -length to avoid having a negative number on the left of %.)


I have some high-level advice based on a cursory read of your code. It would really help if you could refactor it into multiple methods as this function is too long and does too much. That won't help your speed, but it will make it easier for others to grok your code and provide more advice.

Profile your code

You can't hope to make things faster in an orderly fashion without finding out what parts take the most time. Yes, you can devise a faster algorithm, but you might end up spending days optimizing an O(n^2) algorithm to O(log n) only to find out that part took 1ms anyway.

Split each word first

If you only split at word boundaries, you may as well seek forward for a boundary and extract the substring in one call.

Calculate word widths instead of letter widths

First, when I wrote a similar function in Java many years ago, the cost of calling calculating the width of a string had a fairly high overhead that didn't change with the length of the string. Getting the width a character at a time was significantly more costly than calculating the length of a word. Also, since there may be kerning involved that adjusts the space between letters based on the letter pairs, you can't add up the character widths to arrive at the word width.

If you end up needing to split a word midway, use a binary search to find the cutoff point

This goes with the two above, but you won't really know the best route until you profile.

Make sure you're not using a linked list

You add the string to the list (vector?) and modify it for each character. If this is a linked list instead of an array, it will be very costly. I'm not very familiar with the STL if that's what you're using (those declarations would help), so maybe it maintains a tail pointer. In any case, I would build each line and add it to the list only once it's complete even if you're using an array-based vector. It just seems cleaner.

Show a disabled scroll bar instead of restarting once you determine that scrolling is necessary

Really, a disabled scroll bar isn't that horrendous. ;)

Calculate the widest line as you wrap

I'm betting that the work done in updateWidestLine() is very similar to what you're already doing in makeLinesFromWordWrap(). Take advantage of that and maintain a maxLength local variable as you do the wrapping.


What is the best way to deal with multiple return types in Python's is_number?

I am disregarding some questionable code (such as the fact that '3,,,4' would be handled identically to '34', and so forth), and as you mention, the fact that locale's atof is probably more fitting than write-your-own. I am doing so because, worse than those, I really don't like the return_type parameter and its usage.

I would strongly suggest separating this into two functions. For example a to_number which acts like return_type='n', or even throws an exception instead of returning None, and an is_number which calls to_number and converts the exception or None to False, and other values to True. Each function would have very simple usage thanks to very simple definitions, and their code would become simpler accordingly.


As you pointed out, you don't actually need to lay the characters out into a grid.  It would be more efficient to use arithmetic to figure out the indexes of the characters in each row.

For example, if num_rows is 3, then each down-up cycle will consist of 4 characters.  (zigzag_size = 2 * num_rows - 2).  Then we also know that the top of each zigzag will consist of indexes 0, 4, 8, 12, … of the string (for z in range(0, len(s), zigzag_size)).

The middle row will consist of indexes z+1 and z+3.  The bottom row will consist of indexes z+2.  The zigzag_indexes() generator generalizes those calculations for any numRows.

import math

def zigzag_indexes(num_rows):
    yield (0, math.inf)                             # Top of each zigzag
    yield from zip(
        range(1, num_rows),                         # Downward
        range(2 * num_rows - 3, num_rows - 1, -1)   # Upward
    )
    yield (num_rows - 1, math.inf)                  # Bottom of each zigzag

def convert(s, num_rows):
    if num_rows == 1:
        return s
    zigzag_size = 2 * num_rows - 2
    return ''.join(
        (s[z+a] if z+a < len(s) else '') + (s[z+b] if z+b < len(s) else '')
        for a, b in zigzag_indexes(num_rows)
        for z in range(0, len(s), zigzag_size)
    )

print(convert('PAYPALISHIRING', 3))