Create an alternative wait in javascript

Read your framework's documentation

Before you actually do some voodoo magic on your code, I suggest you read your framework's documentation. It's quite impossible that a web framework has not taken into account JS's asynchronous nature. There should be a proper way to do this.

For instance, in Meteor we have the .rendered handler which runs when the template has rendered or rerendered. This is usually where we hook stuff or modify the DOM to the newly rendered template.

Mutation observers

This is one of the new, shiny toys of JS and should be the proper way to do this operation in plain JS. Mutation Observers listen for changes on the DOM and fire assigned callbacks. You can configure them to listen for specific changes on the DOM, like attribute modifications, subtree modifications (adding or removing DOM). As of this writing, current browsers support them already.

Using AJAX? The callbacks!

When there is AJAX, there should be some mechanism to attach handlers to know when the data arrived. Use that instead.

For example, in jQuery you can do this:

$.get('some_resource_url')
 .done(function(data){
   //Do something with the data when it arrives
 });


Rename subkeys of nested dictionary dynamically

Clarity probably trumps speed, but then again, it's not quite clear
why you need this format and what is further going to happen to that
dictionary.

You can definitely get rid of the innermost loop by computing the
replacement index on the fly instead of testing all possibilities:

from collections import OrderedDict

year = int("1996") # comes as string
lag_length = 2
replacement = ["lag%s_fte_count" % (i - 1) for i in range(lag_length, 0, -1)]

for ID, value in my_dict.iteritems():
    for subkey in value.keys():
        year_string = subkey[:4]

        if not year_string.isdigit():
            continue

        parsed_year = int(year_string)

        if not year - lag_length <= parsed_year < year:
            continue

        value[replacement[lag_length + parsed_year - year]] = value.pop(subkey)

I also used iteritems to get both values at the same time; for
value.keys() that's sadly not possible while iterating.  The year
input should also be parsed immediately as it'll always be used in the
integer form.

Next I'm assuming the keys start with the four-character year, so then
the year can be parsed and compared with the target range and if it's in
the range, the key is renamed by calculating the correct index.

Furthermore you could remove the isdigit call if the format allows for
it and replacement could be removed by always generating the string
immediately, e.g. like this:

value["lag%s_fte_count" % (year - parsed_year - 1)] = value.pop(subkey)


At least to me, this seems like an excessively complex design.

I'd guess the intent is to create something on the order of a pushdown automata. In other words, the code processes a stream of incoming characters one at a time, with no global view of all the incoming data, and (almost) no memory other than the stack.

The obvious way to do this would be to read a character of input. If it's an 'a', push it onto the stack, and repeat. If it's a 'b', pop one 'a' from the stack, and repeat:

stack<char> inputs;

char ch;

while ((ch = getinput()) == 'a')
    inputs.push(ch);

while (ch == 'b') {
    if (inputs.empty())
        error("Mismatch: more 'b's than 'a's");
    inputs.pop(ch);
    ch = getinput();
}

if (!inputs.empty())
    error("mismatch: more 'a's than 'b's");

Note that we're not really using any of the data we push onto the stack though--we're basically just using its depth (which can lead to an even simpler design, but on that doesn't appear to fit the specifications).


Using a map of shared_ptr instead of single pointers as class members

I'm not particularly familiar with libcurl, but using a std::map for storing the callbacks is a good thing. One of my rules when programming is; If I need to store more than 1 thing of the same type, use a container for it. Which you've done, and it's a good thing.

There are a couple of nitpicks, and I'm assuming you have the possibility to use C++11.

Variables in class can be initialized with a default value.

...
Nan::Callback *cbChunkBgn = nullptr;
Nan::Callback *cbChunkEnd = nullptr;
Nan::Callback *cbDebug = nullptr;
Nan::Callback *cbHeader = nullptr;
...

Your constructor initializer lists aren't readable.

Change this:

Easy::Easy( Easy *orig ) :
    callbacks(), cbOnSocketEvent( nullptr ), pollHandle( nullptr ),
    isCbProgressAlreadyAborted( false ), isMonitoringSockets( false ),
    readDataFileDescriptor( -1 ), id( Easy::counter++ ), isInsideMultiHandle( false ), isOpen( true )

Into this:

Easy::Easy( Easy *orig )
    : callbacks()
    , cbOnSocketEvent( nullptr )
    , pollHandle( nullptr )
    , isCbProgressAlreadyAborted( false )
    , isMonitoringSockets( false )
    , readDataFileDescriptor( -1 )
    , id( Easy::counter++ )
    , isInsideMultiHandle( false )
    , isOpen( true )

You may also benefit from using delegating constructors. I'm not sure how it will fit into your design.

Easy::Easy( Easy *orig )
    : Easy()

Maybe you can skip the long constructor initializer lists by using default arguments all together.

Use auto where necessary. Transform this;

CallbacksMap::iterator it = obj->callbacks.find( CURLOPT_FNMATCH_FUNCTION );

Into this;

auto it = obj->callbacks.find( CURLOPT_FNMATCH_FUNCTION );

There is probably more, but those are what I saw at the first glance of the code.


Is this correct?

Maybe.

For a start, the >>> operator doesn't exist in C#.

Taking a guess, I replaced >>> with >> and then wrote the following 'unit test' for it:

    static void assertFloat(float fval)
    {
        int i = fromFloat(fval);
        float f2 = toFloat(i);
        if (fval != i)
            throw new ApplicationException();
    }

    static void Main(string[] args)
    {
        assertFloat(0);
        assertFloat(1);
        assertFloat(0.5f);
        assertFloat(-0.5f);
        assertFloat(-0);
        assertFloat(float.PositiveInfinity);
        assertFloat(float.NaN);
        float big = 1024 * 1024;
        big *= big;
        assertFloat(big);
    }

It failed the second test: because 1.0 is round-trip-converted to 1.000122.

I am disappointed by an encoding scheme which cannot encode '1.0' exactly.

However you didn't say how exact you expect the round-trip to be, so I don't know whether it's correct.

The following is a list of some input with corresponding output:

0 -> 0
1 -> 1.000122
1.1 -> 1.099609
-1 -> -1.000122
0.5 -> 0.500061
-0.5 -> -0.500061
0.001 -> 0.001000404
5.5 -> 5.5
5.6 -> 5.601563
5.7 -> 5.699219
0 -> 0
Infinity -> Infinity
NaN -> NaN
1024 -> 1024.125
1048576 -> Infinity

So it seems approximately correct for those numbers.

I can't say whether it's the best encoding. For example, this encoding gains the ability to express decimals but loses the ability to express integers (they become approximated) and big integers (they become infinity).

A different encoding scheme could be devised (and might be more useful depending on your application) which cannot express decimals but which gains the ability to express (approximately) some numbers which are bigger-than-the-biggest integer.

There are a lot of 'magic numbers' (i.e. hard-coded constants) in the code. To inspect for correctness I would need to guess/reverse engineer the way in which you encode/use the 16 bits for your "half precision float" numbers. You could make it easier by documenting the format using comments: which bits do you use for what?

Note this comment in the post you linked to:

  I see what you mean but these NaN values wont be returned from Float.floatToIntBits which normalizes all NaNs to 0x7fc00000. The rounded val can thus never become nagative. Maybe it would be faster to use floatToRawIntBits (which does not do NaN normalization) and then deal with the overflow NaNs i.e. by adding || val < 0 to the first branch. This would also allow to preserve some of the extra NaN bits. I remember that I had planned to do this but couldn't find sufficient documentation on how to handle these bits and thus settled with normalized NaNs.

The BitConverter which you use may not (I haven't tested it) normalize NaN values in the same way.

The original OP linked to an spec for Half-precision floating-point format which says,

  Integers between 0 and 2048 can be exactly represented

So my testing, which shows error in round-tripping 1, suggests that this spec is NOT implemented correctly.

When I test it, 1.0f is encoded as 0x3c00 which is correct according to the spec. So the bug is presumably being introduced in the toFloat method, specifically this statement:

return BitConverter.ToSingle(BitConverter.GetBytes( ( hbits & 0x8000 ) << 16
                                        | exp << 13 | 0x3ff ), 0);

This is a line which the "obvious expert on the subject" said they "implemented [as a] small extension compared to the book".

IOW you may have made a translation from the Java, but the Java doesn't correctly/fully implement the spec (it tries to improve on the spec, perhaps resulting in an inability to accurately decode small integers).


A listener and callback mechanism is a common pattern in many places in Java.

The logical place to look for examples is in the Swing API. Will get back to that in a second, but, there are two items that are useful first:

Instead of using an int value to track the source of the event/Task, you should use the task itself.

   public void onResult(String result){
     myListener1.onResult(this, result);
   }

The Listener itself should implement an interface, something like: TaskResultListener:

 public interface TaskResultListener {
     public onResult(Task task, String result);
 }

and the constructor for the Task should take an instance of a TaskResultListener instead of a MyListener1

For examples of how this is used, consider the ActionListener interface and usage in Swing:

ActionListener
Example implementation of ActionListener: TextAction
Example component that calls-back to an ActionListener: JButton / AbstractButton

In the Swing API, it is common to have support for multiple listeners. You have just one. That is OK.


Is it possible to use switch case for more than one array.indexOf

You could for example put all actions in an object

var actions = {
  "session": function() { console.log("session"); },
  "virtual": function() { console.log("virtual"); },
};

and loop over its keys:

var activities = [
    "session",
    "virtual",
    "other"
];

for(let i = 0; i < activities.length; i++) {
  let action = actions[activities[i]];
  if (action) action();
}


You should probably inherit from std::runtime_error rather than std::exception.
The std::exception and all its descendants already implement what() so there is no need to implement that in your code. So you can remove these:
  // Returns member_err.
  virtual const char* what() const throw();

  protected:
  // A description of the error. Should probably set this to private.
  const char* member_err;

There is no need for a virtual destructor. That is already taken care of in the base class std::exception. Since you are not doing memory management (your example shows string literals) these methods are empty anyway. So you can remove this:
  virtual ~LibException() throw ();
  virtual ~ProcessException() throw ();

This seems obtuse:
  // Returns a char* pointer to the reason.
  //
  // E.g. NETWORK = "NETWORK"
  // @return: <const char*> member_reason.
  const char* getReasonChar() const throw();

Why not just return Reason?
I personally don't like interfaces that take pointers. There is no ownership semantics associated with the pointer and thus people can mistakenly provide the wrong type of pointer (ie a dynamically allocated one in this case). So I would change the interface to be std::string const& this guarantees the correct semantics are used (and you can still use the string literal). This also jibes with the std::exception (and family) which all accept a std::string for the constructor.
LibException(std::string const& err);

Edit: Moreover I have another exception class called ParseException (very similar to the derived class above) which is thrown when a parser that is parsing a file or a command from the shell fails unexpectedly.

I think the key phrase here is fails unexpectedly. If its unexpected to fail for this reason then its an exception.

I have read that such errors are better handled via assert statements because they don't represent "exceptional" cases.

Asserts are the worst type of control and they are really only good for debugging; not for error handling. Remember assert() compiles to the NO-OP when in release mode so there is no checks.

Could anyone please comment on this?

Control flow is usually not best handled with exceptions. But everything is situational. If you find it useful feature to use then go ahead.
Creating your Own exceptions
I used to create exceptions for different situations but found I never used them. So I have started simply using std::runtime_error. The only time I define a specific exception is when it can be usefully caught outside the library layer I am throwing from.
The trouble is the definition of "usefully caught". This not only means that the exception needs to carry information that I can use to fix the problem but the library itself must provide a public API that will allow me to fix the situation.
If all you can do with the exception is log it (including dump to std::cout). Then is it really a useful exception to catch?


Just do the sieve once, this should give you about 5-10x increase.

int main(){
    system("clear");

    std::vector<bool> primes;
    std::vector<input> programInput;

    programInput = parseInput();

    auto maxPrime = programInput.begin()->end;
    for(auto& m : programInput){
         maxPrime = max(maxPrime, m.end);
    }
    primes = findPrimes(0, maxPrime);

    for (int i = 0; i < programInput.size(); ++i){
        printPrimes(primes , programInput[i].start, programInput[i].end);
    }
}

Then avoid the vector copies by taking all vector parameters by const & and you should be golden.


Build a Person class, delegate don't duplicate

Just so you know, undefined in JS is mutable. It's value can be changed. You could resort to using void 0 instead of undefined.
In JS, assignment operations are as good as values, equivalent to the value assigned. Also, the || acts like a "default" operation, where if the left-side value is falsy (ie, blank string, undefined, null, false, 0), the right-side value is used. And so, getFirstName (and similarly, getLastName) can be simplified into:

return this.firstName = this.firstName || this.defaultFirst();

For defaultFirst and defaultLast, essentially you're splitting by space and getting the first and last contiguous word, respectively. And so, it can be simplified using split and shift or pop:

// For first name:
return this.fullName.split(' ').shift();

// For last name:
return this.fullName.split(' ').pop();


My major critique of your code is that you mix up all kinds of concerns all over the place. The code that computes the subsets also does the printing and the counting and all that stuff.

Some thoughts on how to improve this:

The problem is the subset sum problem. Its input is a set of integers.  So why do you do everything in arrays?  Make a class Set, or use an existing class, and have that represent your set of integers.
Once you have that class, build basic operations out of it.  So for example, a Set<T> should have a PowerSet member, which returns Set<Set<T>>, or even better, EnumeratePowerSet, which returns IEnumerable<Set<T>>.
Now that you have those operations, you can use LINQ to do queries against them.

In short, I'd like to see a method like this:

// Takes a set and a sum, returns a sequence of subsets that
// sum to the given value.
static IEnumerable<Set<int>> SubsetSum(Set<int> items, int sum)
{
  return from subset in items.EnumeratePowerSet()
         where subset.Sum() == sum
         select subset;
}
static void Display(IEnumerable<Set<int>> subsets)
{
  if (!subsets.Any())
    Console.WriteLine("No subsets sum to that value.");
  else
    foreach(var subset in subsets)
      PrintSubset(subset);

Now, can you implement the EnumeratePowerSet method on Set<T>?

  Is the complexity of this algorithm 2n, where n - number of elements in the array?

Yes.

  Is there more efficient approach to that problem, probably iteration instead of recursion?

There is no known algorithm that does better than exponential in general.  (There is no proof that there is no such algorithm. The discovery of such an algorithm or a proof that none exists would be a major result in computer science.)

However there are algorithms that do better on typical subset sum problems given certain constraints. There is a huge amount of research on this problem; I leave it to you to consult your local university library.


Mapping from multiple sources to destination using JMapper

I can understand the usefulness of a class/tool like this. The basic thinking is:

need to transform class A to class B.
also need to transform class C to class B.
JMapper can help.
there are other classes that need transformations as well
we should make a generic factory for it.
we can also make the concept referencable as an interface, so things other than JMapper can do the mapping if necessary.

This is what I assume your thought process was, so I will review based on that assumption...

Interface

First up, the interface idea is a good one.... but the varargs Object parameter is a problem. You should only have a single argument. Also, since you want to keep the input argument anonymous (Object instead of <T>), you should have some exception handling for those times when invalid data is supplied....

The reason for suggesting you have only a single input parameter is because the logic for choosing which instance is used for the transform is not easy to specify when there's multiple candidate input values. You should let the calling code make the decision as to which instance to convert from (note, this is related to a second problem I will address again in a moment)

I would also recommend renaming the interface method to something more verb-like, such as mapToDestination(...) instead of getDestination(...)

Bottom line, I would recommend an interface like:

public interface ObjectMapper<D> {

    public D mapToDestination(Object source) throws IllegalArgumentException;

}

Right, now for the actual implementation.... using JMapper. Unfortunately there are some real concerns I have in here.

DestinationClazz

Do you have an actual class called DestinationClazz? I imagine not. I think this is supposed to be a generic type, but then you are not treating it like a normal type. For example, your class definition is:

public class JMapperImpl<S1, S2> implements ObjectMapper<DestinationClazz> {

but then your constructor is:

private JMapperImpl(Class<DestinationClazz> destination, Class<S1> source1, Class<S2> source2) {
    final String mappingFile = getMappingFile(destination);

This makes no sense because since you have declared the ObjectMapper as an exactly typed value, you may as well have a constructor that knows it is production DestinationClazz instances... no need to pass in the class:

private JMapperImpl(Class<S1> source1, Class<S2> source2) {
    final String mappingFile = getMappingFile(DestinationClazz.class);

So, because of this inconsistency, I imagine that you really want the DestinationClazz to be a generic type.... and you should specify it as part of the class signature:

public class JMapperImpl<S1, S2, D> implements ObjectMapper<D> {
    private JMapperImpl(Class<D> destination, Class<S1> source1, Class<S2> source2) {
        final String mappingFile = getMappingFile(destination);
        ....

    @Override
    public D getDestination(Object source) {
        ....

Static Singleton

This code is broken for a number of reasons:

public static <S1, S2> ObjectMapper<DestinationClazz> getJMapperInstance(Class<DestinationClazz> destination, Class<S1> source1, Class<S2> source2) {
    if(INSTANCE == null) {
        INSTANCE = new JMapperImpl<S1, S2>(destination, source1, source2);
    }
    return INSTANCE;
}

Here you have a lot of pretty complicated problems going on. I will try to address them in a sensible way....

synchronization - you are vulnerable to having multiple instances of the same JMapper since multiple threads could be calling this at any one time, and ending up with different instances.
misleading generics - This is a generic method and not a method with generic arguments. What I am saying is that the <S1, S2> here are not the same ones as those on the class (public class JMapperImpl<S1, S2> implements ....). Your code implies that this static method takes the same generic arguments as the INSTANCE instance, but this static method is not related to any particular class instance anywhere.
Generic Erasure - when a class with Generics is compiled, the compiler uses the generics to do compile-time validation of the code. Once the compile is validated though, the generic information is completely erased. The effect of this is that there is actually only one class called JMapperImpl. You can create many instances of this class each with different generic types: new JMapperImpl<Double, Long>(Double.class, Long.class), or new JMapperImpl<String, StringBuilder>(String.class, StringBuilder.class), etc.... but only the first one you create using the static method will be the INSTANCE, and the others will never exist.... ;-)

Where to, Sir?

In your actual mapping method you loop through the input source variables, and, if they match one of your defined source classes, you create a destination instance using the JMapper.

Unfortunately, you keep going until you run out of input source values.... If the user supplies 100 source values, you map them all! and only return the last one....

Which one is the right destination (what's the destination? ... where to, Sir)?

Conclusion....

You should:

add the D Destination generic type to your class definition
completely remove the static INSTANCE and factory method
make the constructor public.... these are light-weight classes, and you can easily have multiple instances.
change the mapping method name to something more meaningful.
change the mapping argument to a single source parameter which is the only thing to map.
throw an exception if the source does not match one of the anticipated sources.


Fetching the definition of a word using a REST API

Inside the if let json = ... { ... }, all the execution branches will call delegate.dictionaryDidLoad,
and the value of forWord is always params.word.
Instead, you could initialize value and error to nil,
set them in the appropriate conditional branches,
and finally call the delegate.
Something like this:

if let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as? NSMutableArray{

    NSLog("Response: \(json)")

    if json.count == 0 {
        error = self.buildError(404, message: "No definitions found")
    } else if let definitionJSON = json[0] as? NSMutableDictionary{
        value = definitionJSON.valueForKeyPath("text") as? String,
    } else {
        error = self.buildError(401, message: "Unexpected Result Format")
    }
} else {
    error = self.buildError(401, message: "Unexpected Result Format")
}

delegate.dictionaryDidLoad(
    value,
    forWord: params.word,
    error: error
)


Sort array of Numbers with some values always first

This can be easily done using a two-phase approach, one to shift values to the front that you want to keep, the other to sort the remainder.

Note, for sorting, use the native functions in the libraries... in this case, Arrays.sort(...)

It would also be much better to wrap this up in a function, taking 2 arguments, the number to put first, and the array to sort.

public static void sortFirst(int first, int[] array) {
    int left = 0;
    for (int right = 0; right < array.length; right++) {
        if (array[right] == first) {
            // swap left and right... put the first values first.
            array[right] = array[left];
            array[left] = first;
            left++;
        }
    }

    // OK, now we have "left" pointing to the actual data that needs sorting
    Arrays.sort(array, left, array.length);
}


You could always set up a list of Actions that need to be worked on, and then loop through them checking for Stop each time.

Something like :

List<Action> actions = new List<Action> {
  () => LengthyMethodA(),
  () => LengthyMethodB(),
  () => LengthyMethodC() };

  for(int i = 0; i < Length; i++)
  {
    foreach (Action action in actions)
    {
       action();
       if(stop)
            return;
    }
  }

This may or may not be better. It depends on the actual code. The actions list would represent an ordered set of transactional units of code - each unit must be completed, but the whole set can be broken apart and cancelled if necessary.


Interesting question,

find_substrings should really be findSubstrings
I dislike arr, and prefer list
If you sort the array by the length of strings, then you never have to check prior elements
If you kept a list of matches and non-matches, then you would never have to check matches again
I found the test case troubling, since you are looking for only 1 set, whereas the code will retrieve any number of sets
The complexity calculation becomes tricky here, I would think a worst case would be n*n/2, and best case n.

In the end, I came up with something like this:

function findSubstrings(list) {
  var out = [],
    match, rest, i, j;
  //Sort the array by the length of the string
  list.sort((a, b) => a.length - b.length);

  for (i = 0; i < list.length - 1; i++) {
    match = [];
    rest = [];
    for (j = i; j < list.length; j++) {
      if (list[j].indexOf(list[i]) > -1) {
        match.push(list[j]);
      } else {
        rest.push(list[j]);
      }
    }
    //Did we find a set?
    if (match.length > 1) {
      out = out.concat(match);
      list = rest;
      i = 0;
      //Shortcut, should we still bother looking?
      if (rest.length == 0 || rest.length == 1) {
        return out;
      }
    }
  }
  return out;
}
var testCase = ["abc", "abcd", "abcde", "xyz", "tom", "tomd"];
console.log(findSubstrings(testCase));


You could follow the below approach:
public class PredicateBuilder {

    private Predicate predicate;
    private CriteriaBuilder cb;
    private Runnable[] tasks;

    private static final PredicateBuilder instance = new PredicateBuilder();
    private PredicateBuilder(){
    }

    public static PredicateBuilder with(Predicate p, CriteriaBuilder c) {
        instance.predicate = p;
        instance.cb = c;
        return instance;
    }

    public PredicateBuilder tasks(Runnable... tasks) {
        instance.tasks = tasks;
        return instance;
    }

    public Predicate build() {
        Arrays.stream(instance.tasks)
              .forEach(Runnable::run);
        return instance.predicate;
    }

    public static void like(Path<String> path, String value) {
        if (StringUtils.isNotEmpty(value)) {
            CriteriaBuilder c = instance.cb;
            instance.predicate = c.and(instance.predicate,
                                       c.like(c.lower(path), "%" + value.toLowerCase() + "%"));
        }
    }

    public static <T> void eq(Path<T> path, T value) {
        if (value != null) {
            CriteriaBuilder c = instance.cb;
            instance.predicate = c.and(instance.predicate, c.equal(path, value));
        }
    }

    public static <T extends Enum<T>> void eqEnumVal(Path<T> path, Class<T> enumType, String name) {
        if (StringUtils.isNotEmpty(name)) {
            instance.predicate = eq(instance.predicate, instance.cb, path, Enum.valueOf(enumType, name));
        }
    }

}

Then you could invoke as below:
return PredicateBuilder.with(predicate, cb)
                       .tasks(() -> eqEnumVal(root.get(regType), RegType.class, filter.getRegType()),
                              () -> eq(userJoin.get(Acct_.id), filter.getAcctId()),
                              () -> like(root.get(regNumber), filter.getRegNumber())
                       .build();

```


Nesting loops on same array but skipping same element

Note that you are just doing a permutation of two elements from a set, and there is an abstraction in the core for that, Array#permutation(n):

arr.permutation(2).each { |x, y| x.apply(y) }


Can't say I've simplified it much... but I've removed some syntactic extras that were unnecessary in the original version, made the method itself static (no reliance on instance data or methods) and hoisted out the seed to a one-time initialized class-level variable for speed/GC (over multiple calls) sake:

private static readonly IEnumerable<IEnumerable<string>> seed =
    new List<IEnumerable<string>> { Enumerable.Empty<string>() };

public static string[] GetPowerSet(string input)
{
    return input.Split(',').Aggregate(
        seed,
        (a, b) => a.Concat(a.Select(x => x.Concat(new[] { b })))).Select(subset => string.Join(",", subset)).Skip(1).ToArray();
}


I would guess that you're never going to take another 50% off. You could consider pulling the problem down into C or Haskell or Awk or whatever and then binding that more tightly optimized implementation back up into python; IDK.

As for more incremental improvements, it depends a bit how the thing is going to be used.

You flagged the question for multi-threading. That certainly might help, but you'll have to figure out how to divy up the job. Maybe there are natural split-off points that can be identified without actually reading the subject data, in which case any parallelization system will probably work. Maybe you can figure out the size of the subject on disk, and open multiple readers against that file starting at evenly spaced offsets; in this case you'll need to figure out the fence-posting when you combine the results of each of the workers.

I notice that the function preprocessing just wraps the iterable results up in a list. Is that necessary? If you can avoid ever actualizing the whole 10k-items list in memory that will likely help some.

Similarly, you're reading the whole file (http payload) as a single string. Both file handles and HTTPResponse objects will let you read just a chunk at a time; this would let you handle the subject data like a lazy iterable (similar to the way you're yielding from .finditer()). Of course how much of an advantage this is for you will depend on the underlying implementation, and you'll have to be careful about fence-posting again. This may also be a good way to break off jobs for parallelization.


K&R 4-12 recursive converter int to string

No, this is not a correct solution.  Since i is static, the function will fail the second time it is used.

It also fails to handle INT_MIN correctly, since -INT_MIN will overflow an int.

You should never omit the "optional" braces for if, else, for, and while blocks.  By doing so, you are contributing to future coding accidents.  See this recent Apple security vulnerability and this quote from the author of jQuery:

  I really dis-liked having unnecessary braces. This… unfortunate… style preference plagued us for quite a while and caused all sorts of avoidable logic errors.


I've been experimenting with the best data structure for this. Here is what I have for now. It is definitely a work in progress, I hope to keep updating it constantly.

The CSV output was unexpected, ultimately a result of my decision to use a namedtuple. I chose namedtuples because, like you, I thought the data fit that tabular style quite well. You wrote given job listings have pretty much similar attributes, could it make sense to create a class listing with attribute and a method to push it to db, and I mostly agree, I just didn't feel that the data itself warranted a whole class.

import collections as colls
import csv
import datetime as dt

import requests
from lxml import etree

Job = colls.namedtuple('Job', ['guid', 'title', 'url', 'author', 'logo', 'description', 'pub_date', 'update_date',
                               'categories'])

html_parser = etree.HTMLParser()

req_session = requests.Session()
req = req_session.get(url_1)

root = etree.fromstring(req.content)
ns_map = root.nsmap

job_elems = root.xpath('/rss/channel/item')[:10]

def parse_job_item(job_item):
    guid = job_item.findtext('guid')
    title = job_item.findtext('title')
    link = job_item.findtext('link')
    author = job_item.findtext('a10:author/a10:name', namespaces=ns_map)
    description = job_item.findtext('description')
    pub_date = job_item.findtext('pubDate')
    if pub_date:
        pub_date = dt.datetime.strptime(pub_date, "%a, %d %b %Y %H:%M:%S Z")
    update_date = job_item.findtext('a10:updated', namespaces=ns_map)
    if update_date:
        update_date = dt.datetime.strptime(update_date, "%Y-%m-%dT%H:%M:%SZ")
    categories = [elem.text for elem in job_item.findall('category')]

    job_page_elem = etree.fromstring(req_session.get(link).content, parser=html_parser)
    # "//body/div[@class='container']/div[@id='content']/header/div/a/img/@src"
    # contains(concat(' ', normalize-space(@class), ' '), ' s-avatar ')
    company_logo = job_page_elem.xpath(
        "/html/body/div[@class='container']/div[@id='content']/header/div[contains(concat(' ', normalize-space(@class), ' '), ' s-avatar ')]//img/@src")
    if company_logo:
        company_logo = company_logo[0]
    res_item = Job(guid, title, link, author, company_logo, description, pub_date, update_date, categories)
    return res_item

job_data_list = (parse_job_item(curr_elem) for curr_elem in job_elems)

with open('../out/jobs_out.csv', 'w', newline='') as out_file:
    writer = csv.writer(out_file)
    writer.writerow(Job._fields)
    writer.writerows(job_data_list)


Your method seems thread safe, but you are blocking getDownloadURL() because task.get() will only return once the underlying job finishes. Try reading up on Java's  future and see how you can use them more efficient and correct.

Your executor service should most likely only be created once for your application.

By the way: if you pass ServerAdapter and id to MyCallable (as constructor arguments) you no longer need to keep getDownloadURL synchronized or MyCallable non-static.


Reading SQL file using injection and utility reader

The idea to extract SQL queries from the code into in a separate resource is good in general. Its main advantage is that when there is a non-substantial change at the database side, it might be enough to change the resource file, without recompiling the code.

However, it slightly reduces the readability: the query is in a separate file, you do not have it immediately visible near the instructions that process the ResultSet. That can become confusing if the query is passed to a PreparedStatement with a number of parameters, but everything finally depends on each case. This discussion can easily end up with arguing whether inline SQL is better than using an ORM :)

For the solution that you submitted, I can observe the following:

each *.sql file can contain only one query. If there are a lot of queries used by objects within a package, this can easily pollute the folder and you'll need to be careful when choosing a naming convention for the files, otherwise one will be easily lost among them. selectStatement.sql is just an example and real resources should have names like selectBookByAuthor.sql etc.
a single string with plain and directly usable SQL is replaced with two values which are not obvious to change and maintain if necessary: the class name (com.mycompany.SqlReader) and the file name (com/mycompany/selectStatement.sql), because both are packed in the same string expression. Would you rely on your IDE or make all changes manually for each occurrence when these two values are changing?
the UnsupportedOperationException is not the best choice for this case. Logically, the operation is supported, but something gone wrong here and the expected predefined statement could not be read. The application is thus in an invalid state: the .sql was not included in the build sequence or a typo in the file name... I think that IllegalStateException is much better here. It also should be moved inside the catch block and chained with the IOE (throw new IllegalStateException(ioexception);). You should probably consider adding to the catch block other exception types, if any, that can result from calling FileUtils.readFileToString.

Another Approach

I can suggest another approach that has more or less the same result of externalizing SQL queries, but can be achieved without the dedicated SqlReader class, only by using the features of Spring.

The fields representing SQL queries can be initialized from property file sources:

@Value("${sql.select.products}")
private String selectProductsQuery;

The properties file must contain the key sql.select.products.

The annotation @PropertySource is used to point to the properties file to look in:

@PropertySource("classpath:/queries.properties")
public class TestDAO { ... }

In queries.properties you just specify the queries to use:

sql.select.products=SELECT p.id, p.name ... FROM product p...

The advantages:

it's all managed by Spring, once the configuration is set up properly.
You have all the queries in the same file.


What do you plan to do if a class doesn't grade like this?  I've had classes where each assignment, test, and quiz had its own weight.  Are you just going to make each its own category?  Note that you'll have to calculate the percentages prior to entering the data here.  Unfortunately, not every professor will return grades in the form of percentages.

If I had this as a task, I think that I'd just use a spreadsheet for it.  A spreadsheet already has the relevant computing capacity and is very flexible in the face of arbitrary rules.  It also supports saving, which this program doesn't.  You'll have to enter the categories and such every time you use the program.  With a spreadsheet, you'd save and would just need to update as grades arrive.

All that said, for learning purposes, I'm going to go over the code that you have.

string categories[10];
int percent[10];

This looks risky.  The fact that you are using 10 in two places suggests that it has special significance.  If so, you should declare a constant to hold the value:

const int MAX_CATEGORIES = 10;

Another problem is that you apparently want categories and percents to be linked, one percent per category.  So the C++ way to handle this is to make a class, but in this case, let's make a struct instead:

struct Category {
    public std::string name;
    public float percentOfGrade;

We use a struct because I'm not up to explaining classes in an answer.  Anyway, now you can just declare one array rather than two (yes, std::vector would be better, but it would bypass some of the things that I want to criticize).

Category categories[MAX_CATEGORIES];

Notice that categories is plural.  I use this to tell me that categories refers to a collection of objects.  If I were referring to just one category, I'd use a singular name.

Let's continue looking at your code:

int totalPoints[50];
int totalItems[50];

OK, first we have the same problem as before.  It looks like 50 has some significance, so we want to make it a constant, say MAX_ITEMS_PER_CATEGORY.  However, looking at your code, totalItems is an array showing how many items in a category.  That suggests that it should not have MAX_ITEMS_PER_CATEGORY entries.  In fact, we should add it to the category struct:

    public int numberOfItems;
};

Note that I renamed it.  I don't like totalItems as a name because total is singular but you're defining an array.  I would expect something named total to be the sum of the items or something like that.

I'm going to leave off describing what to do with totalPoints, as you haven't written code using it.  Again though, I don't like the name.

cout << "How many grade categoies do you have: ";

Note that categories is misspelled there.  Also, you probably should have written std::cout`` rather than plaincout`.

for(int i = 1; i <= a; i++)
{
    cout << "Enter the category title: ";
    cin >> categories[i];
}
for(int i = 1; i <= a; i++)
{
    cout << "Enter the total percentage for " << categories[i] << ": ";
    cin >> percent[i];
}
for(int i = 1; i <= a; i++)
{
    cout << "How many items are there for " << categories[i] << ": ";
    cin >> totalItems[i];
}

First, why do three for loops when one would do?  Avoid things where two or more parts of your program have to synchronize.  These lead to bugs as synchronicity is hard to maintain.

Second, C++ arrays are zero-indexed.  You're starting with 1 but should be starting with 0.  The end changes as well.  Note the < where there was a <=.

for ( int i = 0; i < numberOfCategories; i++ )  {
    std::cout << "Enter the category title: ";
    std::cin >> categories[i].name;
    std::cout << "Enter the total percentage for " << categories[i].name << ": ";
    std::cin >> categories[i].percent;
    std::cout << "How many items are there for " << categories[i].name << ": ";
    std::cin >> categories[i].numberOfItems;
}

I also changed a to numberOfCategories for readability.

And of course, I started using the struct fields that we declared.

return 0;

You don't need to return from main at the end of execution.  The compiler will handle this for you.  Only return if you need to do so early.

If you do explicitly return, then do it as follows:

return EXIT_SUCCESS;

or

return EXIT_FAILURE;

This is cross-platform and doesn't rely on the OS understanding 0 the same as you do.

Note:  I hinted at this previously, but I'll say it explicitly now.  A class would be a better solution in general.  I only skipped it because it's too complicated to explain.  The struct solution is inferior but closer to how your existing code worked.  Similarly, a std::vector would be a better data structure but is less like your current code.  I prioritized critiquing your current code over restructuring it.

Another problem that I slid past is that you're doing no validation of your input.  If someone enters input that doesn't fit, you should either handle it or abort the program.  For example, if numberOfCategories is greater than MAX_CATEGORIES, you will get a runtime error when adding the first extra category.


Avoid comments that are identical to the code:

# check if clusters have converged  <-- Remove this
def has_converged(centroids, old_centroids, iterations):

MAX_ITERATIONS = 1000

Constants should be put at the top of the file to be easier to tweak.

Separate calculations from IO, your function kmeans should return the values and then another function (maybe pretty_format_k_means) should create a human readable message.

# k = number of clusters
# c = initial list of centroids (if provided)

Multi-character variable names are allowed, rename your variables (and function arguments) to more meaningful names, and then you can delete the comments.


It looks like you should be implementing IDisposable here. See on MSDN.

Then, in your Dispose(bool) method, you can call CloseDppClient (or, better yet, do them the other way around and call Dispose() from your CloseDppClient method).

You should also be putting explicit access modifiers on your classes, properties, methods, fields, events, etc. As it stands now, DppTCPClient is internal.

Also, it's usually expected to follow PascalCasing throughout C# programs for public, class, interface and enum definitions.

I've left DppTcpClient as internal, but if you want it accessible outside the assembly simply replace internal with public.

An example would look like:

internal class DppTcpClient
    : IDisposable
{
    // Flag: Has Dispose already been called?
    bool disposed = false;

    // Original code

    public void CloseDppClient()
    {
        Dispose();
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposed)
        {
            return;
        }

        if (disposing)
        {
            if (m_client.Connected)
            {
                m_client.GetStream().Close();
                m_client.Close();
            }
            // Free any other managed objects here.
        }

        // Free any unmanaged objects here.
        disposed = true;
    }

    ~DppTcpClient()
    {
        Dispose(false);
    }
}

Then, you should be using your DppTcpClient where you need it:

using (DppTcpClient client = new DppTcpClient())
{
    // Code to use `client` here
}

So long as you always wrap any DppTcpClient objects with a using, you'll never run into a stale client left open.

Always use braces.

if (data.Length != length)
    throw new Exception("WriteBytes: Length should be same");

Should be written as:

if (data.Length != length)
{
    throw new Exception("WriteBytes: Length should be same");
}

Braces can't prevent bugs, but they can help prevent bugs. (If you know what I mean.)

From what I can tell, your ReadAllBytes method is actually not supposed to read all the bytes in the stream (or so it sounds), by this manner you should be changing how you work with it internally.

Instead of having the user supply a buffer, you should supply it by use of either:

A return type;
An out parameter;

The return type would be more appropriate here, so you could do something like:

public byte[] ReadAllBytes()
{
    using (MemoryStream ms = new MemoryStream())
    {
        m_client.GetStream().CopyTo(ms);
        return ms.ToArray();
    }
}

See: https://stackoverflow.com/questions/19387979/get-length-of-data-available-in-networkstream for more information on reading the entire stream.

This simplifies it greatly, and takes a large brunt of the work off your shoulders.

Just as well, you can completely remove the int length parameter from the WriteBytes method:

public void WriteBytes(byte[] data, int length)
{
    // Get access to network stream
    Stream stm = m_client.GetStream();
    stm.Write(data, 0, data.Length);
}

Lastly, I would rename your ReadAllBytes method to ReadBytes, since that's what it's doing.


I liked your DP approach and use of stringbuider instead of string.

But, the code gives null pointer exception :

 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at Test.longestSubstring(Test.java:157)
at Test.main(Test.java:22)

for the input System.out.println(longestSubstring("aabb", "akk"));

The reason is that whenever the resultant substring starts from index 0, this code will throw a null pointer exception because  checker[0][0] is 1(instead of 0), if the first characters match. Because, you're using if(checker[r][c] == 0) break; as the criteria to end the while loop. One solution is to have the while loop run for max number of times. Other approach is to use an array of 1 greater size i.e. int[][] checker = new int[row+1][col+1];

Moreover, there is a small bug in this code :-

For input System.out.println(longestSubstring("aabb", "abbbb"));, the output is "bb". But, the right answer is "abb". Even for the given test cases,

  String str3 = "aaaaaaatyuieo";
   String str4 = "aaaaaklui";

    System.out.println(longestSubstring(str1, str2));

The answer should be "aaaaa". But, it returns "ui". The reason for that is that you should check if checker[i][j] is greater than max before assigning

max = checker[i][j];
r = i;
c = j;

You need not write else continue; as the last statement in the loop.

Here is the complete code:-

    public static String longestSubstring(String str1, String str2){
    int row = str1.length();
    int col = str2.length();

    int[][] checker = new int[row+1][col+1];

    int max = 0;
    int r = 0;
    int c = 0;
    for(int i = 1; i <= row; i++){
        for(int j = 1; j <= col; j++){
            if(str1.charAt(i-1) == str2.charAt(j-1)){
                checker[i][j] = checker[i-1][j-1] +1;
                if(checker[i][j] > max){
                    max = checker[i][j];
                    r = i;
                    c = j;
                }
            }
        }
    }
    StringBuilder sb = new StringBuilder();
    while(true){
        if(checker[r][c] == 0) break;
        sb.append(str1.charAt(r-1));
        r--;
        c--;
    }
    return sb.reverse().toString();
}


Macro to run code once during the lifetime of the program

It is not thread safe.  You can use Boost, or standard C++11 std::call_once.

Answer to comment:

Boost and C++11 are defining include library for launching threads and thread synchronization (locks, atomic variables…). The call_once function can either use those to ensure thread safety or use the thread lib of the OS (pthreads for *nix).

A very simplified (unefficent) implementation might be:

static std::mutex mutex;
static bool called = false;
{
   std::lock_guard<std::mutex> lock(mutex);
   if (!called) {
      f(); // <- User code
      called = true;
   }
}

It is not very efficient because the lock is always taken. An optimisation it to atomically check the once flag before taking the mutex:

static std::mutex mutex;
static std::atomic<bool> called = false;
{
   if (!called) {
     std::lock_guard<std::mutex> lock(mutex);
     if (!called) {
        f(); // <- User code
        called = true;
     }
   }
}

The implementation of pthread_once in glibc is interesting: it is much more complicated as it tries to behave correctly in presence of fork.

Boost/C++11 use a functor (function pointer or object with operator()): this way it can be implemented as a function and not a macro (you can use lambda in C++11 to avoid defining a separate function).


creating own javascript join and push methods

first of all you can use the "new" class syntax instead of changing the prototype directly.
This is how I would do it:
class Errey {
    #currentArray;

    constructor(...elements) {
        this.#currentArray = elements;
    }

    get errey() {
        return this.#currentArray;
    }

    push(...elements) {
        const startLength = this.#currentArray.length;
        elements.forEach((curEl, index) => this.#currentArray[index + startLength] = curEl);
        return this.#currentArray.length;
    }

    join(union = " ") {
        return this.#currentArray.reduce((prev, cur) => prev + union + cur);
    }
}

//run a few examples
const myArray = new Errey("3","blue","1","brown")

console.log(myArray.join(", "));
console.log(myArray.push("Subscribe", "To", "Him"));
console.log(myArray.errey);

push:
the standard array.prototype.push allows for multiple elements to be added at once, so I allow multiple elements and loop over them using forEach, you could also do [...this.#currentArray, ...elements] (or use Array.prototype.concat()).
join:
here I use reduce to create a join operation. Reduce takes the first 2 elements and applies a function on them (in this case a + union + b), makes them the new first element and repeats that until there is only one element left, our joined erray.
I also made the internal Array private using the prefixed # and created a getter (get errey()) instead, this way the internal array can only be changed using the push method.
Using the factory pattern (which I personally prefer):
const Errey = (...elements) => {

    const push = (...newElements) => {
        const startLength = elements.length;
        newElements.forEach((curEl, index) => elements[index + startLength] = curEl);
        return elements.length;
    };

    const join = (union = " ") => elements.reduce((prev, cur) => prev + union + cur);

    const get = () => elements;

    return {
        push,
        join,
        get,
    };
};

const myArray = Errey("3","blue","1","brown")

console.log(myArray.join(", "));
console.log(myArray.push("Subscribe", "To", "Him"));
console.log(myArray.get());


I honestly think your first version is the best one. It's readable, and makes more sense at a glance than the refactorings. That said, I would consider a couple of things.

def generate
  violations = relevant_violations
  comments = convert_to_cleaned_up_comments(violations)
  text = convert_to_text(comments)
  save_to_file(text)
end

The comments and text temp variables represent a transitional state. I would ask myself if I will use them in any other form. If not, and if their entire reason for existence is to transition to text, I would do away with them and have one entry point for clean, or savable text.

I would consider if generating the report is the Violation class responsibility. The report is a presentational concern, and I feel it should have its own class.

class ViolationsReport
  attr_reader :violations, :file

  def initialize(violations, file)
    @violations = violations
    @file = file
  end

  def generate
    save_to_file formatted_violations
  end

private

  def formatted_violations
    convert_to_comments violations
  end

  def save_to_file(text)
    file.open(LOCAL_PATH, 'w') { |f| f.write text }
  end

  # more methods here to do the job
end

The idea is to isolate presentation logic that is only needed for the report, in the report class itself. You then have cleanly defined responsibilities for each class.


aggregate sheets from many excel workbooks into one workbook

I think the way you are doing this is reasonable.  Regarding pre-existing blank sheets..The rewritten code below removes blank worksheet(s) in the importing workbook, after the selected workbooks' worksheets have been inserted.

Sub openDialogBoxAndSelectFiles()

  Dim wb1 As Workbook
  Set wb1 = ActiveWorkbook

    'Cache worksheet references
    Dim originalWorksheets As Collection
    Set originalWorksheets = New Collection
    For i = 1 To wb1.Sheets.Count
      originalWorksheets.Add wb1.Sheets(i)
    Next i

    With Application.FileDialog(msoFileDialogFilePicker)
        .AllowMultiSelect = True
        .InitialFileName = ThisWorkbook.Path & "\"
        .Title = "Paddington Bear Selection Window"
        .ButtonName = "Omlette"

        .Filters.Clear
        'only interested in Exel workbooks
        .Filters.Add "All Files", "*.xls*"

        If .Show = True Then
            For Each file In .SelectedItems
                ImportWorksheets wb1, file
            Next file
        End If
    End With

    'Delete non-imported blank worksheets
    If wb1.Sheets.Count > originalWorksheets.Count Then
        DeleteBlankSheets originalWorksheets
    End If

End Sub

Private Sub ImportWorksheets(ByRef wb1 As Workbook, ByVal filename As Variant)
On Error GoTo ErrorExit
    Dim wb2 As Workbook
    Set wb2 = Workbooks.Open(filename:=filename, ReadOnly:=True)

On Error GoTo WorkbookOpenError
    Dim i As Long
    For i = 1 To wb2.Sheets.Count
      wb2.Sheets(i).Copy before:=wb1.Sheets(1)
    Next i

WorkbookOpenError:
    wb2.Close

ErrorExit:
End Sub

Private Sub DeleteBlankSheets(ByRef originalWorksheets As Collection)
On Error GoTo ErrorExit

    Dim displayAlertsFlagCurrentValue As Boolean
    displayAlertsFlagCurrentValue = Application.DisplayAlerts

    'Prevent Sheet deletion prompts
    Application.DisplayAlerts = False

    Dim wksht As Worksheet
    For Each wksht In originalWorksheets
        If IsBlank(wksht) Then
            wksht.Delete
        End If
    Next wksht

ErrorExit:
    Application.DisplayAlerts = displayAlertsFlagCurrentValue
End Sub

Private Function IsBlank(ByRef wksht As Worksheet) As Boolean
    IsBlank = WorksheetFunction.CountA(wksht.UsedRange) = 0 And wksht.Shapes.Count = 0
End Function


1) I've been searching online for exception class design, and haven't found anything like this. This worries me. Is there something wrong with designing exceptions this way?

Here is my opinion: What is a 'good number' of exceptions to implement for my library?

  2) Are there any considerations to think about when deriving from one of the standard exceptions? Or should I just derive from std::exception and not worry about?

You should probably derive from std::runtime_error.

  3) One problem with this design is that the format of the string is dependent on this class. Is there any good way to decouple this?

Use the string in the exception solely for logging (not for generating a user error message). The exception will generally carry technical information that is not relevant to the user.

But when displaying information to the user you should generate a formatted string at the catch point (not the throw point). This is because you can not tell what the output device is going to be used at the throw point.


Take a look at what translating
1241234113

results in when aligned slightly differently
                       One       Billion
Two  Hundred   Forty   One       Million
Two  Hundred   Thirty  Four      Thousand
One  Hundred           Thirteen

you can see that there are several patterns here.

Every number can be chunked into groups of 3 digits like this 1,241,234,113.

Each chunk has a different value for the last column, which is one of "Billion", "Million", etc.

Within each chunk, there is one digit at the hundreds place.

Within each chunk, the last 2 digits have a special case till 20, otherwise it's a special word for the ten's place, and the one's place.

So the only variables you need are just
std::string const till_twenty[20] = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
std::string const tens_place[10] = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
std::string const thousands[4] = {"", "Thousand", "Million", "Billion"};

Note that I've renamed the variables slightly, and made them const. Also, there's no need for the word Zero, since that will only be written if the entire number is 0.
Now you can build up the functions for the 3 digit chunks
//for the first digit
std::string hundreds_place(int n) {
   return n ? till_twenty[n] + " Hundred " : "";
}

// for the 2nd and 3rd digit
std::string ones_and_tens_place(int n) {
    return n <= 20 ? till_twenty[n] : tens_place[n / 10] +
                                      (n % 10 ? " " + till_twenty[n % 10] : "")
}

// putting all 3 digits together
std::string by_hundreds(int n) {
    return hundreds_place(n / 100) + ones_and_tens_place(n % 100);
}

Now you can recursively build the 3 digit numbers by keeping track of which power of 1000 is being currently processed
std::string by_thousands(int n, int i) {    // i keeps track of the chunk
    return n ? by_thousands(n / 1000, i + 1) +
               by_hundreds(n % 1000) + " "
               + thousands[i] + " "
             : "";
}

and then finally it can all be put together
std::string numberToWords(int num) {
    std::string res = num ? by_thousands(num, 0) : "Zero  ";
    // with a bit of processing to get rid of trailing spaces
    return res.substr(0, res.length() - 2);
}


Calling one method both dynamically and statically

The first thing you should now is that magic methods are slow __call and __callStatic, that is. The second thing I'd like to point out is that, given that you declared the method as static, you should always call it as such. Failing to do so is just going to leave you with code that is a nightmare to maintain: every call to every function will need to be checked and double checked, just to know if that method is indeed static or not.

Lastly: why aren't you simply calling the method statically on your instance?

$file = new File('dynamic');
$file::exists();

That'll work just fine, too. But all in all: a method should be either static (which isn't that useful in PHP 9/10 times anyway) or not. Trying to allow for static calls aswell as instance calls means you are writing a class that offers a messy API. Don't


You could, but don't have to, check your googleMaps variable to be falsy, instead of undefined or null.
To make this code more readable, you could seperate the function from your object. That way, if you have more functions, you have an overview of your object's implementation.

1.

old

if (googleMaps === undefined || googleMaps === null)

new

if(!googleMaps)

2.

old

var googleMaps = {
  getLatLngFromAddressString : function(addressStr, callback){
  //...
  }
}

new

var getLatLngFromAddressString = function(addressStr, callback){
//...
}

var googleMaps = {
  getLatLngFromAddressString : getLatLngFromAddressString
}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

If all your method does is call up to the super class's implementation of the method, you can safely omit the method entirely.  I understand this is boilerplate code that Xcode automatically inserts any time you create a new view controller, but at the end of the day, it's just clutter that should be cleaned up.

override func viewDidLoad() {
    super.viewDidLoad()

    let prefs = NSBundle.mainBundle().pathForResource("Settings", ofType: "plist")
    let dict = NSDictionary(contentsOfFile: prefs!)
    userDefaults.setObject(dict, forKey: "defaults")                // without this code doesn't work
    userDefaults.registerDefaults(dict as! [NSObject : AnyObject])  // with or without this code works... do I need this?
    userDefaults.synchronize()

    // this just toggles the aBool value
    if let defaults = userDefaults.valueForKey("aBool") as? NSNumber {
       if defaults as NSObject == 1 {
            println("inside the conditional: \(defaults)")
            userDefaults.setValue(0, forKey: "aBool")
            userDefaults.synchronize()
            println("Setting aBool to true")
        } else {
            userDefaults.setValue(1, forKey: "aBool")
            userDefaults.synchronize()
            println("setting aBool to false")
        }
    }
}

I don't want to say this is objectively too much code for viewDidLoad, but it's not appropriate for this to all go in viewDidLoad.  This really doesn't belong in the viewDidLoad of any view controller, really.  This is code we seem to only want to load once.  This really belongs in our app delegate, in application(_:didFinishLaunchingWithOptions:).

Once we get our list loaded into NSUserDefaults, we just need to access the values through NSUserDefaults, which is a singleton we can easily access from anywhere.

As a final note about all of this, calling synchronize is generally going to be unnecessary.  NSUserDefaults will synchronize itself when it finds a convenient time.  Moreover, all synchronize does is synchronize what NSUserDefaults has stored in memory with what it has stored in long-term storage.  The only time you can lose something that you put in NSUserDefaults is if your app crashes after you changed a value and before NSUserDefaults had a chance to synchronize.  This is extraordinarily rare.  And for emphasis, realize that I said this happens when your app crashes.  If the user exits your app, NSUserDefaults will synchronize before the app is allowed to completely exit.

And when you access the values in NSUserDefaults, you'll get the value it was most recently set to (which isn't necessarily what is saved to the permanent storage at that moment).

Calling synchronize just forces the synchronization to happen at that very instant, which is entirely unnecessary.

And, for the record, our inner most conditional can be simplified:

if let defaults = userDefaults.valueForKey("aBool") as? NSNumber {
    userDefaults.setValue(!defaults.boolValue, forKey: "aBool")
}


Sums of columns and diagonals of a matrix

Use Symbolic Constants Rather Than Numeric Constants
In most programming languages there is a way to define symbolic constants for numbers which makes the code more readable and easier to maintain. When raw numbers are used in code they are sometimes called Magic Numbers. Using Magic Numbers is generally considered a poor programming practice as discussed in this stackoverflow question.

While the number 30 isn't quite a magic number since it is used as the maximum dimensions for the arrays in the matrix, it would be beneficial to anyone that needs to read or maintain the code to define symbolic constants for it. This would allow anyone who needs to edit the code to change the maximum dimensions to change 1 number in 1 place.

In C this would be:

#define MAXIMUM_MATRIX_DIMENSION 30

and in C++ this would be:

const int MAXIMUM_MATRIX_DIMENSION = 30;

Then the integer array arr could be declared as:

int arr[MAXIMUM_MATRIX_DIMENSION][MAXIMUM_MATRIX_DIMENSION];

It then becomes very easy to change the maximum size of the matrix by only changing one line.

Meaningful Variable Names
The code might be easier to read if the variables m and n had more meaningful names, m could be matrixDimension. It's not really clear what n since it could also be `matrixDimension.

The code might also be more readable if the variable arr had a more meaningful name, perhaps baseMatrix.

Declare Variables as Needed
The C programming language now allows variables to be created where they are needed, for instance the variables i and j could be created within the for loops

    for(int i = 0; i < m; i++){
        for(int j = 0; j < n; j++){
            printf("Type elements: ");
            printf("Element[%d,%d]: ",i,j);
            scanf("%d",&arr[i][j]);
        }
    }

The variables used to contain the sums should also be declared where they are initialized.

Error Checking on Input
It is always better to check user input before using it to perform actions in the code. For example checking the size of the dimensions before using it as a control value in the previous loop. If the user enters a number less than 1 or greater than 29 the program will experience undefined behavior and may crash. If the number is 0 or less the loops will never execute and if the number is greater than 29 matrix values will be written to memory that hasn't been allocated to the arrays.

    m = -1;
    while (m < 1 or m >= MAXIMUM_MATRIX_DIMENSION)
    {
        printf("What dimensions of matrix you want?(1 integer number greater than 0 and less than %d) ", MAXIMUM_MATRIX_DIMENSION);
        scanf("%d",&m);
    }

Complexity
The function main() is too complex (does too much). As programs grow in size the use of main() should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.

There is also a programming principle called the Single Responsibility Principe that applies here. The Single Responsibility Principle states:

  Every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.

There are at least 4 possible functions in main() and possibly more. Each of the outer for loops is a good candidate for a function. The possible functions are:

Get the dimensions of the matrix
Get the individual values of the matrix
Print the matrix
Calculate and report the sums of the matrix columns, rows and diagonals (this could be 2 functions).


Function to check if received message matches any of the expected messages

Unfortunately your code is incomplete and can't be run in this state. Still I want to recommend some improvements to this snippets.

My first impression from this code is that it looks like plain C, not C++  (besides the use of std::equal).

To pass your Message and compare it you are using plain char arrays.
With this approach you have to also pass the size. You shouldn't feel the need for this in C++ any more. Check out containers such as std::array (fixed size) std::vector, std::string or std::string_view.

There's a bug which can make your program truncate the compared values depending on the platform:

static const char readReq[] = { 0x92 };

Consider that 0x92 = 146(int).

Not all platforms have char == unsigned char.  If you are not lucky it can mean char == signed char. See https://stackoverflow.com/questions/2054939/is-char-signed-or-unsigned-by-default

I found this by accident when I switched your plain C Array:

static const char readReq[] = { 0x92 };

To C++ std::vector:

const std::vector<char> readRequest = { 0x92 };

This doesn't event compile. The compiler complains that 0x92 truncates. So I changed it to:

const std::vector<unsigned char> readRequest = { 0x92 };

Then I thought probably it is event better to really declare your values as an array of constants. So I changed to std::array like this:

constexpr std::array<unsigned char, 1> readRequest = { 0x92 };
constexpr std::array<unsigned char, 5> readResponse = { 0x00, 0x02, 0x12, 0x34, 0xA1

Now it is similar to the old macro defines in C but better because it follows the rules of the language.:

#define readRequest 0x92

With std::array I refactored your code like this:

#include <algorithm>
#include <array>
#include <iostream>
#include <vector>

template<typename MessageBegin, typename MessageEnd, typename ReceiveType,
    typename ResponseType>
void replyMessage(
    const MessageBegin& messageBegin,
    const MessageEnd& messageEnd,
    const ReceiveType& receive,
    const ResponseType& response)
{
    if (std::equal(messageBegin, messageEnd, receive.begin())) {
        for (const auto& sign : response) {
            std::cout << sign;
            //serialPC.putc(sign);
        }
    }
}

void searchFunction(int number, const std::vector<unsigned char>& message)
{
    constexpr std::array<unsigned char, 1> readRequest = { 0x92 };
    constexpr std::array<unsigned char, 5> readResponse = { 0x00, 0x02, 0x12, 0x34, 0xA1 };

    constexpr std::array<unsigned char, 2> writeRequest = { 0x0A, 0xE0 };
    constexpr std::array<unsigned char, 5> writeResponse = { 0x00, 0x02, 0x11, 0x01, 0x98 };

    constexpr std::array<unsigned char, 2> resetRequest = { 0x00, 0xFF };
    constexpr std::array<unsigned char, 7> resetResponse = { 0x00, 0x21, 0x23, 0x0E, 0xAE, 0x11, 0x3A };

    constexpr std::array<unsigned char, 2> verReqeust = { 0x00, 0xA2 };
    constexpr std::array<unsigned char, 7> verResponse = { 0x00, 0x03, 0x82, 0xAA, 0x07, 0x88, 0xA9 };

    constexpr std::array<unsigned char, 2> typeRequest = { 0x00, 0x67 };
    constexpr std::array<unsigned char, 6> typeResponse = { 0x00, 0x03, 0x00, 0x00, 0xC4, 0x77 };

    constexpr std::array<unsigned char, 2> askRequest = { 0x00, 0x55 };
    constexpr std::array<unsigned char, 4> askResponse = { 0x00, 0x01, 0xFE, 0xFF };

    if (number == 4) {
        replyMessage(message.begin() + 2, message.begin() + 3, readRequest, readResponse);
    }
    else if (number == 5) {
        replyMessage(message.begin() + 2, message.begin() + 4, writeRequest, writeResponse);
        replyMessage(message.begin() + 2, message.begin() + 4, resetRequest, resetResponse);
        replyMessage(message.begin() + 2, message.begin() + 4, verReqeust, verResponse);
        replyMessage(message.begin() + 2, message.begin() + 4, typeRequest, typeResponse);
        replyMessage(message.begin() + 2, message.begin() + 4, askRequest, askResponse);
    }
}

In this code, other stuff was improved:

Cryptic names like msg, resps, respl or replyMsg were renamed. Sure, you can find out what they mean, but it is more stressful to read the code and get the meaning. Make a experiment. Forget the code for 6 months and come back to it. How long does it take you to get its meaning?
Functions can now accept Containers, which know their size. Also, we can simply iterate over them.

Compare this:

void replyMsg(char msg[], int startArr, int endArr, const char* receiv, const char* resps, int respL) {
    if (std::equal(msg + startArr, msg + endArr, receiv)) {
        for (int x = 0; x < respL; x++) {
            serialPC.putc(resps[x]);
        }
    }
}

with this:

template<typename MessageBegin, typename MessageEnd, typename ReceiveType,
    typename ResponseType>
void replyMessage(
    const MessageBegin& messageBegin,
    const MessageEnd& messageEnd,
    const ReceiveType& receive,
    const ResponseType& response)
{
    if (std::equal(messageBegin, messageEnd, receive.begin())) {
        for (const auto& sign : response) {
            std::cout << sign;
            //serialPC.putc(sign);  // btw what is this???
        }
    }
}

Besides the template, which we had to use because of different array sizes, which is easier to understand?


Well here's my take on it.  If you want efficient in terms of speed, write a loop.  LINQ is not for writing fast code, it's for writing concise code.

memoryInUse is just a collection of the memory counts of all the machines that are on.  You then essentially partition those machines by some memoryCalcFactor to do some calculation.

The call to ToArray(), while somewhat helpful (you do the filter/projection once) isn't really needed.  You can perform your calculation in one pass and therefore don't need it at all.  Look at the following lines in your calculation:

var x = memoryInUse.Where(ram => ram <= memoryCalcFactor).Sum();
var y = memoryInUse.Count(ram => ram > memoryCalcFactor) * memoryCalcFactor;
return x + y;

What are we doing here?

Adding up all the sizes that are less than some factor
Counting all those that are greater than that factor multiplying by that factor.
Adding the previous results

Looking at this at a much higher level, what are we doing here?  We're adding up the sizes limiting each size by some factor (a maximum).  Write your code to do that.

This is how I'd write it:

var memorySizes = machines
    .Where(machine => machine.IsOn)
    .Select(machine => machine.MemoryInMB);
var result = memorySizes.Sum(size => Math.Max(size, memoryCalcFactor));

Otherwise if you don't want to take the performance hit LINQ will give you and use a loop, here's the equivalent:

var sum = 0;
foreach (var machine in machines)
{
    if (machine.IsOn)
    {
        sum += Math.Max(machine.MemoryInMB, memoryCalcFactor);
    }
}


Checking if a computer is part of a domain

Different approaches to determine the domain membership of a computer

Usage of command line tools

If you use command line tools you have the burden to parse the output of the process.

A naive implementation to execute command line tools in windows:

public class CmdExecutor {

    private String cmdString;

    public CmdExecutor(String cmdString) {
        this.cmdString = cmdString;
    }

    public void execute() throws IOException, InterruptedException {

        final Process process = Runtime.getRuntime().exec("cmd /C " + cmdString);

        final BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String line = br.readLine();

        while (line != null) {

            System.out.println(line);

            line = br.readLine();

        }

        process.waitFor();

    }

}

wmic

    public static void main(String[] args) throws IOException, InterruptedException {
        new CmdExecutor("wmic computersystem get domain").execute();
    }

systeminfo

    public static void main(String[] args) throws IOException, InterruptedException {
        new CmdExecutor("systeminfo | findstr /B /C:\"Domain\"").execute();
    }

LDAP access

If you have access to the LDAP interface of your Active Directory you can query LDAP for a specific computer account:

(&(objectClass=computer)(name=MyPC))

Comparing the approches

Using JNA and the command line approaches on the local machine can only return the local state. The only reliable information you can get from LDAP. This especially relates to disabled or deleted computer accounts.

Querying LDAP and evaluating the result (including server not reachable) may be difficult. But as the ldap schema does not change frequently you can rely on the query parameters and the result fields to remain stable.

Command line tools and Windows system libraries tend to change in usage from time to time. That is a lot more probable than in LDAP. So you have to expect to adapt the result parsing or the parameter structure.

This you can say for the command line tools as well, but there is a higher abstraction. You can deal with standard command line tools very well and easily provide alternate implementations. This is even possible with JNA but you a dealing with system libraries and not with command line tools. (My personal view on this is that command line tools are easier to handle).


General Retry Strategy #3 with TryResult

Let’s put the cart before the horse – I mean Catch before the Try :)

class Program
{
    static void Main(string[] args)
    {
        using (new Catch<InvalidOperationException>())
        using (new Catch<FormatException>(ex => Console.WriteLine("Oops!")))
            Try.Retry(100, 3, 3).Execute(() =>
            {
                Console.WriteLine("Trying!");
                throw new FormatException();
            });
    }
}

These using Catch statements define exceptions we can tolerate and continue trying. All other exceptions will be interpreted as critical. We can also rethrow or log in the optional handler.

Library classes:

public class Catch<TException> : Catch
    where TException : Exception
{
    public Catch()
        : this(ex => { })
    {
    }

    public Catch(Action<TException> handler)
    {
        Handler = handler;
    }

    protected internal override bool HandleCore(Exception ex)
    {
        if (ex is TException)
        {
            Handler(ex as TException);
            return true;
        }

        if (Previous == null)
            throw ex;
        else
            return Previous.HandleCore(ex);
    }

    Action<TException> Handler { get; }
}

And:

public abstract class Catch : Ambient<Catch>
{
    public static void Handle(Exception ex) =>
        Current?.HandleCore(ex);

    protected internal abstract bool HandleCore(Exception ex);
}

And:

public abstract class Ambient<T> : IDisposable where T : Ambient<T>
{
    static readonly string Id = typeof(T).FullName;
    protected static T Current
    {
        get { return (T)CallContext.LogicalGetData(Id); }
        set { CallContext.LogicalSetData(Id, value); }
    }

    protected Ambient()
    {
        Previous = Current;
        Current = (T)this;
    }

    public void Dispose() => Current = Previous;
    protected T Previous { get; }
}

And we also need to update Retry strategy:

    public override void Execute(Action action, CancellationToken cancellationToken)
    {
        foreach (var delay in Delays)
            try
            {
                action();
                return;
            }
            catch(Exception ex)
            {
                Catch.Handle(ex); // <- NEW LINE
                cancellationToken.WaitHandle.WaitOne(delay);
                cancellationToken.ThrowIfCancellationRequested();
            }

        action();
    }

UPDATE

Let's have this for the Log class - note Log.IfFail():

class Log : Ambient<Log>
{
    public static Exception IfFail(Action action)
    {
        try
        {
            action();
            return null;
        }
        catch(Exception ex)
        {
            Write(ex.Message);
            return ex;
        }
    }

    public static void Write(string line) =>
        Current?.WriteCore(line);

    public Log(string fileName)
    {
        FileName = fileName;
    }

    void WriteCore(string line) => File.AppendAllText(FileName, line);
    string FileName { get; }
}

And:

public static class Error
{
    public static void Rethrow(this Exception ex)
    {
        if (ex != null)
            throw ex;
    }
}

So we can have TryExecute:

    public override bool TryExecute(Action action, CancellationToken cancellationToken)
    {
        foreach (var delay in Delays)
            try
            {
                Log.IfFail(action).Rethrow();
                return true;
            }
            catch(Exception ex)
            {
                Catch.Handle(ex);
                cancellationToken.WaitHandle.WaitOne(delay);
                cancellationToken.ThrowIfCancellationRequested();
            }

        return Log.IfFail(action) == null; // yes, ugly :) let's invent something better
    }

We can pass more context for logging at the moment of ambient log construction.

UPDATE #2 :)

public static class Error
{
    public static void Rethrow(this Exception ex)
    {
        if (ex != null)
            throw ex;
    }

    public static bool ToTryResult(this Exception ex)
    {
        return ex == null;
    }
}

And:

    public override bool TryExecute(Action action, CancellationToken cancellationToken)
    {
        foreach (var delay in Delays)
            try
            {
                Log.IfFail(action).Rethrow();
                return true;
            }
            catch(Exception ex)
            {
                Catch.Handle(ex);
                cancellationToken.WaitHandle.WaitOne(delay);
                cancellationToken.ThrowIfCancellationRequested();
            }

        return Log.IfFail(action).ToTryResult();
    }


Best voting decision should be made just before the 20s timer ends to count most of the votes.
Instead of $(".egg-action").find("button") use a '.egg-action > button" selector
Too much jQuery, go back to VanillaJS and for loops

PS: works on Firefox also


Assuming you have an xml structure that would be similar to:

<Responses>
    <Response>
        <Item>
            <cityname>abc</cityname>
            <regionname>def</regionname>
            <latitude>101.2345</latitude>
            <longitude>34.3456</longitude>
        </Item>
        <Item>
            <cityname>ghi</cityname>
            <regionname>jkl</regionname>
            <latitude>101.2345</latitude>
            <longitude>34.3456</longitude>
        </Item>
        <Item>
            <cityname>mno</cityname>
            <regionname>pqr</regionname>
            <latitude>101.2345</latitude>
            <longitude>34.3456</longitude>
        </Item>
        <Item>
            <cityname>stu</cityname>
            <regionname>vwx</regionname>
            <latitude>101.2345</latitude>
            <longitude>34.3456</longitude>
        </Item>
    </Response>
</Responses>

You could use the XMLSerializer class to deserialize the whole file all at once, by creating a class to contain the data:

Public Class Responses
    Public Class Item
        Dim cityname As String = ""
        Dim regionname As String = ""
        Dim latitude As Double = 0.0
        Dim longitude As Double = 0.0
    End Class
    <XmlArrayAttribute("Response")>
    Dim items As New List(Of Item)
End Class

Getting the data would be as simple as:

XMLDoc.Load(GetXML)
Dim result As Responses = CType(New XmlSerializer(GetType(Responses)) _
.Deserialize(New StringReader(XMLDoc.OuterXml)), Responses)

You would access the data through the items field of result:

result.items(0).cityname


I don't know if you can make it less complex in terms of lines of code, but I'd recommend structuring it a bit differently.

You've already got class << self around the attr_reader, so you might as well wrap the remaining methods in it.

You've also got the session_FF method that's independent of the module it "belongs to", and which messes with the module's static variables. Just for convenience, it'd be nice to keep things more encapsulated.

Here's my take:

module Session_FF
  class << self
    def element *args
      elements = browser.elements *args
      raise "found #{es.size} nodes instead of one" if elements.size > 1
      elements.first
    end

    def method_missing m, *args, &block
      browser.send m, *args, &block
    end

    # lazily instantiate a browser
    def browser
      @browser ||= Watir::Browser.new :ff
    end

    # quit and nil the browser instance
    def quit
      @browser.quit if @browser
      @browser = nil
    end
  end

  # included method
  def session_FF &block
    Session_FF.module_eval &block
  ensure
    Session_FF.quit
  end
end

which you can then include in your test code:

include Session_FF

session_FF do
  element(text: "test").click
  # ...
end

I'm guessing "FF" means "Firefox", so I'd probably just call the proxy method firefox, and the module FirefoxSession, but that's a different story.


Regarding the HTML:

script element

For JavaScript, you can simply use <script> without the type attribute:

  If the language is not that described by "text/javascript", then the type attribute must be present

The language attribute is obsolete:

  Authors should not specify a language attribute on a script element.

a element

I'd say a real button should be used here, not a link:

button element with button type: <button type="button" onclick="…">Click here to hear a sound</button>
input element with button type: <input type="button" onclick="…" value="Click here to hear a sound" />


The code works, and it seems that you're take care of invalid input. But the logic of the workflow is not - well - that logic.

  int[] numbers = new int[5];

Here 5 is a magic number. Why five? Why not four or six or 20?

You should announce the number of input before asking for it (and maybe why).

Alternatively you could let the user enter a number of numbers to be calculated.

int sum = 0;

You probably have the sum variable for optimization reasons. Alternatively you could let the built in extension Sum() handle that:

numbers.Sum();

  if (!error)

You have this negation of a "negative" variable. Why not be positive and call it success:

if (success)
  Console.Write("Enter Number: ");

Instead of:

    if (Int32.TryParse(Console.ReadLine(), out input))
    {
      numbers[i] = input;
      sum += numbers[i];

you could write:

    success = Int32.TryParse(Console.ReadLine(), out input);

    if (success)
    {
      ...
    }
    else
    {
      ...
    }

      continue;

I don't see any reason for calling continue in your loop? You use continue to step over the rest of the loop and reenter it - if the condition is still true, but here it is the last expression in the loop, so there is nothing to skip.

According to the overall design you should always split your code into meaningful methods in order to accommodate to principles like DRY and Single Responsibility:

For instance:

void Main()
{
  if (!GetCountOfNumbers(out int numCount))
    return;

  if (!GetUserInput(numCount, out int[] numbers, out int sum))
    return;

  PrintValues(numbers);
  Console.WriteLine("");
  PrintResult(sum, numbers.Length);
  Console.WriteLine("");
}

Where:

private bool GetCountOfNumbers(out int numCount)
{
  if (!GetIntInput("Enter count of Numbers", "Must be a positive number", x => x > 0, out numCount))
  {
    Console.WriteLine("User aborted the calculation");
    return false;
  }

  return true;
}

and

private bool GetUserInput(int numCount, out int[] numbers, out int sum)
{
  numbers = new int[numCount];
  sum = 0;
  int input;

  for (int i = 0; i < numCount; i++)
  {
    if (!GetIntInput($"Enter number {i + 1}", "Enter any valid integer (32 bit) value", x => true, out input))
    {
      Console.WriteLine("User aborted the calculation");
      return false;
    }

    numbers[i] = input;
    sum += input;
  }

  return true;
}

Both methods are calling GetIntInput() which could be defined as follows:

private bool GetIntInput(string message, string errorMessage, Predicate<int> predicate, out int result)
{
  result = default;

  while (true)
  {
    Console.Write($"{message} ['q' to Exit]: ");
    string input = Console.ReadLine();
    if (input == "q" || input == "Q")
      return false;

    if (int.TryParse(input, out int number) && predicate(number))
    {
      result = number;
      return true;
    }
    Console.WriteLine($"Invalid input: {errorMessage}");
  }
}

It takes a message to the user, a predicate to validate the input against and an error message if the predicate returns false on the input, and it returns the result in an out variable (result). Further it allows the user to exit the input loop and then returns true or false accordingly.

In this design everything is counted for through descriptive method names and the logic in the workflow is easily understood and separately maintainable.

It could surely be done in more sophisticated ways, but as a simple user input driven console application like this, the above is a simple way to structure the code properly.


Getting the list of people who RT'd a particular Twitter account (using Twitter4J)

GOing through some general style issues first:

getmyretweeters is a class, and should have Camel-Case capitalization -> GetMyRetweeters. I would prefer MyRetweeters with a method get().
Your class should not have the static methods you have, but shouild rather have a constructor that takes a twitter name, and then initializes itself to that: public MyRetweeters(Twitter account) {...}
your getRetweeters(...) method is static, but should really be an instance method, and the name is implied by the class-name (Retweeters). get() is just fine. Since the class should have been constructed with a Twitter handle, there is no need for any arguments either...

Note about the twitter-API rate limits. Sleeping for 2 minutes is a bad idea in your code. If you really have to be doing this sleeping, then you should change your code to do a background mechanism for accessing Twitter, and have a callback to your application with the results of your query. Also, you should have some sort of caching mechanism so that you do not need to re-query data you already have from Twitter. A limit of 1 query every 2 minutes is a really tight limit.

You should also consider reading up on the Twitter API rate limits... they are not as harsh as you have allowed for. Also, there are headers returned as part of tyour request that shows you how many requests are available in the current window, and when the window ends. Bottom line is that you should be smarter about your rate limiting.

Finally, your factory that gets Twitter sessions should not have a method TwitApplicationFactory.getjoereddingtonTwitter() but should instead have something like: TwitApplicationFactory.getTwitter("joereddington");

Your main method becomes:

public static void main(String[] args) throws TwitterException {
    Twitter twitter = TwitApplicationFactory.getTwitter("joereddington");
    Retweeters retweets = new Retweeters(twitter);
    String temp[] = retweeters.get();
    for (String string : temp) {
        System.out.println(string);
    }
}


Python program to calculate the sun angle

One immediate thing I would improve is the naming of your variables. While in general very descriptive, it took me a while to realize that start_dt is actually the time of sunset and end_dt the time of sunrise, instead of the other way around. I would also make these variables global constants and use those as default values. This way you can do it all in one still short and readable function.

I would add some docstring describing what your function(s) do and use a compound comparison instead of two comparisons to determine if the time is day or night.

The datetime module is often imported as from datetime import datetime, although your import is also OK.

The calling of the code should happen under a if __name__ == "__main__": guard, where I would also put at least some very rudimentary testing code.

from datetime import datetime

SUNRISE = datetime.strptime('06:00', '%H:%M')
SUNSET = datetime.strptime('18:00', '%H:%M')

def sun_angle(time, sunrise=SUNRISE, sunset=SUNSET):
    """Return the angle of the sun at `time`.
    Assumes that the sun moves 180 degrees between `sunrise` and `sunset`.
    During night return 'I don\'t see the sun!'.
    """
    time = datetime.strptime(time, '%H:%M')
    if not sunrise <= time <= sunset:
        return "I don't see the sun!"

    angle_per_hour = 180 / (sunset - sunrise).seconds * 3600
    time_since_sunrise = (time - sunrise).seconds / 3600
    return time_since_sunrise * angle_per_hour

if __name__ == "__main__":
    test_cases = [("07:00", 15),
                  ("01:23", "I don't see the sun!"),
                  ("12:15", 93.75)]
    for time, expected in test_cases:
        output = sun_angle(time)
        print(f"solar_angle({time!r}) == {output!r}")
        assert output == expected, f"Failed: expected {expected!r}!"

The calculation of the sun angle could probably still be a bit better in order to be able to be extended for different latitudes in the future.

If this is not a class exercise or programming challenge, I would also recommend to change the interface of the function a bit. Make time always a datetime object and instead of returning a string in case of invalid input raise a custom exception:

class NightTimeException(ValueError):
    pass

...

    if not sunrise <= time <= sunset:
        raise NightTimeException("I don't see the sun!")


Be consistent.
You use a blank line to separate classes Student and Professor: Person and Studentdeserve no less. (Same goes for change in accessibility; alternatives to a blank line include (less) indent.)
Don't write, never present uncommented code.
Use all machine/tool support you can get: have a look at doxygen.
make classes (and functions) final when further derivation/overriding is bound to break something, only.
Think of derivation as extension or specialisation.
You declared common attributes for Person: try and do the same for behaviour, even if it is more cumbersome in C++ (& influenced languages) than in Simula: There, a virtual function gets to call inner - with common code before&after.
In C++, I know no better than starting Derived::f() with Base::f();.
In this example, getdata() & putdata() shouldn't be pure virtual:
Person::getdata() should input name and age; Person::putdata() output them. We are stuck without a method to handle specialised output is complete imposing. One can define void putdata() const { std::cout << toString() << std::endl; } (with toString() facing the exact problem with cur_id "on the other side").
Avoid overly long lines.

name + " " + std::to_string(age)
     + " " + std::accumulate(marks.begin(), marks.end(), 0)
     + " " + std::to_string(cur_id)

is easier to read and probably works just as well as a one-liner.

(While this review has been received exceedingly friendly,
the following code misses the mark correct contemporary C++ by a mile.
(Hopefully closing in with revisions (incorporating advice from Edward's answer);
Having "fun" with IDEone - don't hold your breath.))

Shots from the hip:

/*! \brief Person sporting common attributes
 *         and get/putdata().
 *
 *  Attributes include name, age, and an in-subclass ID.
 *  getdata() reads from std::cin, starting with name&age;
 *  putdata() writes a line to std::cout.
 */
class Person {
 protected:
    //    const int cur_id;
    std::string name;
    int age;
    /*! terse human readable representation.
    */
    virtual std::string toString() const {
        return name + " " + std::to_string(age);
    }
    ~Person(){}
 public:
    /*! read name&age from std::cin.
     */
    virtual void getdata() {
        std::cin >> name >> age;
    }
    /*! putdata() writes a line to std::cout.
     */
    virtual void putdata(std::ostream &out = std::cout) const {
        out << toString() << std::endl;
    }
};

/*! Student adds marks for subjects to the common attributes.
 */
class Student : public Person {
    const int cur_id;
//    static std::atomic<int> id_count(0);
    std::array<int, 6> marks;
 protected:
    std::string toString() const override {
        return Person::toString()
        + " " + std::to_string(
            std::accumulate(marks.begin(), marks.end(), 0))
        + " " + std::to_string(cur_id);
    }
 public:
    static int id_count;// = 0;
    Student() : cur_id(++id_count) {}
    /*! read as Person from std::cin; add marks.
     */
    void getdata() override {
        Person::getdata();
        for (auto &mark : marks)
            std::cin >> mark;
    }
};

/*! Professor adds a publication count to the common attributes.
 */
class Professor final : public Person {
    const int cur_id;
//    static std::atomic<int> id_count(0);
    int publications;
 protected:
    std::string toString() const override {
        return Person::toString()
        + " " + std::to_string(publications)
        + " " + std::to_string(cur_id);
    }
 public:
    static int id_count;// = 0;
    Professor() : cur_id(++id_count) {}
    /*! read as Person from std::cin; add publications.
     */
    void getdata() override {
        Person::getdata();
        std::cin >> publications;
    }
};

int Student::id_count = 0;
int Professor::id_count = 0;


Superior improved stack implementation using a linked list

Code Review
I find your placement of & inconsistent with *
    Node(const T & t, Node* link) :item{t}, next{link} { }

And r-value reference declaration stranger still
    Stack(Stack & & );  // I am surprised that compiled. As each `&` is a separate token
                        // While `&&` is a single token.

This is all part of the type information. Put it with the type.
    Node(const T& t, Node* link) :item{t}, next{link} { }
    Stack(Stack&& rhs);

You provide a push by copy.
void push(const T & );

and you are familiar with move semantics. Why not provide a push by move?
void push(T&& val);

Very Minor personal preference.
Personally I prefer const on the right of the type. The rule is that const binds left unless it is on the very left hand side then it binds right. There is one obsecure corner case were this makes a difference. But it is obscure so don't worry.
    Node(T const& t, Node* link) :item{t}, next{link} { }

I just find it easier when reading types (as you read them right to left).
    char const * const  x;
    // x is "const pointer" to a "const char"

    char const *   x;
    // x is "pointer" to a "const char"

    char * const  x;
    // x is "const pointer" to a "char"