Automatic variable generation from data table

Use array, this will reduce by a lot your number of variables.
Name your variable properly ("ten" should be "tenant")
Normaly, variable starts with a lower case in .net
Do not concatenate your strings for queries, this will increase your chances of injections
Your datatable is a bit useless in your case, you can write directly to your variables with a datareader
Your listReport is only needed at the end, I think you could initialize it there instead
I would separate this into multiple functions. A "GetTenants" that returns the list, a "GetTenantID" and a "ShowReport". This way these function can be out of the UI and reused if needed.
Your report takes multiple tenant names but only one ID, this seems strange.

If cmbReports.Text = "Conditions Of Tenancy" Then

    Dim tenants As New List(Of String)
    Dim tenantID As Integer

    Dim propertyId As Integer
    Dim leaseId As Integer

    If Not Int32.TryParse(lblPropertyIDValue.Text, propertyId) Then
        ' Not an integer, this is an error
    End If

    If Not Int32.TryParse(lblLeaseIDValue.Text, leaseId) Then
        ' Not an integer, this is an error
    End If

    tenants = GetTenants(propertyId, leaseId)
    tenantID = GetTenantID(propertyId, leaseId)

    ShowReport(tenants, tenantID, propertyId, leaseId)

End If

Function GetTenants(ByVal propertyId As Integer, ByVal leaseId As Integer) As List(Of String)

    Dim tenants As New List(Of String)

    Using cnn As New SqlConnection(My.Settings.BMSSouthSideConnectionString)
        cnn.Open()

        Dim command As New SqlCommand("Select  TenantForename + ' ' + TenantSurname as FullName From Tenants Where LeaseID = @LeaseID and PropertyID = @PropertyID", cnn)

        command.Parameters.Add("@LeaseID", SqlDbType.Int).Value = leaseId
        command.Parameters.Add("@PropertyID", SqlDbType.Int).Value = propertyId

        Using reader As command.ExecuteReader()
            Do While reader.Read()
                tenants.Add(reader.GetString("FullName"))
            Loop
        End Using

        cnn.Close()
    End Using

    Return tenants
End Function

Function GetTenantID(ByVal propertyId As Integer, ByVal leaseId As Integer) As Integer

    Dim tenantID As Integer

    Using cnn As New SqlConnection(My.Settings.BMSSouthSideConnectionString)
        cnn.Open()

        Dim command As New SqlCommand("Select Top 1 TenantID From Tenants Where LeaseID = @LeaseID and PropertyID = @PropertyID", cnn)

        command.Parameters.Add("@LeaseID", SqlDbType.Int).Value = leaseId
        command.Parameters.Add("@PropertyID", SqlDbType.Int).Value = propertyId

        Using reader As command.ExecuteReader()
            If reader.Read() Then
                tenantID = reader.GetInt32("TenantID")
            End If
        End Using

        cnn.Close()
    End Using

    Return tenantID
End Function

Sub ShowReport(ByVal tenants As List(Of String), ByVal tenantID As Integer, ByVal propertyId As Integer, ByVal leaseId As Integer)

    Dim listReport = New FastReport.Report

    listReport.Load("C:\Users\richard\Documents\BMSSouthSide\BMSPanda\Reports\CONDITIONSOFTENANCY.frx")
    listReport.SetParameterValue("CRMConnectionString", "Data .....

    Dim tenantList As String = String.Join(" ", tenants.ToArray())

    ListReport.SetParameterValue("PropertyID", propertyId)
    ListReport.SetParameterValue("LeaseID", tenantID)
    ListReport.SetParameterValue("TenantID", tenantID)
    ListReport.SetParameterValue("TenantList", tenantList)
    ListReport.Show()

End Sub


I think all the comments should be removed. The point of a comment is to explain why you wrote this code, not what the code does. If anyone reads the code, they will be able to understand what it does without reading the comments. When you write comments, always ask yourself : "Will this comment help me understand why I wrote this code 5 years ago?" (Or.. 2 weeks if you have a bad memory like mine), if you can't answer, you probably don't need comments!

The formatting looks perfect in my opinion.


Infinite monkey theorem demonstration in Python

In Python you don't need to declare your variables. So the randSent = [""] * (len(userSent) - 1); randSent.clear() part is completely unnecessary.

Second, Python has an official style-guide, PEP8, which programmers are encouraged to adhere to. It recommends using lower_case_with_underscores as variable and function names.

Python also has a built-in module called string, which has all lowercase characters. With it, generating a random sentence becomes a lot easier. I renamed this function generate, to adhere more closely to the requirements. It uses random.choice, which just chooses a random element from a sequence and _ as a placeholder for the unused loop variable.

import random
import string

ALLOWED_CHARS = string.ascii_lowercase + " "

def generate(n):
    return "".join(random.choice(ALLOWED_CHARS) for _ in range(n))

The requirements also mention a score function, which you have kind of implemented in your main function. I would implement it using sum and iterating over both sentences simultaneously:

def score(user_sentence, sentence):
    return sum(user_char == char for user_char, char in zip(user_sentence, sentence))

Alternatively, you could use the Levenshtein distance as score:

$ pip install python-Levenshtein

Which you can then use like this:

import Levenshtein

def score(user_sentence, sentence):
    return len(user_sentence) - Levenshtein.distance(user_sentence, sentence)

When testing these two score functions, the Levenshtein seems to be about twice as fast:

In [8]: s1 = generate(27)
In [9]: s2 = generate(27)
In [10]: %timeit score(s1, s2)
100000 loops, best of 3: 3.47 µs per loop

In [11]: %timeit score_levenshtein(s1, s2)
1000000 loops, best of 3: 1.75 µs per loop

The actual main function can be a lot simpler, I use itertools.count to have a loop that runs infinitely long and keeps track of how many iterations it has gone through.

I think your code has a bug, in that it seems to set a position as True if you ever found a string that has the correct character in that position. The requirements are quite clear that you should generate new sentence each time and discard the old characters (even if some were correct). I also implemented the output every 1000 iterations. I call the code with a if __name__ == "__main__": guard to allow importing parts of this script from another script.

import itertools

def compare(user_sentence):
    n = len(user_sentence)
    max_score = 0
    best_fit = " " * n

    sentence = generate(n)
    for i in itertools.count():
        if sentence == user_sentence:
            # We are done
            print i
            break

        # Calculate score of current sentence and update best score if necessary
        current_score = score(user_sentence, sentence)
        if current_score > max_score:
            max_score = current_score
            best_fit = sentence

        # Output every 1000 iterations
        if i % 1000 == 0:
            print i, best_fit, max_score

        # Get a new random sentence
        sentence = generate(n)

if __name__ == "__main__":
    compare("methinks it is like a weasel")

As alluded to in the problem statement, this takes quite a long time to run. Mine has been running about 10 minutes now and has gone through about 32 million iterations and has a maximum score of 11/27. But considering that there are \$27^{27} = 443426488243037769948249630619149892803\$ permutations for a 27 character long string with 27 possible characters at each position, this could take quite a bit longer...


Calculating a quality score of something based on attributes

This approach sounds logically good, as it allows to determine how much the profile has been completed. There seems to exist a correlation between people completing their profile fully and giving interesting data in these. It also provides an incentive for completion.

A first iteration of improvement could be to decouple the data and the calculation operation.

First, define an array with a bunch of scores.

Then, loop on this array and compute it:

/**
 * Computes the quality of a contact, according profile completion
 *
 * @return float The score calculated from profile completion (between 0 and 1)
 */
public function getQualityAttribute()
{
    $propertiesScore = [
        'firstname' => 1,
        'lastname' => 1,
        'nin' => 5,
        'birthdate' => 2,
        'mobile' => 4,
        'email' => 4,
        'postal_address' => 3,
    ];
    $totalScore = array_sum($propertiesScore);

    $qualityScore = 0;
    foreach ($propertiesScore as $property => $score)
    {
        if (isset($this->$property))
        {
            $qualityScore += $score;
        }
    }

    return $qualityScore / $totalScore * 100;
}

This is a first naive approach to illustrate the method, but introduces something not desirable, $this->$property: this works, but it's not easy to parse by a static analyzer, as the type is not easy to determine. Normally, such code should be replaced by an array.

A more robust approach is so something like this:

    $qualityScore = 0;
    $instanceProperties = get_class_vars($this);
    foreach ($propertiesScore as $property => $score)
    {
        if (isset($instanceProperties[$property]))
        {
            $qualityScore += $score;
        }
    }

Then, we could see the properties score array is a preference. Laravel offers a config repository to store that.

Move this array to config/app.php or better, create a config/quality.php so you'll be able to put future settings too:

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Quality score per user profiles
    |--------------------------------------------------------------------------
    |
    | This option allows to balance the equation which determines the quality
    | score of a profile, according its level of completion.
    |
    | You can assign a weight (the greater the more important) to each property.
    |
    */

    'scores' => [
        'profile' => [
            'firstname' => 1,
            'lastname' => 1,
            'nin' => 5,
            'birthdate' => 2,
            'mobile' => 4,
            'email' => 4,
            'postal_address' => 3,
        ],
    ],
];

Now you can access it from the getQualityAttribute method using $propertiesScore = Config::get('quality.scores.profile');. Don't forget to add use Config; at the top of your file to get this facade.

Finally, if 0 is never a valid answer, you could use empty instead of isset, so you avoid a bug if the property is "" instead of null (that would give score).


This is some fantastic first Go code!

Great use of anonymous structs for test fixtures. I disagree with @sineemore, these are incredibly idiomatic. Nice job writing tests, as well!

There isn't much to be said for the code itself. It's simple and reads clearly. Perhaps you'd want to document it (go doc is fantastic).

I guess strings.Builder is the idiomatic way to do string concatentation in Go >=1.10. However, this is largely for performance reasons.

var roman strings.Builder
for _, conversion := range conversions {
    for number >= conversion.value {
        roman.WriteString(conversion.digit)
        number -= conversion.value
    }
}
return roman.String()

Your next steps are learning about packaing and naming. I'd suggest that instead of calling the field digit you call it something more descriptive like numeral (conversion.numeral reads better than conversion.digit to me). Perhaps you can also come up with better names for roman and number?

I'd also give the function a better name. And to do so, I'd place it in a package called roman. Then call it FromInt. In this way, you use it like roman.FromInt(42), which reads much better. Package naming is really important in Go and you'll find a lot of the standard libraries follow this pattern of making the package name part of the "sentence" instead of just some extra stuff you have to prepend.

In doing this, I'd also recommend putting your tests in package roman_test so they can't access any private functions or variables. This is convention.


Simple Rock-Paper-Scissors to get more comfortable with OOP

I think that one another class Choice will be useful. You have two functionality to move to this class:

make random choice. You can simple write def make_random(self):
compare two choices. You can define standard operators def __lt__(self, oth): and def __gt__(self, oth):. If you want handle ties than __eq__ operator will be useful also.

Then your gameplay function could be like

def gameplay(self):
    self.player_one.choice.make_random()
    self.player_two.choice.make_random()
    if self.player_one.choice > self.player_two.choice:
        self.player_one.score += 1
    elif self.player_one.choice < self.player_two.choice:
        self.player_two.score += 1


Naming:
Your class is named Input_Window which violates standard Java naming conventions of PascalCase (without underscores).
Formatting:
An equal sign should be surrounded by spaces:

myslideA = slider(0,10,3,1,true,true);
//and so on...

Visibilities:

Your JSliders should most probably be private. nobody aside from
your InputWindow should have to know about them. If there's someone out there who wants to know about GUI except the GUI you're doing things wrong ...
slider should also be private. If somebody else uses it, extract it to a utility-class. Hide the information where ever you can. If you don't things may happen with your stuff when you're not watching.

Responsibilities:
Your constructor shouldn't request focus and set the window to visible himself. That's things that should be done in calling code. You don't expect a JFrame to show up on instantiation either, right?


Logging all API call traffic in Java servlets

private static final Logger LOG = LoggerFactory.getLogger(CommentServlet.class);

This is considered as bad practice ... of course there is an argument from the other side as well.

The right thing to use should be

private final Logger LOG = LoggerFactory.getLogger(getClass());

This basically helps you leverage the capabilities of polymorphism and use the same logger in inherited classes with its real name.


Pure Python script that saves an HTML page with all images

Your code is pretty good! I do have a few tips regarding style, and such.

As mentioned in the comments, even though it looks like you aren't, you shouldn't be trying to parse HTML with Regexes.
Where are your comments? While good code can be pretty readable, comments are still a valuable asset. You should probably flesh out your page_loader function with a docstring, and any unclear blocks of code with an inline comment.
If you're only going to use part of a module, e.g, one function or variable, you should do from ... import ....

That's about all I can really think of right now. If there's anything else you want me to comment on, just mention it below, and I'll see if I can cover it. Hope this helps!


Any side effects from this Python logging code?

The logging module already supplies a function name to log messages.  If you want to include the function name in your log message just set the appropriate formatter with %(funcName)s in the format string on your log handler with: http://docs.python.org/2/library/logging.html#logging.Handler.setFormatter

See also http://docs.python.org/2/library/logging.html#logrecord-attributes

The typical usage is to create a global log variable in your module like

logger = logging.getLogger(__name__)

and use that logger within functions in that module.  But creating a separate logger for every single function is excessive.

I (just now) realized this is a pretty old question, but if you're still interested I can provide a full working example.


Assistance requested to refactor a section of Typescript code for readability

To make it easier to follow the flow of the logic, I'm just going to pull out the longer parts of these conditions into helper variables. They may not stay like that in the final version, but it helps as I'm revising it.
const isDocumentTypeMandatory = this.allInputs.documentsType === 'mandatory';

if (source.length > 0) {
    const mandatory = source[0].mandatory;
    if (mandatory === true && isDocumentTypeMandatory) {
        item.mandatory = !item.mandatory;
    } else if (mandatory === false && this.allInputs.documentsType === "mandatory") {
        item.mandatory = !item.mandatory;
    }
} else {
    const mandatory = target[0].mandatory;
    if (mandatory === true && this.allInputs.documentsType === "mandatory") {
        item.mandatory = !item.mandatory;
    } else if (mandatory === false && isDocumentTypeMandatory) {
        item.mandatory = !item.mandatory;
    }
}

The trick to simplifying these kinds of things is to figure out what is similar, figure out how to change the code to make those parts exactly the same, then DRY it up.
For example, I'm noticing that the two branches of the outer if-else are almost exactly the same. The only differences are where it gets the mandatory variable from, and the ! that is sometimes in front of isDocumentTypeMandatory.
Lets start by extracting out the diferences from the two branches:
const isDocumentTypeMandatory = this.allInputs.documentsType === 'mandatory';
const mandatory = source.length > 0 ? source[0].mandatory : target[0].mandatory;
const sourceHasContent = source.length > 0;

if (source.length > 0) {
    if (mandatory === true && isDocumentTypeMandatory !== sourceHasContent) {
        item.mandatory = !item.mandatory;
    } else if (mandatory === false && isDocumentTypeMandatory === sourceHasContent) {
        item.mandatory = !item.mandatory;
    }
} else {
    if (mandatory === true && isDocumentTypeMandatory !== sourceHasContent) {
        item.mandatory = !item.mandatory;
    } else if (mandatory === false && isDocumentTypeMandatory === sourceHasContent) {
        item.mandatory = !item.mandatory;
    }
}

Now those the two branches of the outer-if are now exactly the same, which lets me just get rid of it.
const isDocumentTypeMandatory = this.allInputs.documentsType === 'mandatory';
const mandatory = source.length > 0 ? source[0].mandatory : target[0].mandatory;
const sourceHasContent = source.length > 0;

if (mandatory === true && isDocumentTypeMandatory !== sourceHasContent) {
    item.mandatory = !item.mandatory;
} else if (mandatory === false && isDocumentTypeMandatory === sourceHasContent) {
    item.mandatory = !item.mandatory;
}

At this point, we can just combine the two conditions into one. I personally prefer avoiding multiline if conditions and instead extract the condition into an external variable.
const isDocumentTypeMandatory = this.allInputs.documentsType === 'mandatory';
const mandatory = source.length > 0 ? source[0].mandatory : target[0].mandatory;
const sourceHasContent = source.length > 0;

const flipMandatoryValue = (
    (mandatory === true && isDocumentTypeMandatory !== sourceHasContent) ||
    (mandatory === false && isDocumentTypeMandatory === sourceHasContent)
);

if (flipMandatoryValue) {
    item.mandatory = !item.mandatory;
}

This is probably about as good as it'll get. Certainly, the variable naming can be a ton better (without much context, its hard to give them good names).

There is one other trick that can be applied to simplify things even further, but there's already so much going on here that it might just make the code even less readable, but I'll present it anyways.
This whole time I've been assuming that mandatory can take on other values besides "true" or "false", which is why you're explicitly checking if they're === true or === false. In the following revisions, I'll preserve this idea by doing a typeof check. I'll then modify the condition as follows:
const flipMandatoryValue = typeof mandatory === 'boolean' && (
    (mandatory && isDocumentTypeMandatory !== sourceHasContent) ||
    (!mandatory && isDocumentTypeMandatory === sourceHasContent)
);

// is the same as
const subCondition = isDocumentTypeMandatory !== sourceHasContent;
const flipMandatoryValue = typeof mandatory === 'boolean' && (
    (mandatory && subCondition) ||
    (!mandatory && !subCondition)
);

// is the same as
const subCondition = isDocumentTypeMandatory !== sourceHasContent;
const flipMandatoryValue = typeof mandatory === 'boolean' && (
    // Either both of these booleans should be true, or both should be false,
    // so we can just compare them to each other with ===.
    mandatory === subCondition
);

// is the same as
const subCondition = isDocumentTypeMandatory !== sourceHasContent;
// We can drop the typeof check - we're comparing with a boolean anyways
const flipMandatoryValue = mandatory === subCondition;

This gives us the final revision as follows:
const isDocumentTypeMandatory = this.allInputs.documentsType === 'mandatory';
const mandatory = source.length > 0 ? source[0].mandatory : target[0].mandatory;
const sourceHasContent = source.length > 0;
const subCondition = isDocumentTypeMandatory !== sourceHasContent;

if (mandatory === subCondition) {
    item.mandatory = !item.mandatory;
}

As I said before, using === to compare booleans can be a useful trick to simplify complicated if-thens, but here I feel like it adds more complexity than value, unless you can find good ways to name everything and make it more intuitive.


I would write that simply:

def deep_len(lst):
    """Returns the deep length of the list.

    >>> deep_len([1, 2, 3])     # normal list
    3
    >>> x = [1, [2, 3], 4]      # deep list
    >>> deep_len(x)
    4
    >>> x = [[1, [1, 1]], 1, [1, 1]] # deep list
    >>> deep_len(x)
    6
    """
    return sum(deep_len(el) if isinstance(el, list) else 1 for el in lst)

Note that:

This doesn't create lots of new lists with slices, so I would expect it to be more efficient;
isinstance is a much more Pythonic way to check types than type, despite what the "hint" says, as it handles inheritance better; and
There's no need to special-case an empty lst, as the result is already zero in that case.


Boost Threads - Producer Consumer threads with synchronization

Your usage of the condition variable will probably work but is a-typical.

This is what you basically have:

while (1)
{
    boost::mutex::scoped_lock lock(m);
    if (<Test OK>)
    {
        <Do Work>
        <Notify Consumer>
    }
    else
    {
        <Wait for consumer to signal conditional>
    }
}

Notice that here you lock the mutex m. If the test is not OK then you wait for the consumer to signal the condition variable. This releases the lock on m. Once the condition variable is signaled then your thread must wait to re-aquire the lock to continue. Once it does it releases the lock and then re-starts the loop which immediately try to re-aquire the lock.

A more typical pattern would be:

// pseudo code.
std::unique_ptr<WORK> getWork()
{
    boost::mutex::scoped_lock lock(m);
    while(! <Test OK> )
    {
       <Wait for consumer to signal conditional>
    }
    return <getWorkObjectFromQueue>;
}
.....
while(1)
{
    work = getWork();

    <Do Work>
    <Notify Consumer>
}

This way when you are waiting on the conditional variable and are signaled you do not have multiple attempts to re-acquire the lock before you do the work. As soon as you are signaled and have acquired the lock you can do a bit of work.


Singleton Design Pattern Implementation: Bill Pugh

I read the article Java Singleton Design Pattern Best Practices with Examples, it is an interesting discussion about Singleton Pattern and thread safe.

The basic pattern:

public class TrivialSingletonTest {
    private static TrivialSingletonTest instance;

    private TrivialSingletonTest() {}

    public static TrivialSingletonTest getInstance() {
        if (instance == null) {
            instance = new TrivialSingletonTest();
        }
        return instance;
    }

    public static void main(String[] args) {
        TrivialSingletonTest st1 = getInstance();

        TrivialSingletonTest st2 = getInstance();

        String className = "[" + TrivialSingletonTest.class.getName() + "] ";

        if (st1 == st2) {
            System.out.println(className + "Same object");
        } else {
            System.out.println(className + "Is not a singleton");
        }
    }
}

This is a basic implementation of the Singleton Pattern with a main() method that test it.

The issue with this implementation is just in a multi threading program, where you could have more than 1 instances.

So the fix proposed:

public static synchronized TrivialSingletonTest getInstance() {
    if (instance == null) {
        instance = new TrivialSingletonTest();
    }
    return instance;
}

The issue here is just about performances, that's why the proposition of a different approach, using a private static inner class as an helper to obtain the singleton instance.

The main advantages of this solution is that is thread safe without the need of synchronized, and that the instance is is created only after the first getInstance(), instead of a creation when the class is loaded (thanks to the static stuff).

Now about your code.

As I saw your code is not working.

First issue: your class is SingletonRetrofit but the object type of your instance is Retrofit. So I'm not sure you want to use all the main class as an helper or just a typo.

Second issue: you create the instance every time you call getInstance() this is not the purpose of a singleton.

Your code should look like:

public class SingletonRetrofit {

    private SingletonRetrofit(){}

    private static class SingletonRetrofitHelper
    {
        private static final SingletonRetrofit INSTANCE = new SingletonRetrofit();
    }

    public static SingletonRetrofit getInstance()
    {
        return SingletonRetrofitHelper.INSTANCE;
    }

    private Retrofit makeRetrofit(final String apiBaseUrl)
    {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .addInterceptor(interceptor)
                    .readTimeout(20, TimeUnit.SECONDS)
                    .connectTimeout(15, TimeUnit.SECONDS)
                    .build();

        return new Retrofit.Builder()
                .baseUrl(apiBaseUrl)
                .client(okHttpClient)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
}

So the makeRetrofit() will became a method of the singleton class that you can call in your code to create the Retrofit object as needed.

If you want to create this Retrofit object just once, and the singleton purpose was this, then you have to design your singleton class in a way that this class cover all the Retrofit class interface.


Using QXmlStreamReader to read configuration file of key-value pairs

Case for not using a class

It's not clear to me whether you need a class for what you are doing. Unless you need to be able to construct an instance of ConfigurationReader and pass it around, I would say get rid of the class. You can have a function with the simple interface

QHash<QString, QString> getConfigurationMap(QFile& input);

I would further suggest putting the function in a namespace that is specific to your app.

namespace MyApp
{
   QHash<QString, QString> getConfigurationMap(QFile& input);
}

Use smaller functions

Instead of one large function, divide the code into multiple functions. Think of what you are doing rather than how you are doing it. The whats usually translate to smaller functions and hows translate to loops, conditionals, branches, etc.

Given that, getConfigurationMap can be implemented as:

namespace MyApp
{
   // Implementation detail.
   void getConfigurationMap(QXmlStreamReader& reader,
                            QHash<QString, QString>& map);

   // User facing interface.
   QHash<QString, QString> getConfigurationMap(QFile& input)
   {
      QXmlStreamReader reader(input);
      QHash<QString, QString> map;
      getConfigurationMap(reader, map);
      return map;
   }
}

The second overload (the one that's listed first) can be implemented as:

namespace MyApp
{
   void skipUntilConfiguration(QXmlStreamReader& reader);

   void readParamters(QXmlStreamReader& reader,
                      QHash<QString, QString>& map);

   // Implementation detail.
   void getConfigurationMap(QXmlStreamReader& reader,
                            QHash<QString, QString>& map);
   {
      skipUntilConfiguration(reader);
      readParamters(reader, map):
   }

   // User facing interface.
   QHash<QString, QString> getConfigurationMap(QFile& input)
   {
      QXmlStreamReader reader(input);
      QHash<QString, QString> map;
      getConfigurationMap(reader, map);
      return map;
   }
}

The code can be wrapped up by implementing the final two helper functions.

namespace MyApp
{
   void skipUntilConfiguration(QXmlStreamReader& reader)
   {
      whiile ( !reader.atEnd() )
      {
         if ( reader.tokenType() == QXmlStreamReader::StartElement &&
              reader.name() == "configuration" )
         {
            return;
         }
      }
   }

   void readParamters(QXmlStreamReader& reader,
                      QHash<QString, QString>& map)
   {
      while ( reader.readNextStartElement() ) {
          if ( reader.name() == "parameter" ) {
              QString id = reader.attributes().value("id").toString();
              map.insert(id, reader.readElementText());
          }
          else {
              reader.skipCurrentElement();
          }
      }
   }

   void getConfigurationMap(QXmlStreamReader& reader,
                            QHash<QString, QString>& map)
   {
      skipUntilConfiguration(reader);
      readParamters(reader, map):
   }

   QHash<QString, QString> getConfigurationMap(QFile& input)
   {
      QXmlStreamReader reader(input);
      QHash<QString, QString> map;
      getConfigurationMap(reader, map);
      return map;
   }
}

The above code assumes that there is only one "configuration" element in your XML file. If that assumption is not correct, the functions need to be tweaked a bit.


Use linq to compute length of line defined as array of points

Another possible answer (first time I've ever suggested two answers) is to keep your existing approach, but modified just a little bit by using .Select()'s under-appreciated little brother that gives you access to an index variable:

float length = line.Skip(1)
    .Select((point, index) => (point - line[index]).Magnitude)
    .Sum();

Heck, speaking of overloads.  You can also keep your existing approach but use .Sum()'s overload:

Enumerable.Range(0, line.Length - 1)
    .Sum(pointIndex => (line[pointIndex + 1] - line[pointIndex]).Magnitude)


Welcome to Code Review!  This is actually pretty good code for a beginner, but here are some things that may help you improve your program.

Simplify the code

The gcd routine looks like this:

long gcd(long a, long b)
{
    long t;

    if (b == 0) return a;

    while (b != 0) {
        t = b;
        b = a % b;
        a = t;
    }
    return a;
}

It can be simplified in three ways.  First, we can declare t within the loop.  Second, we can eliminate the if statement entirely.  Third, we can simplify the while loop condition to simply while (b) which is the same as while (b != 0):

long gcd(long a, long b)
{
    while (b) {
        long t = b;
        b = a % b;
        a = t;
    }
    return a;
}

Use const where appropriate

The value of n is constant, so it would make sense to declare it either const or even better constexpr.

Consider signed versus unsigned

It's always worth thinking about the domain of the numbers in a calculation.  In this case, it seems that all of the numbers are probably intended to be unsigned, but they're declared long which gives signed numbers.

Think of alternative algorithms and implementations

I think your algorithm is fast enough, but an alternative approach would instead be to calculate all of the unique prime factors of all of the numbers < 20 and simply multiply them together.  With the judicious use of constexpr, one could even calculate everything at compile-time which would make for a very fast calculation.  For inspiration, see Compile-time sieve of Eratosthenes


Your solution is not good as you use a single method, stuffing everything inside, with no order nor logic.

It must be rebuilt from scratch.

public class TriagularNumberWithManyDivisors {

Use long, descriptive names, Example is not acceptable by any standard.

static final int DIVISORS_WANTED = 500;

I may have fun running this code for any number of divisors and I really do not want to go haunting for a magic number to change inside the code.

public static int triangular(int n) {
    return n * (n + 1) / 2;
}

This is a function, a part of your program that does only one thing, the function name also serves as documentation.

public static int divisors(int n) {
    int counter = 0;
    int limit = (int) Math.sqrt(n);
    for (int i = 1; i <= limit; i++) {
        if (n % i == 0) {
            counter += (n % i == i ?  1 : 2);
        }
    }
    return counter;
}

The code for counting divisors was kinda mixed in the main loop, and you had to pay the cost for not extracting it to a function in terms of an ugly boolean flag and two nested loops.

public static void main(String[] args) {
    for (int i = 0; true ; i++) {
        if (divisors(triangular(i)) > DIVISORS_WANTED) {
            System.out.println(triangular(i));
            break;
        }
    }
}

The main method, it is incredibly trivial to understand what this does now. It calls the others methods in a high level fashion, highlighting the algorithm.


Error handling to restart Word from Excel inside a loop

The name Update_Word_DocMs_In_Folder isn't following the PascalCase convention that's otherwise observed by your code; underscores should generally be avoided in procedure names in VB6/VBA (especially for Public members), because underscores have a very specific meaning in identifier names:

[Interface]_[Member]
[EventSource]_[EventName]

So Properties_Update is a problem, or can become one.

I find the indentation hard to follow, it doesn't seem consistent: some statements aren't indented, others are, but there's no apparent rhyme or reason to it.

The Call statement is obsolete and its use isn't consistent either; I'd remove it.

Call OpenWordDocAndApplyTreatment(oW, FolderToScan & NewFile, PathTxtWithInfo)

Becomes:

OpenWordDocAndApplyTreatment oW, FolderToScan & NewFile, PathTxtWithInfo

The RestartWord label is misleading: it's just an error handler subroutine, it doesn't necessarily "restart Word".

oDoc and oW have that useless and annoying Systems Hungarian prefix ("o" for "object", right?) and the identifiers are rather poorly named. I would've had wordApp instead of oW (funny just noticed that's quite exactly what another procedure is calling it), and oDoc is declared and assigned to Nothing, but it's never assigned an actual object reference, never passed ByRef to anything, and never referenced either: it's not used, and should be removed.

Not sure why CreateObject is being fully-qualified with the VBA standard library identifier - seems rather arbitrary. Why isn't MsgBox fully-qualified then?

I find this a bit dangerous:

MsgBox Err.Number & vbCrLf & Err.Description, vbCritical + vbOKOnly, "Error not handled"
DoEvents
Resume

If the error is unknown and unhandled, IMO the right thing to do is to gracefully halt execution, not enter a potentially infinite "try that again in an unknown error state" loop.

If Not NormalWordLaunch Then Resume ReOpenWordFile

I don't like this jumping into a loop body. If OpenWordDocAndApplyTreatment is what's throwing error 462, then OpenWordDocAndApplyTreatment is what should be handling error 462 - I'd make the procedure a Function that returns False when that error is thrown and the Word instance needs to be reset.

Honestly, that procedure-that-should-be-a-function wants its own error handling: it can blow up given an invalid path/filename, or Documents.Open fails for whatever reason, or there's no Properties_Updating module, or there's no Properties_Update macro, or .Save fails - so many things can go wrong in that scope, and all of it is just bubbling back up to the calling code's loop body - that's why you have all this jumping-around.

Handle these errors in OpenWordDocAndApplyTreatment, and the loop body and its error-handling logic can get much more straightforward.

OpenOrReopen has its side-effects backwards IMO. I would have returned a Boolean and altered an Optional ByRef outWordApp As Object = Nothing parameter. The ClassName parameter is misleading too: that's a registered ProgId, not a ClassName. Not sure why a ProgId would be needed though - it looks like you could use it to get any registered object, but then there's this:

OpenOrReopen.Visible = False
OpenOrReopen.Options.UpdateLinksAtOpen = False

Which, aside from treating the return value as if it were a declared local variable (a bad practice IMO), assumes things it shouldn't be assuming about the object's members - if it's meant to only work with a Word.Application, then don't take a ProgId parameter, hard-code it in (or make it a Const somewhere, but don't pretend it's a parameter).


Implementation of Dijkstra's algorithm in C++

Design

So not really Dijkstra algorithm.

while (visited.size() < number_of_nodes)

This condition may not be met in all graphs (if there is a subset of nodes not connected to other nodes).

Also Dijkstra uses two lists.

List of nodes that have been visited. (starts empty)
A sorted frontier list.

You have the 1st list but seem to cobbling the second list out of thin air each iteration.

Code Review.

int dijkstra(vector<vector<int>> graph, int source, int target) {

Sure. You are returning the shortest length from source to target. But would it not be more interesting to return the path most of the time.

Also a graph being a vector of vector of int is a bit restrictive. You could have created a concept of a graph. Then templatized the algorithm based on the concept. Then writing a wrapper for vector of vector of int to implement the concept would have been trivial.

// Concept.
Graph
    Node const& getNode(int id) const // returns a reference to a node.

Node
    int edgeCount() const             // returns number of outbound edges
    Edge const& getEdge(int id) const // returns a reference to an edge

Edge
    int getDst() const               // returns the id of the dst vertices.
    int getCost() const              // returns the cost from this node to dst.

Algorith for Dijkstra

template<typename Graph>
vector<int> dijkstra(Graph const& graph, int start, int end)
{
    std::vector<int>                seen;
    std::priority_queue<Frontier>   frontierList;

    frontierList.push({start, 0, {start}});

    while(!frontierList.empty())
    {
        Frontier  head = frontierList.top();
        frontierList.pop();

        if (head.location == end) {
            return head.path.append(end);
        }

        if (std::find(std::begin(seen), std::end(seen), head.location) != std::end(seen)) {
            continue;
        }

        for(int loop=0;loop < graph.getNode(head.location).edgeCount(); ++loop) {
            auto const& edge = graph.getNode(head.location).getEdge(loop);
            frontierList.push({edge.getDst(),
                                 head.cost + edge.getCost(),
                                 head.path.append(head.location)});
        }
    }
    return {}; // empty path as none was found.
}


First, the most serious problem with your code:

Never, ever, ever use def inside of defn, unless you really know what you're doing. def creates global variables that last even once the function has returned:

(defn func []
  (def x 1))

(func)
(println x) ; Prints 1! Ouch!

The only time it's really ever appropriate to use def locally is when you intend to create globals. This is an extremely rare case though.

Instead, you should be using let. For example:

(defn cos-denominator [map-1 map-2]
  (let [p-1 (sum (squares (vals map-1)))
        p-2 (sum (squares (vals map-2)))]
    (* (Math/sqrt p-1) (Math/sqrt p-2))))

let creates a limited scope for the vals that it defines. Once you leave the let, they go out of scope.

That's the only really outright wrong thing I see in your code. The rest of my comments will be best practice related.

use, require and related functions shouldn't really be used directly. It's much cleaner to have them as part of the ns macro:

(ns clojure-first-try.core
  (:use [clojure.string :only [split]]
        [clojure.set :only [intersection]]))

Your use of $ as an identifier is bizarre. I had to double take there. I would recommend using something a little more descriptive. If you can't think of a good identifier to use, I think even a single letter would be better than a odd symbol like $.

(reduce + 0.0 arr))

is more typically written as

(apply + arr)

Your ways not wrong, the latter is just generally considered more idiomatic. This works because + has a var-arg overload that is basically an explicit reduction.

Also, you don't need to specify 0.0 as the starting accumulator of the reduction. + handles that for you.

(reduce + []) ; 0

(filter (complement empty?) arr)

can be written as

(remove empty? arr)

remove adds complement for you! Here's the core definition (basically):

(defn remove [pred coll] ; Abridged defintion
   (filter (complement pred) coll))

It reads much nicer without the explicit call to complement.

(= b 0.0)

can also be written as just:

(zero? b)

Although the gains aren't huge. I find it's better when in an already busy line, like when checking for factors of a number. I find:

(zero? (rem a b))

to be neater than

(= 0 (rem a b))

For cos-numerator:

(intersection (set (keys map-1)) (set (keys map-2)))

is really inefficient. You iterate both maps just to put them in a set to test for intersections. Without doing more timing, it's unclear what the complexity of keys is. If it's O(n), this iterates each map twice, then again as a set. It's much more concise, and significantly faster to just use filter:

(filter map-1 (keys map-2))

Maps return nil on a bad lookup, so they can be used as predicates to check for membership.

I also think this could be cleaned up with ->>. I changed it to:

(defn cos-numerator [map-1 map-2]
  (->> (filter map-1 (keys map-2))
       (map #(* (map-1 %) (map-2 %)))
       (sum)))

squares could also be written as

(map * arr arr))

You're going to have a little bit of duplication somewhere. It just depends what you want it to look like. I find this a little neater.

I'm a big fan of local anonymous functions to clean up code. cos-denominator has you doing the exact same thing to both maps, then taking their product.

I'd make the common transformation a local function, then use that instead:

(defn cos-denominator [map-1 map-2]
  (let [proc #(-> % (vals) (squares) (sum) (Math/sqrt))]
    (* (proc map-1) (proc map-2))))

That has much less duplication. You could even go a little overboard and get rid of the duplicate calls to proc:

(defn cos-denominator2 [map-1 map-2]
  (let [proc #(-> % (vals) (squares) (sum) (Math/sqrt))]
    (apply * (map proc [map-1 map-2]))))

Which could also be made a little neater with ->>:

(defn cos-denominator3 [map-1 map-2]
  (let [proc #(-> % (vals) (squares) (sum) (Math/sqrt))]
    (->> [map-1 map-2]
         (map proc)
         (apply *))))

After the above changes, and a few other touchups that I thought made it neater, this is what I ended up with:

(ns clojure-first-try.core
  (:use [clojure.string :only [split]]
        [clojure.set :only [intersection]]
        [clojure.test :refer :all])
  (:require [criterium.core :as c]))

(defn sum [arr]
  (apply + arr))

(defn squares [arr]
  (map * arr arr))

(defn words-frequency [text]
  (as-> text t
        (split t #"\s+")
        (filter (complement empty?) t)
        (frequencies t)))

(defn cos-numerator [map-1 map-2]
  (->> (filter map-1 (keys map-2))
       (map #(* (map-1 %) (map-2 %)))
       (sum)))

(defn cos-denominator [map-1 map-2]
  (let [proc #(-> % (vals) (squares) (sum) (Math/sqrt))]
    (->> [map-1 map-2]
         (map proc)
         (apply *))))

(defn cos-similarity [freq-1 freq-2]
  (let [a (cos-numerator freq-1 freq-2)
        b (cos-denominator freq-1 freq-2)]
    (if (zero? b)
      0.0
      (/ a b))))

(defn sort-by-similarity [base options]
  (let [base-freq (words-frequency base)
        sorter (comp #(cos-similarity base-freq %) words-frequency)]
    (sort-by sorter > options)))


I see a number of things that may help you improve your code.

Understand the purpose of a hash table

The purpose of a hash table is as an associative array.  In this code, the id element of the customer structure is used as the hashed value and the hash function converts that int value into a number in the smaller range of size.  It's a valid use of a hash function and hash table.  The only thing missing is a means to actually use the hash function to quickly find a customer record.  To do that, you might implement a find_customer function that would search only in the appropriate "bucket" of the hash_table given the id.  With a large number of records \$n\$ where \$n \gg\$ size, this could save look-up time by needing to search only 20% of the records rather than all of them.  With that said, what follows is a review of the code you posted.

Eliminate unused variables

The parameter a in the list_customer() function, adr in main(), and start in add_customer() are all unused variables and should be omitted from the program.

Free allocated memory

Generally speaking, if you allocate memory using malloc or calloc, you should also free that memory to avoid "leaking" memory.

Eliminate "magic numbers"

In a number of cases, the code uses "magic numbers" such as 8999 and 1000 that have no obvious meaning.  These would be better as named constants.  Also, a named constant size is already defined in the code, and should be used within list_customer() instead of hard coding 5.

Use better variable names

The names hash_table and id are good names, but pointer is not a good name because it is too generic.  I'd recommend something like cust_ptr (or Kunde if you prefer German).

Declare variables in the smallest practical scope

By declaring variables in the smalles practical scope, you reduce the chance for name collisions and make it clear to the reader of your code where variables are and are not needed.  With any C compiler conforming to the 1999 specification (which should be all of them at this point!) one could rewrite list_customer like this for example:

void list_customer(){
    for(int x = 0; x < size; x++){
        printf("%d. ----------\n", x);
        for (struct customer *cust_ptr = hash_table[x];
                cust_ptr != NULL; cust_ptr = cust_ptr->next)
        {
            printf("KNR: %d, PIN: %d\n", cust_ptr->id, cust_ptr->pin);
        }
        printf("-------------------------\n");
    }
}

Note also that I have converted your while loop into a for loop which I think clarifies the nature of the code.

Check the return value of malloc

If the system is running out of memory, malloc will return NULL.  Code must check the return value to make sure it is not NULL before dereferencing the variable or the program will crash.

Avoid repeating code

Two places in the code use the construct rand() % 8999 + 1000 which suggests that they should probably be made into a function or macro.

Functions taking no parameter should be declared void

A function declared as void add_customer() in C may actually take any number of parameters which is an old misfeature of the C language.  What you probably want instead is to declare it as taking no parameters which is done like this:

void add_customer(void)

Create subfunctions to keep the code clear and neat

The add_customer() code needs to create a new customer and then put it into the hash_table.  We can delegate the creation to a separate function:

struct customer *new_customer(int id)
{
    struct customer *cust_ptr = malloc(sizeof(struct customer));
    if (cust_ptr != NULL) {
        cust_ptr->name[0] = '\0';
        cust_ptr->id = id;
        cust_ptr->pin = myrand();
        cust_ptr->money = 0;
        cust_ptr->next = NULL;
    }
    return cust_ptr;
}

Note that this code initializes the name member which the original code did not.  Now the add_customer code can be much simpler:

void add_customer(void){
    int id_set = myrand();
    int adress = hash_function(id_set);
    struct customer *cust_ptr = hash_table[adress];
    if (cust_ptr == NULL) {
        hash_table[adress] = new_customer(id_set);
        return;
    }
    while(cust_ptr->next != NULL) {
        cust_ptr = cust_ptr->next;
    }
    cust_ptr->next = new_customer(id_set);
}

And of course the myrand() function:

int myrand(void)
{
    return rand() % 8999 + 1000;
}

Omit return 0 at the end of main

The compiler will automatically generate the equivalent to return 0 for code that successfully gets to the end of main.


More groovifed way of sublist with varying range

You could start with:

def groups = [:]
teacherNodes.each { teacher ->
    groups[teacher] = studentNodes.take(incrementBy)
    studentNodes    = studentNodes.drop(incrementBy)
}


Constructing a simple tree with ASCII in F#

There's a couple of simple things you can do to reduce the clutter in your code. For example, this:

let isEven = fun i -> if i % 2 = 0 then true else false

Firstly,

if someCondition then true else false

can always be written simply as

someCondition

You're also missing a trick with your declaration:

let someFunction = fun i -> ...

Can simply be written as

let someFunction i = ...

So your isEven function is simply:

let isEven i = i % 2 = 0

I'm coming back to F# after a long break (2+ years) so I'm not going to suggest anything else as I'm still relearning!

Edit:

Actually...

let emptyRow = String.concat "" (Seq.map (fun x -> "_") (seq{ 1..100}))

Is simply:

 let emptyRow = String.replicate 100 "_"


dup2 handles equal file descriptors very nicely. There is no need to test for in != 0 etc.
On the other hand, you must check the return values, especially those of the system calls, and give a proper diagnostics when necessary.
An idea of executing the last pipeline component inside a master process is dubious. You lose the control over children's lifecycle. I recommend to run each component in its own process, and wait for all of them.

An i < n - 1 loop terminating condition looks alarming. It takes some mental effort to understand what you are after. You may try to heal it with the comment, but most likely you should treat all pipeline components equally.
Keep in mind that some commands (cd being most prominent) must be builtins. Spawning a shell for them would be a design mistake.


How can this Encryption Class be more secure?

Some issues:

No MAC => say hello to padding oracles. This is fatal flaw that allows decryption of the message in many usage scenarios (when there is an active attacker).
You use CBC mode with constant IV. A new IV must be chosen for each message. It should be unpredictable and random.
Your keying is only secure with really strong passwords (over 100 bits of entropy). I recommend using an actual binary key drawn from a secure CSPRNG encoded with Base64 instead of a password.

A related stylistic problem is that you don't clearly distinguish between keys (which should be uniformly random) and passwords.
Does the key ever leave the trusted systems? It looks like you're hardcoding a key into a client, which might run on an untrusted machine. Even if it stays on the server, put it in a config file, not the code.

Your program should be secure even if the whole code is known. Logistically it's also much easier to keep a config file secure, since it doesn't need to be checked into version control.
Why would you choose 3DES over AES in new code? AES is faster and stronger. It also has 128 bit blocks instead of 64 bit blocks, so it doesn't weaken once you encrypt a couple of gigabytes using the same key.
All those streams are unnecessarily complicated. Simply call encryptor.TransformFinalBlock on a byte array instead.


Exercise: Reading doubles from a file and printing mean, max and min (from Programming Principles and Practice using C++)

Here are some suggestions for you to improve your code.

#include <iostream>
#include <vector>
#include <fstream>
#include <stdexcept>
#include <algorithm>

Sort the #include directives in alphabetical order.  This helps navigation.

using std::vector;
using std::string;
using std::fstream;
using std::ios_base;
using std::runtime_error;
using std::cout;
using std::max_element;
using std::min_element;

This is much better than using namespace std;, but I still suggest getting into the habit of explicitly qualifying the names with std:: as soon as possible (especially for those names which you only use once, e.g., max_element).  For small programs like this it doesn't matter, but for larger programs, qualification adds clarify — when I see string, does it mean std::string?  Jewelry::string, a string of pearls?  Or Minecraft::string, used to craft bows and fishing rods?  This problem is especially evident for common identifiers, like count, arg, or data — these are all top level names in std!

Moreover, using unqualified names sometimes cause ADL (argument dependent lookup), an additional phase for name lookup, to kick in.  As a result, an attempt to call a function in the standard library may end up inadvertently calling a function in an irrelevant namespace.  Such problems come up often in large programs, so again, it's better to get into the habit of using std::.

It is acceptable to use using declarations or derivatives in reduced scopes, to reduce clutter.  But using them globally for the whole program is likely to cause problems.  Moreover, std:: is only 5 characters — reducing clutter is more relevant for things like

boost::math::double_constants::pi

or

boost::multiprecision::number<
    boost::multiprecision::mpfr_float_backend<300>,
    boost::multiprecision::et_off
>;

const string distances_file_name = "distances.txt";

Use constexpr std::string_view (defined in header <string_view>) for string constants:

constexpr std::string_view file_name{"distances.txt"};

or

using namespace std::literals;
constexpr auto file_name = "distances.txt"sv;

vector<double> load_file_of_doubles_to_vector ( string file_name )
{
    vector<double> distances;
    fstream my_file ( file_name, ios_base::in );
    double temporary_number;
    while ( my_file >> temporary_number )
    {
        distances.push_back ( temporary_number );
    }
    if ( !my_file.is_open() )
    {
        throw runtime_error ( string ( "Failed to load " ) + file_name );
    }
    return distances;
}

The parameter type should be std::string_view to avoid redundant copies.

The file stream should be of type std::ifstream instead of std::fstream because it is used for input only.  Then, you can omit the in option, which is the default for std::ifstream.

string ( "Failed to load " ) + file_name is too verbose.  Use "Failed to load "s.

Consider using std::istream_iterator, std::back_inserter (both defined in <iterator>), and std::copy to read the values:

// requires NTBS as argument
auto load_file(std::string_view file_name)
{
    // std::string_view doesn't have c_str()
    std::ifstream in{file_name.data()};
    if (!in.is_open()) {
        // assuming 'using namespace std::literals;'
        throw std::runtime_error{"the file doesn't exist"};
    }

    std::vector<double> data;
    std::copy(std::istream_iterator<double>{in},
              std::istream_iterator<double>{},
              std::back_inserter(data));
    return data;
}

void print_distances_mean_max_min ( const vector<double>& distances_vector )
{
    if ( distances_vector.empty() )
    {
        throw runtime_error ( string ( "There are no entries in " ) + distances_file_name );
    }
    double total_distance = 0;
    for ( auto& n : distances_vector )
    {
        total_distance += n;
    }
    cout << "The sum of all distances is: " << total_distance << "\n";
    double max_distance = 0;
    max_distance = *max_element ( distances_vector.begin(), distances_vector.end() );
    cout << "The maximum distance is: " << max_distance << "\n";
    double min_distance = 0;
    min_distance = *min_element ( distances_vector.begin(), distances_vector.end() );
    cout << "The minimum distance is: " << min_distance << "\n";
    double mean_distance = 0;
    mean_distance = total_distance / distances_vector.size();
    cout << "The average(mean) distance is: " << mean_distance << "\n";
}

IMO, this function is unnecessary and can be built into main directly, because it doesn't have a coherent logic — it just shows what the program does.

Catching exceptions in the main function and printing the messages helps the end user know what kind of error happened.

Don't reinvent the wheel — use std::accumulate or std::reduce (defined in header <numeric>) to calculate sums.

You can calculate the minimum and maximum values simultaneously in
\$\lfloor 3(N-1)/2 \rfloor\$ comparisons using std::minmax_element, which returns a std::pair of iterators pointing to the minimum and maximum elements respectively.  Then, we can use a structured binding to conveniently obtain the two iterators and dereference them to get the values:

int main()
try {
    auto data = load_file(file_name);
    if (data.empty()) {
        throw std::runtime_error{"no entries"};
    }

    auto sum = std::accumulate(data.begin(), data.end(), 0.0);
    auto mean = sum / data.size();
    auto [min_it, max_it] = std::minmax_element(data.begin(), data.end());

    std::cout << "The sum of all distances is: " << sum << '\n'
              << "The maximum distance is: " << *max_it << '\n'
              << "The minimum distance is: " << *min_it << '\n'
              << "The average (mean) distance is: " << mean << '\n';
} catch (std::runtime_error& error) {
    std::cerr << "Runtime error: " << error.what() << '\n';
    return 1;
} catch (...) {
    std::cerr << "Unknown error\n";
    return 2;
}

I've made an online demo by putting everything together so that you can play with the code.


Pointers to polymorphic classes saved in vector that reference data in a list as source

Avoid using namespace std

While it is nice to save some typing, using namespace std should be avoided. See this post for more details: https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice

Have class Scene take ownership of the list

At the moment, the list data lives outside class Scene. This means other code can modify the list without Scene knowing about it. If you only want to allow items being added via Scene's add() and del() member functions, then make the list a private member variable. But in fact you already have a copy of the list in Scene, named _items. So make that the sole container of strings.

If you really need to have a std::vector<shared_ptr<Item>>, and a std::list<std::string>, then maybe they can be both member variables of class Scene?

Add virtual destructors to polymorphic classes

Whenever you inherit from a base class, you want the right destructor to be called. Therefore, especially if you have any non-trivial member variables, you need to declare a virtual destructor, even if it's empty:

class Item {
    public:
    Item() {}
    virtual ~Item() {}
    ...
};

class String: public Item {
    public:
    String(...) {...}
    virtual ~String() override {}
};

Consider:

Item *item = new String("foo");
delete item;

Without the virtual destructor, the base classes destructor would be called, which doesn't clean up String's member variable _s.

Consider making some member variables private

If a member variable should only ever be modified via a member function, then you should make that variable private. If other code needs to access it anyway, but only for reading, then add a function to get a const pointer or reference to the data. For example, in Scene, you don't want something to remove items directly from _items, because it would bypass the removal of strings from data. So make it private and add const access to it:

class Scene {
    std::vector<std::shared_ptr<Item>> _items;

public:
    ...
    const std::vector<std::shared_ptr<Item>> &get_items() const {
        return _items;
    }
}

Maybe the same can be applied to String as well.

Avoid reinventing the wheel

Perhaps there is a reason for it, but if I just look at the code you posted, I wonder why you create your own class String. If Scene is just a container for strings, then why not have it have std::vector<std::string> _items?

Use auto where appropriate

You can avoid repeating types by using auto in several places. For example, in del() you could write:

auto pa = items[n];
auto pb = dynamic_pointer_cast<String>(pa);

Use range-based for-loops

Whenever you are iterating over the items in a container, use range-based for loops. They are easier to write, and there is less chance of errors. For example:

for (auto item: _items) {
    item->print();
}

Consider using if-statements with initializers

C++17 made if-statements a bit more powerful. For example, especially when doing dynamic-casts, you can write shorter code:

if (auto pb = dynamic_pointer_cast<String>(pa); pb) {
    data.remove(pb->ret());
}

Prevent out-of-bounds access

In Scene::del(), you don't check whether the supplied parameter n is smaller than the size of _items. If this function is called with a too large value, this will result in an out-of-bounds access, which, in the best case, causes a segmentation fault, but in the worst case results in weird behavior that is hard to debug.

If it's something that could happen due to wrong input to the program, you should add a run-time check, and for example throw an exception if n is too large. If the only time n would be too large is due to a programming error somewhere else in the code, then consider adding an assert() statement.

Avoid using std::endl

Use \n instead. See this post for the rationale:
https://stackoverflow.com/questions/213907/c-stdendl-vs-n

Consider overloading operator<<()

Instead of writing a print() function that always prints to std::cout, you could rewrite this to an overload of operator<<(), so that you could print your objects to any output stream. There is a slight problem when having derived classes though, the solution is to modify your print() functions to take an output stream object as a parameter, and then only overload operator<<() in the base class:

class Item {
public:
    ...
    virtual void print(std::ostream &out) const = 0;

    friend std::ostream& operator<<(std::ostream& out, const Item &item) {
        item.print(out);
    }
};

class String: public Item {
public:
    ...
    virtual void print(std::ostream &out = std::cout) const override {
        out << *_s << '\n';
    }
};

Now you can write:

String s;
...
std::cout << s;

I recommend you don't print the newline character in your print() functions though, so code that wants to print items can decide itself whether they should be on separate lines or not.

Make member functions that don't modify anything const

As I already did in the above example, functions that don't change any of the member variables should be made const. This will allow the compiler to perform more optimizations, and will cause it to generate errors when you accidentily do change something in const functions.

Another thing to consider is that if you have a const variable or const reference to a variable, then only member functions of that variable that are marked const can actually be called.

Don't move an iterator past the end

In your main(), you iterator over data. After the for loop, it is equal to data.end(). Then you write:

*it++;

Depending on the implementation of std::list<>, this might cause the iterator to become invalid, and either that statement itself will cause some error, or the subsequent *it = "$$$" will.


To start, let me heartily compliment you on your code! You have clearly put effort into learning what idiomatic Rust code looks like. Spacing of operators seems to be accurate, and using code like Vec<_> is top-notch.

I actually took a long time to write a review because there didn't seem to be much to say! After a bit, there were some small things:

I agree that your code could be improved by splitting out some functions:

Separates the concerns of building the primes and printing them.
Allows parameterizing the maximum easier.
Cordons off the mutability of the BitVec to a smaller scope.
Gives names to what is being printed.

Instead of passing the maximum prime when printing, it can be based on the size of the BitVec. It's a little odd as you have to subtract one, so maybe you might want to create a type for the primes that abstracts that away...
Generally, I'd recommend avoiding array indexing due to performance concerns — indexing has slight overhead due to bounds checking. I'm not sure if that applies for a BitVec though. I still like the enumerate solution better.
From previous Sieves, I think that you may want to write ((MAXIMUM_PRIME as f64).sqrt() as u32) + 1 as (MAXIMUM_PRIME as f64).sqrt().ceil() as u32. I think that's more correct in more cases, and probably communicates intent better.

extern crate bit_vec;

const MAXIMUM_PRIME: u32 = 1000;

use bit_vec::BitVec;

fn primes_up_to(max: u32) -> BitVec {
    let mut prime_bit_vector = BitVec::from_elem((max + 1) as usize, true);
    let sqrt_prime = ((max as f64).sqrt() as u32) + 1;

    for i in 2..(sqrt_prime+1) {
        if prime_bit_vector[i as usize] {
            let mut j = i * i;
            while j <= max {
                prime_bit_vector.set(j as usize, false);
                j += i;
            }
        }
    }

    prime_bit_vector
}

fn print_table(prime_bit_vector: &BitVec) {
    let max = prime_bit_vector.len() - 1;
    let maximum_prime_length = max.to_string().len();

    for (i, is_prime) in prime_bit_vector.iter().enumerate() {
        println!("{index:<width$} {is_prime}", index = i, is_prime = is_prime, width = maximum_prime_length);
    }
}

fn print_primes(prime_bit_vector: &BitVec) {
    let primes: Vec<_> = prime_bit_vector.iter().enumerate().filter(|t| t.1).map(|t| t.0).collect();
    println!("Primes: {:?}", primes);
}

fn main() {
    let prime_bit_vector = primes_up_to(MAXIMUM_PRIME);
    print_table(&prime_bit_vector);
    print_primes(&prime_bit_vector);
}

In the future, two Rust enhancements will help the code look even better:

Someday we will have inclusive ranges, which would transform x..(y+1) into some nicer syntax (perhaps x...y?).
Someday the step_by range iterator adapter will exist, which would transform the j += i to something like ((i*i)...MAXIMUM).step_by(i)


Anytime you have a stacked if with basically all of the same comparisions, you should consider another method.
Use a dict:
The most common way to do this sort of thing is a dict.  The dict makes it easy to map a string to a method like:
sha_methods = dict(
    sha1=hashlib.sha1,
    sha224=hashlib.sha224,
    sha256=hashlib.sha256,
    sha384=hashlib.sha384,
    sha512=hashlib.sha512,
)

def hexrandom(minint, maxint, shamode="sha1"):
    if shamode not in sha_mthods:
        raise ValueError("Unknown hashlib method {}".format(shamode))
    x = str(rand.randint(int(minint), int(maxint)))
    return sha_methods[shamode](x.encode()).hexdigest()

Use a direct method lookup:
In this case, since the shamode string matches the method name hashlib, we can use getattr to directly lookup this method like:
def hexrandom(minint, maxint, shamode="sha1"):
    method = getattr(hashlib, shamode, None)
    if method is None:
        raise ValueError("Unknown hashlib method {}".format(shamode))
    x = str(rand.randint(int(minint), int(maxint)))
    return method(x.encode()).hexdigest()


O(n)

You can transform the (row,column) coordinate of a bishop to a (row+column, row-column) coordinate. The row+column coordinate tells you which upper-left to lower right diagonal the bishop is on.  The row-column coordinate tells you which upper-right to lower-left diagonal the bishop is on.

      row + col                     row - col
7  8  9 10 11 12 13 14       7  6  5  4  3  2  1  0
6  7  8  9 10 11 12 13       6  5  4  3  2  1  0 -1
5  6  7  8  9 10 11 12       5  4  3  2  1  0 -1 -2
4  5  6  7  8  9 10 11       4  3  2  1  0 -1 -2 -3
3  4  5  6  7  8  9 10       3  2  1  0 -1 -2 -3 -4
2  3  4  5  6  7  8  9       2  1  0 -1 -2 -3 -4 -5
1  2  3  4  5  6  7  8       1  0 -1 -2 -3 -4 -5 -6
0  1  2  3  4  5  6  7       0 -1 -2 -3 -4 -5 -6 -7

Now create two dictionaries.  One that maps each row+col value to a list of bishops on that diagonal.  The other one similarly maps the row-col value.  Any dict entry with more than one bishop, means all of those bishops are in danger.

bishops = [(0, 0),
           (1, 1),
           (0, 2),
           (1, 3),
           (2, 0),
           (2, 2)]

nwse = {}
nesw = {}

for row,col in bishops:
    nwse_index = row + col
    if nwse_index not in nwse:
        nwse[nwse_index] = [(row,col)]
    else:
        nwse[nwse_index].append((row,col))

    nesw_index = row - col
    if nesw_index not in nesw:
        nesw[nesw_index] = [(row,col)]
    else:
        nesw[nesw_index].append((row,col))

in_danger = set()

for k,v in nwse.items():
    if len(v) > 1:
        in_danger.update(v)

for k,v in nesw.items():
    if len(v) > 1:
        in_danger.update(v)

safe_bishops = set(bishops) - in_danger

print(len(safe_bishops))

Improved code

based on AJNeuman's answer and my comment below.

The row - col index is offset by adding -8 so that all the values will be < 0.
The row + col index are all > 0. So just one dict is needed.

from collections import defaultdict

bishops = [(0, 0),
           (1, 1),
           (0, 2),
           (1, 3),
           (2, 0),
           (2, 2)]

occupied_diagonals = defaultdict(list)

for bishop in bishops:
    row, col = bishop
    occupied_diagonals[row + col].append(bishop)
    occupied_diagonals[row - col - 8].append(bishop)

in_danger = set()

for bishop_list in occupied_diagonals.values():
    if len(bishop_list) > 1:
        in_danger.update(bishop_list)

print(len(in_danger))


Lazy-loading iframes as they scroll into view

General Feedback

The code in the jsFiddle Demo appears to function well (although it isn't the same as the code above- see the next section for an explanation). There is good usage of const for values that are not re-assigned and functional programming with arrow functions.

Flaw with event listener setup

It appears that the fiddle has different code than appears here, but nonetheless, the code above contains the following line:

d.addEventListener("DOMContentLoaded", [preloadPath, loadFrame]);

The second argument appears to be an array. I haven't seen an array there used before and it doesn't appear to work. The Parameters section of the MDN documentation for addEventListener reads:

  listener
  The object which receives a notification (an object that implements the Event interface) when an event of the specified type occurs. This must be an object implementing the EventListener interface, or a JavaScript function. See The event listener callback for details on the callback itself.1

If you did need to have both functions run when that event occurs, you would either need to have a single callback function that calls both or call addEventListener once for each function. It appears that in the fiddle preloadPath has been removed...

Suggestions

Variable naming

The variable name frame sounds singular, yet it returns a NodeList which would typically contain multiple DOM elements.

const frame = d.querySelectorAll("iframe");

Thus a more appropriate name would be frames. That way when statements like frames.forEach() is read, it implies that a function is invoked for each of the frames.

The setAttributes() function

Correct me if I am wrong but this function appears to do the same thing that Object.assign(). I was able to replace calls to that function with calls to Object.assign() and still saw the attributes set as expected in Opera and Chrome.

Arrow functions with empty argument lists

You don't have to do this, but _ could be used instead of empty parentheses for arrow functions with no named arguments. Refer to this SO post and its answers for more context.

timeout in function returned by throttle()

While it would only save a couple lines, the arrow function passed to setTimeout() in the function returned by throttle() could be simplified to remove the curly braces. While this would mean that true would be returned, it doesn't affect anything.

const throttle = (fn, delay) => {
  let canCall = true;
  return (...args) => {
    if (canCall) {
      fn.apply(null, args);
      canCall = false;
      setTimeout(_ => canCall = true, delay);
    }
  };
};

1https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Parameters)


Create a list of random numbers with sum = n

Your logic is hacky, and your array should be dynamic.
Then, you should generalise your function so it can be used in other circumstances.

Also, Logic Error:

You've *assumed* that you won't need more elements than your target sum. But what if Rnd() returns 100 zeroes? You'll get to i = 101, try to set the value of arr(101) and error because you only sized it for 100 elements. Hence why you need a dynamic array.

Dynamic array:

Dim dynamicArray () As Integer
ReDim dynamicArray (1 to 1)

Dim i As Long
For i = 1 to 100
    ReDim Preserve dynamicArray (1 to i)
Next i

Redim Preserve extends the dimension whilst preserving all the values already in it. It only works on the last dimension so if, for instance, you had a 2-D Array, you could only Redim Preserve the 2nd Dimension.

Better Logic:

Start a counter at 100 (call it remainder)
Add random Int from 0-9 to list
Remove Int from counter
Do until counter <= 0
Reduce the last Int by the negative amount now held by remainder

Like so:

Dim sumList() As Long
ReDim sumList(1 To 1)

Dim remainder As Long
remainder = 100

Dim i As Long
Dim rndNum As Double
Do Until remainder <= 0
    i = i + 1
    ReDim Preserve sumList(1 To i)
    rndNum = WorksheetFunction.Floor(10 * Rnd(), 0)
    sumList(i) = rndNum
    remainder = remainder - rndNum
Loop
sumList(i) = sumList(i) + remainder

Refactoring/Generalising:

Your sub is very specific (0-9, sum of 100, integers). Why not make it a function that accepts these things as parameters? Then, whenever you need any kind of random list, you can just call your function with whatever parameters
you need without writing a new one.

Parameters:

Allowed Value Range (2 parameters. A minValue and a maxValue)
targetSum
(Optional) level of precision (integers (0 DP), 1 Decimal Place, 2 etc.)

Mathematical Note:

Allowing for any value space (say, numbers from 2.7 to 3.81 with values of 3 decimal places):

First, compute the size of the space (max - min). For a range of 2 to 7, the size would be 7-2 = 5.
We then add an extra buffer so that Floor() has an equal chance of hitting the top of our value space. This will be 1 * 10 ^ (-numDecimalPlaces).
We then multiply Rnd() by the size of the space to get a random position within our value space.
Then add that value to our minValue, and Floor() to the appropriate level of precision.

Function:

Public Function RandList(ByVal minValue As Double, ByVal maxValue As Double, ByVal targetSum As Double, Optional ByVal numDecimalPlaces As Long = 0) As Double()

    sumTotal = WorksheetFunction.Floor(sumTotal, numDecimalPlaces) '/ In Case, e.g. the total is 100.24 but we're only working in whole numbers

    Dim sumList() As Double
    ReDim sumList(1 To 1)

    Dim remainder As Double
    remainder = targetSum

    Dim valueSpace As Double
    valueSpace = maxValue - minValue + 1 * 10 ^ (-numDecimalPlaces) '/ 1 * 10 ^ (-numDecimalPlaces) is our Floor() buffer so we can still hit the top of the value space.

    Dim i As Long
    Dim rndNum As Double
    Do Until remainder <= 0
        i = i + 1
        ReDim Preserve sumList(1 To i)
        rndNum = WorksheetFunction.Floor(minValue + (Rnd() * valueSpace), numDecimalPlaces)
        sumList(i) = rndNum
        remainder = remainder - rndNum
    Loop
    sumList(i) = sumList(i) + remainder

    RandList = sumList

End Function

Which you can then call like so:

Public Sub DescriptiveName()

    Dim sumList() As Double
    sumList = RandList(0, 9, 100)

    '/ Stuff to print sumList goes here

End Sub

N.B. Thanks to @arcadeprecinct and @raystafarian for suggestions and improvements.


Why don't you just use the overloaded constructor of the NetworkCredential class which takes the password as SecureString?

In this way you can remove the ConvertToUnsecureString() method at all and you don't have to read the decrypted value of the password.

It is always recommended to use System.IO.Path.Combine() instead of adding up the path by using string concatenation. In this way you will be safe regarding illegal characters in the path, missing \ etc.


Retrieve rich text from GridFS with Java

Since you are already on Java 7, you can use try-with-resources on your BufferedReader for safe and efficient handling of the underlying I/O resource.

Also, if all you are interested in is to read a file contents as a single String, you can consider reading them into a String, and then there appears to be three simple ways using either Guava, Apache Commons IO or Spark (web framework) libraries:

// Guava
String content = new String(ByteStreams.toByteArray(is));
// Apache Commons IO
String content = IOUtils.toString(is, Charset.defaultCharset());
// Spark (web framework)
String content = IOUtils.toString(is);

Where applicable, it's recommended to specify the Charset explicitly, instead of relying on the default.

One difference with this approach is that newlines aren't normalized to System.getProperty("line.separator") like what you have done here. If this is crucial for your usage, then a slight refactoring can be:

private static String getStringFromInputStream(InputStream is) {
    try (InputStreamReader source = new InputStreamReader(is);
            BufferedReader bufferedReader = new BufferedReader(source)) {
        StringBuilder builder = new StringBuilder();
        // using for-loop for nicer scoping of 'line' variable
        for (String line = bufferedReader.readLine(); line != null;
                line = bufferedReader.readLine()) {
            if (builder.length() > 0) {
                builder.append(System.lineSeparator());
            }
            builder.append(line);
        }
        return builder.toString();
    } catch (IOException e) {
        // recommended to do something about it instead of just printStackTrace()
        // e.printStackTrace();
    }
}

Since you also suggest giving ideas about Java 8, you can use StringJoiner as a slightly better replacement - there is no need to handle the appending of System.lineSeparator() manually:

private static String getStringFromInputStream(InputStream is) {
    try (InputStreamReader source = new InputStreamReader(is);
            BufferedReader bufferedReader = new BufferedReader(source)) {
        StringJoiner builder = new StringJoiner(System.lineSeparator());
        for (String line = bufferedReader.readLine(); line != null;
                line = bufferedReader.readLine()) {
            joiner.add(line);
        }
        return joiner.toString();
    } catch (IOException e) {
        // do something
    }
}


"Can a given array be made strictly increasing by removing one number?"

I'm not completely sure I've interpreted the requirements correctly, but I think this should do it:

def almost_increasing_array?(array, tolerance)
  unmatched = 0
  array[1..-1].each_with_index do |item, index|
    unmatched += 1 if array[index] >= item
    return false if unmatched > tolerance
  end
  true
end

The tolerance is extra but it basically says this:

Ignore the first item in the array
For the rest, compare them to the previous item
If the previous item was more than this, increment 'unmatched' count.
If more than the tolerance didn't increase, false. It's not 'almost increasing'

It looks like it works for all cases.

almost_increasing_array?([1, 3, 5], 1) # true
almost_increasing_array?([5, 4, 3, 2, 1], 1) # false
almost_increasing_array?([1, 2, 5, 4], 1) # true (only one decrease)
almost_increasing_array?([1, 7, 5, 4], 1) # false (two decreases)
almost_increasing_array?([1, 7, 5, 4], 2) # true (two decreases, but we said that's okay)

You could easily simplify by removing the tolerance argument (hard coding 1).

def almost_increasing_array?(array)
  unmatched = 0
  array[1..-1].each_with_index do |item, index|
    unmatched += 1 if array[index] >= item
    return false if unmatched > 1
  end
  true
end

Weaknesses:

This includes an array which is fully increasing, too.
This will fail as soon as an issue is found, but it may run slowly on huge arrays where there's a decrease right at the end.

Strengths:

It's pretty simple to understand.
This doesn't even have to be an array, it'll work for an instance of any Ennumerable class. Such as ActiveRecord::Relation, or Hash.


Implementing find middle element of singly linked list without using 2 pointers

It could be a little easier to read like this:

public Object findMiddleElement() {
    Node node = head;

    if(hasMiddleElement()) {
        for(int i = 0; i < size / 2; i++) {
            node = node.getNext();
        }
    } else {
        System.out.println("there is no middle element");
        node.setElement(null);
    }
    return node.getElement();
}

private boolean hasMiddleElement() {
   return size % 2 == 1;
}

This works if size is set in the class.


How to optimize population projections for speed?

First, the syntax error:

        String [] = arr = tL.split(" ");

You probably meant

        String[] arr = tL.split(" ");

Now, let's make all of your variable names readable. Longer names take the same amount of time to access:

    java.io.InputStreamReader inputStream = new java.io.InputStreamReader(System.in);
    java.io.BufferedReader reader = new java.io.BufferedReader(inputStream, 16 * 1024);
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
    String input;
    BigDecimal GrowthA, GrowthB, PopulationA, PopulationB; //no need to assign initial values to them; the values are never used
    int repetitions = Integer.parseInt(reader.readLine());

Now, as always, choosing a better algorithm is a far bigger deal than small things such as your particular means of input and output. On my computer, the code between input = reader.readLine(); and writer.flush(); takes 6 milliseconds to run once and 24 milliseconds to run 50 times for the example input you gave; make sure that your timing measurement does not include the amount of time it spends waiting for you to enter input. For your algorithm, you have chosen to iteratively simulate each year of population growth; this is mathematically inefficient. Your problem algebraically reduces to

PA*(1+PRA/100)^t>PB*(1+PRB/100)^t, solve for t.
=PA*((PRA+100)/100)^t>...
=PA*(PRA+100)^t*(1/100)^t>...
PA*(PRA+100)^t>...
ln(PA)+t*ln(PRA+100)>ln(PB)+t*ln(PRB+100)
t(ln(PRA+100)-ln(PRB+100))>ln(PB)-ln(PA)
t>(ln(PB)-ln(PA))/(ln(PRA+100)-ln(PRB+100)) (assuming PRA > PRB)

It will be much faster to just use this one computation, and as bonus you will get more precise answers. Also, since you will not be increasing your numbers exponentially in your algorithm, you will now be able to directly use Integer.parseInt instead of having to ever make BigDecimals.

Marginal changes: Testing reveals that using final local variables is faster than reusing larger-scope variables, and that using BufferedReader and BufferedWriter does not create any significant difference in performance (at least on my machine), so unless you test it and get a different result you should use Scanner and System.out just because it's simpler. Also, you should mark all variables that are never modified as final.

    final Scanner scanner = new Scanner(System.in);
    final int repetitions = scanner.nextInt();
    scanner.skip("\n");
    for(int j = 0; j < repetitions; j++){
        final String input = scanner.nextLine();
        final String[] arr = input.split(" ");
        final double PopulationA = Double.parseDouble(arr[0]);
        final double PopulationB = Double.parseDouble(arr[1]);
        final double GrowthA = Double.parseDouble(arr[2]);
        final double GrowthB = Double.parseDouble(arr[3]);
        System.out.print((Math.log(PopulationB)-Math.log(PopulationA))/(Math.log(GrowthA+100)-Math.log(GrowthB+100)) + " anos.\n");
    }

If integer output is required, throw in a call to Math.ceil. On my machine, the code after final String input = scanner.nextLine(); runs once in 3 milliseconds, 50 times in 6 milliseconds, and 10,000 times in 450 milliseconds, with your example input. A doubling of speed for one run, and faster and faster for the same input repeated.


Test if two IDictionary objects contain the same values

Your code doesn't work, because items in a dictionary aren't ordered in any way.

Example code that fails your test:

dictionary(
    new Dictionary<int, int> { { 0, 0 }, { 1, 1 } },
    new Dictionary<int, int> { { 1, 1 }, { 0, 0 } });

Some more notes about your code:

public static void dictionary(IDictionary pExpect, IDictionary pActual)

dictionary is a bad name for this method, because it doesn't really explain what it's supposed to do. Something like DictionaryEqualityTest would be better.

Also, I would avoid using the non-generic IDictionary if possible, IDictionary<TKey, TValue> would be better (though it would complicate the recursion).


Your code looks pretty good. Just a couple of details:

Instead of hardcoding DateTime.now within the method, add an optional argument. Easier to test and more versatile to use.
The month leap is not considered.

I'd write:

def week_range(date: DateTime.now, start_day: :monday)
  start_date = date.beginning_of_week(start_day)
  end_date = date.end_of_week(start_day)
  start_date_string = start_date.strftime("%B %d")
  week_end_string = (start_date.month == end_date.month) ?
    end_date.strftime("%d") : end_date.strftime("%B %d")
  "#{start_date_string} - #{week_end_string}"
end


Instead of splitting from the ?, you can use location.search. It returns everything from (and including) the ? until the end of the query string. If there's a hash, it stops right before #.

Since it includes the ?, you can do location.search.slice(1) to get the string without the ?.

Then you can do:

var queries = location.search
                      .slice(1)
                      .split('&')
                      .reduce(function(carry, query){
                        var queryPair = query.split('=');
                        carry[queryPair[0]] = queryPair[1];
                        return carry;
                      },{});

From ?foo=foovalue&bar=barvalue, you can get something like:

var queries = {
  foo: 'foovalue',
  bar: 'barvalue',
}

I have to add that this only works for 1-level query string. Stuff like arrays (foo[]=foo0&foo[]=foo1) and key-value pairs (foo[bar]=bar&foo[baz]=baz) isn't covered in this logic.


The graph is actually an adjacency graph. This is a much better name than graph to avoid people confusing it with a grid of nodes.

The next node should be the unvisited node with the lowest cost.

for (int k = 0 ; k < graph.length ; k++) {
    if (!visited[k] && result[k] < nextNodeCost) {
        nextNode = k;
        nextNodeCost = result[k];
    }
}

This way you avoid needing to visit nodes multiple times because you will then never change a visited node's cost.

The result array should be initialized with result[0] = 0; then you can remove the check in the for loop.


PDO multiple queries with 2 different tables

Well, I hardly understand the whole affair but from what I can get about it

$sql = "SELECT a.*, b.token FROM $this->tableName a
        LEFT JOIN `requests` b ON a.$this->user_id = b.uid
        WHERE $this->user_id=:user_id";
$this->conn->prepare($sql);
$stmt->execute(array(":user_id"=>$user_id));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
unset($row[$this->user_id]);
return $row;


Count the accumulated rainfall in a 2D mountain range

It's possible to do it in \$O(n)\$ using \$O(n)\$ additional memory. For that we should find the amount of rain collected at each index in \$O(1)\$. It can be calculated from the heights of the highest mountain to the right and to the left:

$$\tt{rainfall[i]} = \max(0, \min(\tt{leftHighest}, \tt{rightHighest}) - \tt{height[i]})$$

We can have the height to the left updated on the fly in the same loop, but we have to precalculate the heights to the right in a separate loop.

Here is the sample code:

import java.util.Arrays;

public class Solution {
    public static int getCollectedRainfall(int[] heights) {
        int[] highestToTheRight = Arrays.copyOf(heights, heights.length + 1);
        for (int i = heights.length - 1; i >= 0; --i) {
            highestToTheRight[i] = Math.max(highestToTheRight[i], highestToTheRight[i + 1]);
        }

        int collectedRainfall = 0;
        int highestToTheLeft = 0;
        for (int i = 0; i < heights.length; ++i) {
            collectedRainfall +=
                Math.max(0, Math.min(highestToTheLeft, highestToTheRight[i]) - heights[i]);
            highestToTheLeft = Math.max(highestToTheLeft, heights[i]);
        }

        return collectedRainfall;
    }
}


Adding a Node to the Linked List is taking a longer Time when using a reference to the Tail Node

In terms of the times on LeetCode, they can be dependent upon the server load as much as the code.  I tried your code and got a range of times from 100 ms to 136 ms.  Holding onto the last node is a better solution than repeatedly trying to find it but on a list of only a few nodes I don't know how much impact it would have.

In terms of the code, this strikes me as a good place to use the Null Condtional Operator (?.).  We can get around the repeated null check on the tailnode by using a dummy head for the return list.

public ListNode AddTwoNumbers(ListNode l1, ListNode l2)
{
    ListNode l3 = new ListNode(-1);  // dummy head
    ListNode tailNode = l3;
    int remainder = 0;
    while (l1 != null || l2 != null) {

        var sum = (l1?.val ?? 0) +
                  (l2?.val ?? 0) +
                  remainder;
        l1 = l1?.next;
        l2 = l2?.next;

        if (sum > 9) {
            remainder = sum / 10;
            sum = sum % 10;
        }
        else {
            remainder = 0;
        }
       tailNode.next = new ListNode(sum);
       tailNode = tailNode.next;

    }
    if (remainder != 0) {
        tailNode.next = new ListNode(remainder);
    }
    return l3.next; // skip the dummy head when returning
}


More efficient and readable nested loop to compare keywords

Note: last refactoring with rich domain model approach is at the bottom. But you can see my 3 refactoring steps which lead to nice object-oriented design.

You can use Linq to make your code more readable. Also you can give names for intermediate results:

var articlesWithRoles = from a in articles
                        where a.Roles != null && a.Roles.Any()
                        select a;

var primaryRole = roles.First().ToLower();

var highWeightArticles = from a in articlesWithRoles
                         where a.Roles.First().ToLower() == primaryRole
                         select a;

foreach(var article in highWeightArticles)
    article.Weight += 3;

var lowWeightArticles = from a in articlesWithRoles.Except(highWeightArticles)
                        from ar in a.Roles
                        join r in roles on ar.ToLower() equals r.ToLower()
                        select a;

foreach(var article in lowWeightArticles)
    article.Weight += 1;

var articlesWithTopics = from a in articles
                         where a.Topics != null
                         from at in a.Topics
                         join t in topics on at.ToLower() equals t.ToLower()
                         select a;

foreach(var article in articlesWithTopics)
    article.Weight += 0.8;

I also would recommend to use named constants instead of magic numbers 3, 1, 0.8. Also maybe you don't need to create new list, because it will share same articles as list yo passed to method.

Further improving readability could involve splitting this method into three methods:

 AddRolesWeights(articles, roles);
 AddPrimaryRoleWeights(articles, roles.First());
 AddTopicsWeights(articles, topics);

Which could look this way:

void AddRolesWeights(IEnumerable<Article> articles, IEnumerable<Role> roles)
{
    const double RoleWeight = 1;

    var nonPrimaryArticles =
        from a in articles
        where a.Roles != null && a.Roles.Any() &&
        from ar in a.Roles
        join r in roles on ar.ToLower() equals r.ToLower()
        select a;

    foreach(var article in primaryArticles)
        article.Weight += RoleWeight;
}

Yes, its less efficient. But you always should chose between readability and performance:

void AddPrimaryRoleWeights(IEnumerable<Article> articles, string primaryRole)
{
    const double PrimaryArticleWeight = 2;
    var primaryArticles =
       from a in articlesWithRoles
       where a.Roles != null && a.Roles.Any() &&
           String.Equals(a.Roles[0], primaryRole, StringComparison.CurrentCultureIgnoreCase)
       select a;

    foreach(var article in primaryArticles)
        article.Weight +=  PrimaryArticleWeight;
}

Same way you can update articles with selected topics.

Final solution

Further refactoring can include moving weights calculation logic to article class, thus making it reach instead of anemic, and increasing cohesion:

 // add this to Article class
 public double Weight { get; private set; } // probably you don't need setter

 public void AddWeights(IEnumerable<Role> roles)
 {
     const double RoleWeight = 1;
     const double PrimaryRoleWeight = 3;

     if (!roles.Any())
        return;

     if (Roles == null || !Roles.Any())
         return;

     var pirmaryRole = roles.First();
     if (String.Equals(Roles[0], primaryRole, StringComparison.CurrentCultureIgnoreCase))
     {
         Weight += PrimaryRoleWeight;
         return;
     }

     foreach(var role in roles)
        if (Roles.Contains(role, StringComparer.CurrentCultureIgnoreCase))
            Weight += RoleWeight;
 }

Adding topics weights:

 public void AddWeights(IEnumerable<Topic> topics)
 {
     const double TopicWeight = 0.8;

     if (Topics == null || !Topics.Any() || !topics.Any())
        return;

     foreach(var topic in topics)
        if (Topics.Contains(topic, StringComparer.CurrentCultureIgnoreCase))
            Weight += TopicWeight;
 }

And your original code will look like:

 foreach(var article in articles)
 {
     article.AddWeights(roles);
     article.AddWeights(topics);
 }

I think it's a little more readable now :)


Saving the contents of a TextArea to a file

Some suggestion:

A "save to file" method without a valid file is useless. If the file is null your method is a no-op without a warning for the user.
Code reuse: your code works with TextArea only. A better solution would be a String argument instead of TextArea.
Method name: "saveFile" is too generic
Exception handling: you should catch the exception only if you know how to handle it or if you enrich the exception with new information before rethrow it

My version:

public void writeStringToFile(File file, String text) throws IOException {
    if (file == null)
        throw new IllegalArgumentException("file cannot be null");

    if (text == null)
        throw new IllegalArgumentException("text cannot be null");

    String filePath = file.getAbsolutePath();

    try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(filePath))) {
        writer.write(text);
    }
}

But... DON'T REINVENT THE WHEEL!

A better solution is the Apache FileUtils class, see writeStringToFile method.

ps: English is not my mother tongue