subclassing standard containers? I have read so many times that one should not subclass standard containers.
Is there cases that one can subclass them ?
for example, I have the following case:

struct Materials
{

  std::map<std::string, std::unique_ptr<Material>> materials;

  void setFrom(const Database& db);
  void echo(std::ostream&) const;

};

I want my materials class to act like a map, so I have to add methods like

Material& getMaterial(std::string& key);
void addMaterial(std::string& key, Material& material);

which could have been avoided if I just sublcassed the container.

 struct Materials:public std::map<std::string, std::unique_ptr<Material>> materials;
    {
      void setFrom(const Database& db);
      void echo(std::ostream&) const;
    };

is this a horrible thing to do ?

Yes it is horrible.

The only time where inheritance over composition makes any sense is when you want to take advantage of the empty baseclass optimization. A container is not a empty class.

In a struct all fields are public so you don't need to public inherit anyway.

None of the methods of the std containers are virtual so you cannot override them. Which in turn means you cannot prevent user code from invalidating any invariants you want to impose. This last is an issue with public member field as well.

If you ever want to change containers to one with a different api you have to change all code dealing with the container part instead of only changing the type in the header and the implementation of the wrapper functions.


Return the product of the pythagorean triplet if a+b+c == 1000 I have found the answer to the problem I am trying to solve, but I am curious if there can be any improvements made to my code.

#include <iostream>
#include <limits>
#include <cmath>
using namespace std;

unsigned long pythagoreanTriplet();
int main() {
cout << pythagoreanTriplet() << endl;
}

unsigned long pythagoreanTriplet()
{
int a,b;
   unsigned long c;
for(a = 1; a < 1000;a++)
{
    for(b = a+1; b <= 1000;b++)
    {
        c = sqrt(pow(a,2)+pow(b,2));

        if(pow(a,2)+pow(b,2) == pow(c,2))
        {
            if(a+b+c == 1000)
            {
                unsigned long product = a*b*c;
                return product;
            }
        }
    }
 }
}

Don't use std::pow(n, 2) to square an integer - not only is it slower than n*n, it's much less accurate (so you'd want to add 0.5 before assigning to c, to round to nearest).

Instead of computing c as the hypotenuse of triangle (a,b,c), it's simpler to take c as 1000-a-b, then check if that makes a right-triangle:
        c = 1000 - a - b;
        if (a*a + b*b == c*c) {
            return a*b*c;
        }

Look, no <cmath>!

We can reduce the limits of our search, by noting that a can't be as much as 500 (because a < b and a+b < 1000):
for (a = 1;  a < 500;  ++a) {
    for (b = a+1;  b < 1000-a;  ++b) {
        c = 1000 - a - b;

Keep your types consistent.  You seem to be aware that int is only guaranteed to be able to hold values up to 32,767, so that's obviously the wrong choice for c and for the result.  But it's also the wrong choice for a and b, because expressions such as a*b can overflow (500*500 = 250,000), so that computing the return value could be Undefined Behaviour.  The best approach is to use one of the fixed-size types defined in <cstdint> for all three quantities - I recommend std::uint_fast32_t for this.

Make sure you return a value even if no match was found.  At present, we just run off the end of the function (and get a compiler warning, so we have no excuse for missing that).  We can safely return zero to indicate "no match", as that could never be the result of a successful search.

Modified code
#include <iostream>
#include <cstdint>

std::uint_fast32_t pythagoreanTriplet()
{
    for (std::uint_fast32_t a = 1;  a < 500;  ++a) {
        for (auto b = a+1;  b < 1000-a;  ++b) {
            auto c = 1000 - a - b;
            if (a*a + b*b == c*c) {
                return a*b*c;
            }
        }
    }
    return 0;                   // not found
}

int main()
{
    std::cout << pythagoreanTriplet() << std::endl;
}

Exercise
Instead of hard-coding the target sum 1000, pass it as a parameter to your function.


Creating instance of all classes that have certain attribut value I have a simple custom attribute MessageDeliveryAttribute that has one string filed. Also I have several classes that mark with this attribute like:

[MessageDeliveryAttribute("MessegaToDb")]

In the app.config are settings like:

  <appSettings>
    <add key="MessageToConsole" value="true"/>
    <add key="MessageToDb" value="true"/>
    <add key="MessageToService" value="false"/>
    <add key="MessageToFile" value="false"/>
  </appSettings>

I'm trying to implement class that will read all keys with value "true" from app.config, find all classes that marked with attribute

[MessageDeliveryAttribute("value of key from app.config where value = true")]

and then create a list with instance of these classes.
Here are working code, but I need your suggestions how to improve that?

public static List<IMessageDelivery> GetMessagesDelivery()
{
    var instances = new List<IMessageDelivery>();

    // list of settings from app.config where value is true
    List<string> settingValues = ConfigurationManager.AppSettings.AllKeys
        .Where(key => ConfigurationManager.AppSettings[key].Equals("true"))
        .Select(value => value)
        .ToList();

    foreach (var types in GetTypesWithMessageDeliveryAttribute())
    {
        var attributeValue = GetAttributeValue(types);
        if (settingValues.IndexOf(attributeValue) >= 0)
        {
            instances.Add(Activator.CreateInstance(types) as IMessageDelivery);
        }
    }

    return instances;
}
// Get all classes with my custom attribute
public static IEnumerable<Type> GetTypesWithMessageDeliveryAttribute()
{
    var assembly = Assembly.GetExecutingAssembly();
    return from type in assembly.GetTypes()
           where type.IsDefined(typeof(MessageDeliveryAttribute), false)
           select type;
}
// get value of attribute
public static string GetAttributeValue(Type t)
{
    var messageDeliveryAttribute = (MessageDeliveryAttribute)Attribute.GetCustomAttribute(t, typeof(MessageDeliveryAttribute));

    return messageDeliveryAttribute != null ? messageDeliveryAttribute.DeliveryPointName : string.Empty;
}

I'm not sure what feedback specifically you're looking for. There are minor formatting and naming questions, but only two things I would specifically draw attention to.

The first thing is that you're enumerating all the settings in the App.config, but you're only interested in settings that relate directly to message delivery. You should name-space your setting keys, and filter the settings before evaluating them.

<appSettings>
    <add key="MessageDelivery.MessageToConsole" value="true"/>
    <add key="MessageDelivery.MessageToDb" value="true"/>
    <add key="MessageDelivery.MessageToService" value="false"/>
    <add key="MessageDelivery.MessageToFile" value="false"/>
  </appSettings>

and

List<string> settingValues = ConfigurationManager.AppSettings.AllKeys
        .Where(key => ConfigurationManager.AppSettings[key].Equals("true"))
        .Where(key => key.StartsWith("MessageDelivery."))
        .Select(value => value.Replace("MessageDelivery.",""))
        .ToList();

Secondly, avoid using two different forms of Linq expression building:

List<string> settingValues = ConfigurationManager.AppSettings.AllKeys

        .Where(key => ConfigurationManager.AppSettings[key].Equals("true"))
        .Select(value => value)
        .ToList();

and

return from type in assembly.GetTypes()
           where type.IsDefined(typeof(MessageDeliveryAttribute), false)
           select type;


Search through fortran source for a string ignoring comments I am trying to write a python script that can search through Fortran code
ignoring comments. I didn't find a simple way of doing this using grep. So I startwed writing my own.
The rules for comments that I am following are:

the first character is not a space or a number. It is usually a c, C but I've seen * and other variations
the above condition can be violated if its a fortran90/95 code in that case, its complicated so I am not treating that case for now.
the first non-space character is a "!"

I could not find a simple solution that ignores all types of fortran comments in text so I started writing my own in python 2.x. It looks dirty but works in many cases.
#!/usr/bin/python
import sys
def fgrep(file_name, cond):
      first_valid_chars=tuple(range(0,10 )) + (' ',)
      with open(file_name, 'r') as f:
          for line in f:
            if line[0] in first_valid_chars:
                line1 = line.strip()
                if line1:    # ignore empty lines
                     if line1[0] != '!':
                         # fortran is case insensitive so comparing lower to lower
                         if cond.lower() in line1.lower():
                               print(line1)

if __name__ == "__main__":
   print(sys.argv[1])
   file_name = sys.argv[1]
   cond = sys.argv[2]

   fgrep(file_name, cond)

It's drty, not clean and too many indents. How do I clean this up? Because I copy-pasted from editor, there could be errors due to indentation.

Shebang
#!/usr/bin/python is not portable, #!/usr/bin/env python is preferred.
White Space
There should be a blank line between your imports and your function declarations.
Efficiency
You are constantly converting your cond to lowercase.  You don't need to repeatedly do this; just do it once, before the loop.
Right Leaning Code
As you've mention, the code is way-too right leaning.
You could fix this with continue type statements ...
def fgrep(file_name, cond):
    first_valid_chars=tuple(range(0,10 )) + (' ',)

    # Fortran is case insensitive so comparing lower to lower
    cond = cond.lower()
    with open(file_name, 'r') as f:
        for line in f:
            if line[0] not in first_valid_chars:
                continue

            line1 = line.strip()
            if not line1:    # ignore empty lines
                continue

            if line1[0] == '!':
                continue

            if cond in line1.lower():
                print(line1)

RegEx
You could use a Regular Expression to identify comment lines.

\s*! would find an exclamation mark after any number of spaces.
[^\d\s] would match anything but a digit or a white-space character.

Combined these with the | or-operator, and use .match() to search from the start of the string, and you get an easy comment-line predicate:
def fgrep(file_name, cond):
    # A comment line starts with an exclamation mark as the first non-blank character,
    # or any non-blank character other than a digit as the first character.
    comment = re.compile(r'\s*!|[^\d\s]')

    # Fortran is case insensitive so comparing lower to lower
    cond = cond.lower()

    with open(file_name, 'r') as f:
        for line in f:
            if not comment.match(line) and cond in line.lower():
               print(line)

Line numbers
You might want to print out the line number of the matching line, to make it easier to find the lines in the file.  enumerate would help:
def fgrep(file_name, cond):
    # A comment line starts with an exclamation mark as the first non-blank character,
    # or any non-blank character other than a digit as the first character.
    comment = re.compile(r'\s*!|[^\d\s]')

    # Fortran is case insensitive so comparing lower to lower
    cond = cond.lower()

    with open(file_name, 'r') as f:
        for line_no, line in enumerate(f, 1):
            if not comment.match(line) and cond in line.lower():
               print(line_no, line, sep=": ")


Is this a correct implementation of quicksort in C? I'm learning C at the moment and chose implementing quicksort as an exercise.

My code is sorting correctly, but afterwards I looked at some tutorials online about quicksort. And they implement it differently.

I don't know, if I misunderstood quicksort, or if I simply implemented it differently.

How I understood quicksort:

  Choose pivot
  bin elements according to their size (bigger/smaller than pivot)
  repeat till array is sorted

I use middle element as pivot to avoid standard worst cases.

My code:

#include <stdio.h>
#include <math.h>

void quicksort(unsigned int* array, unsigned int length)
{
    if (length <= 1)
    {
        return;
    }

    unsigned int length_tmp = length/2;

    //pivot is middle element
    unsigned int pivot = array[length_tmp];

    unsigned int array_tmp[length];
    unsigned int length_small = 0;
    unsigned int length_big = 0;

    //binning array - bigger / smaller
    //left of pivot
    for (unsigned int i = 0; i < length_tmp; i++)
    {
        if (array[i] < pivot)
        {
            array_tmp[length_small] = array[i];
            length_small++;
        }
        else
        {
            array_tmp[length-1-length_big] = array[i];
            length_big++;
        }
    }

    //right of pivot
    for (unsigned int i = length_tmp+1; i < length; i++)
    {
        if (array[i] < pivot)
        {
            array_tmp[length_small] = array[i];
            length_small++;
        }
        else
        {
            array_tmp[length-1-length_big] = array[i];
            length_big++;
        }
    }

    //inserting pivot unsigned into temporary array
    array_tmp[length_small] = pivot;

    //copying values unsigned into array
    for (unsigned int i = 0; i < length; i++)
    {
        array[i] = array_tmp[i];
    }

    //recursive function calls
    quicksort(array+0, length_small);
    quicksort(array+length_small+1, length_big);

    return;
}

int main()
{
    unsigned int array[] = {1,2,3,7,8,9,6,5,4,0};
    unsigned int length = sizeof array / sizeof array[0];  //alternative: sizeof array / sizeof *array

    //printing array
    printf("unsorted array: ");
    for (unsigned int i = 0; i < length; i++)
    {
        printf("%d", array[i]);
    }
    printf("\n");

    //calling sorting function
    quicksort(array, length);

    //printing array
    printf("sorted array: ");
    for (unsigned int i = 0; i < length; i++)
    {
        printf("%d", array[i]);
    }
    printf("\n");

    return 0;
}

I had posted this before on stackoverflow, but was informed of my mistake and that I should post it here. I didn't get answer to my question in that short time, but a few pointers regarding my code which I tried to implement in my solution.

The most valuable feature of quicksort is that it sorts in-place, without a temporary array. The average space complexity quicksort is logarithmic, whereas the one of your solution is linear. The time complexity is also affected by the copying from temporary back to original.

NB: If you can afford a linear temporary, don't use quicksort. Mergesort will win hands down: it doesn't have a worst case, and besides it is stable.
Choosing middle element for the pivot, while harmless, doesn't avoid the worst case. The performance of the quicksort is affected not by where the pivot is chosen, but by where it lands after partitioning. Worst case arises when they consistently land near the edges of the array.
I don't see the need to treat left of pivot and right of pivot separately:

Swap the pivot with the first element (`array[0]` now holds the pivot)
Partition the entire [1..length) range in one pass
Swap the `array[0]` (which holds the pivot) with `array[length_small]`.

A length of the array should be size_t. There is no guarantee that unsigned int is wide enough to represent a size of a very large array.
The code before the recursive call implements an important algorithm, namely partition and deserves to be a function of its own. Consider

void quicksort(int *array, size_t length)
{
    if (length <= 1) {
        return;
    }
    size_t partition_point = partition(array, length);
    quicksort(array, partition_point);
    quicksort(array + partition_point + 1, length - partition_point - 1);
}

Further down, you may want to implement two improvements:

Recursion cutoff: when the array becomes small enough, insertion sort performs better
Tail call elimination (not really necessary, the C compilers are good in it)


Deleting an item from a Set while iterating I know that I'm not suppose to alter a Set as I iterate through it. But, in the deleteRow(String counter, String reading) method below, doing just that will make the code much more readable and clean.

Because there is so little going on in each iteration:

Is there risk?
Would a respectable coder look at that and consider it flawed?

public static class DbTable {
    public enum Columns { counter, reading, dfEng }
    public Set<Row> tableData = new HashSet<Row>();

    public void deleteRow(String counter, String reading) {
        Row deleteThis = null;
        for(Row r : tableData) {
            if((r.counter.equals(counter)) && (r.reading.equals(reading))) {
                // tableData.remove(r); <--- I want to do this, and
                // return; <--- then this to have cleaner code.
                deleteThis = r;
                break;
            }
        }
        if(deleteThis != null) { tableData.remove(deleteThis); }
    }
            public static class Row {
                public final String counter, reading, dfEng;
                public Row(String counter, String reading, String dfEng) {
                    this.counter = counter;
                    this.reading = reading;
                    this.dfEng = dfEng;
                }

                public String toString() {
                    String s = counter + String.valueOf((char) 9) + reading + String.valueOf((char) 9) + dfEng;
                    return s;
                }
            }
}

No, there is no risk because you are returning directly after removing, or breaking directly after setting the deleteThis variable.

However, to make each part of your code as safe as possible, I would recommend to use the Iterator approach. The idea is that if you would forget to use break; or return; then you would have problems. If you use Iterator.remove(), then you are still safe.

There is another variant as well, based on Java 8 (if you have that available),

tableData.stream().filter(r -> r.counter.equals(counter)
        && r.reading.equals(reading))
    .findAny()
    .ifPresent(r -> tableData.remove(r));

This will not have a big impact on performance thanks to the fact that you are using a Set.

Now, I am not fully aware of your exact situation but another option might be to implement hashCode and equals in your Row class, in which case two Row objects with the same properties won't be added to the Set in the first place, and if you want to remove one and replace with another, you can do so with \$O(1)\$ complexity instead of your current \$O(n)\$. This assumes though that you are actually free to do this. Implementing hashCode and equals can have other unforeseen consequences.

Other comments

enum values should be named UPPERCASE according to Java naming conventions.
It is unclear what a Row really represents, and what a dfEng is.
Since Java 7, you can use the "diamond operator" <>, you can do new HashSet<>();
Not necessary to store the String in a local variable in toString (although it can be useful if you want to debug and see what the method will return).


Assigning properties based on string parameters I am using the below method to assign value to my object(Team.Driver/Team.Codriver). This works fine but just wanted to know if I could improve this code via LINQ or other options.

public void MoveDriverCodriver(
    Team source, string sourceType, Team target, string targetType)
{
    if (sourceType == "Driver")
    {
        if (targetType == "Driver")
        {
            target.Driver = source.Driver;
        }
        else
        {
            target.Codriver = source.Driver;
        }
    }
    else
    {
        if (targetType == "Driver")
        {
            target.Driver = source.Codriver;
        }
        else
        {
            target.Codriver = source.Codriver;
        }
    }
}

Also second part is I want to update target Driver/Codriver details with the appropriate source. But I want to retain the id's of target Driver/Codriver.

class Driver
{
  public Guid Id { get; set; }
  public string Firstname { get; set; }
  public string Lastname { get; set; }
  public int Age { get; set; }
}

class Team
{
  public Guid Id { get; set; }
  public Driver Driver { get; set; }
  public Driver Codriver { get; set; }
}

calling move operation.

Team team1 = new Team(); //Do some operation on team1
Team team2 = new Team(); //Do some operation on team2
MoveDriverCodriver(team1, "Driver", team2, "Codriver"); //Here I am trying to assign team1's driver to team2's codriver.

Making the assumption you can't just use team1.Driver = team2.Codriver because you don't know the name of the properties first hand, I would build an even more generic function where it can be used with any type.

Also, I wouldn't name it Move because there is no move involved since the source still retains its values,

That said, my approach would be:

public void CopyProperty<T>(T source, string sourcePropertyName, T target, string targetPropertyName)
{
    if (source == null)
    {
        throw new ArgumentNullException(nameof(source));
    }

    if (target == null)
    {
        throw new ArgumentNullException(nameof(target));
    }

    if (string.IsNullOrWhiteSpace(sourcePropertyName))
    {
        ThrowInvalidParameterNameException(nameof(sourcePropertyName));
    }

    if (targetPropertyName == null)
    {
        ThrowInvalidParameterNameException(nameof(targetPropertyName));
    }

    Type elementType = typeof(T);
    PropertyInfo sourceProperty = elementType.GetProperty(sourcePropertyName);
    if (sourceProperty == null)
    {
        ThrowPropertyDoesNotExistException(sourcePropertyName, nameof(sourcePropertyName), elementType.Name);
    }

    if (!sourceProperty.CanRead)
    {
        ThrowPropertyAccessException(sourcePropertyName, PropertyAccessType.Read);
    }

    PropertyInfo targetProperty = elementType.GetProperty(targetPropertyName);
    if (targetProperty == null)
    {
        ThrowPropertyDoesNotExistException(targetPropertyName, nameof(targetPropertyName), elementType.Name);
    }

    if (!targetProperty.CanWrite)
    {
        ThrowPropertyAccessException(targetPropertyName, PropertyAccessType.Write);
    }

    if (sourceProperty.PropertyType != targetProperty.PropertyType)
    {
        throw new Exception(string.Concat("Property ", sourcePropertyName, " is not the same type as Property ", targetPropertyName));
    }

    targetProperty.SetValue(target, sourceProperty.GetValue(source, Type.EmptyTypes), Type.EmptyTypes);
}

private void ThrowInvalidParameterNameException(string parameterName)
{
    throw new ArgumentException("Invalid parameter name ", parameterName);
}

private void ThrowPropertyDoesNotExistException(string propertyParameter, string propertyParameterName, string typeName)
{
    throw new ArgumentException(string.Concat("Property ", propertyParameter, " does not exist in type ", typeName, " "), propertyParameterName);
}

private enum PropertyAccessType
{
    Read,
    Write
}

private void ThrowPropertyAccessException(string propertyParameter, PropertyAccessType accessType)
{
    throw new AccessViolationException(string.Concat("Property: ", propertyParameter, ", Access type: ", accessType));
}

With this you would get a safe and generic method to copy properties where you can use with any type and don't know which property is going to be copied (does not account for indexed properties).

You can use it calling:

CopyProperty(team1, "Driver", team2, "Codriver");

There is no collections to query for (unless you are searching for the right property) so I don't see how you can use linq.

This however has more if's than your first attempt.


Rearrange list by modifying the original list, put even-index values at front I am relatively new to python and I am still trying to learn the basics of the language. I stumbled upon a question which asks you to rearrange the list by modifying the original. What you are supposed to do is move all the even index values to the front (in reverse order) followed by the odd index values.

Initial:

 0  1  2  3  4  5  6
[3, 5, 2, 8, 7, 9, 0]

Rearranged:

 6  4  2  0, 1, 3, 5
[0, 7, 2, 3, 5, 8, 9]

This is how I approached the question:

even = []
odd = []
for i in range(len(l)):
    if i % 2 == 0:
        even.append(i)
    else:
        odd.append(i)
even = even[::-1]
index = even + odd
l2 = []
for i in index:
    l2.append(l[i])
for i in range(len(l)):
    l[i] = l2[i]

Although it works, and does what is being asked, I was wondering if there is a more efficient way to get the result. I feel that creating three empty lists just to rearrange one list is not the best approach.

Any input would be greatly appreciated.

I'm not sure if you are actually trying to solve this problem in-place, but based on what you have done, you could condense your code by using Python list slices instead of separating even and odd indices in a for loop. Slices work by

list[start_index:end_index:step]

So, you could get the even indices with

l[::2][::-1]

which gets the even indices in reverse order, and the odd indices by offsetting the start by 1,

l[1::2]

This works because a step size of 2 means you get every other #, so starting at 0 results in all even indices and starting at 1 results in all odd indices. Without the start index it starts at 0, and without the end index it goes until the end of the list.

This combines into a single line, assigning using slice notation to keep the modification in-place,

l[:] = l[::2][::-1] + l[1::2]


C-string appender for buffers and strings Is this C appender safe, and reasonably optimal?

#define REALLOC_BUFFER_SIZE 4096

char *append(char *orig_str, size_t *orig_str_size, const char *append_str) {
    // no action required if appending an empty string
    if (append_str[0] == 0) {
        return orig_str;
    }

    // does the current char* have enough space?
    size_t req_space = strlen(orig_str) + strlen(append_str) + 1; // +1 for NULL byte

    // resize if the required space is greater than the original buffer size.
    if (req_space > *orig_str_size) {
        // prepare the variable with the amount of space we want
        size_t allocate = *orig_str_size + req_space + REALLOC_BUFFER_SIZE;

        char *new_str = (char *)realloc(orig_str, allocate);
        // resize success..
        if (new_str == NULL) {
            fprintf(stderr, "Couldn't reallocate memory\n");
            return NULL;
        }

        // the realloc didn't fail, here is our new pointer
        orig_str = new_str;

        // overwrite the free space with NULL's
        memset(orig_str + strlen(orig_str), 0, req_space);

        // copy the appending text to the string
        strcpy(orig_str + strlen(orig_str), append_str);

        // modify the original size
        *orig_str_size = allocate;

    } else {
        // append the string
        strcpy(orig_str + strlen(orig_str), append_str);
    }

    return orig_str;
}

Example usage:

char *buffer;
size_t buffer_size = 20;
int i;

buffer = (char *)malloc(sizeof(char) * buffer_size);
strcpy(buffer, "1234567890123456789"); // fill some data prior..

// original string
for (i=1; i < 100; ++i) {
    buffer = append(buffer, &buffer_size, "AABBCC");
}

free(x);

Latest changes: GitHub

In addition to what the other answers say and I generally agree with:

Don't call strlen more than once.  That's just a waste.  Count the length of orig_str and append_str once at the beginning of the function and store them away in const variables.  That will also make your initial check whether append_str is empty look cleaner:

const size_t append_len = strlen(append_str);
if (!append_len)
    return orig_str;
const size_t orig_len = strlen(orig_str);

Moving the strlen(orig_str) above the conditional would look cleaner in my eyes but it might be a pessimization if append_str is often empty.

Of course, the most efficient way would be if you could pass orig_len as an additional input parameter.  Or you could use a

struct string_buffer
{
  size_t length;
  size_t capacity;
  char * data;
};

that encapsulates all the required info and change your function's signature to

ssize_t
append_string(struct string_buffer * buffer, const char * appendix);

where the function could return the number of bytes successfully appended or –1 on error.

My second remark would be that you are growing your buffer by a constant amount each time you reallocate.  It should really grow exponentially unless you really know that linear growth will be preferable in your specific use-case, which I find hard to imagine how that could be.

Concerning your comments: there is no NULL byte.  NULL is a macro constant for the null pointer.  The null byte is abbreviated as NUL in the ASCII character set.  I would also find it helpful to have your function's semantics exactly documented in a comment.  For example, should the user free the buffer if it fails and returns NULL?  Will the existing data be modified in that case?  I can try answering those questions by reading your implementation but that doesn't allow me to distinguish a bug in your code from a different valid design decision.


Reversing the vowels in a String Given a string, reverse only the vowels present in it and print the
    resulting string.

    Input:

  First line of the input file contains an integer T denoting the
  number of test cases. Then T test cases follow. Each test case has a
  single line containing a string.

    Output:

  Corresponding to each test case, output the string with vowels
   reversed.

    Example:

    Input:

    4

    geeksforgeeks

    practice

    wannacry

    ransomware

    Output:

    geeksforgeeks

    prectica

    wannacry

    rensamwora

My approach:

/*package whatever //do not write package name here */

import java.util.Scanner;
import java.io.IOException;
import java.lang.StringBuffer;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;

class GFG {

    private static String reverseVowels (String str) {

        List <Character>vowels = new ArrayList <>();
        vowels.add('a');
        vowels.add('e');
        vowels.add('i');
        vowels.add('o');
        vowels.add('u');

        List <Character>values = new ArrayList <>();
        List <Integer>keys = new ArrayList <>();

        for (int i = 0; i < str.length(); i++) {
            if (vowels.contains(str.charAt(i))) {
                keys.add(i);
                values.add(str.charAt(i));
            }
        }

        StringBuffer sb = new StringBuffer(str);

        Collections.reverse(values);
        int count = 0;

        for (Integer num : keys) {
            sb.replace(num.intValue(),num.intValue() + 1,String.valueOf(values.get(count)));
            count++;
        }

        return sb.toString();

    }

    public static void main (String[] args) throws IOException {
        Scanner sc = new Scanner (System.in);
        int numTests = sc.nextInt();

        for (int i = 0; i < numTests; i++) {
            String str = sc.next();
            System.out.println(reverseVowels(str));
        }
    }
}

I have the following questions about my code:

1) How can I further improve my approach?

2) Is there a better way to solve this question?

3) Are there any grave code violations that I have committed?

4) Can space and time complexity be further improved?

My time complexity is O(n) and space complexity is also O(n) currently.

Reference

Time complexity is \$O(n)\$ indeed. Since every input character must be inspected, this asymptotic is impossible to improve. However, it is possible to improve the constant. See below.
Space complexity is \$O(n)\$ indeed. However, it is possible to solve the problem is \$O(1)\$. Consider two iterators, one running left to right, and another running right to left. As long as the first iterator points a consonant, print it. As soon as it hits a vowel, scan the second iterator (right to left) until it finds a vowel, and print that vowel. Notice that this approach also doesn't need values and keys - and hence doesn't need to build them. This is how time complexity is also improved.
The line

sb.replace(num.intValue(),num.intValue() + 1,String.valueOf(values.get(count)));

is very hard to read. It is even harder to prove that it works correctly.


Modularize more efficiently in an if/else setup I wrote a program for one of my Object Oriented Programming in Java classes(Program 2) and I got docked off because my method was too long, which I'm not complaining about.

I got the note: "Modularize more, method too long."

I was wondering what any of you more experienced programmers would do to simplify/shorten my code for future sake so that I learn how to shorten this sort of code.

public void run() throws java.io.IOException
{
   stdin = new Scanner(System.in);
   String input;
   String fraction;
   int numPerLine;
   boolean inList = false;
   input = stdin.next(); // Get the read

  while(!input.equalsIgnoreCase("Q"))
  {
     if(input.equalsIgnoreCase("A"))
     {
        fraction = stdin.next(); // Get the fraction read
        thisFract = new Fraction(fraction);
        list.add(thisFract);
        System.out.println(thisFract.toString() + " was added "
              + "to the list.");
     }
     else if (input.equalsIgnoreCase("D"))
     {
        fraction = stdin.next();
        thisFract = new Fraction(fraction);
        inList = list.delete(thisFract);

        if(inList == true)
           System.out.println(thisFract.toString() + " was removed "
                 + "from the list.");
        else
           System.out.println(thisFract.toString() + " is not in the"
                 + " list.");
     }
     else if(input.equalsIgnoreCase("S"))
     {
        System.out.println("The sum of the list is: " + list.sum());
     }

There are some code smells in your code.

Duplicated Code:

fraction = stdin.next(); // Get the fraction read
thisFract = new Fraction(fraction);
list.add(thisFract);

fraction = stdin.next();
thisFract = new Fraction(fraction);
inList = list.delete(thisFract);

These lines do (almost) the same thing. It is commonly practice in software development to hold solutions at one place. In this case a method which reads the next fraction and another method which add a fraction to a list. This is meant by modularization. Divide your solution in little subsolutions which can be changed at one place and used at different places.

This code optimization is called Refactoring.
There a lots of patterns for code refactoring.

Replace Conditional with Polymorphism:

You could think about using a switch-statement instead of the if-else blocks but it is highly recommended to use Polymorphism instead of conditional checks in object oriented programming languages.

Clean Code:

I would recommend also to read the book Clean Code written by Robert "Uncle Bob" C. Martin which explains lots of patterns to write well organized code.

For Example you can modularize your code like this:

move the if-else in one method
find code clones in the condition blocks and separate into methods
refactor methods top-down

public void run() throws java.io.IOException {
    stdin = new Scanner(System.in);
    String input;
    input = nextFraction();

    while (!input.equalsIgnoreCase("Q")) {
        handleInput(input);
    }
}

private void handleInput(String input) {
    String fraction;
    int numPerLine;
    boolean inList = false;

    if (input.equalsIgnoreCase("A")) {
        handleA();
    } else if (input.equalsIgnoreCase("D")) {
        handleD();
    } else if (input.equalsIgnoreCase("S")) {
        handleS();
    }
}

private void handleA() {
    assignNextFraction();
    addFractionToList();
    outputFractionAdded();
}

private void handleD() {
    assignNextFraction();
    inList = deleteFractionFromList();
    if (inList) {
        outputFractionRemoved();
    } else {
        outputFractionNotInList();
    }
}

private void handleS() {
    outputListSum();
}

private boolean deleteFractionFromList() {
    boolean inList;
    inList = list.delete(thisFract);
    return inList;
}

private void addFractionToList() {
    list.add(thisFract);
}

private void assignNextFraction() {
    String fraction;
    fraction = nextFraction();
    thisFract = createFraction(fraction);
}

private void outputFractionAdded() {
    output(thisFract.toString() + " was added " + "to the list.");
}

private void outputFractionRemoved() {
    output(thisFract.toString() + " was removed " + "from the list.");
}

private Fraction createFraction(String fraction) {
    return new Fraction(fraction);
}

private String nextFraction() {
    String fraction;
    fraction = stdin.next(); // Get the fraction read
    return fraction;
}

private void outputFractionNotInList() {
    output(thisFract.toString() + " is not in the" + " list.");
}

private void outputListSum() {
    output("The sum of the list is: " + list.sum());
}

protected void output(String s) {
    System.out.println(s);
}


PHP function to check if something valid or return error message I would like to make a function that checks if something is valid, but if it can't then I want to return an error message that will probably be used to to throw an exception.

public function isTodayWithinDateRange(\DateTime $start, \DateTime $end) {
    $now = new \DateTime();
    if($now >= $start && $now <= $end) return true;
    if($now < $start) return 'Today is before the start date';
    if($now > $end) return 'Today is later than the end date';
}

And would probably use within a foreach as a validation check such as...

if(isTodayWithinDateRange($myStart, $myEnd) !== true) {
    throw new Exception(isTodayWithinDateRange($myStart, $myEnd));
}

Is this a good way to go about it?  I thought about putting the exception within the function, but this doesn't seem right as all that function should be doing is doing a check and the thing calling it should decide if an error is exceptional or not.

I also thought about returning an array such as...

    return array(
        'success' => false,
        'error' => 'Today is later than the end date'
    );

But I would expect isTodayWithinDateRange to return true if the answer is 'yes'.

Simply , the method isTodayWithinDateRange can throw the exception in this case since the responsability of the method is to check the constraint .
So , i think that you can try it as :

function isTodayWithinDateRange(\DateTime $start, \DateTime $end) {
  $now = new \DateTime();
  if($now < $start) throw new Excception('Today is before the start date') ;
  if($now > $end) throw new Exception('Today is later than the end date');
  return true;

}

First , start with case where you are looking to throw exception , in this case , it's not clearly , but think about a case where you have a lot of logic , here you should start with cases where you don't need to manipulate your logic (like if the argument is null , or missing ...) .

Call you  method as :

$myStart = new Datetime('01-06-2012');
$myEnd = new Datetime('01-06-2020');

// loop

try{

if(isTodayWithinDateRange($myStart, $myEnd)) {
 echo 'contraint validated';

}
}catch(Exception $e){

    echo $e->getMessage();
}
//end loop

I hope this help you .


Code to fetch BitBucket repos This actually works nicely (we have > 2k repos) but I would really like it to start producing results right away as soon as it has any. Mostly so it seems faster than it is (by being more responsive).

   bbrepos(){
        #clone[1] is ssh using a filter made the escaping really ugly.
        #If it becomes necessary we can use a jq arg
        # get max number of repos, ceil(repos / 50), then create a page
        #sequence and curl them all
        local url=https://api.bitbucket.org/2.0/repositories/twengg
        local project=${1:+"q=project.key=\"$1\""}
        curl -snL  "$url?pagelen=0&page=1" | jq '"$(((\(.size) / 50) + 1 ))"' \
            | xargs bash -c 'eval "echo $1"' _ | xargs seq 1 | xargs -L 1 printf "?pagelen=50&page=%s&${1:-$project}\n" \
            | xargs -I {} -L 1 -P 20 -I {} bash -c 'curl -snL  "$1/$2" | jq -er .values[].links.clone[1].href' _ $url {} \ #clone[1] is ssh
            | sort -u
    }

Sample workflow:

bbsearch something | xargs -P 20 git clone

Alternatively, it might also be handy to have these other workflows:

bbsearch something other thing | xargs -P 20 git clone

cat things-to-find.txt | bbsearch | xargs -P 20 git clone

Sample payload (it's normally huge, so I stripped it down to what is needed):

{
  "pagelen": 1,
  "size": 3054,
  "values": [
    {
      "links": {
        "clone": [
          {
            "href": "https://chb0bitbucket@bitbucket.org/twengg/development-process.git",
            "name": "https"
          },
          {
            "href": "git@bitbucket.org:twengg/development-process.git",
            "name": "ssh"
          }
        ],
        "self": {
          "href": "https://api.bitbucket.org/2.0/repositories/twengg/development-process"
        }
      }
    }
  ],
  "page": 1,
  "next": "https://api.bitbucket.org/2.0/repositories/twengg?page=2"
}

eval is evil

Always look for ways to avoid eval.

Relevant snippet from the posted code:

curl -snL  "$url?pagelen=0&page=1" \
    | jq '"$(((\(.size) / 50) + 1 ))"' \
    | xargs bash -c 'eval "echo $1"' _

The code uses jq to create a formatted expression to evaluate by Bash,
with .size injected in the middle of the expression.

A better way to achieve the same thing would be to make jq simply output the variable itself, and then write the expression in Bash:

curl -snL  "$url?pagelen=0&page=1" \
    | jq -r .size \
    | xargs bash -c 'echo $((($1 / 50) + 1))' _

Unnecessary pipeline

It's strange to use xargs to process one line of input,
and it's strange to spawn another Bash just to evaluate an expression.
There's really no need to force a chain of operations in a single pipeline.

I'd rewrite the above snippet like this:

repos_count=$(curl -snL "$url?pagelen=0&page=1" | jq -r .size)
((pages_count = (repos_count / 50) + 1))

Store positional arguments in variables with descriptive names

It's a mental burden to have to remember what $1 and $2 mean.
I'd store them in local variables with descriptive names at the beginning of the function.

Avoid seq

Is it obsolete, and not available in all systems.
Use a Bash counting loop instead:

for ((page = 1; page <= pages_count; page++)); do
    ...
done \
| xargs -L 1 ...

Break lines in long pipelines

It's easier to read code when there's one statement per line.
This is especially true when a line is so long you have to scroll to the right to see it.
So instead of this:

| xargs bash -c 'eval "echo $1"' _ | xargs seq 1 | xargs -L 1 printf "?pagelen=50&page=%s&${1:-$project}\n" \
| xargs -I {} -L 1 -P 20 -I {} bash -c 'curl -snL  "$1/$2" | jq -er .values[].links.clone[1].href' _ $url {} \ #clone[1] is ssh
| sort -u

I recommend to write like this:

| xargs bash -c 'eval "echo $1"' _ \
| xargs seq 1 \
| xargs -L 1 printf "?pagelen=50&page=%s&${1:-$project}\n" \
| xargs -I {} -L 1 -P 20 -I {} bash -c 'curl -snL  "$1/$2" \
| jq -er .values[].links.clone[1].href' _ $url {} \
| sort -u

Always double-quote variables used as command line arguments

In | jq -er .values[].links.clone[1].href' _ $url {}
you forgot to double-quote $url.


Ring datatype in Python I wanted to write something that would be useful for the indices of a grid where if one walked off the edge of the grid they would re enter on the opposite side. This could in theory help with checking for special cases when checking for neighbours to a certain position on the grid. For example the neighbours of position (0, 0) on a 10 x 10 grid would be (0, 1), (1, 1), (1, 0), (9, 9), (0, 9), (1, 9), (9, 0), (9, 1).

def _adj_index(method):
    def _dec(instance, *args):
        if isinstance(args[0], int):
            index = args[0] % len(instance)
            return method(instance, index, *args[1:])
        return method(instance, args)
    return _dec

class Ring(list):
    """
    Ring datatype.
    """

    def __iter__(self):
        while True:
            for i in xrange(len(self)):
                yield self[i]

    def __getitem__(self, item):
        if isinstance(item, tuple):
            slice = item[0]
            return Ring([
                self[i]
                for i in xrange(slice.start, slice.stop, slice.step)])
        return super(Ring, self).__getitem__(item)

    __getitem__ = _adj_index(__getitem__)
    __setitem__ = _adj_index(list.__setitem__)
    __delitem__ = _adj_index(list.__delitem__)

    def __getslice__(self, i, j):
        return Ring([
            self[x]
            for x in range(i, j)])

I don't like the special case for __getitem__ of having to check if it is an integer or a tuple containing a slice.

You shouldn't inherit from builtin data types - there's a UserList type that's more appropriate.

On top of that, you probably shouldn't inherit from UserList either: your code is not a list and doesn't fill its contractual obligations. This is a time to favour composition over inheritance.

Before I look at implementing this, here are a few quick things I noticed. One is

if isinstance(item, tuple):
    ...

in __getitem__, which doesn't seem to work since _adj_index is packing any tuples it gets into another tuple.

Another thing was the use of for i in xrange(len(self)):, which would be much simpler if you could just do for i in self._items - another advantage of composition. You can actually manage this with super(Ring, self).__iter__(), though.

Your __getslice__ returns another ring; this seems strange - a slice of a ring is rarely itself also a ring. If you have a ring of paper and cut a section out, that section has ends!

Finally, your __str__ and __repr__ are the default ones for list, which is entirely misleading and very bad practice.

Back to the point, looking at the abstract base classes in collections (later moved to collections.abc), the only interfaces it makes sense to support are Container and Iterable, since the class doesn't have a __len__. Adding __{get,set,del}item__ and __repr__ on top of that would give something like

def _adj_index(method):
    def _dec(instance, *args):
        if isinstance(args[0], int):
            index = args[0] % len(instance._items)
            return method(instance._items, index, *args[1:])
        return method(instance._items, args)
    return _dec

class Ring:
    """
    Ring datatype.
    """

    def __init__(self, items):
        self._items = list(items)

    def __iter__(self):
        while True:
            for i in xrange(len(self._items)):
                yield self._items[i]

    __getitem__ = _adj_index(list.__getitem__)
    __setitem__ = _adj_index(list.__setitem__)
    __delitem__ = _adj_index(list.__delitem__)

    def __getslice__(self, i, j):
        return [self[x] for x in range(i, j)]

    def __repr__(self):
        return "Ring({})".format(self._items)

This discards __getitem__ since it's no longer needed but keeps it similar to your code.

__iter__ could just delegate to itertools.cycle.

__getslice__ is deprecated and has been for ages. Let's consider doing this properly:

def __getitem__(self, idx):
    if isinstance(idx, slice):
        return ???

    return self._items[idx % len(self._items)]

What should ??? be? Well, we'd like something akin to

[self[i] for i in xrange(idx.start, idx.stop, idx.step)]

but start, stop or step might be None. We can say that start and stop should not be None (since both directions extend infinitely), but step can reasonably be asked to default to 1. Unfortunately, slice.indices isn't appropriate here, as with other tricks you can normally use.

Thus:

step = 1 if idx.step is None else idx.step
return [self[i] for i in xrange(idx.start, idx.stop, step)]

Now, __setitem__ probably has no good semantics for slice assignment because:

If a slice is larger than len(self._items), there is no obvious cannonical mapping on how to handle the assignment.
If a slice crosses through the start index (has idx % len(self._items) == 0) and assigns to a slice of a different size, there is no obvious way to decide where the new start is moved to.

You could restrict slice assignments to slices of the same size, and on slices no more than len(self._items) in size - but then you're not giving much bang for the buck. For this reason, I think __setitem__ and __delitem__ should remain as they are, operating only on integers.

However, _adj_index is not worth its cost. You could just implement them as

def __setitem__(self, idx, value):
    if not isinstance(idx, int):
        raise TypeError("Ring indices must be integers, not {}".format(type(idx)))

    self._items[idx % len(self._items)] = value

def __delitem__(self, idx):
    if not isinstance(idx, int):
        raise TypeError("Ring indices must be integers, not {}".format(type(idx)))

    del self._items[idx % len(self._items)]

(the error mirrors that of indexing lists).

In the scheme of things, this code is simpler, faster and contains not too much logical duplication. However, deduplication is nice, so one could merely add a _from_integer_index method:

def _from_integer_index(self, idx):
    if not isinstance(idx, int):
        raise TypeError("Ring indices must be integers, not {}".format(type(idx)))

    return idx % len(self._items)

def __getitem__(self, idx):
    if isinstance(idx, slice):
        step = 1 if idx.step is None else idx.step
        return [self[i] for i in xrange(idx.start, idx.stop, step)]

    return self._items[self._from_integer_index(idx)]

def __setitem__(self, idx, value):
    self._items[self._from_integer_index(idx)] = value

def __delitem__(self, idx):
    del self._items[self._from_integer_index(idx)]

In this case, wrapper methods do not seem to be the most appropriate solution to the problem.

This also allows checking for indexing 0-length rings.

All together:

import itertools

class Ring:
    """
    Ring datatype.
    """

    def __init__(self, items):
        self._items = list(items)

    def __iter__(self):
        return itertools.cycle(self._items)

    def _from_integer_index(self, idx):
        if not isinstance(idx, int):
            raise TypeError("Ring indices must be integers, not {}".format(type(idx)))

        if not len(self._items):
            raise IndexError("Indexing empty ring")

        return idx % len(self._items)

    def __getitem__(self, idx):
        if isinstance(idx, slice):
            step = 1 if idx.step is None else idx.step
            return [self[i] for i in xrange(idx.start, idx.stop, step)]

        return self._items[self._from_integer_index(idx)]

    def __setitem__(self, idx, value):
        self._items[self._from_integer_index(idx)] = value

    def __delitem__(self, idx):
        del self._items[self._from_integer_index(idx)]

    def __repr__(self):
        return "Ring({})".format(self._items)


Joining url path components intelligently I'm a little frustrated with the state of url parsing in python, although I sympathize with the challenges. Today I just needed a tool to join path parts and normalize slashes without accidentally losing other parts of the URL, so I wrote this:

from urlparse import urlsplit, urlunsplit

def url_path_join(*parts):
    """Join and normalize url path parts with a slash."""
    schemes, netlocs, paths, queries, fragments = zip(*(urlsplit(part) for part in parts))
    # Use the first value for everything but path. Join the path on '/'
    scheme   = next((x for x in schemes if x), '')
    netloc   = next((x for x in netlocs if x), '')
    path     = '/'.join(x.strip('/') for x in paths if x)
    query    = next((x for x in queries if x), '')
    fragment = next((x for x in fragments if x), '')
    return urlunsplit((scheme, netloc, path, query, fragment))

As you can see, it's not very DRY, but it does do what I need, which is this:

>>> url_path_join('https://example.org/fizz', 'buzz')
'https://example.org/fizz/buzz'

Another example:

>>> parts=['https://', 'http://www.example.org', '?fuzz=buzz']
>>> '/'.join([x.strip('/') for x in parts]) # Not sufficient
'https:/http://www.example.org/?fuzz=buzz'
>>> url_path_join(*parts)
'https://www.example.org?fuzz=buzz'

Can you recommend an approach that is readable without being even more repetitive and verbose?

I'd suggest the following improvements (in descending order of importance):

Extract your redundant generator expression to a function so it only occurs once. To preserve flexibility, introduce default as an optional parameter
This makes the comment redundant because first is a self-documenting name (you could call it first_or_default if you want to be more explicit), so you can remove that
Rephrase your docstring to make it more readable: normalize  and with a slash don't make sense together
PEP 8 suggests not to align variable assignments, so does Clean Code by Robert C. Martin. However, it's more important to be consistent within your project.

def url_path_join(*parts):
    """Normalize url parts and join them with a slash."""
    schemes, netlocs, paths, queries, fragments = zip(*(urlsplit(part) for part in parts))
    scheme = first(schemes)
    netloc = first(netlocs)
    path = '/'.join(x.strip('/') for x in paths if x)
    query = first(queries)
    fragment = first(fragments)
    return urlunsplit((scheme, netloc, path, query, fragment))

def first(sequence, default=''):
    return next((x for x in sequence if x), default)

If you're looking for something a bit more radical in nature, why not let first handle several sequences at once? (Note that unfortunately, you cannot combine default parameters with sequence-unpacking in Python 2.7, which has been fixed in Python 3.)

def url_path_join(*parts):
    """Normalize url parts and join them with a slash."""
    schemes, netlocs, paths, queries, fragments = zip(*(urlsplit(part) for part in parts))
    scheme, netloc, query, fragment = first_of_each(schemes, netlocs, queries, fragments)
    path = '/'.join(x.strip('/') for x in paths if x)
    return urlunsplit((scheme, netloc, path, query, fragment))

def first_of_each(*sequences):
    return (next((x for x in sequence if x), '') for sequence in sequences)


Sending n requests in one time I need to test my new functionality by sending about 100 requests in one time.

public class MyTest {
    // ...

    @Test
    public void test() throws Exception {
        Runnable[] runners = new Runnable[size];
        Thread[] threads = new Thread[size];

        for(int i=0; i<threads.length; i++) {
            runners[i] = new RequestThread(i);
        }

        for(int i=0; i<threads.length; i++) {
            threads[i] = new Thread(runners[i]);
        }

        for(int i=0; i<threads.length; i++) {
            threads[i].start();
        }

        while (!threadsAreDead(threads)) {}
    }

    private boolean threadsAreDead(Thread[] threads) {
        for(int i=0; i<threads.length; i++) {
            if (threads[i].isAlive()) return false;
        }

        return true;
    }
}

class RequestThread implements Runnable {
    public RequestThread(int id) {
        this.id = id;
    }

    @Override
    public void run() {
        try {
            b2b.execute(request);
        } catch (B2BException e) {
            // ...
        }
    }

}

Have you any idea how to optimize above code to send requests more 'in one time'?

Your test case looks relatively comprehensive in the sense that, yes, it fires off the 100 concurrent threads, but, you ask "how to make it more 'at the same time' ?"
There are two aspects I can suggest:

Use an ExecutorService
Use a CountDownLatch

ExecutorService
One of the novelties about the ExecutorService system is the concept of the Future, and it's foundation, the Callable class. The Callable interface is similar to the Runnable, except it can return a value, and throw an exception. These are two important differences.
The exception thrown in a Callable is trapped, and then re-thrown when the Future's get() method is called. This means that exceptions in remote threads can be collected in the calling thread.
In your case, throwing the exception is the most significant.
Consider the following code that sets up your threads appropriately:
@Test
public void test() throws Exception {
    ExecutorService threads = Executors.newFixedThreadPool(size);
    List<Callable<Boolean>> torun = new ArrayList<>(size);
    for (int i = 0; i < size; i++) {
        torun.add(new Callable<Integer>() {
            public Boolean call() throws B2BException {
                b2b.execute(request);
                return Boolean.TRUE;
            }
        });
    }

    // all tasks executed in different threads, at 'once'.
    List<Future<Boolean>> futures = threads.invokeAll(torun);

    // no more need for the threadpool
    threads.shutdown();
    // check the results of the tasks...throwing the first exception, if any.
    for (Future<Boolean> fut : futures) {
        fut.get();
    }

    //check the threadpool is now in fact complete
    if (!threads.isShutDown()) {
        // something went wrong... our accounting is off...
    }

}

OK, that is a better way of setting up the threads, and gets the exceptions to be thrown inside the test thread, rather than inside the remote threads.
CountDownLatch
If you are concerned that the threads should all be doing things more 'at the same time', and not worrying about start up time, etc. then consider using a count-down latch.
This device is set with a counter, and, when triggered, it will count down by one, and then lock, until all the counts are counted down.
You can use it in the above example code like:
@Test
public void test() throws Exception {
    ExecutorService threads = Executors.newFixedThreadPool(size);
    List<Callable<Boolean>> torun = new ArrayList<>(size);
    final CountDownLatch countdown = new CountDownLatch(size);
    for (int i = 0; i < size; i++) {
        toron.add(new Callable<Integer>() {
            public Boolean call() throws B2BException, InterruptedException {
                countdown.countDown();
                countdown.await();
                b2b.execute(request);
                return Boolean.TRUE;
            }
        });
    }

    // all tasks executed in different threads, at 'once'.
    List<Future<Boolean>> futures = threads.invokeAll(torun);

    // no more need for the threadpool
    threads.shutdown();
    // check the results of the tasks...throwing the first exception, if any.
    for (Future<Boolean> fut : futures) {
        fut.get();
    }

    //check the threadpool is now in fact complete
    if (!threads.isShutDown()) {
        // something went wrong... our accounting is off...
    }

}

The above system will set up all the threads, so they are all 'runnable', and then only when every thread is established and ready, will the locks be released.
You will still not get complete concurrent use, but it will/may be better having more threads start 'at once'.
Other....
You should consider using a custom ThreadFactory for the thread pool, like I suggested in this answer.


How can I speed up my IDA* algorithm for N-puzzle? I'm trying to solve the N-Puzzle problem using IDA* algorithm with a Manhattan heuristic. I already implemented the algorithm from the pseudocode in this Wikipedia page (link).
Here's my code so far :
class Node():
    def __init__(self, state, manhattan):
        self.state = state
        self.heuristic = manhattan

    def __str__(self):
        return f"state=\n{self.state}\nheuristic={int(self.heuristic)}"

    def __eq__(self, other):
        return np.array_equal(self.state, other.state)

def customSort(node):
    return node.heuristic

def nextnodes(node):
    zero = np.where(node.state == 0)

    y,x = zero
    y = int(y)
    x = int(x)

    directions = []
    if y > 0:
        directions.append((y - 1, x))
    if x > 0:
        directions.append((y, x - 1))
    if y < constant.SIZE2 - 1:
        directions.append((y + 1, x))
    if x < constant.SIZE2 - 1:
        directions.append((y, x + 1))

    arr = []
    for direction in directions:
        tmp = np.copy(node.state)
        goal = np.where(constant.GOAL_STATE == tmp[direction])

        tmp[direction], tmp[zero] = tmp[zero], tmp[direction]

        tile1_score = manhattan_distance(direction, goal)
        tile2_score = manhattan_distance(zero, goal)

        arr.append(Node(tmp, node.heuristic - tile1_score + tile2_score))

    arr.sort(key=customSort)

    return arr

def manhattan_distance(a, b):
    return abs(b[0] - a[0]) + abs(b[1] - a[1])

def count_distance(number, state1, state2):
    position1 = np.where(state1 == number)
    position2 = np.where(state2 == number)

    return manhattan_distance(position1, position2)

def manhattan_heuristic(state):
    distances = [count_distance(num, state, constant.GOAL_STATE) for num in constant.SIZE]
    return sum(distances)

def search(path, g, threshold):
    node = path[-1]
    f = g + node.heuristic

    if f > threshold:
        return f
    if np.array_equal(node.state, constant.GOAL_STATE):
        return True

    minimum = float('inf')
    for n in nextnodes(node):
        if n not in path:
            path.append(n)
            tmp = search(path, g + 1, threshold)
            if tmp == True:
                return True
            if tmp < minimum:
                minimum = tmp
            path.pop()

    return minimum

def solve(initial_state):path = solve(initial_state)
    initial_node = Node(initial_state, manhattan_heuristic(initial_state))
    threshold = initial_node.heuristic

    path = [initial_node]

    while 1:
        tmp = search(path, 0, threshold)
        if tmp == True:
            print(f"GOOD!")
            return path
        elif tmp == float('inf'):
            print(f"WRONG!")
            return False
        threshold = tmp

You can call the solve() function (and create some needed global variables) like this:
def define_goal_state(n):
    global GOAL_STATE
    global SIZE
    global SIZE2
    global ZERO

    m = [[0] * n for i in range(n)]
    dx, dy = [0, 1, 0, -1], [1, 0, -1, 0]
    x, y, c = 0, -1, 1
    for i in range(n + n - 2):
        for j in range((n + n - i) // 2):
            x += dx[i % 4]
            y += dy[i % 4]
            m[x][y] = c
            c += 1

    GOAL_STATE = np.array(m)
    SIZE = range(1, len(GOAL_STATE) ** 2)
    SIZE2 = len(GOAL_STATE)
    ZERO = np.where(GOAL_STATE == 0)

initial_state = np.array([8 7 3],[4 1 2],[0 5 6])
define_goal_state(len(initial_state))
path = solve(initial_state)

My implementation of the Wikipedia pseudocode is working and I get pretty fast results in a 8-Puzzle problem. But it gets really slow with a 15-Puzzle problem and above.
Regarding the solve() and the search() functions I think I respect almost identically the pseudocode. I also optimized my nextnodes() function to count only the tile that has been moved, not all tiles every time. Should be good here.
So where's the catch ? Why is my implementation taking so long ?
Does anyone have a clue ?

The code does not compile as it is:

The solve function's signature contains unnecessary code
def solve(initial_state):path = solve(initial_state)

A NumPy array cannot be initialized like np.array([8 7 3],[4 1 2],[0 5 6])
Globals are not initialized
constant.GOAL_STATE is not defined

Review

In the method search, checking if n not in path is an expensive operation that can be optimized using a set or a dictionary. This drops the runtime on my machine by 70%. A dictionary seems to be a good option since it keeps insertion order (if Python >= 3.7) and can be used as a queue.
manhattan_heuristic uses many times np.where, it can be optimized. An option is to iterate through the puzzle and when an element is different from the goal, calculate the difference. Converting GOAL_STATE to a dictionary will also improve the performance, instead of calling position1 = np.where(state1 == number) every time.
nextnodes also uses np.where two times which can be avoided. For example, instead of calling zero = np.where(node.state == 0) every time, Node can contain the coordinates of zero as a class property.
Naming: variable SIZE and SIZE2 are confusing because one is a generator and the other is the size of the puzzle. Consider giving more meaningful names.
Globals: try to reduce the use of globals as much as possible as it makes the code hard to test.

Note: this is not a comprehensive review, I think there is still room for improvements, I hope you will get more reviews.
Runtime after the improvements:

Puzzle
Original
Improved

3x3
0.696 s
0.097 s

4x4
7.021 s
0.549 s

Reworked code:
from time import perf_counter as pc

import numpy as np

GOAL_STATE = [[]]
GLOBAL_STATE_DICT = {}
N = 0

class Node:
    def __init__(self, state, manhattan, zero_pos):
        self.state = state
        self.heuristic = manhattan
        self.zero_pos = zero_pos

    def __str__(self):
        return f"state=\n{self.state}\nheuristic={int(self.heuristic)}"

    def __eq__(self, other):
        return np.array_equal(self.state, other.state)

    def __repr__(self):
        return f"state=\n{self.state}\nheuristic={int(self.heuristic)}"

    def __hash__(self):
        return hash(self.state.tobytes())

def customSort(node):
    return node.heuristic

def nextnodes(node):
    zero = node.zero_pos

    r, c = map(int, zero)
    directions = ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1))
    nodes = []
    for direction in directions:
        if 0 <= direction[0] < N and 0 <= direction[1] < N:
            tmp = np.copy(node.state)
            goal = GLOBAL_STATE_DICT[tmp[direction]]

            tmp[direction], tmp[zero] = tmp[zero], tmp[direction]

            dir_goal_distance = manhattan_distance(direction, goal)
            goal_zero_distance = manhattan_distance(goal, (r, c))

            nodes.append(Node(tmp, node.heuristic - dir_goal_distance + goal_zero_distance, direction))
    return sorted(nodes, key=customSort)

def manhattan_distance(a, b):
    return abs(b[0] - a[0]) + abs(b[1] - a[1])

def manhattan_heuristic(state):
    distance = 0
    for i in range(N):
        for j in range(N):
            num = state[i][j]
            if num != GOAL_STATE[i][j] and num != 0:
                goal = GLOBAL_STATE_DICT[num]
                distance += manhattan_distance((i, j), goal)
    return distance

def search(path, g, threshold):
    node = list(path.keys())[-1]

    f = g + node.heuristic

    if f > threshold:
        return f
    if np.array_equal(node.state, GOAL_STATE):
        return True

    minimum = float('inf')
    for n in nextnodes(node):
        if n not in path:
            path[n] = None
            tmp = search(path, g + 1, threshold)
            if tmp == True:
                return True
            if tmp < minimum:
                minimum = tmp
            path.popitem()

    return minimum

def solve(initial_state):
    zero = np.where(initial_state == 0)
    initial_node = Node(initial_state, manhattan_heuristic(initial_state), zero)
    threshold = initial_node.heuristic
    # The dictionary keeps insertion order since Python 3.7 so it can be used as a queue
    path = {initial_node: None}
    while 1:
        tmp = search(path, 0, threshold)
        if tmp == True:
            print("GOOD!")
            return path.keys()
        elif tmp == float('inf'):
            print("WRONG!")
            return False
        threshold = tmp

def define_goal_state(n):
    global GOAL_STATE
    global N
    global GLOBAL_STATE_DICT

    m = [[0] * n for i in range(n)]
    dx, dy = [0, 1, 0, -1], [1, 0, -1, 0]
    x, y, c = 0, -1, 1
    for i in range(n + n - 2):
        for j in range((n + n - i) // 2):
            x += dx[i % 4]
            y += dy[i % 4]
            m[x][y] = c
            c += 1

    GOAL_STATE = np.array(m)
    N = len(GOAL_STATE)
    GLOBAL_STATE_DICT = {m[r][c]: (r, c) for r in range(N) for c in range(N)}

tests = {'3x3': np.array([[8, 7, 3], [4, 1, 2], [0, 5, 6]]),
         '4x4': np.array([[13, 2, 10, 3],
                                [1, 12, 8, 4],
                                [5, 0, 9, 6],
                                [15, 14, 11, 7]])}

for name, puzzle in tests.items():
    define_goal_state(len(puzzle))
    print('Puzzle:\n', puzzle)
    t0 = pc()
    path = solve(puzzle)
    t1 = pc()
    print(f'{name} depth:{len(path)} runtime:{round(t1 - t0, 3)} s')


Function to store data in MySQL database (using OurSQL) I am parsing a huge XML file. It contains some million article entries like this one:

<article key="journals/cgf/HaeglerWAGM10" mdate="2010-11-12">
  <author>Simon Haegler</author>
  <author>Peter Wonka</author>
  <author>Stefan Müller Arisona</author>
  <author>Luc J. Van Gool</author>
  <author>Pascal Müller</author>
  <title>Grammar-based Encoding of Facades.</title>
  <pages>1479-1487</pages>
  <year>2010</year>
  <volume>29</volume>
  <journal>Comput. Graph. Forum</journal>
  <number>4</number>
  <ee>http://dx.doi.org/10.1111/j.1467-8659.2010.01745.x</ee>
  <url>db/journals/cgf/cgf29.html#HaeglerWAGM10</url>
</article>

I step through the file and parse those articles by LXML. If I let the code without storing the items into my database it makes some 1000 entries in ~3 seconds. But if I activate the storage which is done by the function below it makes some 10 entries per second. Is this normal? I remember parsing the file once upon a time and the database was not such a bottleneck. But I had a different approach... (looking through my files to find it)

def add_paper(paper, cursor):
    questionmarks = str(('?',)*len(paper)).replace("'", "") # produces (?, ?, ?, ... ,?) for oursql query
    keys, values = paper.keys(), paper.values()
    keys = str(tuple(keys)).replace("'", "") # produces (mdate, title, ... date, some_key)
    query_paper = '''INSERT INTO dblp2.papers {0} VALUES {1};'''.\
                    format(keys, questionmarks)
    values = tuple(v.encode('utf8') for v in values)
    cursor.execute(query_paper, values)
    paper_id = cursor.lastrowid
    return paper_id

def populate_database(paper, authors, cursor):
    paper_id = add_paper(paper, cursor)
    query_author ="""INSERT INTO dblp2.authors (name) VALUES (?) ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id)"""
    query_link_table = "INSERT INTO dblp2.author_paper (author_id, paper_id) VALUES (?, ?)"
    for author in authors:
        cursor.execute(query_author, (author.encode('utf8'),))
        author_id = cursor.lastrowid
        cursor.execute(query_link_table, (author_id, paper_id))

Edit:

I was able to narrow the problem to those three cursor.executes. Perhaps it is a database problem. I will ask over at Stack Overflow, if someone has an idea, why it is that slow. Meanwhile I would be interested if the code can be refactored to be more pythonic. Any ideas?

Edit 2:

If use a similar approach like me storing row per row into the database, don't use the InnoDB engine.  It's slower in orders of magnitude. The code is speeding up again, after I changed the engine.

You might want to try doing everything inside a transaction. It may be faster that way. I think with InnoDB you might be creating a committing a transaction for every statement which will be slow.

keys = str(tuple(keys)).replace("'", "")

That's an odd way of doing that, use

keys = '(%s)' % ','.join(keys)


Is there a more elegant way of arranging my forms? I'm a rather novice programmer who recently came up with a solution that works for my project, however I'm always looking for ways to improve my code.

So essentially, I have a settings form that pop's up and I was looking for a way to put it next to my main form but not covering it nor appearing partially off of the screen the main form is on.  I came up with this but it's not very dynamic because it only checks 4 different locations and if none of them work it uses the default, which is center screen.

Here is what I have:

private void Place_Form(Form formToPlaceNextTo, Form formToPlace)
    {
        Point alignRightTop = new Point(m_parent.Location.X + m_parent.Width, m_parent.Location.Y);
        Point alignRightBottom = new Point(m_parent.Location.X + m_parent.Width, (m_parent.Location.Y + m_parent.Height) - this.Height);
        Point alignLeftTop = new Point(m_parent.Location.X - this.Width, m_parent.Location.Y);
        Point alignLeftBottom = new Point(m_parent.Location.X - this.Width, (m_parent.Location.Y + m_parent.Height) - this.Height);

        if (Screen.FromControl(formToPlace).WorkingArea.Contains(new Rectangle(alignRightTop.X, alignRightTop.Y, this.Width, this.Height)))
        {
            this.Location = alignRightTop;
            return;
        }
        if (Screen.FromControl(formToPlace).WorkingArea.Contains(new Rectangle(alignRightBottom.X, alignRightBottom.Y, this.Width, this.Height)))
        {
            this.Location = alignRightBottom;
            return;
        }
        if (Screen.FromControl(formToPlace).WorkingArea.Contains(new Rectangle(alignLeftTop.X, alignLeftTop.Y, this.Width, this.Height)))
        {
            this.Location = alignLeftTop;
            return;
        }
        if (Screen.FromControl(formToPlace).WorkingArea.Contains(new Rectangle(alignLeftBottom.X, alignLeftBottom.Y, this.Width, this.Height)))
        {
            this.Location = alignLeftBottom;
            return;
        }
    }

Any suggestions or preferred coding techniques?

Addendum#1:  I agree that it's easier and probably more preferred to let the framework decide where to put forms, however this settings form changes the visual look of the main form and the default position of the settings form is almost directly on top of the main form.  This poses a problem in regards to user friendliness (in my eyes).

My bad, I think see now what you wanted. I just did not feel like reading your logic fully (too many details). After I did read it, I saw that you got the details right. All you needed was to stick your points into a list or enumerate over them, as in this example. This way, if you feel like adding more options - you can. Let me know if this works, so that I can delete the other answer.

private void Place_Form(Form formToPlaceNextTo, Form formToPlace)
{
    foreach (Point pointToTry in EnumerateFormPlacement(formToPlaceNextTo, formToPlace))
    {
        var rectToTry = new Rectangle(pointToTry.X, pointToTry.Y, formToPlace.Width, formtoPlace.Height);
        if (Screen.FromControl(formToPlace).WorkingArea.Contains(rectToTry))
        {
            formToPlace.Location = pointToTry;
            return;
        }
    }

    // Else no match, hence default location.
}

private IEnumerable<Point> EnumerateFormPlacement(Form formToPlaceNextTo, Form formToPlace)
{
    Point alignRightTop = new Point(
        formToPlaceNextTo.Location.X + formToPlaceNextTo.Width,
        formToPlaceNextTo.Location.Y);
    yield return alignRightTop;

    Point alignRightBottom = new Point(
        formToPlaceNextTo.Location.X + formToPlaceNextTo.Width,
        (formToPlaceNextTo.Location.Y + formToPlaceNextTo.Height) - formToPlace.Height);
    yield return alignRightBottom;

    Point alignLeftTop = new Point(
        formToPlaceNextTo.Location.X - formToPlace.Width,
        formToPlaceNextTo.Location.Y);
    yield return alignLeftTop;

    Point alignLeftBottom = new Point(
        formToPlaceNextTo.Location.X - formToPlace.Width,
        (formToPlaceNextTo.Location.Y + formToPlaceNextTo.Height) - formToPlace.Height);
    yield return alignLeftBottom;
}


Get list from database in 3 layer model I'm working on some testing project. For some reason I think I'm doing something wrong with the architecture. I have a simple example to show what I mean.

Database class

Imports DAO
Imports System.Data.SqlClient

Public Class PatientDB

    Dim connectionString As String = "Data Source=GSABBOZMAINPC;Initial Catalog=TestDB;Integrated Security=True"

    Public Function GetAllPatientFromDB() As List(Of PatientDAO)

        Using connection As New SqlConnection(connectionString)

            Dim list As New List(Of PatientDAO)

            Dim sqlString As String = "select * from patient ;"

            Using Command As New SqlCommand(sqlString, connection)

                connection.Open()

                Using reader As SqlDataReader = Command.ExecuteReader

                    While reader.Read

                        Dim firstName As String = reader("firstnamePT").ToString()

                        Dim Name As String = reader("naamPT").ToString()

                        Dim patient As New PatientDAO(Name, firstName)

                        list.Add(patient)

                    End While

                End Using

                Return list

            End Using

        End Using

    End Function

End Class

PatientDAO

Public Class PatientDAO

    Private _name As String
    Private _lastname As String

    Sub New(naam As String, lastname As String)

        _name = naam
        _lastname = lastname

    End Sub

    Public ReadOnly Property Name As String
        Get
            Return _name
        End Get
    End Property

    Public ReadOnly Property Lastname As String
        Get

            Return _lastname

        End Get
    End Property

End Class

Patient

Imports DAO
Imports database_layer

    Public Class Patient

        Property naam As String

        Property lastname As String

        Sub New()

        End Sub

        Sub New(_naam As String, _lastname As String)

            naam = _naam

            lastname = _lastname

        End Sub

        Public Sub New(patientDAO As PatientDAO)

            naam = patientDAO.Name
            lastname = patientDAO.Lastname

        End Sub

        Public Function GetDO() As PatientDAO

            Return New PatientDAO(naam, lastname)

        End Function

        Public Function getAllPatientsInList() As List(Of Patient)

            Dim list As New List(Of Patient)
            Dim database As New PatientDB

            For Each PatientDAO As PatientDAO In database.GetAllPatientFromDB()

                Dim patient As New Patient(PatientDAO)
                list.Add(patient)
            Next

            Return list

        End Function

        Public Overrides Function ToString() As String
            Return naam + " " + lastname
        End Function

    End Class

In this example I'm using Windows form. When the form is loaded I use the following event:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load

    Dim patient As New Patient

    For Each item As Patient In patient.getAllPatientsInList()

        list.Add(item)

    Next

End Sub

Should I use Dim patient As New Patient with an empty constructor like this example or should I approach this another way? And are there other suggestions you think would improve the architecture of this example?

Well, you were right to think you are wrong.  We shouldn't need to instantiate an object with an empty constructor to something like this.  This is exactly what the Shared keyword is for.

First, make your getAllPatientsInList function Shared:

Public Shared Function GetAllPatients() As List(Of Patient)
    ' method implementation
End Function

And now we can call the method without instantiating an instance of the class:

For Each item as Patient in Patient.GetAllPatients()
    ' do something with item
Next

And once we've done this, arguably, we may want to eliminate the default, zero-argument constructor.


Checking if a set of checkboxes have a certain number of options checked I'm coding a jQuery plugin that basically checks if a set of checkboxes groups have at least x options checked. A checkbox group is named as name=group[]. You'd call the plugin like:

$(':checkbox').checkpass({min: 1}) // Make sure at least one checkbox per group is checked

I've been working on this piece of code for a couple days trying to make it as short and fast as possible because I'm going to implement this on a very large form.  Is it possible to make it shorter/faster, or have I reached the limit?

You can check a live example here.

(function($) {
    $.fn.checkpass = function(options) {

        var opt = $.extend({
            min: function() {
                return (min === 'undefined') ? 1 : min;
            },
            errorContainer: '
',
            errorWrap: '
'
        }, options);

        var $ckboxes = this,
            names = [],
            num = 0,
            $errors = $(opt.errorContainer);

        $ckboxes.each(function() {
            var name = this.name;
            if (!~$.inArray(name, names)) {
                names.push(name);
            }
        });

        for (var i = 0, l = names.length; i < l; i++) {
            $checked = $ckboxes.filter('[name="' + names[i] + '"]:checked');
            if ($checked[opt.min - 1]) {
                num++;
            } else {
                if (opt.min > 0) {
                    var $err = $(opt.errorWrap),
                        _remaining = opt.min - $checked.length,
                        _name = names[i].match(/\w+/).toString()
                                .replace(/^\w/, function($0) {
                                    return $0.toUpperCase();
                                });
                    $err.html('' + _name +
                              ': Check ' +
                              _remaining + ' more.').appendTo($errors);
                }
            }
        }

        return {
            isValid: !! (num === names.length),
            errors: $errors
        };
    };
})(jQuery);

Instead of using an array for names, you could use some implementation of a set, which automatically skips duplications; see here.

Instead of keeping the num variable, I would just check if errors is empty to set isValid.

Actually, you can combine both suggestions by replacing names by an object that stores the unique names associated with their respective error message (or null if it passes).

{"animals[]" : someErrorMessage,  "drinks[]" : null, "colors[]" : someOtherErrorMessage}

You would need to replace your for-loop by a for (name in names) and you would only check if there is not enough check marks and add an error if that's the case.

I played with your fiddle and made a fork:

(function($) {
    $.fn.isIncomplete = function(options) {

        var opt = $.extend({
            min: function() {
                return (min === 'undefined') ? 1 : min;
            }
        }, options);

        var $ckboxes = this;
        var names = {};

        $ckboxes.each(function() {
            names[this.name] = null;
        });

        var errors = [];
        for (name in names) {
            var $checked = $ckboxes.filter('[name="' + name + '"]:checked');
            if ($checked.length < opt.min) {
                isValid = false;
                var _remaining = opt.min - $checked.length;
                var _name = name.match(/\w+/).toString().replace(/^\w/, function($0) {
                    return $0.toUpperCase();
                });
                errors.push('<strong>' + _name + ':</strong> Check ' + _remaining + ' more.');
            }
        }

        if (errors.length == 0) return null;
        else return errors;
    };
})(jQuery);

// Testing...
$('button').click(function() {
    var incompleteErrors = $(':checkbox').isIncomplete({
        min: 1
    });
    if (incompleteErrors) {
        ul = $('<ul>');
        for (var i = 0; i < incompleteErrors.length; i++)
        ul.append($('<li>').html(incompleteErrors[i]));
        $("#errors").html(ul);
    } else {
        $("#errors").html("");
        alert('Passed!');
    }
});


Printing heads of stand-alone lists Please review my code to help improve its quality.

public void printHeadOfNonIntersectingLinkedList(List<Standalone> listStandalones) {
    final Map<Node, Node> tailHeads = new HashMap<Node, Node>();

    for (Standalone ll : listStandalones) {
        Node temp = ll.first;
        while (temp.next != null) {
            temp = temp.next;
        }
        if (tailHeads.containsKey(temp)) {
            tailHeads.put(temp, null);
        } else {
            tailHeads.put(temp, ll.first);
        }
    }

    for (Entry<Node, Node> entry : tailHeads.entrySet()) {
        if (entry.getValue() != null) {
            System.out.println(entry.getValue().element);
        }
    }
}

First of all, you have provided very little context for your code. Therefore, my criticism may not be valid in the context of your full program.

Second, you have not a single comment in your code. One can argue that code does not need comments once it is self-documenting. But your code does not achieve that.

Your method does not use any variables defined outside of your function. This shows that

… it should be marked as static – it clearly does not operate on an instance of the class where this function is defined.
… Static methods can be an indication that your code is not object oriented. It may need to be redesigned.
… You do operate on an object: List<Standalone>. Maybe that should be a class of its own, and this method be an instance method over there.

printHeadOfNonIntersectingLinkedList is far to long as a name. I know that Java code has the tendency to prefer such long names, but you are not doing anyone a favour with that. In addition:

The name does not match the behaviour of the method. Doesn't it print the heads belonging to unique tails of linked lists? The lists itself may intersect.
The name tells us that this method is doing too many unrelated things. It needs to be refactored. The different parts are: finding the tails of all lists, deduplicating the nodes, and printing them out.

List<Standalone> – why not Iterable<Standalone>? There is no need to be extra specific, and all we do is call an implicit .iterator() on it.
+1 for using final, although you could designate the loop variables as final as well.
tailHeads is a confusing name. seenTails might be better.
ll is a bad name. Avoid short names, especially abbreviations. Exceptions to this rule are integer loop variables (i, j, …) and domain-specific code where not using common abbreviations would be more confusing. Examples would be highly mathematical (e.g. cryptographic) code. In this case, linkedList could be a better choice.
Finding the last element in a list is an implementation detail, and should be encapsulated in the Standalone class – it doesn't seem to be very “standalone” after all. If you didn't write that class: Subclass it and implement these helpers there.

final Node tail = linkedList.tail();

The next part makes a lot of sense, and can't be written any better. But it is crucial to use comments to tell a reader what you are doing here:

// If that tail is already known, mark it as seen,
// but unwanted with a null.
if (seenTails.containsKey(tail)) {
    seenTails.put(tail, null);
} ...

Using .entrySet() is a bit akward, considering that you are only interested in the values. Why not for (final Node head : seenTails.values()) { ... }?
Let another method do the printing – just return a collection or iterator of the values of each head, and be done with it.

Here is my take on making that code more self-documenting, heeding some of my above criticism. Untested.

class Standalone {
  private Node head;  // proper encapsulation
  private NodeValue element;
  ...

  public Node head() {
    return head;
  }

  // you might want to cache this
  public Node tail() {
    // handle zero-length lists
    if (head == null)
      return null;

    // find and return last element
    Node pointer = head;
    while (pointer.next != null)
      pointer = pointer.next;
    return pointer;
  }

  public NodeValue element() {
    return element;
  }

  public static Iterable<Standalone> withUniqueTails(Iterable<Standalone> standaloneCollection) {
    final HashMap<Node, Standalone> uniqueTails = new HashMap<Node, Node>();
    final HashSet<Node>             duplicates  = new HashSet<Node>();

    for (final Standalone list : standaloneCollection) {
      final Node tail = list.tail();
      if (duplicates.contains(tail)
        continue;
      if (uniqueTails.containsKey(tail)) {
        uniqueTails.remove(tail);
        duplicates.add(tail);
      } else {
        uniqueTails.put(tail, list)
      }
    }

    return uniqueTails.values();
  }
}

Calling code could be like

for(final Standalone standalone : Standalone.withUniqueTails(someStandalones)) {
  System.out.println(standalone.head().element());
}

Do you notice something? The method is actually just a filter that skips over some values (we could lift this kind of code to all kinds of iterator transformation strategies). And this is the only thing my version of that method does. If you need a wrapper that extracts the head values, you can write it, without having to concern yourself with filtering out unwanted values.

If you need a helper that prints out each element in some iterable one line at a time, you can write that too. Make it private to reduce the shame.

private static <T> void printCollection(OutputStream stream, Iterable<T> collection) {
  for(final T item : collection)
    stream.println(item);
}

Update:

Programming is a game of tradeoffs. We can optimize along axes of readability, theoretical elegance, memory usage, speed, and sometimes other resources like network requests. If in doubt, it is advisable to optimize for readability.

In my suggested rewrite, I introduced duplicates mostly in order to make the code more self-documenting: If a duplicate node is detected, then it is literally removed from the unique nodes, and added to the duplicates. I avoided the (otherwise completely legitimate) use of null as a special value.  This intends to make the code simpler to understand.

We can estimate the performance characteristics of introducing another data structure.

Space

First, memory usage. The worst case scenario is that our input data is unique throughout the first half of the input, then repeats one or more times: A, B, C, ..., Z, A, B, C, ..., Z, where the number of elements n is chosen in a way that it forces a resizing of the hash table.

After that code has been filtered, we find zero elements in uniqueTails, because all were duplicates. That data structure has capacity for (n-1)*2 elements (hash table size is doubled when a certain load factor is reached). We have n elements in duplicates, which also has size for (n-1)*2 elements. Thus in the worst case, we have allocated 2× as much memory as neccessary. But if one of those elements is unique, we can avoid the table size doubling in duplicates, thus using only 1.5× as much memory. If the duplicates are adjacent (A, A, B, B), then the uniqeTails never grow (best case scenario).

Depending on the exact numbers of unique duplicate elements, the acceptable load factor, and the longest streak of unique elements, we can get anything from 1× to 2× the memory usage (plus overhead), but will rather stay at the lower end of that range. I consider this acceptable for most scenarios.

Time

The addition of another data structure comes at the cost of more recalculations of the hash. The hash code must be calculated for contains, containsKey, remove, add, put. Per element, a 1–4 calculations can occur in my code. Your original code does this in always exactly 2 calculations. Only when a key occurs more than eight times, less recalculations occur.

Summary: My code will quite certainly perform worse – but it was never tuned for performance. By all means, use tricks like null pointers as special values to express an extra level of information. But if you do so, document it with a comment (you'll note that I did exactly that in the main part of my review).


Simplify a Unix-style absolute path I have a match arm in rust, I think it may be simplified, but after googling and read books, I haven't find the solution. Especially for the str_vec.pop(), it returns an option type, I have to write a meanless () to make it compileable.
pub fn simplify_path(path: &String) -> String {
    let mut str_vec: Vec<&str> = Vec::with_capacity(20);
    for line in path.split('/') {
        match line {
            "" | "." => {}
            ".." => {
                str_vec.pop();
                ()
            }
            _ => str_vec.push(line),
        }
    }

    "/".to_string() + &str_vec.join("/")
}

The () is not needed in this example - the following example compiles fine.
match line {
    "" | "." => {}
    ".." => {
        str_vec.pop();
    }
    _ => str_vec.push(line),
}

This is as all arms need to return the same type, and in this case it is the type (). Luckily this type is inferred, and as such you can just make a block and (as long as it doesn't return anything), it will be inferred that the () type is being returned instead.
I would recommend making some other changes to your code though - namely changing the &String argument to &str, which can improve performance in some cases and allow more string types (such as a string literal) to be passed to the function. This type of issue can be picked up by running clippy, which also picks up a wide variety of issues - a full list can be found at https://rust-lang.github.io/rust-clippy/master/.


Use async/await to implement mutual exclusion in JavaScript I needed to execute a sequence of async tasks in JavaScript. They are async because I need them to be non-blocking, but I still want the current task to end before starting the next one.
The order of tasks doesn't matter, the only important thing is that they are in mutual exclusion with each other.
For this reason, maybe because of C/C++ background, I was about to implement a queue and a system of locks. Then I stop to think if the problem could be solved just using async/await, and I ended up with this solution:
previousPromise = null;

async function enqueue(task) {
  while (previousPromise) {
    await previousPromise;
  }

  previousPromise = executeTask(task);
  await previousPromise;
  previousPromise = null;
}

In practice, I use the promise subscribers internal queue as the lock queue, in order to achieve a non-blocking wait. When the promise resolves, it awakes all the async tasks† and the first finding previousPromise equals to null will continue.
Here is a codepen example.
Is there any problem in this solution?
Thank you

Side note 1: a real lock system is obviously not needed. JavaScript is single-threaded, so there isn't any risk to be preempted after the while and before executeTask assignment.

Side note 2: the tasks arrive from the server in an asynchronous fashion, so I can't collect them all before executing.

† It actually calls the first callback in the subscriber's list

This loop:
async function enqueue(task) {
  while (previousPromise) {
    await previousPromise;
  }

will (asynchronously) block forever, after the first time previousPromise has been assigned to. An expression which is a Promise (for example, the previousPromise) will always remain a Promise, and will be truthy. You can use await previousPromise to extract its resolve value into a different expression, but the previousPromise remains a Promise. No more than two tasks can be completed using that enqueue.
A better method would be to reassign the Promise every time enqueue is called, while chaining onto the previous Promise with a .then:
previousPromise = previousPromise.then(() => executeTask(task));

It'll also be easier to manage if the previousPromise stays the same shape (that is, of a Promise), rather than having to manage it possibly being null. Initialize it to Promise.resolve().
Demo below, where a task takes 1 second: it starts 2 tasks immediately, then 2 more tasks after 1.5 seconds (so these 4 together finish after 4 seconds), then another after 7 seconds (which finishes on second 8).

const executeTask = () => new Promise(resolve => setTimeout(() => {
  console.log('task resolving');
  resolve();
}, 1000));
let previousPromise = Promise.resolve();

function enqueue(task) {
  previousPromise = previousPromise.then(() => executeTask(task));
}

console.log('start');
enqueue();
enqueue();
setTimeout(() => {
  enqueue();
  enqueue();
}, 1500);
setTimeout(() => {
  enqueue();
}, 7000);

Another thing to consider is: what do you want to occur when one of the tasks rejects (if that's ever a possibility)? You might want to add on a .catch onto the end of executeTask to make sure the next task can be started, without the whole Promise chain breaking:
previousPromise = previousPromise
  .then(() => executeTask(task))
  .catch((err) => { /* log error? Make sure previousPromise always resolves */ });


Is there something wrong with my remove-duplicates implementation in Scheme? For an assignment I handed in this code to remove duplicates from a stream.

 (define (remove-duplicate lst)
  (cond ((stream-null? lst) '())
        ((not (member-stream? (stream-car lst) (stream-cdr lst)))
         (cons-stream (stream-car lst) (remove-duplicate (stream-cdr lst))))
        (else (remove-duplicate (stream-cdr lst)))))

(define (member-stream? item x)
  (cond ((stream-null? x) #f)
        ((eq? item (stream-car x)) x)
        (else (mems item (stream-cdr x)))))

Appearantly this isn't an ideal way to do this, but I can't see why. I tested it with a stream of numbers, and it correctly removed the duplicates and returned a stream.

stream-cons, stream-car, stream-cdr and stream-null are defined in the SICP book.

It's not enough for your code to "work"; it also must work well. In particular, your code materialises the whole stream at the outset, which defeats the purpose of using a stream in the first place.

Instead of checking whether the current element exists in the rest of the stream, check whether the current element has already been seen. Yes, you have to keep track of the seen elements (preferably via a set, but if your Scheme implementation doesn't have that, a list will do in a pinch), but it will mean that your stream will continue to be a stream, rather than just be a glorified list.

Here's an implementation of the concept using lists to track the seen elements (I used SRFI 41 streams instead of SICP streams, since that's what I'm familiar with):

(define (unique-stream str)
  (stream-let recur ((seen '())
                     (str str))
    (if (stream-null? str)
        stream-null
        (let ((item (stream-car str)))
          (if (memv item seen)
              (recur seen (stream-cdr str))
              (stream-cons item (recur (cons item seen) (stream-cdr str))))))))