Watch out!

jQuery is full of secrets. html method is not just a simple wrapper around innerHTML property.

Possible fail condition:

var src = `if ("<x/>" !== "<" + "x" + "/" + ">") {
  console.log("Math gone wrong.");
}`;

$("<script>").html(src).appendTo(document.head)
<!-- latest jQuery -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

Let's see what exactly is happening here:

console.log($("<i>").html("<x/>")[0].innerHTML)
<!-- latest jQuery -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

jQuery html method replaces <x/> with <x></x>. I guess it is perfectly valid for some HTML, but it fails with our JavaScript input.

The π robbery

Let's try to exploit this with malicious input and steal some valuable data:

var src = `var username = "Kevin <x\";alert(Math.PI);\"/> Mitnick";`;

$("<script>").html(src).appendTo(document.head);
<!-- latest jQuery -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

I suggest you to carefully check jQuery html source code.

Also you may replace it with plain old innerHTML.


An attempt at inheritance (Geometric Shapes)

A second concern is how to prevent creation of Shape objects, since it only represents a concept and nothing tangible. I'm guessing to do this I would need to define the destructor as pure virtual - although I have not reached this stage of reading.

Yep:

class Shape{
public:
    virtual ~Shape() = 0;
};
Shape::~Shape() {}

Now you can't create objects of Shape.


Calculate proper dosage of supplements to take

Here is the list of things I would improve:

for handling the proper answer on the "Are you going to the gym today?", I would start the while loop until "Yes" or "No" is entered
put the execution logic under if __name__ == '__main__':
define a message template with appropriate placeholders - format it with "day on" or "day off" objects and the entered username
define constants in upper case as per PEP8
let the "dosage" function return the dosage object - print the message outside of the function - for the better logic separation
add meaningful comments and docstrings

The code with all the suggested changes applied:

DAY_ON = {
    "BCAA": "10g",
    "White": "50g",
    "Glutamine": "20g",
    "Vitamins": 10
}

DAY_OFF = {
    "BCAA": "5g",
    "White": "25g",
    "Glutamine": "10g",
    "Vitamins": 5
}

MESSAGE_TEMPLATE = """
{username}, you have to take:
    BCAA in dosage of: {obj[BCAA]}
    White in dosage of: {obj[White]}
    Glutamine in dosage of: {obj[Glutamine]}
    Vitamins in number of: {obj[Vitamins]}
"""

def get_dosage(is_training_day):
    """Returns appropriate dosage depending on whether it is a training day or not"""
    return DAY_ON if is_training_day else DAY_OFF

if __name__ == '__main__':
    username = input("What is your name?\n")

    while True:
        choice = input("Are you going to the gym today?\n")

        if choice in ('Yes', 'No'):
            break
        else:
            print("You can only enter 'Yes' or 'No'.")

    dosage = get_dosage(is_training_day=choice == 'Yes')
    print(MESSAGE_TEMPLATE.format(username=username, obj=dosage))

Demo:

$ python3 test.py
What is your name?
Chubaka
Are you going to the gym today?
What?
You can only enter 'Yes' or 'No'.
Are you going to the gym today?
No

Chubaka, you have to take:
    BCAA in dosage of: 5g
    White in dosage of: 25g
    Glutamine in dosage of: 10g
    Vitamins in number of: 5

If you are using Python3.6+, you can also use f-strings for string formatting:

dosage = get_dosage(is_training_day=choice == 'Yes')
print(f"""
{username}, you have to take:
    BCAA in dosage of: {dosage['BCAA']}
    White in dosage of: {dosage['White']}
    Glutamine in dosage of: {dosage['Glutamine']}
    Vitamins in number of: {dosage['Vitamins']}
""")


What is the more effective way to get array of data out of xml for d3 chart?

I suggest you use JSON when manipulating the data because it's easier and less code compared to the same XML counterpart code - and much easier.

I can think of two ways you can do this:

Convert your files to JSON, if you can.
If you can't convert to JSON files, stay with what you are doing, and read the XML but convert them to JS objects before handing them over to the chart. There are XML-to-JSON libraries out there which you can use.

A similar data structure in JSON would look like

{
  "testcase" : {
    "measurement" : [
      {
        "type" : "M8015",
        "interval" : 15
      },{
        "type" : "M8016",
        "interval" : 15
      },{
        "type" : "M8020",
        "interval" : 15
      }
    ]
  }
}

And it's a matter of plucking out the data:

var myData = data.testcase.measurement;


Two script completing the same task, which is the best way?

$string = '1/2/3/4';

$change = str_replace('/',',',$string);

$result = $connection->query("SELECT id, filename FROM pages WHERE id IN($change) ORDER BY FIELD(id,$change)");

$new_string = "";
while($row = $result->fetch_assoc()) {
     $new_string .= $row['filename']."/";
}

$new_string = substr($new_string,0,-1);

echo $new_string;

Less looping - the match[] = $row was unnecessary IMO because you want a string back only...so you concatenate the file name with a / delimiter and then the last slash is removed with sub_str.

Updated the fixes including single query match.


Doc comments for public methods are indispensable.

I'd probably just use a foreach-loop and a DIY stack:

/** @return input stripped of all abutting identical characters */
static String solve(String input) {
    char []remains = new char[input.length()];
    int top = -1; // highest valid index

    for (char c: input.toCharArray())
        if (top < 0 || c != remains[top])
            remains[++top] = c;
        else
            --top;

    return top < 0 ? "Empty String"
        : new String(remains, 0, top+1);
}


Printing the month name for the month number

As you have probably noticed, there is a lot of repetition which we can take advantage of. We can declare an array containing all the string representations of the months like so.

String[] months = {"January", "February", "March", ..., "December"};

Once you have that, we can simply do:

if (num >= 1 && num <= 12) {
    System.out.format("The name of month number %d is %s\n", num, months[num-1]);
} else {
    System.out.println("You have entered an invalid number");
}

Edit: sorry, just saw the bit about "by still using the switch statement". I'll still leave this here though because I think it's a better solution than a switch statement.

If you really insist on using the switch (but you shouldn't),
then you can at least extract the repeated string part and formatting logic to a helper method:

private static void printMonth(int num, String name) {
    System.out.printf("The name of month number %d is %s%n", num, name);
}

And then rewrite the switch using that method:

switch (num)
{
case 1:
    printMonth(num, "January");
    break;
case 2:
    printMonth(num, "February");
    break;
// .... and so on

But really, insisting on a switch here is forced,
and goes against good practices.


ServiceBus QueueClient and TopicClient object resue

Having topicClient and queueClient as class fields is unnecessary here, and potentially leads to exception scenarios.

For example, if you were to create a new MessageBroker and immediately call Dispose() without first calling both the other methods then a NullReferenceException will be thrown as topicClient and queueClient are only defined within these methods.

An alternative could be to make use of the using syntax to instantiate a client and dispose of it when done. e.g.

using(var topicClient = TopicClient.CreateFromConnectionString(appConfiguration.BrokerConnectionString, topicName))
{
    BrokeredMessage brokeredMessage = new BrokeredMessage(message);
    await topicClient.SendAsync(brokeredMessage);
}

Using this approach would allow you to remove the IDisposable implementation.

If you want to be able to re-use the same topicClient and queueClient then you could have a MessageBroker for a specific queueName and/or topicName, and define the clients from the constructor.
(Creating new MessageBrokers as necessary for new queue and topic names.)

public class MessageBroker : IMessageBroker, IDisposable
{
    private readonly TopicClient topicClient;
    private readonly QueueClient queueClient;

    public MessageBroker(IAppConfiguration appConfiguration, string queueName, string topicName)
    {
        this.queueClient = QueueClient.CreateFromConnectionString(appConfiguration.BrokerConnectionString, queueName);
        this.topicClient = TopicClient.CreateFromConnectionString(appConfiguration.BrokerConnectionString, topicName);
    }

    public async Task SendMessageToQueueAsync(string message)
    {
        BrokeredMessage brokeredMessage = new BrokeredMessage(message);
        await queueClient.SendAsync(brokeredMessage);
    }

    public async Task SendMessageToTopicAsync(string message)
    {
        BrokeredMessage brokeredMessage = new BrokeredMessage(message);
        await topicClient.SendAsync(brokeredMessage);
    }

    public void Dispose()
    {
        this.queueClient.Close();
        this.topicClient.Close();
    }
}

If you have need of only one MessageBroker (i.e. one topicName and queueName) then this will be sufficient, and an instance of this can be registered within your DI.

Otherwise, you will need some sort of MessageBrokerFactory which can be used to create a MessageBroker for a given queue/topic name, that can then be re-used.

public MessageBrokerFactory {
    private readonly IAppConfiguration appConfiguration;

    public MessageBrokerFactory(IAppConfiguration appConfiguration)
    {
        this.appConfiguration = appConfiguration;
    }

    public IMessageBroker Create(string queueName, string topicName)
    {
        return new MessageBroker(
            this.appConfiguration,
            queueName,
            topicName);
    }
}


Implementing Gaussian integers in Haskell

This looks good. All necessary type signatures are there, no type is too strict nor too generic. The indentation style is familiar, and the braces on data Gaussian are easy to read, so no worries about that.

However, there are a few oddities. Let's face them.

Num's signum

There aren't any laws for Num in the Haskell report, however there are some expectations. The operations on (+) and (*) should implement a ring and that's certainly true here. However, Num's documentation indicates that the following should hold:

abs x * signum x = x -- (1)

Unfortunately, we cannot take the easy way and just use

signum x = x / abs x

since the result is unlikely to be in Gaussian's domain. As we cannot hold (1), we're free to do whatever we want, but it should be reasonable. How does it become reasonable? By documenting your decision:

signum = id -- < your documentation here >

Prefix vs. postfix documentation

That took me by surprise. Most of Haskell's documentation is placed before the documented item, not after. The same holds for most other documentation in other languages, where the documentation is placed before or in the function itself:

/** @brief Calculates the absolute value of a Gaussian integer.
 *  @param x is a Gaussian integer
 *  @returns x's absolute value
*/
int g_abs(gint x) {
    return x.r * x.r + x.i * x.i;
}

def g_abs(x):
    """Returns the absolute value of x"""
    return x.r * x.r + x.i * x.i

The usual Haddock documentation also placed the documentation before the item, although it's possible to use postfix.

You're welcome to stay in the postfix style, but you should indicate that your documentation refers to the preceding item, for example with Haddock's ^:

i :: Gaussian
i = 0 :+ 1
--^ The imaginary unit, equal to sqrt(-1).

That removes possible ambiguity.

two = 2 :: Integer and x ^ two

The line two = 2 :: Integer violates the DRY principle, thus any optimization or bugfix on x ^ two needs to get repeated throughout the program, which is error prone.

However, there is a greater issue. GHC rewrites x ^ 2 to x * x (see Note [Inlining (^) in base's documention). An explicit variable might hinder that process.

Instead, you should provide a square function or just immediately multiply a value with itself. Both variants will get rid of the warnings and additional bindings, for example:

--| The Num instance for Gaussian.
--  We use the euclidean norm as abs. norm(a + bi) = a^2 + b^2
instance Num Gaussian
  where
    ...
    abs (a :+ b) = (a * a + b * b) :+ 0
    signum = id -- chosen at random
    ...

By the way: if you chose square x = x ^ (2 :: Int) you won't need to repeat your documentation.

Precision

You always want to stay as precise as possible, unless you are aiming for speed. Therefore, you should try to stay in exact types till the very last moment in magnitude.

Instead of

magnitude :: Floating c => Gaussian -> c
magnitude (a :+ b) = sqrt $ (square $ fromInteger a) + (square $ fromInteger b)

use

magnitude :: Floating c => Gaussian -> c
magnitude (a :+ b) = sqrt $ fromInteger (square a + square b)

You could also reuse abs if you split it into two functions:

instance Num Gaussian where
    ...
    abs x = (absIntegral x :+ 0)
    ...

absIntegral :: Gausian -> Integer
absIntegral (a :+ b) = square a + square b

magnitude :: Floating c => Gaussian -> c
magnitude = sqrt . fromInteger . absIntegral


Time spent by product in process represented by clockin and clock out

I'll attempt to provide something helpful, even though this is old.

To  start with, just syntax-wise, [brackets] are only required if your column name contains a reserved character, such as a space or apostrophe. It looks less cluttered if you don't use them unless needed, and I don't see any need for it in your columns.
Line breaks and tabs make code much easier to read. I know Access is quite limited in the amount of formatting you can do and doesn't allow comments, but every bit helps.
I notice a lot of redundancy in your Iif statements. 3 statements result in ([CLOCK_OUT]-[X])*24*60. 2 statements result in ([Y]-[CLOCK_IN])*24*60. And 4 statements all result in 60 if true. My thought is to group these together as 3 subqueries and use WHERE instead of Iif to sort out the results.

Here is how I would write this. Note I used Your_Table_Name since your code doesn't say, make sure you replace this with the actual table name.

SUM(
    (
    SELECT ((CLOCK_OUT - X) * 24) * 60
    FROM Your_Table_Name
    WHERE CLOCK_IN < X AND X < CLOCK_OUT AND CLOCK_OUT < Y
    OR X < CLOCK_IN AND CLOCK_OUT = Y
    OR X = CLOCK_IN AND CLOCK_OUT < Y
    )
    +
    (
    SELECT ((Y - CLOCK_IN) * 24) * 60
    FROM Your_Table_Name
    WHERE X < CLOCK_IN AND CLOCK_IN < Y AND Y < CLOCK_OUT
    OR  X < CLOCK_IN AND CLOCK_IN < CLOCK_OUT AND CLOCK_OUT < Y
    )
    +
    (
    SELECT 60
    FROM Your_Table_Name
    WHERE CLOCK_IN < X AND Y = CLOCK_OUT
    OR CLOCK_IN = X AND Y < CLOCK_OUT
    OR CLOCK_IN < X AND X < Y AND Y < CLOCK_OUT
    OR X = CLOCK_IN AND Y = CLOCK_OUT
    )
)


List replication problem from Hacker rank

Use scala.collection.generic.SeqFactory.fill(n:Int)(elem: =>A) instead of your self written one:

def listReplication(num:Int,arr:List[Int]):List[Int] = {
      arr.flatMap(each => List.fill(num)(each))
}

Also note that listReplication is a nice candidate for generics:

def listReplication[A](num:Int,arr:List[A]):List[A] = {
      arr.flatMap(each => List.fill(num)(each))
}

That way you can also handle lists that contain something else than Int.


Lets say you defined a module like so after the bootstrap:

myModule = angular.module('myModule',[]);

You can inject this module into ngMeteor after the bootstrap like so:

ngMeteor.requires.push('myModule');

You could easily group your controllers, directives, filters and services into separate modules and then add them to your app level module using this method. However, grouping your controllers, directives, filters and services into separate modules and then injecting it into your app level module is only one of many possible ways to organise your AngularJS app. If you're using AngularJS with MeteorJS, it would be easier to simply attach your controllers, directives, filters and services to the ngMeteor module because you have the ability to scatter these in whatever combination of javascript files as you like without having to enumerate them in your app level module.

For example, each controller could be in a separate javascript file and they could all be located in a folder called controller. Each controller javascript file would look something like this:

ngMeteor.controller('someControllerName',[$scope,function(){...}]);

Alternatively, you could put all controllers, directives, filters and services specific to a particular route into a javascript file under that route's folder. For example, lets say you have a route called "post", you could have a folder called post, and in your post folder you could have post.html, post.css and post.js, and the post.js would look something like this:

ngMeteor
.controller('someControllerName',[$scope,function(){...}])
.directive('someDirectiveName',[$scope,function(){...}])
.filter('someFilterName',[$scope,function(){...}])
.service('someServerName',[$scope,function(){...}]);

At the end of the day though, its personal preference and ngMeteor is flexible enough to allow you to structure your app in multiple ways.


Team Fortress 2 item price lookup using Trade.tf developer API and Steam WebAPI

Hah, this is a fun one cause I play a lot of Tf2. So let's see what could be improved here.

I'll start with you naming. You don't need to use the _from_ naming convention. ie.

def get_item_defindex_from_name(name):

get_item_defindex_from_name(item_name)

You already have the name there, it's clear that you need a name to get the defindex from, so remove that part and save yourself from a 5 word function name

get_item_defindex(item_name)

You should also use constants. qualities is essentially a constant but you haven't signalled it as one. To make it clear it is, write the name in UPPER_SNAKE_CASE (QUALITIES) and define it right after your imports, before running any actual code. I would do the same with your price units, it's not really clear why you treated them differently.

Your with block is a bit misplaced. If you definitely want to load the schema and spreadsheet as part of the global namespace to be accessed in every function, then you should still put them in the if __name__ == "__main__" block. if blocks don't limit scope the way functions do, so they'll still be globally available. You also never use the spreadsheet or the schema without calling .json() on them. Couldn't you just do this here? If you did you could probably save significant time not having to run that function every time. In fact, you only need items out of spreadsheet and ["result"]["items"] out of schema. If you don't need to maintain some sort of connection to the results (which it doesn't seem like you do) then you can just store the relevant values from these dicts and ignore the rest.

In get_item_defindex, you're looping over all the items to try find one with a matching name. Is there any reason to keep looking after you've found a value? I'm assuming not, so in that case you should return as soon as you find it to save time:

def get_item_defindex_from_name(name):
    for items in schema.json()["result"]["items"]:
        if items["name"] == name:
            return items["defindex"]
    print("Invalid item.")

If you specifically need to get the last matching name for some reason, then you should loop over the schema backwards:

def get_item_defindex_from_name(name):
    for items in reversed(schema.json()["result"]["items"]):
        if items["name"] == name:
            return items["defindex"]
    print("Invalid item.")

get_quality_id_from_name seems like a redundant function to me. If it's just going to be a dictionary lookup, it's easier to use that instead of a function. If it included getting the user input then it could be worth being a function. Often single lines of code are only worth being a function if they're particularly complex and worth abstracting or if they're called a lot and it saves repetitive code. Neither is true here. I'd say the same for price unit.

In get_tradetf_price you can make it readable and slightly more performant to grab the item up front, before you get the price and unit:

def get_tradetf_price(item, quality):
    item_data = spreadsheet.json()["items"][str(item)][str(quality)]["regular"]
    price = item_data["hi"]
    unit  = get_price_unit(item_data["unit"])
    return str(price) + unit

Your get_input function is very confusing. It's a good abstraction mostly, but the validation approach is overcomplicated, especially for what you need here. Instead of passing a lambda to test the input, just pass a list of valid values and test if the input is in there, like so:

def get_input(dialog, valid_inputs, error_message):
    while True:
        answer = input(dialog).lower()
        if answer in valid_inputs:
            return answer
        else:
            print(error_message)

You can then call it with a much simpler line:

    quality = get_input("Enter item quality: ", QUALITIES,
                        "Quality not tracked by Trade.tf.")

Also note I added the .lower() to when you call input. When accepting input try to sanitise it immediately. You don't care about the case so lowercase it as soon as you accept the input.

Note that if you can store the dictionary of items from the schema you can then reuse this for your item_name request at the start:

    item_name = get_input("Enter item name: ", schema_items,
                          "Invalid item.")

And lastly, your try block is a bit long. You clearly intend it to catch errors from get_tradetf_price but it's going to swallow any KeyError in your whole main block. Make try blocks as short as possible:

def main():
    item_name = get_input("Enter item name: ", schema_items,
                          "Invalid item.")
    item_id = get_item_defindex(item_name)

    quality = get_input("Enter item quality: ", QUALITIES,
                        "Quality not tracked by Trade.tf.")
    quality_id = get_quality_id_from_name(quality.lower())

    try:
        print("\n {} {} price: {}".format(quality, item_name,
                                          get_tradetf_price(item_id, quality_id))
    except KeyError:
        print("Item not currently tracked by Trade.tf.")


Challenge: phone keypad to letters - return all possible strings

Too long for a comment...

The problem as presented seems to have much in common with the string permutations problem in terms of solution structure.

You should be able to do something similar to: https://stackoverflow.com/questions/4240080/generating-all-permutations-of-a-given-string with slight modification to get a compact recursive formulation.

Pseudo code below:

solution(string digits, string prefix="", array<string> outputs)
    if digits empty then
        add prefix to outputs
    else
        currentDigit := digits.get(0)
        remainingDigits := digits.remove(0);
        for each character in listOfCharsForDigit[currentDigit] do
            solution(remainingDigits, prefix+character, outputs)
        endfor
    endif

Hope that helps...


Flaten array to 1D and assigning 'associative' keynames recursively

So I probably need some kind of recursion, but I have no clue how to get around that with PHP

Recursion in PHP is the same as basically any language (well... at a very high level).

I'm very torn on if I think your question is on topic or not, but it's been a long time since I've written anything recursive, and I'm a shameless rep-whore, so here's my go:

function flatten(array $arr, $prefix = '')
{
    $out = array();
    foreach ($arr as $k => $v) {
        $key = (!strlen($prefix)) ? $k : "{$prefix}[{$k}]";
        if (is_array($v)) {
            $out += flatten($v, $key);
        } else {
            $out[$key] = $v;
        }
    }
    return $out;
}

Or, if you don't like the magical second param:

function _flatten(array &$out, array $arr, $prefix)
{
    foreach ($arr as $k => $v) {
        $key = (!strlen($prefix)) ? $k : "{$prefix}[{$k}]";
        if (is_array($v)) {
            _flatten($out, $v, $key);
        } else {
            $out[$key] = $v;
        }
    }
}

function flatten(array $arr)
{

    $flat = array();
    _flatten($flat, $arr, '');
    return $flat;

}

You could also optimize a bit and make a lot of the things in there references (the for loop values and function params).  I tend to avoid references in PHP though unless I have an extremely strong reason for them.  (If you plan on using this function on arrays larger than a few hundred elements, that may begin to enter into strong reason land.)

(And flatten is a horrible name, but... yeah.)


I would like to know if it is possible to avoid all the if statements for error validations.

No.

This is the way errors are handled in Go. You get the error as return value and you handle it. You may return it, log it, print it or mute. You can panic with it, which is somewhat similar to exceptions. It's all up to you.

Check out this blog post to see reasoning behind the way errors are implemented.

  This is my second program in Go, and I have mainly a Node.js background, so I don't know exactly how to handle errors in Go-style, and also how to make the code more idiomatic.

Node.js also has an error convention which is carefully followed by community users. Same stands for Go.

To make code more idiomatic I suggest you to read more standard library code. It will help a lot. Simply every time you look through the docs click on function (or other identifier) to see the actual code behind it. It's is super easy and may reveal how the things work in Go.

Here follows annotated rewrite:

package main

import (
    "fmt"
    "os"
    "github.com/minio/minio-go"
    "github.com/kelseyhightower/envconfig"
)

// CamelCase is idiomatic in Go, but snake_case.
type AWS struct {
    Endpoint        string `envconfig:"ENDPOINT"`
    AccessKeyId     string `envconfig:"ACCESS_KEY_ID"`
    SecretAccessKey string `envconfig:"SECRET_ACCESS_KEY"`
    SSL             bool   `envconfig:"SSL"`
    Bucket          string `envconfig:"BUCKET"`
    BucketKey       string `envconfig:"BUCKET_KEY"`
    BucketExpiry    string `envconfig:"BUCKET_EXPIRY"`
}

// Exit will write error text to stderr and exit
// with non zero return code.
func Exit(err error) {
    fmt.Fprintln(os.Stderr, err)
    os.Exit(1)
}

func main() {
    var aws AWS

    // Fill configuration from enviroment variables
    err := envconfig.Process("aws", &aws)
    if err != nil {
        Exit(err)
    }

    svc, err := minio.New(aws.Endpoint, aws.AccessKeyId, aws.SecretAccessKey, aws.SSL)
    if err != nil {
        Exit(err)
    }

    url, err := svc.PresignedPutObject(aws.Bucket, aws.BucketKey, aws.BucketExpiry)
    if err != nil {
        Exit(err)
    }

    // stdout is used only to print received URL
    fmt.Println(url)
}


For factorization, the state of the art (as of like 1999, but also today as far as I know) is something like Rob Gaebler's ABIGSIV: https://www.ticalc.org/archives/files/fileinfo/79/7923.html
The essential idea is to use the "wheel" method. Make a list of all the prime numbers between 1 and 2*3*5*7 and stash that list in L1; then, do trial-division by L1+210*I all at once. The important thing is to maximize the amount of time you spend doing divisions and minimize the amount of time you spend doing bookkeeping.


Using a destructuring assignment on a style object to extract two members

I think it is a matter of preference, and also of the size of the file. If it is larger with more variables then I would tend to using the styles. prefix to disambiguate. You could also compromise and go for s = styles followed by s.headerHint.

As to the name changing issue, you could always just write styles = newGangledStyles however most decent IDEs will refactor for you and even if they don't then this type of search and replace is usually pretty straight-forward and risk free also. I also suspect that, if the styles object did change, then it would be likely that the style names would also change. Using a styles. prefix actually makes it easier to locate usages.


Your code is quite nice, and can't really be improved. However, let's put the “generator” back into the code.

Go has channels which can be used to write elegant generators/iterators. We spawn of a goroutine that fills the channel with the fibonacci sequence. The main thread then takes as many fibonacci numbers as it needs.

So let's write a function fib_generator that returns a channel to the fibonacci sequence:

func fib_generator() chan int {
  c := make(chan int)

  go func() {
    for i, j := 0, 1; ; i, j = i+j,i {
        c <- i
    }
  }()

  return c
}

We return a chan int. Here, we use an unbuffered channel. You may want to introduce a bit of buffering, e.g. make(chan int, 7).

Next, we spawn a goroutine. This contains your code, but instead of printing the numbers, we fill the channel with them. Note that the generator does not have a termination condition.

The unusual syntax

go func() { ... }()

is the standard way to start a goroutine. Because the function literal is a closure over the channel c, we can run multiple generators concurrently.

Our main will look like

func main() {
    c := fib_generator()
    for n := 0; n < 12 ; n++ {
        fmt.Println(<- c)
    }
}

That is, we create a new generator, and then pull the first 12 values from the channel. We cannot write for i := range c { ... }, because the fibonacci generator does not terminate.

As I said, we can have multiple generators concurrently:

func main() {
    c1 := fib_generator()
    c2 := fib_generator()

    // read first 12 numbers from 1st channel
    for n := 0; n < 10 ; n++ { fmt.Print(" ", <- c1) }
    fmt.Println()

    // read first 12 numbers from 2nd channel. The same.
    for n := 0; n < 10 ; n++ { fmt.Print(" ", <- c2) }
    fmt.Println()

    // read next   5 numbers from 1st channel.
    for n := 0; n <  5 ; n++ { fmt.Print(" ", <- c1) }
    fmt.Println()
}

Output:

 0 1 1 2 3 5 8 13 21 34
 0 1 1 2 3 5 8 13 21 34
 55 89 144 233 377


Space complexity of the "add two binary strings" challenge

I agree with you, space complexity should be \$O(n)\$, using StringBuilder should not matter because, internally it would store char in an array which would expand / shrink as needed.

Now some code-reviews.

Error check:

Null check? x or y could be null. This (x == null || y == null) looks better.
Your code says "sumofbinary", but what if your string was "123" + "543"?

Name check:

sb is not a professional name, call it sum.

Syntax check:

while(i > = 0 || j >= 0) .. there is a space > = for i > = 0, but not for j.

Misc:

StringBuilder can be marked final.
You end for loop when both i & j are 0. This has a drawback, if i is longer than j, you would waste error checking if (j > 0).


Maintainable way to concatenate strings in JS and vendor prefixes

Changing the many bubble_css += lines to a single long concatenation spanning multiple lines would be an improvement.

Even more improvement would be using a template framework,
for example moustache.

If you don't want to depend on a framework,
you could cook up something simple.
For example, use a single string with markups like {{ bubble_in_ms }},
and create a utility function that takes the template string and a dictionary of key-value pairs to replace in the template.


Coding adjacency list representing graph

Code style: Use typedef struct instead of struct for cleanliness.

This looks generally OK, but is not strictly speaking an adjacency list representation. In an adjacency list representation you store a list of verticies, and each of those verticies store a list of its neighbours. This structure implicitly encodes the edges of the graph.

A more compact adjacency representation might look something more like this:

typedef struct{
    char *data;
    struct vertex **neighbours;
    char **weight; // edge to neighbours[i] stored in weight[i]
} vertex;

typedef struct{
    int num_verticies;
    struct vertex **V;
} graph;

The edges can be recovered by traversing the graph. To improve performance we may choose a structure other than a linked list to store the neighbours of a vertex.

Which further annotations you keep in the graph struct will depend on the final use case. For certain algorithm having an explicit edge list will be vital, whereas for others it will be wasteful.


Sending a string from anonymous thread to UI with PostMessage

Create an object containing the string as a property and pass the pointer to the object as Integer LParam. Then, in the message handler, use the string and free the object. In this way, you could not only send strings but also other data as well.

unit SendingStringWithPostMessageUsingObjectMainForm;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

const
  WM_STRINGMESSAGE = WM_USER;

type
  TStrMsgObject = class(TObject)
  private
    fMsg: string;
  public
    constructor Create(const aMsg: string);
    property Msg: string read fMsg;
  end;

type
  TForm2 = class(TForm)
    btnSetCaption: TButton;
    btnChangeCaption: TButton;
    procedure btnChangeCaptionClick(Sender: TObject);
    procedure btnSetCaptionClick(Sender: TObject);
  private
    { Private declarations }
    procedure WMStringMessage(var Msg: TMessage); message WM_STRINGMESSAGE;
  public
    { Public declarations }
  end;

var
  Form2: TForm2;

implementation

{$R *.dfm}

const
  // WM_STRINGMESSAGE Actions:
  ACTION_SETCAPTION    = 0;
  ACTION_CHANGECAPTION = 1;

constructor TStrMsgObject.Create(const aMsg: string);
begin
  inherited Create;
  fMsg := aMsg;
end;

procedure TForm2.WMStringMessage(var Msg: TMessage);
// Process WM_STRINGMESSAGE messages
var
  mo: TStrMsgObject;
begin
  mo := TStrMsgObject(Msg.LParam);
  try
    case Msg.WParam of
      ACTION_SETCAPTION:
        begin
          Caption := mo.Msg;
        end;
      ACTION_CHANGECAPTION:
        begin
          Caption := Caption + mo.Msg;
        end;
    end
  finally
    mo.Free;
  end;
end;

procedure TForm2.btnSetCaptionClick(Sender: TObject);
begin
  System.Classes.TThread.CreateAnonymousThread(
    procedure
    begin
      PostMessage(Handle, WM_STRINGMESSAGE, ACTION_SETCAPTION, Integer(TStrMsgObject.Create('My new caption')));
    end).Start;
end;

procedure TForm2.btnChangeCaptionClick(Sender: TObject);
begin
  System.Classes.TThread.CreateAnonymousThread(
    procedure
    begin
      PostMessage(Handle, WM_STRINGMESSAGE, ACTION_CHANGECAPTION, Integer(TStrMsgObject.Create(' changed')));
    end).Start;
end;

end.


Self-taught Pythonista: Any criticism welcome for this concurrent word count script!

PEP8 mentions that top-level constructs like functions should be separated by two lines. Hanging indents should have only one level of indentation (lines 43 and 61). Be careful about trailing whitespaces (lines 61 and 89).

I love functional style myself but it is often frowned upon in Python, and Counter(chain(*map(split_and_clean, lines))) or filter(None, re.split(REGEX, line.lower())) will be considered unreadable by some, and elegant by others.

Otherwise your code is awesome, well-written with beautiful docstrings and clever (filter() to drop empty strings, AttributeError and to the call to lower()). Thanks for sharing!


Skip() is not optimized for IList<T>, it always enumerates the skipped elements. This means that your algorithm is O(n2) for no good reason. What you should do instead is to manually iterate just the required part of the input in each iteration using for. Something like:

double sum = 0;
for (int i = 0; i < actualFrameSize; i++)
{
    sum += data[start + i].Y;
}

(I don't like using GetRange() for this, as in tinstaafl's answer, because it unnecessarily copies the frame into a new list.)

If frameSize is large, another optimization would be not to recompute the sum of the frame for each index. Instead, just add the item from the front and subtract the item from the back:

public PointPairList GetMovingAverage(int frameSize, PointPairList data)
{
    var movAvgPoints = new PointPairList();

    //Before zero
    int currentFrameSize = frameSize/2;
    double sum = data.Take(currentFrameSize).Sum(p => p.Y);

    //Smooth each point in the list
    for (int i = 0; i < data.Count; i++)
    {
        int removed = i - (frameSize/2) - 1;
        int added = i + (frameSize/2);

        if (removed >= 0)
        {
            sum -= data[removed].Y;
            currentFrameSize--;
        }
        if (added < data.Count)
        {
            sum += data[added].Y;
            currentFrameSize++;
        }

        movAvgPoints.Add(new PointPair(data[i].X, sum/actualFrameSize));
    }

    return movAvgPoints;
}

If the length of data is n and frameSize is f, then the previous algorithm would be O(fn), but the improved one just O(n).

Another thing: there is usually no need to create types that derive from List, just use List<PointPair> directly.


If you want an easy way to loop an arbitrary command several times...

set /a loop=100
for /L %%P in (1,1,%loop%) do (
    echo Looping for one hundred times
)

The first line is obvious.

The second line is a bit harder - for /L specifies that for every number in a certain set, the batch file will do something. %%P is a parameter that holds what number the for loop is at currently - it can be any letter you like (and some other characters but they are dangerous so stick with letters). in (1,1,%loop%) specifies that this is for every number from 1 to %loop%, increasing by 1 every time. do ( ... ) obviously tells the batch file what it needs to do.

So, in every number from 1 to 100, it will echo Looping for one hundred times. This will obviously scroll down the page seeing as we never clear the screen with cls.

Once a for loop has reached its final number, the batch file continues on executing the commands following the final ) as you would expect.

I can expand this answer if you want to know what you're doing wrong and right in your own code example, but I pretty much just did the same thing in 4 lines which should suffice.

And here comes the expansion. Please note that your code is pretty close to perfect, and these tips only encourage good scripting habits.

To begin with, you spelt variable as varible in line 3 of the :HELP label.

First line of the :RUN label:

set /a counter=%counter% + 1

Instead of this, one can do

set /a counter+=1

This isn't incredibly helpful at the moment, but when you want to add a variable to another variable...

set /a varA+=%varB%

This also works for other operators...

set /a varA*=%varB%

And slightly more complex equations...

set /a varA-=%varB% * %varC%

Which will evaluate %varB% * %varC%, then subtract the result from varA

The command CMD /C "%COMMAND%" is not entirely necessary to my knowledge - simply writing %COMMAND% on a new line will cause the batch parser to expand it, so if %COMMAND% is set as exit, the line will read, at run time, exit. This enables you to use this method rather than the entire CMD /C method.

Another concern that could become more than just a concern is your method for checking the errorlevel - there's a problem. Checking with quotes and == denotes a string comparison - never good when you're dealing with two numbers. So you'll need a fix for this problem, and luckily it's quite simple.

if %errorlevel% EQU 1 ( ... )

This tests for a mathematical equivalence - always good when you're dealing with two numbers. All the operators for mathematical equivalencies are...

EQU - 'equal to'
NEQ - 'not equal to'
GTR - 'greater than'
LSS - 'less than'
GEQ - 'greater than or equal to'
LEQ - 'less than or equal to'

And finally, using if varA==varB (goto label) is not necessary - it works just as well as if varA==varB goto label. The only time you need brackets is when you plan on conditionally executing multiple lines or if you need to use else (just to be safe). When using brackets, always remember to balance them. Indenting isn't required, but it gets really confusing when you start nesting if statements and for loops without it. An example of executing multiple lines...

if %varA% GTR %varB% (
    echo varB is less than varA
    if %varA% GTR %varC% (
        echo varC is less than varA
    ) else (
        echo varC is greater than varA
)

To conclude, your code obviously works fine, but some habits die hard in weird circumstances later on, so it's best to get used to using common conventions (they exist for a reason!). As a side note, remember that batch scripting is not case sensitive. Anything I wrote here, along with anything you wrote, can be written in the opposite case - it has no difference.


Python exception handling class - Getting as much details printed

Python's built-in exception traceback gives us:

Traceback (most recent call last):
  File "D:/code/python/error.py", line 43, in <module>
    error()
  File "D:/code/python/error.py", line 28, in error
    another_level()
  File "D:/code/python/error.py", line 31, in another_level
    return tuple()[0]
IndexError: tuple index out of range

Where your code gives us:

(<type 'exceptions.IndexError'>, 'error.py', 39)
Thrown from __main__

So yours is sparse from the go.
But what makes it bad is line 39 is where I call error().
It's not where the error happens, that's line 31.
It also doesn't give us the path to the file, if I have multiple files with the same name then your program is going to cause me some serious headaches.
And finally the error doesn't throw in __main__ it throws in another_level.

If you are ok with printing the exact same as Python then, as zondo said, you can just change your code to:

def printit():
    traceback.print_exc()

As you probably want to format it yourself, and be able to change the data. You should use sys.exc_info() and traceback.extract_tb(exc_traceback).
And so if you wanted to implement print_exc yourself you can use:

def print_exc():
    exc_type, exc_value, exc_traceback = sys.exc_info()
    print 'Traceback (most recent call last):'
    print '\n'.join([
        '  File "{}", line {}, in {}\n    {}'.format(*level)
        for level in traceback.extract_tb(exc_traceback)])
    print '{}: {}\n'.format(exc_type.__name__, exc_value)

This allows you to format the error however you want.


Looks good to me.

Although, having cache as a simple Map might lay claim to more memory that you like. Associating an LRU with it would allow each addition to evict an ancient job's cached dataframe.


Python2 / Python3

Your code don't working under python 3 (PEP 3113). If possible better use newer python :).

Algorithm

no needs to change Interval to list with two elements. It's bad practise. You try low-level optimizations, not algorithm one. Code is less readable.
local functions is_intersect and merge_interval don't use knowledge that we have sorted intervals, e.g. i1_l <= i2_l
pattern while i < len(my_list): better change to for element in my_list: because we don't need index

Reduced code

class Interval(object):
    def __init__(self, s=0, e=0):
        self.start = s
        self.end = e

class Solution(object):
    def merge(self, intervals_struct):
        if not intervals_struct:
            return []
        intervals = sorted(intervals_struct, key=lambda x: x.start)

        result = [intervals[0]]
        for cur in intervals:
            if cur.start > result[-1].end:
                result.append(cur)
            elif result[-1].end < cur.end:
                result[-1].end = cur.end
        return result


Compact jQuery tool tip code, without jQueryUI

Bind method should be used only when if your element is not loaded into DOM on pageload. So you could attach events to it using bind after wards. also if your using jquery >= 1.7 use 'On' method to achive it. but as per your js fiddle you don't need it at all.

second you could declare a variable to store the jquery object of follow. Make sure about the variable scope though.

var follow=$('#follow');

$('div.a').mousemove(function(e){
    follow.css({
       left:  e.pageX + 20,
       top:   e.pageY
    });
})
.mouseenter(function() {
    follow.css('display','block');
})
.mouseleave(function() {
    follow.css('display','none');
})


I answered this moments ago, but same applies

https://stackoverflow.com/questions/8108175/php-usleep-to-prevent-script-timeout/8108229#8108229

If you simply use : $handle = opendir($working_dir); you can find yourself waiting for the script to timeout on non existing directories. So atleast use:

if (! $handle = opendir($working_dir))
  exit(0);

Its generally way faster to just check if functions are even possible before you start them, although it might feel like your implementing way to many if statements, but if statements are fast and most errors are not ;)


Adding a bulk of items in the middle of a sparse array

You don't need to worry about sparse arrays in JavaScript and there is no need to instantiate with the Array constructor. If you insert into a random index then the rest of the array is just padded with undefined references:

var items = [];
items[5] = 'foo';
console.log(items); // [5: "foo"]
items.toString();   // ",,,,,foo"

To add new items into the middle of an array you can use the splice function:

items.splice(index, 0, bulk);

The index is where to start adding items, 0 is how many items to remove after that point, and bulk is the new items to add at that point. Splice acts on the array directly, and returns any items that were removed.


Sorting an object by value w/ `sort` and `reduce`

Here's my proposal:
function sortObjectByValue (obj) {
  const map = new Map()

  Object.entries(obj)
    .sort((a, b) => obj[b][1] - obj[a][1])
    .forEach(([key, value]) => {
      map.set(key, value)
    });

  return map;
}

You don't need to create a sorted object unless you want to use it, I understand that you are using a Map so that you can preserve the order of the elements, but keep in mind this:

Note: Since ECMAScript 2015, objects do preserve creation order for
string and Symbol keys. In JavaScript engines that comply with the
ECMAScript 2015 spec, iterating over an object with only string keys
will yield the keys in order of insertion.

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
So with that in mind we can skip the Map and we have something like this:
function sortObjectByValue2 (obj) {
  return Object.keys(obj)
    .sort((a, b) => obj[b] - obj[a])
    .reduce((acc, cur) => {
      acc[cur] = obj[cur]
      return acc
    }, {})
}


C++ implementation of recursive_shared_mutex

I strongly recommend not inheriting from standard types, and not using private inheritance even with your own types. If a recursive_shared_mutex IS-A shared_mutex, then announce it publicly; if it IS-NOT-A shared_mutex, then don't use inheritance at all!
(Godbolt. D_view here is isomorphic to std::reference_wrapper<D>, for what that's worth.)

std::size_t writer_cnt_;

should be
std::size_t writer_cnt_ = 0;

so that you don't have to remember to initialize it in the member-initializer-list of the constructor. Once you do that, you can =default your constructor. Even if you don't =default the constructor, please don't do mtx_(), cv_(), and so on. Let default constructors do their jobs; and don't force me to read more code than I need to read.

    // No writer is holding the shared_mutex.
    // Call unlock() anyway. UB expected.

This comment is just completely bogus. If this situation is "should never happen, UB expected," then assert false already! Don't just go on and do some random operation like shared_mutex::unlock() when you know you're in a bad state. Assert false, and let the programmer detect and fix their bug.
Again, this follows the mantra "Don't force me to read more code than I have to." Don't make me read a codepath that does shared_mutex::unlock() and returns, when really that codepath is unreachable. In fact, don't even write that if test! Just do this:
void recursive_shared_mutex::unlock() {
    auto lk = std::unique_lock<std::mutex>(mtx_);
    assert(writer_id_.has_value());
    assert(*writer_id_ == std::this_thread::id());
    assert(writer_cnt_ > 0);
    if (--writer_cnt_ == 0) {
        std::shared_mutex::unlock();  // oops, TODO FIXME
        writer_id_ = std::nullopt;
        lk.unlock();
        cv_.notify_one();
    }
}

Notice my preferred use of lk for lock-guard variables.
Notice I'm avoiding the use of ad-hoc named methods like x.reset() in favor of value-semantic operations like x = nullopt.
You've still got a bug here, which you code-commented — but commenting a bug doesn't make it go away! Frankly, this code is literally off-topic here, because it doesn't work and you know it doesn't work.
Figure out how to use a semaphore (from the <semaphore> header in C++20) or an atomic, instead of the shared_mutex which you already know gives you UB.

I'm 90% sure that there's a deadlock possible between your exclusive lock() and unlock() functions. Suppose Thread A has the mutex exclusive-locked, and Thread B goes to lock it. Then Thread B will enter lock(), take an exclusive lock on mtx_, and block in std::shared_mutex::lock() because Thread B still has it locked. (Assume Thread B drops its lock just long enough to fool the cv_.wait() loop.) Finally, Thread A enters unlock() and blocks in ulock(mtx_) because Thread B still has mtx_ locked.


Word count and most frequent words from input text, excluding stop words

The code is clear, if a bit overly commented.  All in all very good I'd
say.  Once you do become more familiar with it, things like len(...)
should be obvious enough that they generally don't warrant a comment on
their own.

Also in general, single character names are discouraged as they don't
carry much meaning and can be harder to read.  On the top of my head s
is vaguely a string, d could be a dictionary ... but really, what
string and what dictionary I have no idea.

Next, while it works, the general recommendation in longer scripts is
not to use open directly without with, unless you take care to close
the file.  Therefore the input file should be read like follows:

# Open the input file
with open('Obama 2009.txt', 'r') as f:
    s = f.read()

The with
statement will take care to always call close on the open file, which
would otherwise lead to issues in long-running processes taking up too
much system resources (open files).

For the word counting I'd again say it's fine, but can be written more
compact.  Notably using a class from collections,
Counter.

num_words on the other hand does too much work and can just be
len(words).

list.sort actually has a reverse parameter, so you can just use that
instead of the extra call:

lst.sort(reverse=True)

Usually imports go to the start of the file, even though it doesn't
affect function too much (but you'd get an early warning if a library
wasn't available for example).

For formatting output there are a ton of options.  At some point you
might want to look at the
format
method for strings.

Lastly, the loop at the end prints the 50 most frequent words, not
30 like the output suggests.  That is a good opportunity to introduce
a constant for the number of words to print:

PRINT_WORDS = 50

print('\n The {} most frequent words are /n'.format(PRINT_WORDS))

Since it's a constant it's in upper case.  I've also used format here
since using placeholders looks a bit nicer and also is much regular than
either concatenation or the % operator.  But it's kind of up to
preference anyway.

Lastly, the final loop uses an explicit counter, which, again, has an
equivalent and nicer standard library helper called
enumerate.

for i, (count, word) in enumerate(lst[:PRINT_WORDS], 1):
    print('%2s. %4s %s' % (i, count, word))

Which starts at zero normally, but I actually just saw that it supports
an optional start parameter, so might as well use that.


VBA Excel Looping through recordset and storing the data to use later

It is much faster to iterate over an array then a recordset. You should also pass the recordset to a function to return the dictionary.  The fewer tasks a subroutine performs the better.

Function RecordsetMap(ByRef rs As ADODB.Recordset, ByVal KeyColumn As Long) As Scripting.Dictionary
    Dim Map As New Scripting.Dictionary
    Dim Key, Item, Values
    Rem 1000000 is used to ensure all rows are returned
    Values = rs.GetRows(1000000)

    Dim r As Long, c As Long

    For r = 0 To UBound(Values, 2)
        ReDim Item(0 To UBound(Values))

        For c = 0 To UBound(Values)
            Item(c) = Values(c, r)
        Next
        Key = Item(KeyColumn)
        Map.Add Key:=Key, Item:=Item
    Next

    Set RecordsetMap = Map

End Function

Usage

Dim KeyColumn As Long, n As Long

' Get Field Name Index if not know
For n = 0 To rs.Fields.Count - 1
    If rs.Fields(n).Name = "app_number" Then
        KeyColumn = n
        Exit For
    End If
Next

Set dict = RecordsetMap(rs, KeyColumn)
Dim Item, Key

Debug.Print "Iterating over Keys"
For Each Key In dict.Keys
    Item = dict(Key)
    Debug.Print Join(Item, ",")
Next

Debug.Print
Debug.Print "Iterating over Items"
For Each Item In dict.Items
    Debug.Print Join(Item, ",")
Next


Code Quality Catch-22 -- Duplication vs Complexity

Your first version - extending the association - is probably the right approach in general, but there's another way to remove duplication, without resorting to metaprogramming.

Instead of defining methods as inlined extensions you can create a module for the association extensions. But rather than adding that module to the User model, you can add it the associations instead (see the docs)

E.g. if you create a module like so:

module TrackableAssociation
  def <<(item)
    # ...
  end

  def activate(item)
    # ...
  end

  def deactivate(item)
    # ...
  end
end

You should be able to add it like so:

class User < ActiveRecord::Base
  has_many :conditions, through: :user_conditions, -> { extending TrackableAssociation }
  has_many :symptoms, through: :user_symptoms, -> { extending TrackableAssociation }
  has_many :treatments, through: :user_treatments, -> { extending TrackableAssociation }
end

Which, in turn, should let you do things like

user.conditions.activate(condition)

Now your extensions are defined without using duplication or metaprogramming.

However. Your approach of storing an array of "activated IDs" smells fishy. It's fragile, and it requires the association extensions to modify the user instance. The code paths get tricky.

active should be an attribute on a join model - or at least a column in the join table. If I'm reading your code right, you've got Condition, Symptom and Treatment models, and join tables between them and User. You should probably make actual models for the join; said models can then have an active boolean attribute.


public static void main(String[] args) throws Exception {
    final String site1 = "http://codereview.stackexchange.com/questions/";
    String site2;
    String site3;

Why do define site1 as a final constant, but delay the other assignments until later? They should really be static finals for the class. Also some clearer names would not go amiss.

    URL url;

Declare them where they are used, don't declare them ahead of time.

    HtmlGetter htmlGetter = new HtmlGetter();

    while(true) {
        site2 = "69";
        site3 = "is-this-implementation-of-shamos-hoey-algorithm-ok";
        url = new URL(site1 + site2 + "/" + site3);
        htmlGetter.setFileName("[" + site2 + "]" + site3 + ".html");
        htmlGetter.download(url);
        htmlGetter.parse();
        break;

Why do you have a loop if you are just going to break out of it?
        }
    }

public void parse() throws Exception {

You shouldn't throw Exception, your specification should really only include the exceptions that'll actually be thrown

    Scanner scanner = new Scanner(new File(fileName));
    String oneLine;
    String htmlTagRegex = "<(/)?([a-zA-Z]*)(\\s[a-zA-Z]*=[^>]*)?(\\s)*(/)?>";

Parsing HTML by regex is asking for trouble. Instead, you'll find the task much easier if you grab a html parsing library and use that.

    while(scanner.hasNextLine()) {
        oneLine = scanner.nextLine();
        if(oneLine.matches(".*<code>.*")) {

You are just searching for a substring here, there isn't much point in using regex to do that.

            while(scanner.hasNextLine()&&(!oneLine.matches(".*</code>.*"))) {

If you insist on regex, use a single regex to capture the entire code tag.

                oneLine = StringEscapeUtils.unescapeHtml4(oneLine.replaceAll(htmlTagRegex, ""));
                System.out.println(oneLine);
                oneLine = scanner.nextLine();
                // This cannot handle such kind of a line which has <code> and </code> together.
            }
            System.out.println("-------------------------------------------");
        }
    }
}

Using something like jsoup: http://jsoup.org/

Document question = Jsoup.connect("http://codereview.stackexchange.com/questions/69").get();
Elements codes = question.select("code")
for(Element code: codes)
{
   System.out.println(code.text())
}


Dynamic array of integers: another attempt

Your entire CVectorInit function can essentially be trimmed down to this:

vector_status CVectorInit(CVectorInt *vector)
{
    vector->capacity = DEFAULT_CAPACITY;

    // Allocate array
    vector->data = calloc(vector->capacity, sizeof(int));
    if(vector->data == NULL)
        return VECTOR_MEMORYERROR;

    return VECTOR_SUCCESS;
}

Fundamentally though, is there a reason to zero out the allocated array? You make sure that you never access an index that's out of bounds in your functions so there should be no need to zero out the allocated array. Especially on resizing the vector, this will just be a performance hit that you'll take with little benefit (especially when the vector gets to be quite large).

Moreover, I would replace the ints holding the size and capacity of the vector with size_t or something similar. These values are never going to hold negative numbers so there's no need to have them as signed ints.

Also, there seems to be this magic constant 32000. Why is it 32k and what's the reasoning? Create a named variable for this constant. So in your .c file:

static const size_t MAXIMUM_CAPACITY = 32000;

Also, why is that value so low? A standard signed int can hold a maximum value of around 2 billion so 32k seems pretty low. Maybe putting a comment above that named variable to justify your reason could be helpful.

As a design consideration, you might want to think whether or not you want to have DEFAULT_CAPACITY declared as a macro in your header file. As it is, someone could go to your header and set DEFAULT_CAPACITY to a negative value or some other erroneous number. Assuming that you might be compiling this as some sort of library, it might be better to declare DEFAULT_CAPACITY as a private variable to your implementation file to avoid such things:

In your .c file:
static const size_t DEFAULT_CAPACITY = 1000;

This also comes with the added benefit of type safety and avoiding the use of the preprocessor.


Function to convert little endian bytes into big endian

Includes
We have included <iostream> twice, but missed <cstdio>.
Misspelt standard library identifiers
std::printf, std::uint8_t and std::uint64_t are consistently misspelt.  You might sometimes get away with this, as your standard library is allowed to add global-namespace versions of those identifiers; since it's not required to do so, you have a portability bug.
Use appropriate size type
std::size_t is the appropriate type to use for the size of an object, rather than std::uint64_t (which could be unnecessarily big, or - theoretically, at least for now - too small).
Conversion function shouldn't have side-effects
The printf() calls within convertLittleToBig make it unusable in any serious program.
Consider a standard algorithm
The <algorithm> header provides a very useful std::copy() function we can use if we have a reverse iterator to copy from or to.  We can get suitable iterators from std::span views onto the inputs (from C++20 onwards).
Avoid raw pointers
We could do better, using a template to accept values and return by value, inferring the size from the argument type:
#include <algorithm>
#include <span>

template<typename T>
T convertLittleToBig(const T& val)
{
    auto in = std::as_bytes(std::span(&val, 1));
    T result;
    auto out = std::as_writable_bytes(std::span(&result, 1));
    std::copy(in.rbegin(), in.rend(), out.begin());
    return result;
}

That's much simpler - no counting needed, and the caller doesn't need to use sizeof (to work with odd-sized values, they need to be passed as arrays).
This is how we'd use it in a simple test program:
#include <cstddef>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

std::string to_hex(auto const& val)
{
    std::ostringstream oss;
    oss << std::hex << std::setfill('0');
    auto in = std::as_bytes(std::span(&val, 1));
    for (auto c: in) {
        oss << std::setw(2) << std::to_integer<unsigned int>(c);
    }
    return oss.str();
}

// hex-print the value and its reversal
void demo_endian_swap(auto const& val)
{
    std::cout << to_hex(val) << " -> "
              << to_hex(convertLittleToBig(val)) << '\n';
}

#include <array>
int main() {
    // Demonstrate a selection of types
    demo_endian_swap(std::uint16_t{0x1234});
    demo_endian_swap(std::uint64_t{0x123456789abcde});
    demo_endian_swap(std::array<unsigned char,5>{1,2,3,4,5});
    //demo_endian_swap("abc");    // Invalid - can't return an array
    //demo_endian_swap(std::string{"abc"}); // oops - reverses whole structure
}

Example output:
3412 -> 1234
debc9a7856341200 -> 00123456789abcde
0102030405 -> 0504030201


Factorials, loops, break and professional code

The other reviews have covered most items, so I'll just add a few.

Use constant string concatenation

The current code includes this:

printf("\nTABLE OF FACTORIALS\n\n");
printf(" n            n!\n");
printf("-- ------------------------\n");

But we don't really need to make 3 separate calls to printf here.  Instead, let the compiler automatically concatenate string literals together so we can write this:

printf("\nTABLE OF FACTORIALS\n\n"
         " n            n!\n"
         "-- ------------------------\n");

I'd also suggest that puts would be a more appropriate call than printf since all we're printing is a string literal.

Be careful with signed vs. unsigned

If you don't intend for your code to handle negative numbers, I'd suggest that you indicate this clearly by changing the function signature to this:

unsigned long long factorial(unsigned i)

Minimize the scope of variable

In modern C, we don't tend to declare all variables at the top of each function.  Instead, they're declared as they're needed and in as small a scope as possible, as in the following suggestion:

Prefer for to while loops

In the main code, the while(1) suggests that the loop continues forever but it really doesn't.  In fact, we increment i each time and exit when the factorial code detects an overflow.  Why don't we just write it that way instead of making the reader work so hard?

int main(void)
{
    printf("\nTABLE OF FACTORIALS\n\n"
             " n            n!\n"
             "-- ------------------------\n");

    unsigned long long number;

    // factorial() returns 0 on overflow
    for (unsigned i; (number = factorial(i)); ++i) {
        printf ("%2u %24llu\n", i, number);
    }
}

Simplify your code

The current factorial code has the same problem with its loop, which is that it's not made clear when the loop ends.  Also, the code for detecting overflow is much more complex than it needs to be.  Instead, we can simply note that when the multiplication results in overflow, the resulting product is less than the previous value.  Using that, I'd write the code like this:

// return the factorial of i or
// 0 if multiplication overflows
unsigned long long factorial(unsigned i)
{
    if (i == 0) {
        return 1;
    }
    unsigned long long res;
    for (res = i--; i; --i) {
        unsigned long long prev = res;
        res *= i;
        if (res < prev) { // oveflow?
            return 0;
        }
    }
    return res;
}

Omit return 0

When a C or C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no need to put return 0; explicitly at the end of main.

Note: when I make this suggestion, it's almost invariably followed by one of two kinds of comments:  "I didn't know that." or "That's bad advice!"  My rationale is that it's safe and useful to rely on compiler behavior explicitly supported by the standard.  For C, since C99; see ISO/IEC 9899:1999 section 5.1.2.2.3:

  [...] a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0.

For C++, since the first standard in 1998; see ISO/IEC 14882:1998 section 3.6.1:

  If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;

All versions of both standards since then (C99 and C++98) have maintained the same idea.  We rely on automatically generated member functions in C++, and few people write explicit return; statements at the end of a void function.  Reasons against omitting seem to boil down to "it looks weird".  If, like me, you're curious about the rationale for the change to the C standard read this question.  Also note that in the early 1990s this was considered "sloppy practice" because it was undefined behavior (although widely supported) at the time.

So I advocate omitting it; others disagree (often vehemently!)  In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means.


A couple of things I have noticed (and I haven't tested the code):

If you make the return value a Variant, instead of Long, you can also pass Excel Errors (e.g. #VALUE!) as a result from the UDF. This would be particular useful if IfPossible is False.
You set OPERATORS up as a constant so you can check the validity of an input. But you don't use the string position at all. So, instead of Const OPERATORS As String = ">,<,<>,=", you can simply have Const OPERATORS As String = "<>=" which covers <, >, <> and =.
Having set and used OPERATORS, you only check the 1st character, so <> will never be matched.
You don't want to check for <= and `>=' as well?

Codewise:

    If Not UBound(criteriaArray, 1) = UBound(critRangeArray, 1) Then
        isPossible = False
    Else: isPossible = True
    End If

Can be simplified to

isPossible = (UBound(criteriaArray, 1) = UBound(critRangeArray, 1))

Similarily:

If IsEmpty(criteriaArray) Then
    isPossible = False
Else: isPossible = True
End If

can be simplified to:

isPossible = Not IsEmpty(criteriaArray)

That entire If-Then-Else block can become:

If Not IsArray(criteriaArray) Then
    isPossible = Not IsEmpty(criteriaArray)
Else
    isPossible = (UBound(criteriaArray, 1) = UBound(critRangeArray, 1))
End If

Which, of course, you can turn around to get rid of the Not

If IsArray(criteriaArray) Then
    isPossible = (UBound(criteriaArray, 1) = UBound(critRangeArray, 1))
Else
    isPossible = Not IsEmpty(criteriaArray)
End If

Missing something here: Select Case isNumeric. That is not how the IsNumeric(val as variant) function is used. And given this is a Boolean result, a simple if-then statement will work. I am surprised this runs without throwing an error (I am taking your word for it that it works).

I am not going to go through it here (this answer is now long enough), but that case statement needs some serious rework. You have a lot of repetition and could probably get rid of at least two levels of nesting.


This is a nice example of Cooperative Multitasking. Each task has to decide if and when it yields. However based on the fact that the individual tasks are placed in a single program, this could sooner be called Cooperative Multithreading.

In the putstring procedure you erroneously wrote jmp putstring where you clearly wanted to write jmp .continue. That's an honest mistake.
What you do keep neglecting though is the DisplayPage parameter that BIOS expects in the BH register.

If you've programmed in MASM before, it can be hard to adopt the shorter way to load an address via the mov instruction. mov si, task_a does the same as your lea si, [task_a] but it is 1 byte shorter. You used this many times (11x).

    cmp     cx, 3                 ; change this to add more tasks
    jl      .continue
    ret                           ; no free task, return immediately
.continue:

This ressembles a beginner's code, yet I'm sure you are not a beginner!
The spawn_new_task procedure has a nice ret near its end, so why not jump there based on the opposite condition?

    cmp     cx, 3                 ; change this to add more tasks
    jnl     .ret                  ; no free task, return immediately

    ...

.ret:
    ret

Same thing happens here:

    cmp     byte [bx], 1          ; is this stack active
    je      .found_one
    jmp     .loop
.found_one:

Why not write (no need for the label this time):

      cmp     byte [bx], 1          ; is this stack active
      jne     .loop

Because your main task will always be active, there's no reason to consider it in the search for a free task slot. This saves one iteration forever.
Also there's no need to test the CX counter up front. Better have the test near the bottom and avoid the extraneous unconditional jump back. So changing from a Do While loop into a Loop While loop.
Starting from a byte that is known to be 0, inc byte [bx] will produce shorter code than mov byte [bx], 1.

spawn_new_task:                   ; find a free task, start pointers off at -1
    xor     cx, cx
    mov     bx, stack_status
.loop:
    inc     bx
    inc     cx
    cmp     [bx], ch              ; CH=0
    je      .done                 ; if equal, tasks is free
    cmp     cx, 2                 ; change this to add more 'spawnable' tasks
    jb      .loop
    ret                           ; no free task, return immediately
.done:
    inc     byte [bx]             ; task was free, reserve it

What's the comment "start pointers off at -1" about? Your code nowhere has any -1.

The bulk of this program contains empty space. You can easily move the free space for the additional stacks outside of the program file.

The following rewrite (FASM) reveals a code size reduction of 9% (171 → 156) and a file size reduction of 72% (735 → 208).

org 100h

main:
    mov     si, task_a
    call    spawn_new_task
    mov     si, task_b
    call    spawn_new_task

.loop_forever:
    mov     si, main_str
    call    putstring
    call    yield
    jmp     .loop_forever

task_a:
    mov     si, main_a
    call    putstring
    call    yield
    jmp     task_a

task_b:
    mov     si, main_b
    call    putstring
    call    yield
    jmp     task_b

spawn_new_task:                   ; find a free task slot
    xor     cx, cx
    mov     bx, stack_status
.loop:
    inc     bx
    inc     cx
    cmp     [bx], ch              ; CH=0
    je      .done                 ; if equal, task slot is free
    cmp     cx, 2                 ; change this to add more 'spawnable' tasks
    jb      .loop
    ret                           ; no free task, return immediately
.done:
    inc     byte [bx]             ; task was free, reserve it
    mov     bx, stack_pointers
    mov     [bx], sp              ; save main's stack pointer
    add     bx, cx                ; switch to free stack
    add     bx, cx                ; free stack is list of words (not bytes) and add is cheaper than mul
    mov     sp, [bx]              ; change to free stack
    push    si                    ; push stuff
    pusha
    pushf
    mov     [bx], sp              ; save new stack's new pointer
    mov     sp, [stack_pointers]  ; change back to main
    ret

yield:
    ; ret already saved by call
    pusha
    pushf
    movzx   cx, byte [current_task]
    ; save current stack pointer
    mov     bx, stack_pointers
    add     bx, cx
    add     bx, cx
    mov     [bx], sp
    ; loop through stack status looking for a 1
    mov     bx, stack_status
    add     bx, cx                ; make sure we start looking at next task
.loop:
    inc     bx
    inc     cx
    cmp     cx, 3                 ; increment this for more tasks
    jb      .continue
    xor     cx, cx                ; clear cx
    mov     bx, stack_status      ; reset bx back to start
.continue:
    cmp     byte [bx], 1          ; is this stack active
    jne     .loop
    mov     [current_task], cl
    ; switch to new stack
    mov     bx, stack_pointers
    add     bx, cx
    add     bx, cx
    mov     sp, [bx]
    popf
    popa
    ret

    ; takes an address to write to in si
    ; writes to address until a null term is encountered
    ; returns nothing
putstring:
    mov     bh, 0
    mov     ah, 0Eh
    jmp     .first
.next:
    int     10h                   ; call interrupt
.first:
    lodsb                         ; put char to write in al
    test    al, al                ; simulate and
    jnz     .next                 ; was al 0?
    ret

    main_str: db "I am task main", 13, 10, 0
    main_a: db "I am task a", 13, 10, 0
    main_b: db "I am task b", 13, 10, 0

    current_task: db 0

    stack_status:
    status_1: db 1                ; this is for Main
    status_2: db 0
    status_3: db 0

    stack_pointers:
    dw 0                          ; this is for Main
    dw stacks + 256
    dw stacks + 512

    stacks:


Your logic seems good. The problem statement was a tough to understand, but I think I got it.

Since inclusion and exclusion do not change, we should extract that checking from the loop and place it before the loop.

Furthermore, to reduce programmer errors, I reduced the code duplicity. The "do whatever you want" is now only typed once, and the regex pattern is only typed once.

String tempPattern = "(^|.*;)" + temp + "(;.*|$)";

boolean tempInInclusionOrNotInExclusion;
if(inclusion != null && !inclusion.trim().isEmpty()){
    tempInInclusionOrNotInExclusion = inclusion.matches(tempPattern);
} else if(exclusion != null) {
    tempInInclusionOrNotInExclusion = !exclusion.matches(tempPattern);
} else {
    tempInInclusionOrNotInExclusion = true;
}

for(PdsxAttrKey key: pdsxWriteRequest.getAttrKeys()){
    boolean shouldDoWhatIWantToDo;
    if(key.equals("156") || key.equals("155")) {
        shouldDoWhatIWantToDo = tempInInclusionOrNotInExclusion;
    } else {
        shouldDoWhatIWantToDo = true;
    }

    if(shouldDoWhatIWantToDo){
        //Check the PdsxAttrValue has a Synthesizer
        if(metadata!=null){
            Synthesizer synthesizer = metadata.getSynthesizer();
            if(synthesizer!=null){
                //Synthesize the attribute
                PdsxAttrValue synthesizedVal = synthesizer.synthesize(key, record);
                //if(synthesizedVal!=null){
                val = synthesizedVal;
                //}
            }
        }
        if(val!=null){
            writeRecord.getAttrs().put(key, val);
        }
    }
}


Factory for classes unknown at compile time

I don't understand exactly the purpose of the code but having two similar object inheritance tree (Actions and Parts) smells a little bit. It also seems a sample code and I guess it violates the single responsibility principle (the behaviour of a part is separated to two classes) and it might also violates the Liskov substitution principle too (if you have an Action you can't use it with any kind of Part). I'd consider moving the action code to the Part class or creating generic Action classes which ignore unhandled Parts (by class type). Anyway, it's hard to say something more useful without the purpose of the code. See also: SOLID, Parallel Inheritance Hierarchies.

Other notes:

ArrayList<...> reference types should be simply List<...>. See: Effective Java, 2nd edition, Item 52: Refer to objects by their interfaces

List<Part> parts = new ArrayList<Part>();

Public fields usually leads to harder maintenance. See: What's the deal with Java's public fields?

Some other ideas to consider:

Create a separate Action instance for every part and action. Pass the Part instance to the constructor of your Action. For example:

Action rotate = new Rotate(gear);

Store the actions in a list and then you can call execute on the rotate instance:

for (final Action action: actions) {
    action.execute();
}

It's type-safe, clients can't create an Action with a wrong Part type.
I'd move the actions list from the Part object to somewhere else. Why should a part know what actions does a machine do with it? It seems to me that this responsibility should be stored somewhere else. The Macine is the closest object now (but it might deserve separate class).
If the Action classes do not have any state consider moving their code inside the Part object. (The basic idea of OOP is that the data and the logic which operates with the data should be together in a class.) You can mark the action method with an @Action annotation and parse it runtime.

public class Gear {

    ...

    @Action
    public void rotate() {
        ...
    }
}

I guess you still need a class which stores the actions which a machine should do:

public class Action {
    private Part part;
    private String actionMethodName;
}


Get character occurence count along with character in a string

I don't see any problem in your code except using of equality and inequality operators. Use strict equality(===) & inequality(!==) operators.

I'll suggest to use RegEx.

.replace(/(.)\1*/g, function(m, $1) {
    return $1 + m.length;
})

The RegEx (.)\1* will match a single non-line-break character and check if that is followed by the same character any number of times. m here is the complete match and $1 is the first chaptured group value i.e. the character.

var res = 'aaaabbbbaaacccbbb'
    .replace(/(.)\1*/g, function(m, $1) {
        return $1 + m.length;
    });
console.log(res);


PHP DateTime increments, a neater / more efficient way?

I like it.
You could use loops and use a variable for 'DateInterval(P1D)'.

<?php $date = new DateTime('2013-04-01');
      $day = new DateInterval('P1D');
?>
<?php echo $date->format('Y'); ?>
<?php echo $date->format('D jS');?>
<?php
for($i = 0;$i <= 6; $i++){
    $date->add($day)
    echo ''.$date->format('D jS').'	';
}?>


Searching an element in an alternately sorted array

How about an alternate approach: instead of adapting the binary-search algorithm to work with all kinds of alternate sorted collections, how about adapting the collections to be able to run classic binary search on them.

This enables one to use production ready searching methods without reinventing the wheel and risking bugs. Even if one decides to rewrite binary search as an exercise it is still easier as it doesn't have to take the alternating indexes into account.

public static int findInAlternateSortedArray(int[] haystack, int needle) {
    if (haystack.length > 0) {
        List<Integer> sortedAscending = new EverySecondElement(haystack, 0);
        int index = Collections.binarySearch(sortedAscending, needle);
        if (index >= 0) return index * 2;
    }
    if (haystack.length > 1) {
        List<Integer> sortedDescending = new EverySecondElement(haystack, 1);
        int index = Collections.binarySearch(sortedDescending, needle, Comparator.reverseOrder());
        if (index >= 0) return index * 2 + 1;
    }
    return -1;
}

All that is needed to be able to use the standard library provided Collections.binarySearch is to provide two views into the original array, as if he had two independently sorted collections.

Given an index into each of these lists, we can easily calculate the index from the original array from where to fetch an element in \$\mathcal{O}(1)\$ time, thus the runtime of the entire search is still \$\mathcal{O}(\log N)\$.

static class EverySecondElement extends AbstractList<Integer> {
    private int[] array;
    private int offset;

    EverySecondElement(int[] array, int offset) {
        this.array = array;
        this.offset = offset;
    }

    @Override
    public int size() {
        return (array.length - offset + 1) / 2;
    }

    @Override
    public Integer get(int index) {
        return array[offset + index * 2];
    }
}


Separation of concerns

You are mixing user interface and calculations: you should declare function for processing data and doing calculations and other functions to print pretty output. labor() handles both claculating and outputting.

Globals should be avoided

A function should be considered a black box with no knowledge about the outside world, function should never use global variables, because it is hard to mentally keep track of the value of all the global variables. Consider making sqft an argument of labor.

Functions are different from go to

def should_i_stay():
    if answer in move_on:
        program()

So you are basically jumping from one point in the code to an arbitrarly past point in the code. Functions should not be used this way (see above).

User interface

You should strive to offer the best interface possible to the user, your code has several User Interface flaws:

There is no space between the question and the space where you must input, this fells awkard.
Bad input ends the programme immediately or shows a scary error message:

:

This program will help you find the cost of floor covering

What is the cost of the tile per square foot?about 10 dollars
Traceback (most recent call last):
// Omitted for brevity
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]

you should learn about exception handling to make the input more reliable.

Best practices

You are using a magic number 20 in your labor function. A magic number is a number with no explanation whatsoever why you chose it over another.
Do not use from module import *, it will give people (even yourself in the future) problems figuring out where the functions used are taken from and may generate name clashes.
Use an if __name__ == '__main__' guard so that you can import your code in other files.
Global constants should be declared at the start of the file and be ALL CAPS:

:

EXIT_PROGRAM = ["q", "Q"]

MOVE_ON = ["y", "Y"]

MORE_INFO = ["n", "N"]


Generating a unique reference number for logging purposes in a custom exception

concerned if cutting the UUID short will keep it unique

Well, you're outputting 32 bits. So you can do ballpark 64k transactions (2^16) before running into Big Trouble, according to the birthday paradox.

If you realistically expect someone to report issues within a day, then the identifier is effectively (day, reference), which looks more attractive, as you can do some tens of thousands of transactions each day rather than over the lifetime of the service. More generally, resolve ties with "last one wins", and then you're comparing "typical distance between collisions" to "typical time for user to report an issue".

You're putting 4 bits of entropy into each hex nybble, which likely will be copy-n-pasted (or forwarded) by the user. If you're working within an 8-character constraint, consider using a scheme like base36 or base64 so each character sends more bits. Without pasting there will be usability limitations, such as eyeballing an 'l' and sending the digit '1'.

If you're not worried about users making up identifiers, consider using (userid, serial_num), or better: (userid, timestamp).


You are not using a DataContext, so presuming you don't want to for this, I'd suggest that you also consider a connection pool, that way you don't need to incur the connection cost for every select/delete.

Additionally, your catches are very heavy, are you getting that many errors that you need to track?  You may want to see this question as an alternative to logging the errors yourself: https://stackoverflow.com/questions/5076303/sql-server-error-messages

@kubal5003 - good point on automatic connection pooling, here is the MSDN that discusses it and its sibling that lists the connection string properties and defaults


Compute count of unique words using ES6 sets

Two problems

Your code has two problems.

It does not remove punctuation from the words resulting in the same words not matching. Eg text1 has 12 unique words not 13. You count dolor and dolor. as different words.
You are ignoring capitalization. You would count Dolor and dolor as different words rather than the same.

String.match

Update I was not paying attention on first posting. There is no /*RegExp.match*/

The better solution is to use the String.match to convert the matches to an array and then directly create the set from that. The code is just one line and the performance is 2.5 times faster than using String.replace as shown.

thus the ideal solution becomes...

const uniqueWords = txt => new Set(txt.toLowerCase().match(/\w+/g)).size;

String.replace

You can use a string replace to iterate over RegExp matches. It's a little hacky but I much prefer it over other methods such a using a RegExp to split the string, or RegExp.match, or RegExp.exec which have an ugly interface and are slower than String.replace.

Converting the text to lowercase  using String.toLowerCase solves the capitalization problem

const countUniqueWords = text => {
    const words = new Set();
    text.toLowerCase().replace(/\w+/g, word => words.add(word));
    return words.size;
}

const a = "Lorem ipsum dolor sit amet consectetuer adipiscing elit aenean commodo ligula eget dolor.";
const b = "Etiam ultricies nisi vel augue. Curabitur ullamcorper.";
info1.textContent = `A has ${countUniqueWords(a)} unique words`;
info2.textContent = `B has ${countUniqueWords(b)} unique words.`;

A: "Lorem ipsum dolor sit amet consectetuer adipiscing elit aenean commodo ligula eget dolor."

B: "Etiam ultricies nisi vel augue. Curabitur ullamcorper."


You want to use what Rails calls eager loading. This is done with the :include parameter in your AR call. Add it to your lambda block.


Well, I guarantee that qsort doesn't start with a heap allocation. Benchmark several different sizes of array and graph the results, to see where the lines hit the Y-axis: how much of your benchmark is just measuring the speed of malloc?

size_t count[2] = {0};

Depending on the smartness of your compiler, an array that doesn't have to be an array might be a big performance hit. Arrays are often stored in memory, on the stack, as opposed to scalar variables which can be stored in registers without any real cleverness on the compiler's part. Plus, in this case, your code seems to be needlessly convoluted by the use of an array instead of two different variables count0 and count1. Compare:

for (int exp = 0; exp < digits; ++exp) {
    // Count elements
    size_t count0 = 0;
    size_t count1 = 0;
    for (size_t i = 0; i < size; ++i) {
        if ((a[i] >> exp) & 1) {
            count1 += 1;
        } else {
            count0 += 1;
        }
    }

    // Cumulative sum
    count1 += count0;

    // Build output array
    for (int i = size - 1; i >= 0; --i) {
        if ((a[i] >> exp) & 1) {
            b[--count1] = a[i];
        } else {
            b[--count0] = a[i];
        }
    }
    int *p = a; a = b; b = p;
}

After rewriting like this, it becomes apparent that after the first loop, count0 + count1 == size; and after the "Cumulative sum" step, count1 == size. So we can eliminate half of the code.

    size_t count0 = 0;
    size_t count1 = size;
    for (size_t i = 0; i < size; ++i) {
        if (((a[i] >> exp) & 1) == 0) {
            count0 += 1;
        }
    }

    // Build output array
    for (int i = size - 1; i >= 0; --i) {
        if ((a[i] >> exp) & 1) {
            b[--count1] = a[i];
        } else {
            b[--count0] = a[i];
        }
    }

Then, the "Build output array" step is doing the exact same workload (a[i] >> exp) & 1 a second time! That seems like a fruitful source of optimization. What if you folded the second loop into the first loop, something like this?

for (int exp = 0; exp < digits; ++exp) {
    size_t up = 0;
    size_t down = size;
    for (size_t i = 0; i < size; ++i) {
        int x = a[i];
        if ((x >> exp) & 1) {
            b[--down] = x;
        } else {
            b[up++] = x;
        }
    }
    assert(up == down);
    // Now elements [up..size) are in reversed order,
    // so we need to flip them back around.
    reverse_array(b + up, b + size);
    int *temp = a; a = b; b = temp;
}

Writing reverse_array is left as an exercise for the reader.

I'd be interested to see your benchmark results for this "improved" algorithm.


<version>0.1.0</version>

In Maven, note that the concept of a version that is not released and is still in development is called a snapshot. This means that the version should not be a release version, like 0.1.0, but a snapshot version, like 0.1.0-SNAPSHOT. This is important because it distinguishes clearly what is a version in development and a released version.

As such, consider using a snapshot version here. It is when the Maven project is released, with the help of the maven-release-plugin, that the version will automatically be bumped to a release version (without SNAPSHOT) and tagged on version-control with it.

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <version>3.5.1</version>
  <configuration>
    <source>1.8</source>
    <target>1.8</target>
  </configuration>
</plugin>

That is a nice way to configure the Maven project to use Java 8. You can also do it in an alternate way. Both the source and target parameter of the maven-compiler-plugin have a corresponding user property, which are maven.compiler.source and maven.compiler.target, so you can set them in a <properties> section:

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

This will have the same effect as the current <source> and <target> configuration.

Note that you could not specify a version for the Compiler Plugin in this case; it is the default version coming from the Maven installation that would be used (reference here for 3.3.9). In general, it is a good idea not to rely on this default version and specify explicitly the version to use: this helps in ensuring that the build does not depend on a given Maven version; also it documents clearly the version that is used.

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>[4,5)</version>
</dependency>

Be careful when using version ranges. Ideally, you want to declare dependencies on a single fixed version of a dependency: using a version range is bad practice.

The big advantage of using a fixed version is that it makes it clear what is the expected version to use for your project. What specific version of JUnit do you want your project to depend on? Each version are very different, all of them with their respective features and bugs. With a range, you are basically saying "I don't really care, pick one in major version 4". You could even end up with a SNAPSHOT version (MNG-3092). It should be up to you to pick a version; you can upgrade it later if necessary.

Also, you should use the test scope for the JUnit dependency. It is only needed in the test classpath and is not a compile-time dependency of the main classes.

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
  <scope>test</scope>
</dependency>


The functionality you are trying to create already exists in std::function<> using std::bind<> to help.

Comments on the rest of the code:

Here you use emplace back:

  void attach ( CbType cb )
  {
    callbacks_.emplace_back(cb);
  }

Emplace back is usually used when you have the arguments and want to build the object in place using the arguments. By passing the object you are going to just invoke the copy constructor. As a result there is no benefit from using it. Though there is nothing wrong with using it either. Currently I am still working out when to use emplace_back() over push_back() but this is one situation where I would still use push_back().

Also because you pass the argument by value you are copying the object into the function then using the copy constructor to put it in the array resulting in another copy. So here I would pass by reference.

  void attach(CbType const& cb)
  {
    callbacks_.push_back(cb);
  }

Don't use unnecessary casts

broadcast(static_cast<unsigned int>(price*100));

// This is easier to read as:

broadcast(price*100); // double is auto converted to unsigned int

Use standard types:

typedef Callback<void,unsigned int> CbType;

// Replace with:

typedef std::function<void(unsigned int)> CbType;

If you use the standard function then the equivalent to creation becomes much simpler

 p.attach(std::bind(&Strategy::update,this, _1));

Don't use pointers where a reference is a better choice:

Strategy(Pricer*  p) :  p_(p)

You are passing a pointer and not checking for NULL. Actually the code never checks for NULL so you must use a valid pointer. In this case you may as well pass a reference. If you want to store this internally as a pointer then take its address inside your object.

Strategy(Pricer&  p) :  p_(&p)  // p can never be invalid.


A couple of quick minor points:

Try not to abbreviate names, characters cost you nothing.

float distFromCamera

should be renamed to:

float distanceFromCamera

Names should relate to what they are ShipManager shipControls is it a "Manager" or a set of controls? The type name doesn't match the variable name in my opinion. As an aside, I generally dislike ***Manager as a name (and I'm not the only one);

Enum members should be PascalCase:

enum StateOfRotation
{
    Waiting,
    Rotating
}

It is nicer to put all of your fields at the top of your file. You have some mixed in between method definitions.

I prefer explicit access modifiers on everything. e.g. private float distanceFromCamera. In Unity, with the whole public field thing, it can make the class easier to skim as well.