Online command line JavaScript optimization

Looks like arguments_to_array() can be removed.

You may want to consider having cli_parse() call cli_remove_blank_words() rather than cli_run().

Also, depending on the direction you're going with the command line, you can probably simplify cli_run() in other ways. That long document.getElementById expression should probably be isolated in its own function, since it seems it's going to be used the same way every time for the most part. By doing shift() to the cmd array, you can get the function you want to call from that (and the remaining elements in the array are simply your args to that function). Then you can use a logical operator to check whether that function exists, otherwise call a function that handles errors and such.

Here's how I'd do it:

function cli_parse(cmd) {
    return cli_remove_blank_words(cmd.split(/\s+/));
}

function cli_run(cmd) {
    var words = cli_parse(cmd);
    var func_name = words.shift();
    var func = window[func_name] || window.cli_error;
    func.apply(this, words);
}

function cli_print(txt) {
    document.getElementById('commandline').value =  document.getElementById('commandline').value + '\n>>> ' + txt;
}

function cli_error(error_info) {
    cli_print("Unknown command");
}

function add(a,b) {
    var result = parseInt(a)+parseInt(b);
    cli_print(result);
}

Although, I'd really say using a more object oriented approach would probably facilitate expansion easier, but this works fine.


It looks like you're not following the instructions strictly. For example, here:

  1.Write a line of code using the Location object to return the uniform resource locator (URL) of a Web page to a variable called myWebPage.

You didn't write a line of code, you wrote two, and you alerted the value instead of assigning to the variable. You also used a function, where the requirements do not include a function. I think the instructor is expecting something like this:

var myWebPage = window.location.href;


Right way to handle, log and display exceptions

The main reason for exceptions (from a developer point of view) is to detect malfunctioning code. Because once this malfunctioning code is executed, the result of an operation and therefore the state of an application can be considered as undefined, since unexpected/unpredictable side effects will transition the application to an unpredictable state.

Data might be in an unpredictable state i.e. data integrity is not guaranteed any more. Unmanaged resources might be initialized or reserved but not released, which may even affect other applications. So most of the time you want the application to stop execution to avoid unpredictable behavior.

Exceptions are designed to hold a program. They are controlled on OS level so that Operating System can stop the application and also provide a snapshot from the stack memory, that was occupied by the faulting application.

We can say that there are expected errors e.g., not enough disk space to save a file or wrong user credentials and there are unexpected errors e.g. a null reference exception.
So if the application could recover/rollback from an error, this error will be an expected error. You know in advance what can fail and you know how to handle this situation to keep the application operating reliably. You preferably would want to handle such errors "silently", without throwing exceptions, as exceptions have impact on application performance and therefore user experience.
You also don't want the exception to propagate through your complete application, which is expensive in terms of performance. Therefore you would like to handle it directly where the exception occurred. This implies that you better don't handle exceptions in a big catch block around your application. You always catch exceptions where they occur. This is a best practice for the reasons explained.

It's also best practice to use multiple catch blocks and catch specific exceptions only. This way your code becomes more readable. Specific exceptions are those and only those you can handle. And logging is not considered handling (if this exception is not relevant you should have avoided it in the first place). Every other exception must be thrown as they are unexpected or have heavy impact on the stability (predictability) of the application.

This means catching Exception, like it is happening in your code, is a very bad idea:

try
{
  // Create application main directory
  Directory.CreateDirectory(Reference.AppPath);
}
catch (Exception ex) // Bad: this will swallow every exception although unhandled by this catch block
{
  Log.Error(ex);

  if (ex is DirectoryNotFoundException || ex is IOException || ex is NotSupportedException)
  {
    MessageBox.Show("Error");
  }
}

Bad exception handling as all exceptions are swallowed. Logging an exception is not handling an exception.

What is happening here, is that all exceptions are swallowed. Especially those that are critical to the application. By catching Exception you basically handle every exception. Catching Exception at application level makes it even worse: a NullReferenceException will never see the light. A IndexOutOfRangeException will never get attention too, as you didn't even re-throw anything (re-throwing an exception is also generally considered as bad practice). A NullReferenceException must crash your application and requires the developer's full attention. If Reference.AppPath throws a NullReferenceException because Reference or AppPath is null we will never notice it without consulting any log file.

In real life, nobody is reading log files. Every developer avoids it. And for sure, nobody reads them daily to check if any of the hundreds of customers experienced a critical runtime error. Indeed, it's an uncomfortable situation when a customer experiences an application crash, but at least it will draw everybody's attention to look for an immediate fix. An application error reporter can be a very powerful enhancement to provide quick and proper bug support.
Nevertheless log files can be a very valuable support to reproduce and find bugs.

Also, exceptions of the same type might get thrown at different code segments in a totally different context. A global exception handler will have a hard time to get the context of the exception to find out if NotSupportedException was thrown in context of a invalid user input (recoverable error) or a wrong call to an API method (non-recoverable).

To solve the issue of swallowing exceptions, you have to get rid of the smelly switch statement, which already indicates that you are doing something "wrong". Type checking in a switch statement (or ugly and unreadable if-else constructs) is a classic code smell.

The goal is to handle exceptions that are non-critical i.e. the application can recover from and leave every other exception unhandled:

try
{
  // Create application main directory
  Directory.CreateDirectory(Reference.AppPath);
}
catch (DirectoryNotFoundException ex)
{
  // Log
  Log.Error(ex);

  MessageBox.Show("Error");
}
catch (UnauthorizedAccessException ex)
{
  // Log
  Log.Error(ex);

  MessageBox.Show("Error");
}

Now, any developer that comes across this code knows immediately what is going on here. The code has become more readable and the ugly and smelly switch was successfully eliminated. But more important, every unhandled exception will still crash the app, to indicate a critical bug. If Reference.AppPath throws a NullReferenceException we will now notice it first hand this time, without the need of consulting any log file.

Don't catch what you can't handle.

If you wish to log unhandled exceptions, instead subscribe to the Application.DispatcherUnhandled event:

public partial class App : Application
{
  public App()
  {
    this.DispatcherUnhandledException += (sender, args) => this.logger.Error(args.Exception.Message);
  }
}

Free Resources

As a note: it's best practice to take care of managed/unmanaged resources and use finalizers i.e. finally or using blocks, to make sure that these resources are released i.e. disposed properly under any circumstances before letting the application crash.

In case the following code throws an exception, the using statement will execute a finalizer before the forced exit:

using (var sqlConnection = new SqlConnection(args))
{
  sqlConnection.ExecuteQuery(queryArgs);
}

This is equal to:

try
{
  var sqlConnection = new SqlConnection(args);
  sqlConnection.ExecuteQuery(queryArgs);
}
finally
{
  sqlConnection.Dispose();
}

Both implementations won't handle the critical exception, but will release unmanaged resources before the method is put on hold and the exception routing is executed by the OS.

Re-throwing Exceptions

Although re-throwing exceptions is considered bad practice, it makes sense if you need to add data to the exception or like to throw a more specialized maybe custom exception type. But make sure to keep the stack trace intact.

Bad re-throw as it will break the stack trace:

try
{
  // Create application main directory
  Directory.CreateDirectory(Reference.AppPath);
}
catch (DirectoryNotFoundException directoryNotFoundException)
{
  Log.Error(directoryNotFoundException);

  // The previous stack trace of 'directoryNotFoundException' will be lost
  throw new UnknownUserInputException("Custom Message");
}

Good re-throw as it will preserve the full stack trace by setting
the original exception as inner exception of the wrapping exception type:

try
{
  // Create application main directory
  Directory.CreateDirectory(Reference.AppPath);
}
catch (DirectoryNotFoundException directoryNotFoundException)
{
  Log.Error(directoryNotFoundException);

  // Use constructor to set inner exception
  throw new UnknownUserInputException("Custom Message", directoryNotFoundException);
}

Avoiding Exceptions in the First Place

Microsoft best practices recommends to "Design classes so that exceptions can be avoided".
This is especially true for user input, since this are always errors we can recover from. In general, data input whether the source is a user or a client application, can be validated before it enters the application. The goal is to have the application to deal with valid data only. The logic should not process invalid data and throw an exception. The data persistence layers should never persist invalid data.

To prevent invalid data from being processed, you would typically use a form of data validation. In case of a WPF application, which is what you are implementing, I highly recommend to apply the MVVM pattern and implement the INotifyDataErrorInfo interface (example) which is part of the WPF framework and enables error propagation to the UI to provide a visual feedback. If the user enters an invalid file path you can easily make the UI draw e.g. a red border around the concerning input field, with messages or hints, forcing the user to correct the input.

In this special scenario of picking a file or folder, the best way is to use a file or folder picker dialog. This way, invalid filesystem path inputs are almost impossible.

Another example is file saving. Before saving a file, you can check whether the operation can be executed by checking the available disk space to avoid I/O exceptions.

Almost all expected exceptions can be avoided by checking the preconditions before executing a critical operation.

The bottom line is, that you should never catch Exception. Swallowing exceptions is dangerous as it will conceal serious bugs. To log an exception is not handling an exception. Logging an exception and done is equal to swallowing it, as you can't be sure somebody will ever read the log data or search it for random errors.
If you wish to log all unhandled exceptions by default, subscribe to the Application.DispatcherUnhandledException event, but never use a global catch block at application level.
Especially in your case where the errors or exceptions are triggered by invalid user input, you are advised to use data validation. This makes exception handling obsolete and is the preferred way. User input validation e.g., by implementing INotifyDataErrorInfo, includes a convenient way to give the user feedback and prompt him to correct the input.
In case the exception is not critical, in a away that it requires the application to halt, consider to roll it back to a defined state before continuing execution in order to prevent dirty data or undefined states.
Don't forget to free resources using a finally or using block to properly close/dispose those objects.


My first comment is its named badly.

dynamic_array implies that I can use [] operator on it and get a value out.

You have owned RAW pointers in your structure.

private:
  T* array;
  T* scratch;

First this means you need to look up RAII to make sure these members are correctly deleted.

Second you you need to look up the rule of three (or 5 in C++11) to make sure they are copied correctly.

You have owned RAW pointers in your structure. This means you need to correctly manage the object as a resource. This means constructions/destruction/copy (creation and assignment) need to be taken care of correctly.

Either do this manually or use a standard container that will do it for you. I suggest a standard container.

void print_array()
  {
  for (int i = 0; i < size; i++) cout << array[i] << endl;
  }

If you are going to write print_array at least write it so that it can use alternative stream (not just std::cout). Then write the output operator.

std::ostream& operator<<(std::ostream& stream, dynamic_array const& data)
{
     data.print_array(stream); // After you fix print_array
     return stream;
}

Also note that a method that access data but does not modify the state of the object should be marked const. So the signature should be: void print_array() const

Are the following members really part of the array?

void merge_recurse(int left, int right)
int merge_sort()
void quick_recurse(int left, int right)

OK. Lets assume they are for now.
Then  void merge_recurse(int left, int right) should be a private member. There should be no reason to call this from externally.

  scratch = new T[size]();
  if(scratch != NULL)

scratch will Never be NULL.

I think merge (in merge_recurse) is easier to write than you are making it:

    int index = 0;
    int l = left;
    int r = midpoint;
    while((l < midpoint) && (r < right))
    {
      scratch[index++] = (array[l] > array[r]))
                           ? array[l++]
                           : array[r++];
    }
    // One of the two ranges is empty.
    // copy the other into the destination.
    while(l < midpoint)
    {
        scratch[index++] = array[l++];
    }
    while(r < right)
    {
        scratch[index++] = array[r++];
    }

You should only call srand() once in an application:

void rand_to_array()
  {
  srand(time(NULL));

By putting srand() inside the structure you are opening it up to be called multiple times. Call it once just after main() then don't call it again.

When you can use the standard tools:

      tmp = array[l];
      array[l] = array[r];
      array[r] = tmp;

Can be replaced with:

 std::swap(array[l], array[r]);

I am relatively sure these two are wrong:

  while (l <= r)
    if (l <= r)

They should be:

  while (l < r)
    if (l < r)


Conditionally applying and removing css based on a table row clicked

Should your <tr> elements be using normalAvailability, mcAvailabilty, etc. as ID's or as classes?
It looks like you are passing a <tr> element to handleKPI_Selection() not a <td>, so perhaps the parameter should be renamed.
I don't really see great value in your handleKPI_Selection() function being separated out. If don't see where the first conditional case would ever be triggered based on what you have shown (where index value is always 0).  This calls into question you whole design, which seems to alwasy want to pass in a searchFilter value, but then never use it.
Are you sure toggleClass("kpi-selected") is what you want to do here?  What if user repeatedly clicks the same row?
This following conditional seems unnecessary.

Your code:

    if ($(this).attr('id') === "normalAvailability") {

        handleKPI_Selection($(this), 0, 'Normal');
    }
    else if ($(this).attr('id') === "mcAvailability") {

        handleKPI_Selection($(this), 0, 'Mission Critical');
    }
    else if ($(this).attr('id') === "eeAvailability") {

        handleKPI_Selection($(this), 0, 'Entity Essential');
    }

This can be simplified to something like:

var idToSearchMap = {
   'normalAvailability': 'Normal',
   'mcAvailability': 'Mission Critical',
   'eeAvailability': 'Entity Essential'
}
var search = idToSearchMap[$(this).attr('id')] || '';
handleKPI_Selection($(this), 0, search);

Keep your code DRY.

I would avoid non-standard javascript symbol name syntax in your code (i.e. not camelCase). For example, handleKPI_Selection could perhaps instead be handleKpiSelection.
If you are going to have multiple section-list elements, then the following line of code may be problematic

Your code:

$('.section-list tr').removeClass("kpi-selected");

This will remove class from all rows on all section-lists.  If you only want to target current section list, then you would need to do something like:

$(this).closest('.section-list').find('tr').removeClass('kpi-selected');


The only thing that changes in the JSX is the download button, so it'd be more appropriate to use conditional rendering when the JSX comes to that line to decide whether you need to render the last button or not:
const ButtonTemplate = (rowData: any) => (

            <Button type='button' icon="pi pi-pencil" style={{marginRight: '5px'}} onClick={(e) => this.handleClick(rowData, e)} tooltip='Edit'/>
            <Button icon="pi pi-trash" style={{marginRight: '5px'}} tooltip='Delete' />
            {
              rowData.completePathName !== null &&
              <Button icon="pi pi-download" tooltip='Download' />
            }

);

Other notes:

Since you don't use the column parameter, you should remove it entirely

Using any defeats the whole point of using TypeScript, since it effectively disables type-checking for that expression - if you can give proper types to things, it'll make your life a whole lot easier. Consider figuring out how you can type rowData. It may look something like:
rowData: {
  completePathName: string | null
}

(or something similar - just for an example)

If you want to be able to call this as a component, give it an upper-case name: ButtonTemplate, not buttonTemplate. That'll let you do
<ButtonTemplate {...{ rowData, column }} />

to render it.

You have a lot of inline styles, which makes the JSX harder to read. Consider separating out the style into CSS instead. With Sass, you could give the container a class of buttons-container, and then do:
.buttons-container {
    text-align: center;
    width: 6em;
    button:not([tooltip="Download"]) {
        margin-right: 5px;
   }
}

and remove all the inline styles from the JSX.


node *cur is not necessary. A c idiom is

if (node_id < root->node_id) {
    root->left = insert_node(root->left, data, node_id, name);

find_node_data is unnecessarily recursive. The compiler may understand that it is a tail recursion, and optimize it out, but it always better to be explicit:

    while (root) {
        if (root->node_id == node_id) {
            break;
        }
        root = root->node_id > node_id? root->left: root->right;
    }
    return root;

Note the insertion may also be made iterative, although much less elegant.
The line

printf("node data %d %s", find_node_data(root, T)->data, find_node_data(root, T)->name);

looks really strange. Why do you call find_node_data twice, and why don't you call print, which you are already defined?


Grouping the results in an array having same name

General comments

results = sorted(results, key=lambda datum: datum['car_model'])

Good use of sorted!

#removing the car type if car model exists.
d = defaultdict(dict)
for l in results:
    d[l['name']+'-'+l['work_type']] = l

results = d.values()

Why are you using a defaultdict? A normal dict suffices.

#grouping the results at panel level.
d = defaultdict(dict)
for l in results:
    d.setdefault(l['name'],[]).append(l)

Again, why a defaultdict, a normal dict suffices.

#creating dict such that panel name is key and price_list is array of all the panel prices.
output = []
for key,value in d.iteritems():
    output.append({"name":key,"price_list":value})

Good enough, I suppose. Alternatively, use

output = [{"name": key, "price_list": value} for key, value in d.iteritems()]

Variable naming

Variable names such as d and l just don't cut it anymore. Please use descriptive variable names.

Revised code

results = sorted(results, key=lambda datum: datum['car_model'])

# Make sure results are unique by {name}-{work_type}
results = {l['name'] + '-' + l['work_type']: l for l in results}.values()

# Grouping the results at panel level.
d = {}
for l in results:
    d.setdefault(l['name'],[]).append(l)

# Creating dict such that panel name is key and price_list is array of all the panel prices.
output = [{"name": key, "price_list": value} for key, value in d.iteritems()]

Separate by functions

I see several actions: getting unique values, grouping by a key, and finally outputting it.

Getting unique values

def unique_by(lst, key=lambda x: x):
    return {key(v): v for v in lst}.values()

You can call it like

results = unique_by(results, key=lambda l: l['name'] + '-' + l['work_type'])

or better

results = unique_by(results, key=lambda l: (l['name'], l['work_type']))

and using operator.itemgetter:

results = unique_by(results, key=itemgetter('name', 'work_type'))

Grouping by a key

def group_by(lst, key=None):
    assert key is not None, 'You must supply a key function'
    retval = {}
    for v in lst:
        retval.setdefault(key(v), []).append(v)
    return retval

You can call it like

grouped = group_by(results, key=lambda l: l['name'])

or

grouped = group_by(results, key=itemgetter('name'))

Revised, again

from operator import itemgetter

results = sorted(results, key=itemgetter('car_model'))
results = unique_by(results, key=itemgetter('name', 'work_type'))
grouped = group_by(results, key=itemgetter('name'))
output = [{"name": name, "price_list": items} for name, items in grouped.iteritems()]

(where unique_by and group_by are defined as above.)

Note: untested, but it should work (modulo syntax errors).


Best way to optimize this code so it takes up less space?

There is indeed a great deal of repetition in your code. A straight-forward solution to this would be putting your severity levels into a dictionary and iterate over it instead:
test = {
    "version": "0",
    "id": "85fc3613-e913-7fc4-a80c-a3753e4aa9ae",
    "detail-type": "ECR Image Scan",
    "source": "aws.ecr",
    "account":
        "123456789012",
    "time": "2019-10-29T02:36:48Z",
    "region": "us-east-1",
    "resources": [
        "arn:aws:ecr:us-east-1:123456789012:repository/my-repo"
    ],
    "detail": {
        "scan-status": "COMPLETE",
        "repository-name": "my-repo",
        "finding-severity-counts": {
            "CRITICAL": 10,
            "MEDIUM": 9
        }
    }
}

resource = test["resources"][0]
finding_severity_counts = test["detail"]["finding-severity-counts"]

THRESHOLDS = {
    'CRITICAL' : 0,
    'MEDIUM'   : 1,
    'LOW'      : 0
}

for severity in THRESHOLDS:
    if severity in finding_severity_counts:
        count = finding_severity_counts[severity]
        if count > THRESHOLDS[severity]:
            print("Resource {} has {} {} findings".format(resource, count, severity.lower()))

This should produce the exact same result as your code does, by reusing the logic (that's the same for every severity. Note that we can reuse the count, since we're only interested in one value at a time.
That is, assuming you're only interested in the amount of severities if they reach a certain threshold. Hence the name.
It would probably be prettier to put the for-loop into a function though. An even better solution would probably involve one of Python's 'collections' functions, like Counter.


Finding the Pythagorean triplet that sums to 1000

Here are some changes I would do in your code:

Since you already have two variables x and y from the loop, you don't need a and b.  Get the 3 numbers as - x, y, and 1000 - x - y, and use them.
You might well possibly be checking the values same pythagorean triplets twice. Once with x, y, and 1000 - x - y, and then with y, x, 1000 - y - x. For example, when x takes 2 and y takes 3, then you don't want to check this again for x = 3 and y = 2. This might happen, as your inner loop is running from the beginning every time. You can avoid this by iterating from x to 1000.
No need of exit boolean variable. Put those loops inside some function, and return as soon as the result is found.

Modified Code:

def specialPythagoreanTriplet(s):

    for a in xrange(s):
        for b in xrange(a, s):
            c = s - a - b;
            if a**2 + b**2 = c**2:
                return (a, b, c)

In addition to all that, you don't really need to iterate till 1000 for values of a and b. The maximum value that a could take should be much less than 1000. Let's find out.

You have:

  a + b + c = 1000, and
  a < b < c

Replace b and c with a, we get:

  a + a + a < 1000
  3a < 1000
  a < 333

Similarly, you can find out the threshold for b, I'm leaving it for you:

for a in xrange(s / 3):
    for b in xrange(a + 1, s):  # Change `s` to someother value
        # Same as previous code.


Try and engage the move constructor:

m.data.push_back(temp);

Because temp is a named variable it will hit the version that uses const& T. To try and get the alternative version that engages the move constructor add std::move

m.data.push_back(std::move(temp));

The input operator does not make any attempt to make sure each line is the same size.

size_t x_dim() { return data[0].size(); }

So the above may not be accurate.
You can add a fake set of cells at the top/bottom/left/right of type 'WALL' then you don't need the test if (x < 0 || y < 0 || x >= m.x_dim() || y >= m.y_dim()) as it can never reach outside the bounds of the maze (this can be forced to be true because it is part of the code and not part of the user input). This means you don't need y_dim() as that is the only use case.

My main issue is that solve() actually mutates the maze object. Some form of visitor pattern may be a more re-usable technique, or solve() would be better as a member of maze().


`sfinae` proposal... useful or unnecessary?

I just wrote four lines of code...

template<typename T, typename ...>
using sfinae = T;

template<typename T, typename ...>
using SFINAE = T;

You should have written just two lines of code — either the first two or the last two. Not both. "There's more than one way to [spell] it" is the Perl way, not the C++ way. ;) (At least not intentionally! Not intentionally pre-C++2a! Now we're getting both std::filesystem and std::fs, that's a less airtight position.)

As you show, your thing can be used for

template<class T,
    sfinae<bool,
        std::enable_if_t<std::is_integral_v<T>>,
        std::enable_if_t<std::is_arithmetic_v<T>>
    > = true>
void foo();

However, this is pretty verbose; surely we'd rather write std::enable_if_t<std::is_integral_v<T> && std::is_arithmetic_v<T>> than std::enable_if_t<std::is_integral_v<T>>, std::enable_if_t<std::is_arithmetic_v<T>>.

So personally I have a different alias that accomplishes the same goal: bool_if_t.

template<bool B>
using bool_if_t = std::enable_if_t<B, bool>;

template<class T,
    bool_if_t<
        std::is_integral_v<T> &&
        std::is_arithmetic_v<T>
    > = true>
void foo();

This has the advantage that the inner expression is written using normal C++ syntax rules. We don't have to remember some arbitrary rule like "x, y means both x and y must be true"; we just write x && y. And if we want to enable this function when either x or y is true, we don't have to invent a new primitive; we just write bool_if_t<x || y>. bool_if_t is much more composable than your sfinae<Ts...>, because bool_if_t can exploit the existing expression syntax of C++.

Recommended viewing: "A Soupçon of SFINAE" (Arthur O'Dwyer, CppCon 2017). (Yes, that's me.)

You picked examples that don't really show off the power of sfinae, by the way.
Consider this example:

// 3) as a function return type:
template <typename T>
sfinae<T,
    std::enable_if_t<std::is_integral_v<T>>,
    std::enable_if_t<std::is_arithmetic_v<T>>
> const & foo(T const & val);

You take a "value-space" boolean (is_integral_v<T>), lift it up into "SFINAE-space" with enable_if_t, and then apply a logical AND operation in SFINAE-space using your sfinae alias.

template <typename T>
std::enable_if_t<
    std::is_integral_v<T> &&
    std::is_arithmetic_v<T>, T
> const & foo2(T const & val);

Here I take the same "value-space" boolean, perform the logical AND in value space where we have a dedicated operator && for maximum expressiveness; and I lift it up into SFINAE-space after doing the AND. This is clearer and also probably more efficient in terms of compile time.

Where your version helps is when your values start in SFINAE-space!

template<class T>
sfinae<T,
    decltype(std::declval<T>() + std::declval<T>()),
    T*,
    T&
> const & foo3(T const & val);

If we were trying to replicate this code's behavior with the standard tools, we'd say something like

template<class, class=void> struct has_plus : std::false_type {};
template<class T> struct has_plus<T, decltype(void(std::declval<T>() + std::declval<T>()))> : std::true_type {};
template<class T> inline constexpr bool has_plus_v = has_plus<T>::value;

template<class T>
std::enable_if_t<
    has_plus_v<T> &&
    not std::is_reference_v<T> &&
    not std::is_void_v<T>, T
> const & foo4(T const & val);

That is, we start with a value in SFINAE-space (decltype(std::declval<T>() + std::declval<T>())), lift it into value-space (has_plus_v<T>), do the logical AND in value-space, and lift the result back into SFINAE-space.

Whereas with your foo3, you start in SFINAE-space, do the logical AND via sfinae<...> without leaving SFINAE-space, and then you're done. Much simpler! But harder to read, I think.

A simple way to improve readability is to pick a good name. sfinae_space_and<Ts...> might be clearer. Can you think of a way to write sfinae_space_or<Ts...>? How about sfinae_space_not<T>? Does it make sense, maintainability-wise, to provide one without the others?


Custom tableview cell for displaying different foods

I can't talk much about the big picture issue that you are asking about, but I see plenty of improvements that can be made to the code.

When working with Objective-C, it is considered best practice to follow Apple's guidelines and conventions for the language.  One of these is to use the full name of the enum when naming its contents.  I see you have the enum StarState and then you have StateEmpty and StateFull.  These should be changed to StarStateEmpty and StarStateFull.  Sometimes this can lead to really long names, but it is still Apple's recommendation to do things this way.  The biggest reason why is that if two names conflict, the compiler will not be able to determine which one is which.  This is a real problem here, because if you ever want to have fill states for another type of object, you will have problems trying to use just StateFull.  Another option would be to change the name of the enum to ObjectFillState and then you can reuse it for other objects.

If I remember correctly, in a previous question you were advised to fix your irregular white spacing, and to also always use brackets around if-else statements.  It is better to always have brackets so that the code is more readable.

if ([cell isStarredForName:food.name])
    [cell changeStarToState:StateFull];
else
    [cell changeStarToState:StateEmpty];

There are lots of ways that a construct like the above could go wrong in the future, so it is better to just put in the brackets.  Also this cell.foodLabel.text= food.name; is missing a space after text.  A minor nitpick but things like that are still important for readability.

I have a feeling that there is a much better way to go about retrieving the information from the dictionary here (such as an object that returns the proper value from a properly named method):

PFInstallation *installation = [PFInstallation currentInstallation];
NSArray *foodList = (NSArray*)[installation objectForKey:@"favorites"];
return ([foodList containsObject:foodName]);

But I will specifically mention this part: (NSArray*)[installation objectForKey:@"favorites"].  Someone here on Code Review once said this to me, and I think it is very good advice: "The most common purpose of a cast is to turn a compile-time error into a run-time error."  Please click the link and read his expanded explanation of this quote.  I think it is very good advice.

I do not know completely if it is best practice in this case or not, but I am not a fan of uninitialized values such as this: NSString *imgName;.  There is a bigger problem with the method - (void)changeStarToState:(StarState)state however.  The name says that it changes the state of the star, but then it also includes this line:

[self.favButton setImage:[UIImage imageNamed:imgName] forState:UIControlStateNormal];

At the very least the method name should be changed to reflect that the image is being set also.  However, I'm thinking that this is actually an indication of a bigger design problem.  It makes me think that you may want to change your approach. Since that is the reason you posted this question in the first place, I think you are on the right track.  Hopefully someone else will be able to elaborate on the design part of your question.


Optimizing a c# program that creates 2 dictionaries and searches both for a matching value

There are some really obvious optimisations.

Delete all the code relating to b. A dictionary you only insert into is a waste of time, memory, and programmer ability to understand what's going on.
Use g as a dictionary. The way to do that is to change it from a Dictionary<int, BigInteger> into a Dictionary<BigInteger, int>. Then your foreach can be replaced with a simple TryGetValue.
Ditch the cast of j to BigInteger:

int n_int = ((int)Math.Sqrt(247457076132467-1))+1;
...
n = (BigInteger)n_int

And compare j to n_int. If it doesn't fit in an int, j shouldn't be an int either.
Exploit basic arithmetic properties in loops. E.g. rather than

tm = BigInteger.ModPow(2, i, mod);

you should have

tm = 1,
...
for (int i = 0; i < n_int; i++)
{
    ...
    tm = (tm * 2) % mod;
}

PS In fact, if you'd looked at the Wikipedia page on the algorithm you'd have found pseudocode which handles all this already.


This bit worries me:

lastElementAdded = -1;

It assumes that the minimum value in the array is zero. But really, an increasing sequence could start with -3456780 or something.

I'd use null or something non-numeric instead. Or simply add the first element automatically, and start the loop at index 1. You could use Number.NEGATIVE_INFINITY, but it has the same problem: A sequence could start at negative infinity.

Also, don't use for..in loops on arrays. A for..in loop enumerates an object's properties; it's not intended for iterating through an array's elements. Instead, use a regular for loop, or a forEach iterator.

Lastly, I'd change allSubsequence to allSubsequences (plural) simply because it more grammatically correct.

In terms of overall strategy, your current algorithm is doing a bit of unnecessary work. Given the example input, the first 3 subsequences it finds are:

[ 87, 88, 91, 92, 94 ]
[ 88, 91, 92, 94 ]
[ 91, 92, 94 ]

The last two aren't really interesting, since they're just subsequences of the first.

Now, this really isn't a problem for arrays as short as what you've got here. Still, it's a fun exercise, so I tried my hand at it. There's probably an even more elegant solution than what I'm proposing here, though. Algorithms aren't my strong suit, I'm afraid. But here's what I came up with:

Start a sequence with the first element of the input array
Iterate through the array

If a value is greater than the sequence's maximum, append it to sequence
If it's less and it's the first such value we've found, recurse with a subset of the input array, starting at the current index. Store the result.

Return whichever sequence - the current one, or the "fork" - is longer

Kinda hard to explain, actually. Hope the code below will help illustrate:

function findLongestIncreasingSequence(array) {
  var sequence = [],
      fork = null;

  // Always add the first value to the sequence
  sequence.push(array[0]);

  // Reduce the array with. Since no initial accumulator is given,
  // the first value in the array is used
  array.reduce(function (previous, current, index) {

    // If the current value is larger than the last, add it to the
    // sequence and return (i.e. check the next value)
    if(current > previous) {
      sequence.push(current);
      return current;
    }

    // If, however, the value is smaller, and we haven't had a fork
    // before, make one now, starting at the current value's index
    if(!fork && current < previous) {
      fork = findLongestIncreasingSequence(array.slice(index));
    }

    // Return the previous value if the current one is less or equal
    return previous;
  });

  // Compare the current sequence's length to the fork's (if any) and
  // return whichever one is larger
  return fork && fork.length > sequence.length ? fork : sequence;
}

Given the example input, you get:

findLongestIncreasingSequence(sample); // => [ 87, 88, 91, 92, 94 ]

Anyway, what it does is more or less this, where √ means the value was added to a sequence, and F means it "forked" and recursed

Initial input: 87  88  91  10  22  9  92  94  33  21  50  41  60  80
====================================================================
1st call:       √   √   √   F   .  .   √   √   .   .   .   .   .   .
2nd call:                   √   √  F   √   √   .   .   .   .   .   .
3rd call:                          √   √   √   F   .   .   .   .   .
4th call:                                      √   F   √   .   √   √
5th call:                                          √   √   F   √   √
6th call:                                                  √   √   √

Unfortunately, it's not tail-recursive, so call stack depth could be an issue.

And there's probably more optimizations that can be made. For instance, if the current sequence is already 5 items long, there's no reason to fork if the array only has 4 items left. And as I said, there's probably an even cleverer solution overall.

The alternative to the above would be to simply map out the indices at which a value is lower than the one preceding it. Then do the same thing (slice the array at those indices, find increasing sequence) one at a time instead of recursively, and compare sequence lengths at the end. Same result. But recursion is more fun :P


First I'm not a fan of recycling IDs. Too much confusion can happen.  For example Thread 1 adds a Dog Image and gets ID 1.   Thread 2 calls ReleaseAllImages and then adds a Cat image and gets ID 1.  Now Thread 1 think it has a Dog image but instead returns back a Cat image.  There are times we need to recycle ID but only you know the business requirements if it's truly needed or not.

Second It's thread safe but you are not getting the benefit of ConcurrentDictionary this way. Everything is locked.  If two threads are trying to add one will be blocked until the other is free.  It doesn't have to be this way.

I'm going to go down the path that you need to recycle IDs

Instead of leaving the record in the dictionary you can remove it and have a queue of ID to recycle.  Then on the removing methods check if we removed all the records from the Dictionary and if so then enter the lock to see if we can reset the counter and queue. Going to use ReaderWriterLockSlim to allow multiple adds and only block when we are removing.

public static class ImageCache
{
    private static int currentId = 0;

    private static readonly ConcurrentDictionary<int, MemoryStream> images =
        new ConcurrentDictionary<int, MemoryStream>();

    // stores removed ID to reuse
    private static ConcurrentQueue<int> recycle = new ConcurrentQueue<int>();
    private static readonly ReaderWriterLockSlim recycleLocker = new ReaderWriterLockSlim();

    /// <summary>
    /// Release an image based on its id.
    /// </summary>
    /// <param name="id"></param>
    public static void ReleaseIamge(int id)
    {
        ReleaseMemoryStream(id);
        TryReset();
    }

    /// <summary>
    /// Releases all Images
    /// </summary>
    public static void ReleaseAllImages()
    {
        foreach (var id in images.Keys)
        {
            ReleaseMemoryStream(id);
        }

        TryReset();
    }

    private static void ReleaseMemoryStream(int id)
    {
        MemoryStream ms = null;
        if (images.TryRemove(id, out ms))
        {
            recycle.Enqueue(id);
            ms.Dispose();
        }
    }

    private static void TryReset()
    {
        if (!images.IsEmpty)
        {
            return;
        }

        //need to lock here
        if (recycleLocker.TryEnterWriteLock(TimeSpan.FromMilliseconds(100)))
        {
            try
            {
                // make sure another thread didn't sneak in and add another image
                if (images.IsEmpty)
                {
                    currentId = 0;
                    Interlocked.Exchange(ref recycle, new ConcurrentQueue<int>());
                }
            }
            finally
            {
                recycleLocker.ExitWriteLock();
            }
        }
    }

GetBitmap method doesn't need to check if the image is null now we can use the TryGetValue and not need to lock at all

/// <summary>
/// Returns a Bitmap from the cache which is identified by an id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public static Bitmap GetBitmap(int id)
{
    MemoryStream ms = null;
    if (images.TryGetValue(id, out ms))
    {
        return (Bitmap) Image.FromStream(ms);
    }
    return null;
}

Add method will need to let the lock know we are reading from the recycle queue

/// <summary>
/// Adds an Bitmap to the cache
/// </summary>
/// <param name="bitmap"></param>
/// <returns>0 if the Bitmap is null, otherwise a uique id</returns>
public static int Add(Bitmap bitmap)
{
    if (bitmap == null)
    {
        return 0;
    }

    recycleLocker.EnterReadLock();

    try
    {
        var ms = new MemoryStream();
        bitmap.Save(ms, ImageFormat.Tiff);

        // Recycle Id or make new one
        int id;
        if (!recycle.TryDequeue(out id))
        {
            id = Interlocked.Increment(ref currentId);
        }

        // this should never be possible to fail
        images.TryAdd(id, ms);

        return id;
    }
    finally
    {
        recycleLocker.ExitReadLock();
    }
}

Using the ReaderLockerSlim will allow multiple reads but only one write.  Now multiple threads could Add images and Get images without blocking each other and the code only blocks when it's resetting the counters.


Determine if braces in a string are balanced in Clojure

Recursion

Use recur to do tail-call recursion:

  Note that recur is the only non-stack-consuming looping construct in
  Clojure. There is no tail-call optimization and the use of self-calls
  for looping of unknown bounds is discouraged. recur is functional and
  its use in tail-position is verified by the compiler.

Destructuring

You can use :as to avoid the unnecessary let here:

  ([string stack]
    (let [[first-char & other] string]

Instead:

 ([[first-char & other :as string] stack]

Repeated Constants

Here you are entering the same data by hand twice:

(def braces #{\( \) \[ \] \{ \}})

(def pairs { \) \(,
             \] \[,
             \} \{ })

Instead you can do:

(def braces (set (concat (keys pairs) (vals pairs))))

Testing

Use clojure.test to do unit testing. It does have a standard and useful failure reporting. You needn't write a test harness like test-strings yourself. You should only report failures, because test are only useful when they are reporting failures. Most your test should be passing at any time, so any relevant information (a failing test case) should not be lost in noise (dozens of lines of "test-case-xyz passed just as the 937 time before").

Make a habit of putting test code in a separate namespace that does depend on the code tested, but not vice-versa.

After requiring clojure.test:

... (:require [clojure.test :refer :all] ...

You define tests like this:

(deftest non-braces-ignored
  (is (is-balanced? "Hello { ( world ) } [] end")))

(deftest empty-string-is-brace-balanced
  (is (is-balanced? "")))

(deftest some-long-balanced-string
  (is (is-balanced? "{[] () {[{{ }}]} ([{}])}")))

You can group several of similar tests like this until you can find a descriptive name for them, although failure message is not as useful as above tests:

(deftest examples-of-non-balanced-strings
  (are [x] (not (is-balanced? x))
       "Hello { world"
       "{{"
       "])"
       "}}{{"
       "{[))"))

and run these tests like this:

(run-tests)

Namespaces

Don't put function calls inside a namespace. Reloading a namespace should be idempotent.
Also if the function call is something like (main) you don't gain much;
however if you are calling some non-trivial initialization code then it deserves it own function.


Yes, it is generally considered a bad practice because it is considered confusing. Though as you point out it is fairly unlikely to confuse because everything is being set to zeros and the alternative is five lines of repeated code.

However I find myself asking why you don't use an array. i.e.

freqs = [0, 0, 0, 0, 0]
or
freqs = Array.new(5, 0)

or else just define define the final hash:

def freq_progress
    user_flashcards = input_flashcards.includes(:term)
    terms_unicos = user_flashcards.map(&:term).compact.uniq

    result = { f1: 0, f2: 0, f3: 0, f4: 0, f5: 0}
    terms_unicos.each do |term|
      case term.ranking
      when 1..100
        result[:f1] += 1
      when 101..300
        result[:f2]+= 1
      when 301..1000
        result[:f3] += 1
      when 1001..2000
        result[:f4] += 1
      when 2001..5000
        result[:f5] += 1
      end
    end

    result
  end


Using chartJS in Angularjs to plot IOT data

Feedback

The code appears to make good use of AngularJS and ChartJS, as well as promises.

For the function that handles the response, I had to move the line that assigns response.data to $scope.content up before the call to angular.forEach(). Otherwise it seems that the data wouldn't get assigned before the iteration...

Also I don't see the point of calling JSON.stringify() on the response.data object unless that gets assigned to a variable or passed to another function...

function handleResponse(response) {
    //what is the point of this line? the return value isn't assigned to a variable or passed to a function
    JSON.stringify(response.data);
    $scope.content = response.data;
    angular.forEach($scope.content, function (value) {
        vm.dataContent.push(value.inputData);
    });
}

Recommendations

Below are my recommendations. They are by no means a definitive list of improvements but will hopefully be useful in terms of readability, flow of the code, etc. In general, I aim to avoid lengthy functions - with ~10-20 lines or fewer. For more guidance, refer to answers on this post.

Making separate functions

  to make my controller less stacked, get data -> draw chart -> update chart.

First, I would move the implementation of the successCallback() and errorCallback() functions out to be defined later. Hoisting can be utilized here so the functions can be defined after being called, though one could also move the definitions up if desired. And if there was a need to call the functions multiple times, then the functions could be referenced simply by name in each instance.

$http({
    method: 'GET',
    url: 'http://localhost:8080/data/Living Room'
})
    .then(successCallback, errorCallback);

function successCallback(response) {
    JSON.stringify(response.data);
    //skipping the rest of the implementation
}
function errorCallback(response) {
    return alert(response.status);
}

Then I would break out the blocks within successCallback into separate functions. Even if they aren't called in multiple places, it can improve readability. While there are varying opinions, many people argue methods should be kept between 5-15 lines (refer to this answer - I know that is tagged with java and c# but it can apply to many other languages as well).

In the example below, I made one function to handle taking the response, and a separate function to get the settings passed to the chart constructor.

function successCallback(response) {
    handleResponse(response);

    var canvas = document.getElementById("myChart");
    var ctx = canvas.getContext("2d");

    var myNewChart = new Chart(ctx, getSettings());
    setInterval( function(){
        addData(myNewChart, 16,  'working on it');
        // Remove the first point so we dont just add values forever
        remove(myNewChart);
    }, 5000);
};
function handleResponse() { ... }
function getSettings() { ... }

Making URL variable

  to make the get method more generic. The URL is now hardcoded.

There are various ways to make the URL a variable. One approach is to have it be controlled by user interaction. For example, the UI could have inputs bound to the url via ngBind. And another approach might be to have specific URLs defined in the controller and reference those URLs. So in the controller, we could define:

$scope.urls = {
    livingRoom: 'http://localhost:8080/data/Living Room,'
    hallway: 'http://localhost:8080/data/Hallway'
}; //add more elements as appropriate

Then in the UI, have buttons like:

<button ng-click="loadData(urls.livingRoom)">Living Room</button>
<button ng-click="loadData(urls.hallway)">Hallway</button>

And define that function loadData like below, moving the call to $http() into it:

$scope.loadData = function(url) {
    if (interval) { //check if interval is updating data periodically
        clearInterval(interval);
    }
    $http({
        method: 'GET',
        url: url //use variable value based on parameter from button
    }).then(successCallback, errorCallback);
};

You may notice that function begins by checking if (interval) and if that evaluates to true then it will call clearInterval() passing that value. That will handle clearing the previous interval, as long as we assign the return value from setInterval() to that value:

var interval; //set scope outside functions
function successCallback(response) {
    //...handle response
    //...create chart
    interval = setInterval(function() {...},5000);
}

Demonstration

See a demonstration here in this phpfiddle.

Conclusion

If you look at the functions in that phpFiddle example, then you will notice that the longest function (excluding the controller callback) is ~9 lines long. This greatly enhances readbility.

JS error on hover

I noticed that after loading data from one source, then reloading with another source, when hovering over the chart I would see an error in my console:

  Uncaught TypeError: Cannot read property 'skip' of undefined

That appears to be this reported ChartJS bug.


methods in the class so close in what they do

Just judging by the size you can tell that this one method is doing entirely too much. The Single Responsibility Principle states that a method/function should be responsible for one thing to the exclusion of all others. It can request other methods/functions to help it, but it should only be concerned with its purpose, which should be evident by its name.

So, the first thing I would say to do is break this up into even more methods first. The how should be pretty obvious in most cases. In this case, however, it may not be, so let's take a look at what you are doing to get an idea of how we should break this up.

Each if statement sets up an additional part of this growing SQL statement. If you look closely at each of these blocks, you may begin to notice a pattern. When a pattern arises we know that we can apply the "Don't Repeat Yourself" (DRY) Principle to it so that it can be reused. So our pattern here is to append a SQL statement, add to an array, and finally increment a counter. Sounds simple enough.

private
    $sql = '',
    $arr = array()
;

//constructor, etc...

private function append( $sql, $params ) {
    if( strlen( $this->sql ) ) {
        $sql = ' AND ' . $sql;
    }

    $this->sql .= $sql;
    $this->arr = array_merge( $this->arr, $params );
}

So, you may notice that we are doing a few things differently here. First, we add some new properties to our class. The $sql and $arr properties take the place of their respective variables. This is so that our new methods can communicate with each other. Next, we removed the counter $i. The counter is pretty much useless, even in its current form. If we remove the initial value of $sql then we can just check the string's length. If it is empty then of course we don't prepend an AND, but if it isn't then we should. Don't worry, we'll prepend the initial value when we are done. The last thing we do is merge our arrays. Since we are using a standard sequential array there should be no problems here, we just have to be sure to append everything in the right order, which we've just done. So, now to use it.

public function nonFormattedData( $param ) {
    if( ! is_array( $param ) ) {
        return FALSE;
    }

    if( isset( $param[ 'startDate' ] ) ) {
        $this->append( ' date_created between ? AND ?', array(
            $param[ 'startDate' ],
            $param[ 'endDate' ]
        ) );
    }

    //etc...

    $this->sql = '
        select *
        from table1
        where
        ' . $this->sql . '
        group by id.table 1 '
    ;

    //etc...
}

So, there's a few new things to cover here as well. The first is the removal of the static keyword. Static methods and properties are counter to OOP. For the most part you will probably never need them. But specifically in this case they prevent us from using our new method and properties. There are ways around this, but again, that is counter to OOP. The next thing I did was reversed your initial if statement and returned early. This is a good habit to get in to. First it reduces the amount of indentation, meaning we are no longer violating the Arrow Anti-Pattern (even as slight as the violation was), and second it reduces the amount of processing necessary for PHP to determine that it doesn't need to do anything. Not much mind, but still more efficient. The next if statement should look pretty familiar, its exactly the same, but the inner block is different. Here we are using the new method we just created. This should be pretty self-explanatory. Add the custom SQL and pass in the appropriate parameters. Repeat for each if statement. Finally we come to our new SQL statement. I promised you we'd get back to that initial value. Well, here it is, combined with appending the final value, resulting in our complete SQL statement, ready to use. The rest is the same.

Now, we've cleaned up this first method and, as you've already mentioned, the second method is pretty similar. If we apply the above to it it will be better, but we can still do more. As sky py has pointed out, the only difference is that foreach loop in the first method. The second method returns the results the first uses to loop over, or something VERY similar. So the obvious move here would be to call the second method from the first, and use the return to loop from. So our new first method should look like this.

public function nonFormattedData( $param ) {
    $results = array();

    $rs = $this->formattedData( $param );
    foreach( $rs[ 'data' ] AS $row ) {
        $records = new Account();
        $results[] = $records;
    }

    return $results;
}

The only thing new here is that I initialized the $results array, which you should always do before trying to manipulate it. There's a couple of reasons for this. The first, and most obvious, is what happens if $rs[ 'data' ] is empty? The loop never happens and $results is never defined. Resulting in an undefined error and a potential crash. The not so obvious is what would happen if $results was accidentally set somewhere previously, or god forbid, is a global. If that variable happens to be an array you'll just get some funny results. But if it happens to be a string you will be modifying the string using string-array notation, which will definitely cause problems.

So this answers your question, but still isn't as efficient as it could be. To be the most efficient we will want to limit how many times we query the server. Assuming that we always call the second method before the first, then we can have the second method save its results as a new property and access that property in the first method instead of querying the server again. Following that logic we can do the same thing to the first method and then use getters to return the appropriate property instead of calling those methods again and again.

I hope this helps. If you have any questions or need some clarification, don't hesitate to ask.


There is one way I can think of improving this. In angular2, components should only handle view logic.
The problem isn't there at the moment but could be there when you add more functionalities. Let's say you want to add a recorder for the song that saves the song from time 0 to time 1.
You'd have to add that to this component and keep cluttering it.

I would treat this component as a "master" songPlayer. It operates on a song (i.e. Your song model) so that is okay. It could also operate on the "Player" model. Player has a state. It has its time, knows if it is playing and where the current time is.

Perhaps the best way to structure this would be to start with models:
PlayerModel(time, isPlaying, currentTime, song). Song is as it is. What this does is that it creates only one subscription on your playerComponent. To the Player.

I hope I'm not keeping it too abstract with this. It was just an idea.


Create a function with an undetermined number of successive calls

This solution uses a functional approach with currying, which i find more elegant since it doesn't have to rely on global variables

function sum(total) {
    return function () {
        if (arguments.length == 0) {
         return total;
        } else {
         return sum(total + arguments[0]);
        }
    }
}

console.log(sum(4)()) // 4
console.log(sum(4)(5)()) // 9
console.log(sum(4)(5)(9)()) // 18
console.log(sum(4)(5)(9)(1)()) // 19

The first call to ´sum´, returns the inner function. depending on the number of arguments passed to the inner function, it returns the value of sum's argument as it is or it calls again ´sum´ with the updated running total (thus returning again the inner function to be called again).

The limitation (of this implementation) is that you HAVE TO make a final call with no arguments to have to final value.

See this answer (Method 3: Infinite Level Currying) for an example of using .valueOf to get the result out at every call, even those with arguments.


Find allele frequencies at each site for each iteration for each population from FASTA file

let me choose

First things first; your code is chdiring to /path/to/directory/ and opening 0.0.1.fasta. This is woefully inflexible.

The simplest fix is to accept an argument on the command line, as sys.argv[1]. (Don't use chdir.)

numpy

What you're doing looks a lil' bit crazy. To deal with highly-dimensional data, Numpy is often a good candidate.

A first-pass would look something like

from __future__ import division

import os
from Bio import SeqIO
import itertools
import re
import sys
import numpy

#### ReFormat the data ####

filename = sys.argv[1]

maxit = 1
maxpop = 1
maxind = 1
maxlocus = 1
for pos, i in enumerate(SeqIO.parse(filename, "fasta")):
    print(i.seq)

    if pos == 0:
        maxsite = len(i.seq)

    it, pop, ind, locus = [int(d) for d in re.findall(r'\d+', i.id)]

    maxit = max(it+1, maxit)
    maxpop = max(pop+1, maxpop)
    maxind = max(ind+1, maxind)
    maxlocus = max(locus+1, maxlocus)

all = numpy.full((maxit, maxpop, maxind, maxlocus, maxsite), '\0', dtype="S")

for i in SeqIO.parse(filename, "fasta"):
    it, pop, ind, locus = [int(d) for d in re.findall(r'\d+', i.id)]
    all[it, pop, ind, locus] = i.seq

print(all)
print("---")
#### Calculate the frequencies ####

pA = numpy.full((maxit, maxpop, maxsite), 2)
pC = numpy.full((maxit, maxpop, maxsite), 2)
pG = numpy.full((maxit, maxpop, maxsite), 2)
pT = numpy.full((maxit, maxpop, maxsite), 2)

for it in xrange(maxit):
    for pop in xrange(maxpop):
        for locus in xrange(maxlocus):
            for site in xrange(maxsite):
                x = []
                for ind in xrange(maxind):
                    x.append(all[it, pop, ind, locus, site])
                pA[it, pop, site] = x.count("A") / maxind
                pT[it, pop, site] = x.count("T") / maxind
                pC[it, pop, site] = x.count("C") / maxind
                pG[it, pop, site] = x.count("G") / maxind

print(pA)
print(pC)
print(pG)
print(pT)

Then one can use Numpy tools like fancy slicing

from __future__ import division

import os
import re
import sys

import numpy

from Bio import SeqIO

def parse_id(string_id):
    return tuple(map(int, re.findall(r'\d+', string_id)))

def main():
    filename = sys.argv[1]

    data = list(SeqIO.parse(filename, "fasta"))
    header_keys = numpy.array([parse_id(datum.id) for datum in data])

    maxit, maxpop, maxind, maxlocus = header_keys.max(axis=0) + 1
    maxsite = len(data[0].seq)

    all = numpy.full((maxit, maxpop, maxind, maxlocus, maxsite), '\0', dtype="S")

    for header_key, sequence in zip(header_keys, data):
        all[tuple(header_key)] = sequence

    #### Calculate the frequencies ####
    pA = numpy.full((maxit, maxpop, maxsite), 2)
    pC = numpy.full((maxit, maxpop, maxsite), 2)
    pG = numpy.full((maxit, maxpop, maxsite), 2)
    pT = numpy.full((maxit, maxpop, maxsite), 2)

    for locus in xrange(maxlocus):
        for site in xrange(maxsite):
            x = all[..., locus, :]
            pA[...] = (x == "A").mean(axis=-2)
            pT[...] = (x == "T").mean(axis=-2)
            pC[...] = (x == "C").mean(axis=-2)
            pG[...] = (x == "G").mean(axis=-2)

    print(pA)
    print(pC)
    print(pG)
    print(pT)

main()

Note that

for site in xrange(maxsite):

is pointless as you don't use site and the effect is idempotent. Note then that

for locus in xrange(maxlocus):
    x = all[..., locus, :]
    pA[...] = (x == "A").mean(axis=-2)
    pT[...] = (x == "T").mean(axis=-2)
    pC[...] = (x == "C").mean(axis=-2)
    pG[...] = (x == "G").mean(axis=-2)

is just

x = all[..., -1, :]
pA[...] = (x == "A").mean(axis=-2)
pT[...] = (x == "T").mean(axis=-2)
pC[...] = (x == "C").mean(axis=-2)
pG[...] = (x == "G").mean(axis=-2)

Then one can skip the pre-initialization (pA = numpy.full(...)) and just do

x = all[..., -1, :]
pA = (x == "A").mean(axis=-2)
pT = (x == "T").mean(axis=-2)
pC = (x == "C").mean(axis=-2)
pG = (x == "G").mean(axis=-2)

This allows removing even more of the code.

intermission

Don't use all as a variable name; it clashes with the built-in (same for id).

finishing up

I feel this is a bit awkward still, but it's nicer than before.

from __future__ import division

import os
import re
import sys

import numpy

from Bio import SeqIO

def parse_id(string_id):
    return tuple(map(int, re.findall(r'\d+', string_id)))[:3]

def main():
    filename = sys.argv[1]

    data = list(SeqIO.parse(filename, "fasta"))
    header_keys = numpy.array([parse_id(datum.id) for datum in data])

    maxit, maxpop, maxind = header_keys.max(axis=0) + 1
    maxsite = len(data[0].seq)

    sequences = numpy.full((maxit, maxpop, maxind, maxsite), '\0', dtype="S")
    for header_key, sequence in zip(header_keys, data):
        sequences[tuple(header_key)] = sequence

    # Calculate frequencies
    pA = (sequences == "A").mean(axis=-2)
    pT = (sequences == "T").mean(axis=-2)
    pC = (sequences == "C").mean(axis=-2)
    pG = (sequences == "G").mean(axis=-2)

    print(pA)
    print(pC)
    print(pG)
    print(pT)

main()


Finding nearest city from a center place (latitude and longitude) with radius in miles

I din't check your math, because in any case the code doesn't do what it claims to do. The returned points are not within the given distance of the center, but belong to some square-like area.

To calculate a distance as the crow flies, notice that a cosine of the angular distance theta is

$$ \cos\theta = \cos\phi_0\cos\phi_1\cos(\psi_0 - \psi_1) + \sin\phi_0\sin\phi_1 $$

where Phi and Psi are respective latitudes and longitudes. The greater cosine, the closer points are.

Given a distance d, calculate cutoff = cos(d/(2*pi*R)). For each city in the list apply the above formula. The city is "nearby" if the result is greater than cutoff.


Can you describe a bit your algorithm ? There is no comments in your code and it is not straightforward (because no comments is acceptable when the code is easy to read, but not in this case).
A few things that you should consider :

the use of global variables is here totally inapropriate, n should not be global and your function pf should take an argument (and should also return an array of the prime factors found, if you need them)
the while(1) is useless the two times you used it. It is commonly bad practise to use this, and especially when there is only one condition in the loop and when you exit the loop when the condition is not true. You should use while(condition) instead
Name correctly your variables ! What are i, x, n ? It improvs readability by a lot with absolutely no cost, so you should do it
I also don't see why you need the goto. Again it makes your code hard to read for no obvious good reason.
If n is a positive number, you should use an unsigned type. Since you want to be able to process 10 digits numbers, I would recommend using unsigned long long

Aside from that, I think it's mostly the algorithm that you use that is ineffective, which is why you should explain what you tried to do.


Load drinks and their ingredients into dictionaries

Whether you need to store data in the DB is really gonna depend on your testing, but here are a few thoughts about how to reduce memory usage while still building the entire drink table at startup:

While they're convenient, you don't necessarily need to use dictionaries for this.  You could replace each dictionary with a tuple where the first item is the drink name, the second item is the drink id, and the rest of the items are tuples of size 2 with the ingredient name and the ratio for that ingredient.  This would change your example to ('Screwdriver', '4', ('vodka', 2), ('orange juice', 6)).  sys.getsizeof gives 280 for the dictionary and only 88 for the tuple, a significant reduction.
If you're still pressed for space, you can take advantage of the fact that you probably have a lot of overlap in terms of your ingredients.  Build a list with a string for each ingredient that one of your drinks uses.  Then each tuple can simply have an int referring to the index of the ingredient in your ingredient list.  This prevents you from storing a string like 'vodka' 20 different times.  Once again using sys.getsizeof gives a value of 42 for the string 'vodka' and a value of 24 for the number 100.  This will of course only work if you have enough overlap in your ingredients.

If those ideas aren't enough to reduce your memory usage to an acceptable amount, you're probably going to need to go with your second solution(unless some other folks have some better ideas!).  I don't really see one of your solutions as more pythonic than the other, so I wouldn't worry about that.

And enjoy the raspberry pi!


docstring

Your original method is adequately docmented, but you can format your docstring also according to a general style. This SO answer covers some of the templates.

doctest

If you format your example in the correct way, you can use doctest to test it. This format is also recognised by Sphinx and other documentation tools,

alternative approach

Another approach would be to use a collections.defaultdict(list)

def match_ends(list1):
    result = defaultdict(list)
    for item in list1:
        result[item[-1]].append(item)
    return result

This way you don't have to sort the list first, but need to append to it. If you use python >3.6, the original method will also return a alphabetically sorted dict, while this method will be sorted along the occurrence in the original list.


Rewrite

Below is a rewrite with all my further suggestions applied.

const messagesURL = 'https://api.myjson.com/bins/sadap';

const messagesLoadError = () => console.error('broadcastMessages json cannot be loaded');

const forEachMessage = (_, message) => {
  const messageRead  = message.read         ? ' broadcast__message__read__state--unread' : '',
        featureImage = message.featureImage ? ' broadcast__message__image--active'       : '',
        form         = message.form         ? ' broadcast__message__form--active'        : '',
        attachments  = message.attachments  ? ' broadcast__message__attachment--active'  : '';

  const template = `

${message.subject}

${message.group}

${message.dateSent}

${message.content}

`;

  $('.broadcast__messages__list').append(template);
};

$.getJSON(messagesURL, data => $.each(data.broadcastMessages, forEachMessage)).fail(messagesLoadError);

Remarks

API security

Your API endpoint (https://api.myjson.com/bins/sadap) uses insecure and archaic SSL configuration. Actually, I couldn't connect to it at all, since I have tweaked up browser configuration. Few key points about your API's security:

Vulnerable to the OpenSSL CCS vulnerability (CVE-2014-0224),
Relies fully on insecure RC4 or legacy CBC mode of ciphers it uses,
Doesn't support Forward Secrecy.

See Qualys' test result.

Unused callback's parameter

You have the following line in your code:

$.each(data.broadcastMessages, function(i, item) {

but i is never used. In such cases, it's good to replace it with underscore (_).

Naming issues

As Leon Bambrick added on top of Phil Karlton's quote:

  There are only two hard things in Computer Science: cache
  invalidation, naming things, and off-by-one errors.

„Some” of your names are overly verbose (word broadcast seem to be everywhere) and other are not descriptive enough, like item.

Wall of text

This

var broadcastMessageID = (item.ID);
var checkBroadcastMessageRead = (item.read ? " broadcast__message__read__state--unread" : "");
var broadcastMessageSubject = (item.subject);
var broadcastMessageGroup = (item.group);
var broadcastMessageDateSent = (item.dateSent);
var checkBroadcastFeatureImage = (item.featureImage ? " broadcast__message__image--active" : "");
var checkBroadcastForm = (item.form ? " broadcast__message__form--active" : "");
var checkBroadcastAttachments = (item.attachments ? " broadcast__message__attachment--active" : "");
var broadcastMessageContent = (item.content);

would be much easier to read, if you would combine vars and align equality signs, question marks and colons:

var broadcastMessageID         = item.ID,
    broadcastMessageSubject    = item.subject,
    broadcastMessageGroup      = item.group,
    broadcastMessageDateSent   = item.dateSent,
    broadcastMessageContent    = item.content,
    checkBroadcastMessageRead  = item.read         ? ' broadcast__message__read__state--unread' : '',
    checkBroadcastFeatureImage = item.featureImage ? ' broadcast__message__image--active'       : '',
    checkBroadcastForm         = item.form         ? ' broadcast__message__form--active'        : '',
    checkBroadcastAttachments  = item.attachments  ? ' broadcast__message__attachment--active'  : '';

Variables

Most of your variables are unnecessary. If you would rename ambiguous item to message, you could use message.ID instead of doing var broadcastMessageID = (item.ID).

Also, bear in mind that the following three variables are unused: checkBroadcastFeatureImage, checkBroadcastForm, checkBroadcastAttachments.

Use template literals

var broadcastMessageTemplate could become much more easily readable if you used template literals to declare it. Mind however, that this is still not the „most vanilla” method to create DOM elements either. Take a look at createElement().

Fail notification

You should use console.error() instead of console.log() in your fail's callback.


Memory Leaks

You aren't cleaning up after your LinkedList.  When the class is destroyed you want to make sure that all of the memory it has allocated is cleaned up.  At a minimum, you're going to want to:

LinkedList::~LinkedList()
{
    delete head;
}

However you also need to consider each node in the list.  You can either have ~Node delete it's next, or you can put a loop in to delete all the items in the list from the tail backwards.  Usually you would also implement this in a public function like clear or flush so that the whole list can be easily emptied.  For example, something like this would clear up the list:

void clearList() {
    Node *tmp = head;
    while(tmp) {
        head = tmp->get_next();
        delete tmp;
        tmp = head;
    }
}

Exit

You exit if there is insufficient memory to allocate a node.  The exitcode 0 is usually reserved for a successful program exit.  You should be passing a different value to exit (usually a negative number) to indicate failure.

Heads or Tails

In your remove_item method, you're not updating your tail pointer, what is going to happen if the tail happens to be pointing at the node that contains the value you remove?  Similarly, what happens if moving_ptr is pointing at the node that's removed?

reset

I'd honestly expect this to clear/flush/empty the list, not just reset the pointer that's used for iterating over items in the list.  This is likely to be confusing.

templates

Depending on what it is you're practising for, a good next step would be to adapt your Node so that it can support a templated value type.  You could then extend the list to store and retrieve values of any type.


Check if IP address list has subnet or is supernet

This section:
fileobj=open("test.txt")
for line in fileobj:
    lines.append(line.strip())#create the list from the txt file
lines.pop(0)#remove line "name"

has an alternate representation as an iterator-adjustment to skip one line:
with open('test.txt') as fileobj:
    next(fileobj)
    lines = [line.strip() for line in fileobj]

Also note use of a list comprehension and a context manager.
Your separate supernet/subnet checks are redundant. If A is a subnet of B, B is a supernet of A; so it's not even worth doing the second.
Algorithmically: if your list is very, very long you may want to consider moving away from your current nested loop. Your current loop is O(n^2) in time and I don't immediately see a way to avoid this . Consider doing something like - roughly -

Populate a list of tuples of start and end IP address integers and IP objects; the packed integer representation can be obtained by casting an ipaddress object to int
Sort this list; a naive .sort() should work
On your outer loop, iterate over all entries for subnet selection
Prune away any potential supernets whose end is so low that they will never match again
On your inner loop, iterate from the beginning of the list up to the current entry and then quit.

This sortation and early-bail should improve your performance a little.
Example
Edit: "a little" seems to be a (vast) understatement; comparing the two:
from collections import OrderedDict
from functools import partial
from ipaddress import IPv4Network
from random import randrange, randbytes, seed
from timeit import timeit
from typing import Iterable, Tuple, Sequence

NetRow = Tuple[int, int, str]
IndexRow = Tuple[int, int]

def parse_addresses(filename: str) -> Iterable[NetRow]:
    with open(filename) as f:
        next(f)
        for line in f:
            net_str = line.strip()
            net = IPv4Network(net_str, strict=False)
            yield int(net.network_address), int(net.broadcast_address), net_str

def end_indices(nets: Sequence[NetRow]) -> Iterable[IndexRow]:
    for i, (start, end, net) in enumerate(nets):
        yield end, i

def new(filename: str):
    # Start and end integers and network objects ordered by start
    subnets = sorted(parse_addresses(filename))

    # Supernet dictionary by index from subnets; in same order as subnets
    supernets = OrderedDict(enumerate(subnets))

    # List of tuples of subnet end to subnet index, used for pruning
    ends = sorted(end_indices(subnets))

    for sub_start, sub_end, subnet in subnets:

        # If there are any supernets whose end occurs before the current start,
        # they need to be pruned because they will never match
        for n_to_drop, (end, index) in enumerate(ends):
            if end >= sub_start:
                break
            supernets.pop(index)
        del ends[:n_to_drop]

        for super_start, super_end, supernet in supernets.values():
            # Skip comparison to self
            if subnet is supernet:
                continue

            # If the current supernet start is after the current subnet start,
            # there will not be any more supernets that encompass this subnet
            if super_start > sub_start:
                break

            # The supernet start occurs at or before the current subnet start.
            # If the supernet end occurs at or after the current subnet end,
            # then the supernet encompasses the subnet.
            if super_end >= sub_end:
                # assert subnet.subnet_of(supernet)
                print(f'{subnet} is subnet of {supernet}')

def old(filename: str):
    lines = []
    fileobj = open(filename)
    for line in fileobj:
        lines.append(line.strip())  # create the list from the txt file
    lines.pop(0)  # remove line "name"
    for line in lines:
        for j in range(1, len(lines)):
            if (line == lines[j]):  # problem here: j start always at 1
                # print('comparing same line.... skipping')
                pass
            elif (IPv4Network(line, False).subnet_of(
                    IPv4Network(lines[j], False))):  # check if subnet
                print(line
                      + ' is subnet of network ' + lines[j])
            #elif (IPv4Network(line, False).supernet_of(
            #        IPv4Network(lines[j], False))):  # check if supernet
            #    print(line
            #          + ' is super of network ' + lines[j])

def generate_test(filename: str, min_mask: int, rows: int):
    seed(0)  # for repeatability
    with open(filename, 'w') as f:
        f.write('Name\n')
        for _ in range(rows):
            addr = '.'.join(str(b) for b in randbytes(4))
            mask = randrange(min_mask, 31)
            f.write(f'{addr}/{mask}\n')

if __name__ == '__main__':
    generate_test('bigtest.txt', min_mask=14, rows=1_000)

    for method, title in (
        (new, 'New'),
        (old, 'Old'),
    ):
        print(f'{title} method:')
        t = timeit(partial(method, 'bigtest.txt'), number=1)
        print(f'{t:.3f}s\n')

Output
New method:
50.100.190.198/30 is subnet of 50.100.216.175/16
68.143.197.241/26 is subnet of 68.142.21.93/15
87.88.133.166/17 is subnet of 87.88.222.120/17
87.88.222.120/17 is subnet of 87.88.133.166/17
101.186.112.235/19 is subnet of 101.186.155.104/14
106.183.253.213/22 is subnet of 106.180.121.90/14
110.142.177.23/29 is subnet of 110.140.246.97/14
110.206.109.247/20 is subnet of 110.205.222.149/14
125.43.157.205/28 is subnet of 125.42.59.132/15
138.157.204.243/29 is subnet of 138.157.172.230/14
158.221.173.230/30 is subnet of 158.221.69.71/14
239.186.245.174/18 is subnet of 239.185.216.72/14
243.3.157.156/28 is subnet of 243.3.56.96/16
0.029s

Old method:
87.88.222.120/17 is subnet of network 87.88.133.166/17
125.43.157.205/28 is subnet of network 125.42.59.132/15
106.183.253.213/22 is subnet of network 106.180.121.90/14
101.186.112.235/19 is subnet of network 101.186.155.104/14
158.221.173.230/30 is subnet of network 158.221.69.71/14
243.3.157.156/28 is subnet of network 243.3.56.96/16
87.88.133.166/17 is subnet of network 87.88.222.120/17
50.100.190.198/30 is subnet of network 50.100.216.175/16
110.206.109.247/20 is subnet of network 110.205.222.149/14
138.157.204.243/29 is subnet of network 138.157.172.230/14
110.142.177.23/29 is subnet of network 110.140.246.97/14
68.143.197.241/26 is subnet of network 68.142.21.93/15
239.186.245.174/18 is subnet of network 239.185.216.72/14
33.487s

A more "fair" comparison uses your own algorithm but with a pre-parse step:
def old(filename: str):
    lines = []
    with open(filename) as fileobj:
        next(fileobj)
        for line in fileobj:
            net_str = line.strip()
            lines.append((net_str, IPv4Network(net_str, False)))

    for subnet_str, subnet in lines:
        for supernet_str, supernet in lines:
            if subnet_str is supernet_str:
                continue
            if subnet.subnet_of(supernet):
                print(f'{subnet_str} is subnet of {supernet_str}')

This still took 1.87s on my machine, which is ~58x the time of the 32ms of the new method.
Comparing the new and fair-old methods for min_mask=20, rows=10_000 is more dramatic: 0.362s vs. 249.763s, ~690x faster.


Is it possible to solve it mathematically and make it faster?

Not faster than the second solution,
which is \$O(n)\$, making a single pass over the input.
It's easy to see that it's not possible to find the correct answer without inspecting every element. For example, if two values are not inspected, then one could pick arbitrarily high values for them to make them produce the maximum area.

I have some style comments about the second solution:

I dislike the variable name l because in some fonts it can be confused with | or 1.
I would rename l to left and r to right for natural clarity. Still simple enough.
For symmetry with the while (l < r), I would rewrite the if in the loop body to be if (height[l] < height[r]), as I feel it would facilitate understanding of the logic.


From a short review;

arr1 and arr2 are terrible names, we could call them consonants and vowels
accessing sp[i] so often is not efficient, I would store that value in a variable
when dealing with lists, consider going functional (using forEach, map, reduce, join etc.)
sp is not a great name
There is a nicer way to iterate over the characters of a string with for( of )

Finally, I wanted to provide the below as an example where I incorporate the above points;

function vowelsAndConsonants2(s) {
  const vowels = [],
    consonants = [];

  for(const c of s){
    if('aeiou'.includes(c)){
      vowels.push(c);
    }else{
      consonants.push(c);
    }
  }
  console.log(vowels.join("\n"));
  console.log(consonants.join("\n"));
}


Using  element instead of  to get clickable rows

If it's a table, make it a <table>. Write a traditional <tbody> containing <tr>, in turn containing <td>, in turn containing individual <a>. Then the text will be links. This is simpler, doesn't require any fancy CSS, and better communicates your intent to browsers.
All of the usual keyboard and mouse functionality will be preserved.


CyclicBarrier and Thread for optimize for element for tags in Java

String elemento = "" ;

This variable is unused.

Additionally I'd clean up the blank lines you have, it's dangerous to have an if statement end, and then a couple blank lines later, there's an else that continues the if.

            for (int i = 2; i < parts.length - 1; ++i) {
                String element = parts[1];
                String tag = parts[i];
                for (int j = 1; j <= parts[i].length(); ++j) {
                    String tagPrefix = tag.substring(0, j);
                    Set<String> elements = map.get(tagPrefix);
                    if (elements == null) {
                        elements = new HashSet<String>();
                        map.put(tagPrefix, elements);
                    }
                    elements.add(element);
                }
            }

There's a performance optimization here; parts[i].length() is not free. Use final int tagLength = parts[i].length(), then test against that in your for-loop condition.


The base-ten value of n-base number with Python

A few quick comments:

Use a proper function here, not a lambda. It’s generally more readable, and should be preferred unless you’re writing a ~very short function. And then use different variable names for the function and its arguments, otherwise things get confusing.

Trying to make code more concise is good, but be careful not to make it too short.
This function probably needs a docstring (especially because the argument order is the opposite of that used by int()) and a comment. It took me a minute to work out how the code that’s written corresponds to your equation – and indeed, the equation itself isn’t entirely obvious.
Your function allows me to pass inputs that don’t make sense. For example:

>>> print base_v(2, "3")
3

But 3 isn’t a valid base-2 number: you should throw a ValueError here (like int() does).
Rather than indexing from the end of the string with num_a[len(num_a) - ph - 1], you can use negative indexing just to do num_a[-ph-1], which is cleaner and neater.
ETA: The other problem is that it can only deal with the digits 1–10. It doesn’t deal with numeric strings that contain letters, e.g. base_v(16, "a") throws a ValueError, even though a is a valid base-16 number.


I'd start by breaking the host_hardware method into host_cpus and host_memory rather than returning a hash. A hash feels like a too "informal" structure.

Of course, you'll then need to do the case switching in multiple places, but you can streamline that a little bit by having a method that just returns a normalized platform identifier:

def host_platform
  case RUBY_PLATFORM
  when /linux/ then :linux
  when /darwin/ then :darwin
  when /cygwin|mswin|mingw|bccwin|wince|emx/ then :windows
  else :generic
  end
end

You'll still need case statements elsewhere, but at least they'll be simpler.

Alternatively, you can define the cpu/memory "getters" as procs or lambdas in a hash keyed by the platform:

# horrible name, but it's late
cpu_getters = {
  linux: -> { `nproc`.to_i },
  darwin: -> { `sysctl -n hw.ncpu`.to_i },
  windows: -> { `wmic computersystem get numberofprocessors`.split("\n")[2].to_i }
}

And a similar thing for getting memory information, of course.

Then, using the host_platform from before, you can so something like:

def host_cpus
  getter = cpu_getters[host_platform]
  getter ? getter.call : 2
end

And again, similar thing for memory.

Or, going all out, you could make "platform" classes with cpus and memory methods. If you need more than cpu and memory info,

Playing around a bit, I came up with the thing below. I know that is probably waaaay over-engineered for a simple vagrant file, but between one extreme and the other, you might find something useful.

module Platform
  def self.current
    case RUBY_PLATFORM
    when /linux/ then Linux.new
    when /darwin/ then Darwin.new
    when /cygwin|mswin|mingw|bccwin|wince|emx/ then Windows.new
    else Generic.new
    end
  end

  class Generic
    attr_reader :cpus, :memory

    def initialize
      @cpus = 2
      @memory = 2048
    end

    def reasonable_memory
      [1024, memory / 2, 4096].sort[1]
    end
  end

  class Linux < Generic
    def initialize
      @cpus = `nproc`.to_i
      @memory = `sed -n -e '/^MemTotal/s/^[^0-9]*//p' /proc/meminfo`.to_i / 1024
    end
  end

  class Darwin < Generic
    def initialize
      @cpus = `sysctl -n hw.ncpu`.to_i
      @memory = `sysctl -n hw.memsize`.to_i / 1024
    end
  end

  class Windows < Generic
    def initialize
      @cpus = `wmic computersystem get numberofprocessors`.split("\n")[2].to_i
      @memory = `wmic OS get TotalVisibleMemorySize`.split("\n")[2].to_i / 1024
    end
  end
end

With that you can call Platform.current and you'll get an object with the information you need. Note I've moved #reasonable_memory to an instance method too (and used a neat little trick to find the median value).

One obvious improvement would of course be memoizing Platform.current, so it only bothers with instantiating something once.

As a sidenote: I don't actually use Rubocop, though I generally adhere to the style guide, and agree with very nearly all of it (I often link to it in reviews, too). I tested all the code above though, and Rubocop let me off with a warning about line length (and a broken tail light).

But running Rubocop on a little script like this is somewhat overkill. Like getting out Strunk & White when writing a routine email. If you've used Rubocop for a while, I'm sure you've already learned to police your code yourself, and that's probably enough.


The key optimisation can be found in this part:

Dim orderColumnOArray as Variant, orderColumnGArray as Variant, orderColumnXArray as Variant
orderColumnOArray = ThisWorkbook.Worksheets("order").Range("O2:O1000000").Value
orderColumnGArray = ThisWorkbook.Worksheets("order").Range("G2:G1000000").Value
orderColumnXArray = ThisWorkbook.Worksheets("order").Range("X2:X1000000").Value

There above, we are using arrays to store the order data, and we can traverse them more efficiently, rather than repeat a full array formula calculation for each cell.

Note that even then we could cut down on the million rows, and do a lastRow calculation for the order sheet. Perhaps that will bring great improvement too. However if we say for now that you will genuinely have that number of data rows in the order Worksheet, we can still go about it a bit better.

With ThisWorkbook.WorkSheets("sample")
    'I will assume that the column needs to filled from AM3 to AMLastrow
    'I also assume the tested values are strings or integers, not dates or floats
    Dim resultArray() as String
    ReDim resultArray(3 to Lastrow)
    Dim j as Long

    For i = 3 To Lastrow
        resultArray(i) = "review"
        For j = 1 To Ubound(orderColumnOArray)
            'The below nested Ifs can be done in many different ways
            'e.g. And with the 3 equality tests
            'or even by initially making two concatenated arrays!
            If .Range("O" & i).Value = orderColumnOArray(j, 1) Then
                If .Range("G" & i).Value = orderColumnGArray(j, 1) Then
                    If .Range("X" & i).Value = orderColumnXArray(j, 1) Then
                        resultArray(i) = "pass"
                        Exit For
                    End if
                End if
            End if
        Next j
    Next i

    'Now we can write back the array to the worksheet faster
    .Range("AM3").Resize(Lastrow - 3 + 1, 1).Value = resultArray
End With


Fetching a set of event IDs from a database based on a set of company IDs

Not so a direct answer to your question but this may help you.

Most of methods you are using are really extension methods, If your only worry is debugging or logging, you can get code for these methods and create your own extension methods with same names but Namespace must be different.

As these are extension methods, you will not be able to override them.


You won't be able to change the bulkiness much but there are a few things you can do:

indent your code. It will take more space but it will also be more readable:

DateTime dateFrom;
DateTime dateTo;

if (!DateTime.TryParse(txtDateFrom.Text, out dateFrom))
{
    dateFrom = DateTime.Today.AddDays(-7);
}
if (!DateTime.TryParse(txtDateTo.Text, out dateTo))
{
    dateTo = DateTime.Now;
}

Wait for C# 6 which has inline-out-variables. This will make it possible to write the TryParse like this:

if (!DateTime.TryParse(txtDateFrom.Text, out DateTime dateFrom))

or even

if (!DateTime.TryParse(txtDateFrom.Text, out var dateFrom))

Use DateTime.UtcNow. By using DateTime.Now you're dependent on the location of your server which might be a problem some time in the future when you host it elsewhere.
Consider making a datetime picker available in the frontend instead of a textbox. It's a lot more user-friendly and it will avoid invalid dates.


Filtering units by a dynamic Lambda expression

Don't omit braces. Ever. It's such a bad idea (I learned this the hard way).

As far as your lambda, your method is not necessarily a bad thing, though there are always other ways to write it.

var unitGroups = _db.Units
                    .Where(u => (onlyChildren && u.PhaseId == id) || (!onlyChildren && u.PhaseId != id))
                    .GroupBy(m => .UnitTemplate, (m, group) => new UnitTemplateZoneVm()
                    {
                        Id = m.Id,
                        Units = group.ToList()
                    })
                    .ToList();

Whitespace is free, use it. It makes it clearer as to what steps belong together.

I would personally prefer this method, as you can extract this out into LINQ-SQL style, instead of using the methods. Personally, I prefer the LINQ-SQL style rather than the methods, but the choice is up to you.


There's quite a lot of logic in there, so I doubt you will get there completely by using LINQ, and, more importantly, if it would actually be more elegant.

I would rewrite as follows, and be done with it:

        foreach (AddressInfo addressInfo in subDetails)
        {
            grpInfo = lstGroupInfo.SingleOrDefault(x => x.Address1 == addressInfo.Address1);
            if (grpInfo != null)
            {
                grpInfo.Rural = addressInfo.Rural;
                grpInfo.Urban = addressInfo.Urban;
                grpInfo.SubDetails.Add(addressInfo);
            }
            else
            {
                grpInfo = new GroupInfo();
                grpInfo.AddressID = addressInfo.AddressID;
                grpInfo.LocationID = addressInfo.NamedLocationID;
                grpInfo.Rural = addressInfo.Rural;
                grpInfo.Urban = addressInfo.Urban;
            }
        }

In addition, it seems to me that Rural and Urban are mutually exclusive, so why not define an enumeration that contains those two (or more) values, or declare one boolean property IsRural to indicate if it's "Rural", and if not, it's urban. That would bring the code down to:

        foreach (AddressInfo addressInfo in subDetails)
        {
            grpInfo = lstGroupInfo.SingleOrDefault(x => x.Address1 == addressInfo.Address1);
            if (grpInfo != null)
            {
                grpInfo.IsRural = addressInfo.IsRural;
                grpInfo.SubDetails.Add(addressInfo);
            }
            else
            {
                grpInfo = new GroupInfo();
                grpInfo.AddressID = addressInfo.AddressID;
                grpInfo.LocationID = addressInfo.NamedLocationID;
                grpInfo.IsRural = addressInfo.IsRural;
            }
        }


Faster method to find data using search word?

Perhaps the best way to solve this problem is to not have it in the first place. If you are in control of the code that produce this array of string, probably from a text file or a similar input, you could produce a tree of values instead right from the start. That way, instead of trying to find specific values through a text search, you could simply find the nodes in the tree that you need, for instance the "Parameters Table" node, and then dive into each parameters from there. This would look a little bit like this:

<root node>
    A
        B1
        C1
    A
        B2
        C2

If you are not in control of this code, then you have no other choice than to search through the entire list. Marcin Juraszek did propose a pretty good solution for this. Another way to do this search, which would also be a little bit faster would be this:

public static class EnumerableExtensions
{
    private class SearchResults
    {
        public List<String> Values = new List<string>();
        public int SkipCounter = -1;
    }

    public static List<string> FindAllSubItems(this IEnumerable<string> source, string keyword, int distance)
    {
        return source.Aggregate(
            new SearchResults(),
            (sr, v) =>
            {
                if (v.Equals(keyword))
                {
                    sr.SkipCounter = distance;
                }

                if (sr.SkipCounter == 0)
                {
                    sr.Values.Add(v);
                }

                --sr.SkipCounter;

                return sr;
            },
            sr => sr.Values
        );
    }
}

Which can be used like so:

var someList = new string[] {"A", "B1", "C1", "A", "B2", "C2" };
someList.FindAllSubItems("A", 1); // returns { "B1", "B2" }

The idea around this solution is to make sure that only one pass through the list will ever happen. This is an O(n) solution, as opposed to Juraszek's one which is an O(n + m) solution where n is the amount of inputs and m is the amount of matching keys. This solution also adds a safety around keys that does not have at least distance elements. For now, it simply skips it, but it is trivial to check for the value of SkipCounter before resting it if an exception needs to be thrown.

Once we find a match for our first parameter, we set a skip counter based on a distance parameter. We then proceed on decrementing the counter until it reaches zero. If the counter reaches zero, we have a found an item at distance items of the parameter so we save it. If it never reaches zero it means that we are looking for an item further than there is in the list. Providing a negative distance to this algorithm will never yield any results as it is a forward only algorithm. When the final value is returned, we simply trash the counter and only keep the values we saved in our temporary SearchResults object.

EDIT

As requested in the comment, the question author is wondering how to trigger updates to a progress bar in a solution like this. Since this code is using LINQ which works wonders with yield return, you can simply call it like this:

var items = someList
    .Select((x, i) => { UpdateMyProgressBarForIndex(i); return x; })
    .FindAllSubItems(...);

As you expect, the lambda specified in the select block will be called for each element in the list. But because of how LINQ methods are designed (using yield return), this will happen as the aggregate method process them. This is because the list of items that Select returns is built only as new items are requested by the bottom most foreach loop which runs inside the Aggregate method. Basically, you will see this behavior:

Initialize aggregate seed
foreach items in the list
Select's lambda for item (x)
Aggregate lambda for item(x)
when done
extract final values from the seed