how to get variable names at runtime?

Question: The use case is this:
public void testMethod(String para1, String para2, String para3){

 if(para1==null){
         System.out.println("para1 cannot be null");

   }
 if(para2)...
}

As the check null code above, we will be repeating ourselvous on writing the same code to check every parameter. But we cannot really factor out a common method, say, checknull(String para), because we need to output the name of the parameter so the users know which one is wrong.
Maybe there is no way to do this in java I guess. Method parameter names should be gone after compile if I understand it correctly.
So, how do you guys usually address this problem?
Comment: Forgot to say that, yes, we can factor out a common method which takes the parameter name and the value. But thats not what I really want here.

I am thinking with Java6's built in script engine, there might be someone who have solved this in a novle way.

Thanks!
Comment: A novel solution isn't always the best solution, especially for maintainability purposes.
Comment: Do it the hard, boring way.  It is the simplest way to tell maintainers of the code that you do not want nulls.
Comment: What did you end up going with?
Answer: It's put in the message. No other way to do it. And no, you can't get the variable name.
I suggest you consider using Java's assert feature, which is highly-underused. It can be quite concise too:
public void testMethod(String para1, String para2, String para3) {
  assert para1 != null : "para1 is null";
  assert para2 != null : "para2 is null";
  assert para3 != null : "para3 is null";
}

You just need to enable assertions in the VM with the -ea parameter. That's another advantage: you can turn them on or off as a runtime option.
It should be noted that the above will generate an AssertionError, which is an Error (in the Java sense), so won't be caught by a catch (Exception e) block. So they should be used for conditions that really aren't recoverable or things that should never happen.
Generally if a user breaks the contract (by passing in a null when they shouldn't, for example) then an appropriate RuntimeException may be better.
Comment: the null check should always be in there (in my opinion).  As asserts can be disabled, this most likely means that they will BE disabled when you really need them - in a rare production scenario.
Comment: With this approach you should assure that the parameter checking is not part of needed logic of your application (I think you don't want your application works in a different way according a JVM parameter)
Comment: not recomended by SUN: "Do not use assertions for argument checking in public methods." http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html
Answer: If you want to check the value of a variable at run time, you can use reflection to check the instantiated objects fields like this:
package sandbox;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class ReflectionClassChecker {

    public static boolean checkAllPublic(Object someObject){
        System.out.println("Checking someObject " + someObject.toString());
        boolean hasNulls = false;

        Class<?> c = someObject.getClass();

        Field[] fields = c.getFields();

        for(Field field: fields){
            System.out.println("Checking field " + field.getName() + ".");
            if(isFieldPublic(field)){
                System.out.println("Field " + field.getName() + " is public, checking it for null.");
                Object value = getField(field, someObject) ;
                if(value == null){
                    System.out.println("Field " + field.getName() + " is null.");
                    hasNulls = true;
                } else {
                    System.out.println("Field " + field + " has value " + value );
                }
            }
        }

        return hasNulls;
    }

    private static boolean isFieldPublic(Field field){
        int modifiers = field.getModifiers();
        boolean isPublic = Modifier.isPublic(modifiers);
        return isPublic;
    }

    private static Object getField(Field field, Object someObject){
        Object value = null;
        try{
            value = field.get(someObject);
        } catch (IllegalAccessException ignore){
            System.out.println(ignore);
        }
        return value;
    }
}

You can easily go from this implementation to one which uses getter/setter method invocations to check the value of inaccessible fields. If you want something less generic, or you want something which only checks specific fields, you can use c.getField(String) to get just that field, and then call field.get(object) for just that field.
Answer: I believe that Java 7 will have standard annotations requiring that a given parameter cannot be null.  Unfortunately I have not seen these annotation for Java 6 or earlier :(
Answer: Use the varargs notation in Java 1.5 .  Declare your arguments as "Object... objects" and loop thru the collection.
public static void printSpaced(Object... objects)
{
   for (Object o : objects) {
        System.out.print(o + ":");
                if ( o == "x" ) {
                        System.out.print ("x found");
                }
        }
}
Comment: "But we cannot really factor out a common method, say, checknull(String para), because we need to output the name of the parameter so the users know which one is wrong."
Answer: What I do is similar to what you have, except I throw a NullPointerException (per Effective Java, personally, I'd have preferred IllegalArgumentException).
...
if (para1 == null) {
    throw new NullPointerException("para1 cannot be null");
}
...

If you want to refactor it out to a method, you could do something along the lines of:
assertNotNull(Object param, String paramName) {...}

Comment: Thats pretty much what I did in the end. I reckon with normal java we couldnt do better than that, couldnt we.
Comment: I dislike NullPointerExceptions - they should in my opinion only be thrown by the JVM, not by user code.  IllegalArgumetnException("para1 == null") is what  I do.
Answer: Why don't you pass them along as a map? This way you could have a key representing the name of the variable and a value representing the actual String variable.
Answer: Although it may be overkill, I guess it is also worth mentioning that you could check your arguments using a 3rd party design by contract framework. The Java implementations seem to rely on doclet comments or annotations to specify the rules. I've only taken a cursory look at them, so I can't recommend any one in particular.
Answer: Hmm, even if you could dynamically get the parameter names, I don't see that there would be much benefit. It's not that tough to write:
checkNull("parm1", parm1);
checkNull("parm2", parm2);
checkNull("parm3", parm3);

By the way, I hope this is just example code, and you don't REALLY call your parameters parm1, parm2, and parm3, but something more meaningful like customerName, balanceDue, and accountType.
And once you say that, it should quickly become apparent that in a real application, the validation requirements for each parameter will likely be different. customerName should not be null, but it probably also should not be an empty string. balanceDue should contain only digits and at most one decimal point and possibly a leading minus sign. Etc. So you can't just loop through all your parameters performing the same validation on each, rather you must do the appropriate validation for each.
Unless you have dozens of parameters, the code to write a loop would be almost as much trouble as just writing several calls to a common validation function anyway. And if you have dozens of parameters, this is usually a bad thing of itself.
Answer: I haven't used it, but Paranamer can give you runtime access to parameter names (at the cost of requiring debug info in code and using reflection to get parameter names).  This is almost certainly overkill for your problem however.
Also note that the FindBugs and JSR305 annotations (the latter should make it to Java7, but can be used now with FindBugs and downloaded from the FindBugs site or Maven distribution) can be used in Java5 and above, to provide some level of compile-time checking of parameter nullness.  I think that this is nice, and provides at least good documentation (as well as catching some errors), but is definitely not the same as a runtime check (which should catch all such errors, albeit only at runtime), and so as such is not a replacement (though perhaps you could write an AspectJ aspect that validated the parameters to methods with such annotations).
Answer: Use an annotation on the param and add a dynamic proxy (either Java 4 style of CGLIB) to do the check See link text on how to use CGLIB

how to get variable names at runtime?


Where can I find low profile stopcock handles?

Question: I have a stopcock/isolation valve to the outdoor tap in the kitchen, it's located in a kitchen cupboard but unfortunately the distance between the shelf and the valve isn't big enough to turn the handle.
It's a lot like this one but I'm not 100% if it's exactly the same, it's brass with a similar style handle and has the screw in the middle.

I was wondering if you can get replacement handles that are lower profile? I've tried googling low profile stopcock handle and not found any results, or if a low profile one doesn't exist can you get a sliding handle so you turn it half way, slide the bar to the other side and turn it again?
Any help would be appreciated.
Comment: Can you get a picture of the unit in situ. It's hard to tell from just the description quite how this doesn't fit & more importantly, what type of tap it is. The one pictured would seem to be a multi-revolution, that effectively screws up out of a sealed socket to open. Alternatives are simple 90° mechanisms. [Both answers so far seem to be assuming 90°]
Comment: I'll get one tonight, was at work when I wrote the question.  It is a multi-revolution type device hence the handle is bumping up against the shelf inside the cupboard.
Comment: OK. I guess the trick will be to swap to a 90° one then, as mentioned below, then you can get a bigger handle, better leverage, but only have to swing it 90° between fully on & off, so you can pick which 90° is easiest without it banging into the shelf.
Comment: That might not work out so well either, the picture will make it clearer but there is only a small hole to let the shaft through the back of the cupboard, replacing the whole valve will either involve cutting a big hole in the back of the cupboard or some very costly work removing a quartz worktop that I don't want to do.  Sorry for not putting a picture up in the first place.
Answer: Without knowing more of your circumstances, some suggestions.

Remove the screw at the top and you can remove the handle and shift it.
Remove the handle, cut the shaft and put the handle back on.
Turn the tap sideways or upside down
Use a valve like this
Answer: If you undo the screw and remove the handle there will be a square end on the shaft,  turn it with a wrench or cut one end off the handle and use that as a wrench,
Alternatively you could cut a slot in the shelf to allow the handle to be turned.
Many kitchen cabinets have adjustable shelves. maybe you can lift or remove the shelf to make room to operate the valve.
Comment: If it is a small square end then I may have a socket I can put on a ratcheting screwdriver.  I'll take the picture and the end off the handle at the same time and see.
Comment: The first part of this is very interesting, if I could use a wrench to turn it multiple times that woudl be great.  I will give this a go and if it works, mark this as the answer.  No cost which is even better.
Comment: Matt - see my comment above - you need to change the tap to do this, swinging a spanner 42 times to get the full open/closed cycle will be a nuisance.
Comment: Let's hope the handle comes off. Mine doesn't. The ratchet spanner ought to be the one, in that case.
Comment: @Tetsujin there's a trade-off between disassembing the built-in furniture to replace the valve and the valve being hard to operate,.
Answer:
Don't shop for a product like this online - you can't really get a feel for quality and size (dimensions may be measured in strange ways you don't expect) from pictures and descriptions on a web page. Not a problem for a straight replacement, big problem when you are trying to find something "different".

Assuming you already tried your local big box (Home Depot, Lowes, etc.) and didn't find anything, your next stop is the local corner hardware store. If you still have one. I used to have two - one 2 blocks away from home, the other 2 blocks away from my office - both long gone. This is the kind of place where they know all the usual parts for the neighborhood homes, they save everything so they'll have parts that haven't sold in 20 years and know exactly where to find them in the seemingly incomprehensible piles, etc.

And last, but definitely not least, find out where the plumbers go to get their parts. Many plumbers will now get many things at big box stores due to convenience and pricing, but they all have a place to go for the more unusual stuff, better pricing on a lot of the common stuff, special orders, etc. These places won't be in big shopping malls, but every city has them somewhere. They may charge a homeowner more than a regular plumber who comes in twice a week to stock their truck, but most will be happy to sell you the strange parts that you can't get at the big box stores.


Django Error: 'utf-8' codec can't decode byte when trying to create downloadable file

Question: I have created an app, to do some process and zip some files. Now I need to make the zip file downloadable for users, so they can download the zip file.
I am working with Django and here is the in views.py:
def download(request):
    context = {}
if request.method == 'POST':
    if form.is_valid():
        userInput = form.cleaned_data['userInput']
        createFiles(userInput)

        filename = 'reports.zip'
        filepath = '/home/download/'

        fl = open(filepath, 'r')
        mime_type, _ = mimetypes.guess_type(filepath)

        response = HttpResponse(fl, content_type=mime_type)
        response['Content-Disposition'] = "attachment; filename=%s" % filename
        return response
return render(request, 'download.html', context)

But I am getting an error:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x83 in position 11: invalid start byte

Which is breaking on this line:
response = HttpResponse(fl, content_type=mime_type)

Any suggestions how to fix this?
Answer: I would guess, that you should open the zip file with 'rb' flags (binary).
Here's a sample from my working code:
zip_fullpath = os.path.join(zip_path, zip_filename)
zip_file = open(zip_fullpath, 'rb')
resp = FileResponse(
    zip_file,
    content_type="application/force-download"
)
resp['Content-Disposition'] = 'attachment; filename=%s' % zip_filename
os.remove(zip_fullpath)
return resp


Slow Loading of Large MongoDB Database in Node JS

Question: I have created a webpage with Node JS, Express JS, Mongoose and D3 JS.
In the webpage, it contains 3 pull down menus: Department, Employee, Week.
The usage of the webpage is as follows:

When 'Department' is selected, 'Employee' menu will be filtered to show only those from the selected 'Department'. The same goes to 'Week' after 'Employee' is selected.
After the 3 menus are selected and 'PLOT' button is clicked, a line chart (using d3.js) will be plotted to show the employee working hours for the month.

MongoDB Json
{ dep: '1',
  emp: 'Mr A',
  week: 1,
  hrs: [{
          {1,8},
          {2,10},
          ...
       }]
}

Here are the snippets of my codes:
routes.js
// Connect the required database and collection
var dataAll = require('./models/dataModel');

module.exports = function(app) {

app.get('/api/data', function(req, res) {
    dataAll.find({}, {}, function(err, dataRes) {
        res.json(dataRes);
    });
}

app.get('*', function(req,res) {
    res.sendfile('./index.html');
}
}

index.html
... // More codes

...

... // More codes

display.js
//Menu (Department,Employee,Week) Information is gathered here

queue()
.defer(d3.json, "/api/data")
.await(createPlot);

function createPlot(error, plotData) {
var myData = plotData;

var depData = d3.nest()
        .key(function(d) {return d.dep;})
        .rollup(function(v) {return v.length;})
        .entries(myData);

selectField1 = d3.select('#menuSelect1')
        .append("select")
        .on("change", menu1change)
        .selectAll(depData)
        .enter()
        .append("option")
        .attr("value", function(d) {return d.key;})
        .text(function(d) {return d.key;});

function menu1Change() {
    //Filter Next Menu with the option chosen in this menu
    ... // More codes
    var selectedVal = this.options[this.selectedIndex].value;
    var empData = dataSet.filter(function(d) { return d.emp = selectString; });
    ... // More codes
}
... // More codes

}
Problem:
Functionally, it is working as expected. Problem is when the database is getting larger and larger, the loading of the page becomes very very slow (mins to load). I believe it should be due to the routing where all data is retrieved (.find({},{})) but I thought I need it because I am using it in 'display.js' to filter my menu options.
Is there a better way to do this to resolve the performance issue?
Answer: It is rarely necessary to send all the data to the client. In fact, I haven't seen an API with a single endpoint that returns the entire database to everyone.
It's hard to give you any specific solution not knowing how your data looks like, how large it is, how fast it grows etc. The performance issues may be related to querying the database, to large data transfer, or large JSON to parse by the browser.
In any case, you shouldn't send all your database to the client with no limits. Usually it is implemented with a number of records to skip and a maximum number of records to return.
Some frameworks like LoopBack does it for you, see:

https://docs.strongloop.com/display/public/LB/Skip+filter
https://docs.strongloop.com/display/public/LB/Limit+filter

If you're using Express then you'll have to implement the limits yourself.
To test the bottleneck, you can run the Mongo shell and try to run the .find({},{}) query from there to see how long it takes. You can see the transfer size and time in the browser's developer tools. This may find you narrow down the place that needs most attention, but returning the entire database no matter how large it is, is already a good place to start.
Comment: Sorry, have added the JSON data example,Yes, I have already used the debugger in browser and the bottle neck is indeed returning the entire database.
Comment: Are there any other methods to get the required Dep, Emp, Mth data to insert into the pulldown menu if I don't get the whole database?


I would like to resolve when recv function doesn't return 0 when tcpip is disconnected

Question: Is there a case that recv function doesn't return 0 when tcpip is disconnected physicially? There is no calling return 0. So, Tcpip is no closed. What should I do to resolve this issue?
Answer: Recv returns 0 only if TCP connection is closed explicitly by remote side.
Another cases of disconnect:

If TCP connection is explicitly broken (TCP RST or ICMP unreachable packet received) then you can get error when read from the socket.
If transit network goes down or remote host disappears then:

if timeout explicitly specified then read waits and return timeout error
if timeout is not specified then read waits maximum timeout (depends on system for Linux it is about 2 hours)

In last case you may:

Try to enable keepalive requests on socket (SO_KEEPALIVE socket options)
Do keepalive by yourself on application layer:

Send something to the peer and expect answer from it
If nothing received within timeout - close connection


How to get value instead of Promise from Firebase?

Question: I want to get a "value of Data" from Firebase Realtime Database. You can find my code below:
  async function getName() {
    const result = await firebase.database().ref('/users/' + user.user.uid)
    .once('value').
    then(async function(snapshot) {
      console.log("SNapshot =>");
      console.log(snapshot.val().displayName); // returns "John Doe"

      const result2 = await snapshot.val().displayName;

      return result2;
    });

    return result; // returns "Promise Object"
  };

It returns "Promise". But i want to get value not promise.
How should i fix my code?
Thanks.
Comment: `async` functions return a Promise by contract - it is the way they work.
Comment: I only want to get a value of any data from my Firebase Realtime Database. It doesn't matter to use "async" function for me. How can i get value as `firebase.auth().currentUser.email`?
Comment: You can't get a value from the future. Return the promise, have the user wait for the value.
Answer: You are mixing up use of async/await with then()/catch().  You should pick one syntax or the other, not both together in this case.  You are also trying to use await on something that is not a promise.  Just write your function like this:
async function getName() {
  const snapshot = await firebase.database().ref('/users/' + user.user.uid).once('value')
  return snapshot.val().displayName
}

And call it like this:
const name = await getName()

Comment: It still returns "Promise". How can i get any value of data from Firebase with a function ?
Comment: Async functions all return promises, no exceptions.  That's why I'm showing how to call getName using await to unwrap the promise.
Comment: How can i get value from Database as `firebase.auth().currentUser.email`? It returns `firstname.lastname@example.com`.
Answer: The getname function is doing async operation so you can do:
try {
  await result = getName();
} catch (e) {
  throw e;
}

within an async function, or, if you prefer without async :
result.then((res) => console.log(res));

Comment: While this *might* work, the entire getName function is poorly written and has way too many lines of code for what's necessary.
Comment: Thanks but it still returns "Promise".


SIP Register Request using JAIN SIP

Question: I try to develop a sipPhone for the project of the end of study .Now, I still stick in how can I register to Asterisk 1.8 server with authentication. I downloaded this code from here:
package examples.authorization;

import gov.nist.javax.sip.Utils;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Properties;

import javax.sip.ClientTransaction;
import javax.sip.Dialog;
import javax.sip.DialogTerminatedEvent;
import javax.sip.IOExceptionEvent;
import javax.sip.ListeningPoint;
import javax.sip.RequestEvent;
import javax.sip.ResponseEvent;
import javax.sip.SipFactory;
import javax.sip.SipListener;
import javax.sip.SipProvider;
import javax.sip.SipStack;
import javax.sip.TimeoutEvent;
import javax.sip.TransactionTerminatedEvent;
import javax.sip.address.Address;
import javax.sip.address.AddressFactory;
import javax.sip.header.AuthorizationHeader;
import javax.sip.header.CSeqHeader;
import javax.sip.header.CallIdHeader;
import javax.sip.header.ContactHeader;
import javax.sip.header.FromHeader;
import javax.sip.header.HeaderFactory;
import javax.sip.header.MaxForwardsHeader;
import javax.sip.header.ToHeader;
import javax.sip.header.ViaHeader;
import javax.sip.message.MessageFactory;
import javax.sip.message.Request;
import javax.sip.message.Response;

public class SipInit implements SipListener {

    private String ip;
    private SipFactory sipFactory;
    private Properties properties;
    private SipStack sipStack;
    @SuppressWarnings("unused")
    private MessageFactory messageFactory;
    private HeaderFactory headerFactory;
    private AddressFactory addressFactory;
    private ListeningPoint listeningPoint;
    private int port;
    private String protocol;
    private SipProvider sipProvider;
    private String username;
    private Address contactAddress;
    @SuppressWarnings("unused")
    private ContactHeader contactHeader;
    private String server;
    private char[] tag;
    private Request request;
    private String password;
    private ClientTransaction inviteTid;
    private Dialog dialog;

    public void init() {
        try {
            // Get the local IP address.
            this.ip = InetAddress.getLocalHost().getHostAddress();
            // Create the SIP factory and set the path name.
            this.sipFactory = SipFactory.getInstance();
            this.sipFactory.setPathName("gov.nist");
            // Create and set the SIP stack properties.
            this.properties = new Properties();
            this.properties.setProperty("javax.sip.STACK_NAME", "stack");
            this.properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "32");

            this.properties.setProperty(
                    "gov.nist.javax.sip.LOG_MESSAGE_CONTENT", "true");
            this.properties.setProperty("gov.nist.javax.sip.DEBUG_LOG",
                    "mss-jsip-debuglog.txt");
            this.properties.setProperty("gov.nist.javax.sip.SERVER_LOG",
                    "mss-jsip-messages.xml");
            // Create the SIP stack.
            this.sipStack = this.sipFactory.createSipStack(this.properties);
            // Create the SIP message factory.
            this.messageFactory = this.sipFactory.createMessageFactory();
            // Create the SIP header factory.
            this.headerFactory = this.sipFactory.createHeaderFactory();
            // Create the SIP address factory.
            this.addressFactory = this.sipFactory.createAddressFactory();
            // Create the SIP listening point and bind it to the local IP
            // address, port and protocol.
            this.listeningPoint = this.sipStack.createListeningPoint(this.ip,
                    this.port, this.protocol);
            // Create the SIP provider.
            this.sipProvider = this.sipStack
                    .createSipProvider(this.listeningPoint);
            // Add our application as a SIP listener.
            this.sipProvider.addSipListener(this);
            // Create the contact address used for all SIP messages.
            this.contactAddress = this.addressFactory.createAddress("sip:" + this.username + "@"
                    + this.ip + ";transport=tcp");
            // Create the contact header used for all SIP messages.
            this.contactHeader = this.headerFactory
                    .createContactHeader(contactAddress);
            // Display the local IP address and port in the text area.
        } catch (Exception e) {
            e.printStackTrace();
            // If an error occurs, display an error message box and exit.
            System.exit(-1);
        }
    }

    public void register(Response response) {
        Object logger;
        try {
        int cseq;
        cseq++;
        ArrayList<ViaHeader> viaHeaders = new ArrayList<ViaHeader>();
        ViaHeader viaHeader = this.headerFactory.createViaHeader(this.ip,
        this.port, "tcp", null);
        viaHeaders.add(viaHeader);
        // The "Max-Forwards" header.
        MaxForwardsHeader maxForwardsHeader = this.headerFactory
        .createMaxForwardsHeader(70);
        // The "Call-Id" header.
        CallIdHeader callIdHeader = this.sipProvider.getNewCallId();
        // The "CSeq" header.
        @SuppressWarnings("deprecation")
        CSeqHeader cSeqHeader = this.headerFactory.createCSeqHeader(cseq,
        "REGISTER");

        Address fromAddress = addressFactory.createAddress("sip:"
        + username + '@' + server);

        FromHeader fromHeader = this.headerFactory.createFromHeader(
        fromAddress, String.valueOf(this.tag));
        // The "To" header.
        ToHeader toHeader = this.headerFactory.createToHeader(fromAddress,
        null);

        // this.contactHeader = this.headerFactory
        // .createContactHeader(contactAddress);

        request = this.messageFactory.createRequest("REGISTER sip:"
        + server + " SIP/2.0\r\n\r\n");
        request.addHeader(callIdHeader);
        request.addHeader(cSeqHeader);
        request.addHeader(fromHeader);
        request.addHeader(toHeader);
        request.addHeader(maxForwardsHeader);
        request.addHeader(viaHeader);
        request.addHeader(contactHeader);
        if (response != null) {
        boolean retry = true;
        AuthorizationHeader authHeader = Utils.makeAuthHeader(headerFactory, response,
        request, username, password);
        request.addHeader(authHeader);
        }
        inviteTid = sipProvider.getNewClientTransaction(request);
        // send the request out.
        inviteTid.sendRequest();
        this.dialog = inviteTid.getDialog();
        // Send the request statelessly through the SIP provider.
//                  this.sipProvider.sendRequest(request);

        // Display the message in the text area.
        ((Object) logger).debug("Request sent:\n" + request.toString() + "\n\n");
        } catch (Exception e) {
        // If an error occurred, display the error.
        e.printStackTrace();
        logger.debug("Request sent failed: " + e.getMessage() + "\n");
        }
        }

    @Override
    public void processDialogTerminated(DialogTerminatedEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void processIOException(IOExceptionEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void processRequest(RequestEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void processResponse(ResponseEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void processTimeout(TimeoutEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void processTransactionTerminated(TransactionTerminatedEvent arg0) {
        // TODO Auto-generated method stub

    }

}

But I got this erro :

The method makeAuthHeader(HeaderFactory, Response, Request, String,
  String) is undefined for the type Utils

Could please help me  and Thanks.
Comment: Hello! I use the same code and the same error occurs. :S
Comment: No chance. Sorry I couldn't resolve the problem so I wait for someone who could fix it.
Answer: Following snippet might help - (used JAIN-Sip library - https://github.com/RestComm/jain-sip)
package com.sip.light.client;

import java.text.ParseException;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TooManyListenersException;

import javax.sip.ClientTransaction;
import javax.sip.DialogTerminatedEvent;
import javax.sip.IOExceptionEvent;
import javax.sip.InvalidArgumentException;
import javax.sip.ListeningPoint;
import javax.sip.ObjectInUseException;
import javax.sip.PeerUnavailableException;
import javax.sip.RequestEvent;
import javax.sip.ResponseEvent;
import javax.sip.SipException;
import javax.sip.SipFactory;
import javax.sip.SipProvider;
import javax.sip.TimeoutEvent;
import javax.sip.Transaction;
import javax.sip.TransactionTerminatedEvent;
import javax.sip.TransportNotSupportedException;
import javax.sip.address.AddressFactory;
import javax.sip.header.ContactHeader;
import javax.sip.header.HeaderFactory;
import javax.sip.message.MessageFactory;
import javax.sip.message.Request;
import javax.sip.message.Response;

import gov.nist.javax.sip.DialogTimeoutEvent;
import gov.nist.javax.sip.ListeningPointExt;
import gov.nist.javax.sip.SipListenerExt;
import gov.nist.javax.sip.SipStackExt;
import gov.nist.javax.sip.SipStackImpl;
import gov.nist.javax.sip.clientauthutils.AuthenticationHelper;
import gov.nist.javax.sip.clientauthutils.UserCredentials;
import gov.nist.javax.sip.stack.NioMessageProcessorFactory;
import gov.nist.javax.sip.stack.SIPTransactionStack;

public class SipClientLightSip implements SipListenerExt {
    private SipStackExt mSipStack;
    private HeaderFactory mHeaderFactory;
    private String mPeerHostPort;

    private AddressFactory mAddressFactory;
    private MessageFactory mMessageFactory;
    private ListeningPoint mUdpListeningPoint;
    private SipProvider mSipProvider;
    private int mUdpPort = 5082;
    private String mProtocol = "UDP";
   private String mIPAddress ="127.0.0.1"; //
   // private String mIPAddress ="10.90.20.68"; //
    private UserCredentials mUserCredentials;
    private ContactHeader contactHeader;

    @Override
    public void processRequest(RequestEvent requestEvent) {
        System.out.println("RequestEvent "+requestEvent.getServerTransaction().getDialog());
    }

    @Override
    public void processResponse(ResponseEvent responseEvent) {
        System.out.println("responseEvent.getResponse()" + responseEvent.getResponse());
        if(responseEvent.getResponse().getStatusCode() == Response.UNAUTHORIZED){

            AuthenticationHelper authenticationHelper =
                    mSipStack.getAuthenticationHelper((challengedTransaction, realm) -> mUserCredentials, mHeaderFactory);
            try {

                authenticationHelper.handleChallenge(responseEvent.getResponse(),responseEvent.getClientTransaction(),mSipProvider,2000).sendRequest();
            } catch (SipException e) {
                e.printStackTrace();
            }
        }else if(responseEvent.getResponse().getStatusCode() == Response.OK){
            System.out.println("responseEvent.getResponse()" + responseEvent.getResponse());

        }
    }

    @Override
    public void processTimeout(TimeoutEvent timeoutEvent) {
        Transaction transaction;
        if (timeoutEvent.isServerTransaction()) {
            transaction = timeoutEvent.getServerTransaction();
        } else {
            transaction = timeoutEvent.getClientTransaction();
            System.out.println(timeoutEvent.getTimeout().getValue());

        }
        System.out.println("state = " + transaction.getState());
        System.out.println("dialog = " + transaction.getDialog());
        System.out.println("Transaction Time out");
    }

    @Override
    public void processIOException(IOExceptionEvent exceptionEvent) {
        System.out.println("Expcetion occured "+exceptionEvent.getPort());
    }

    @Override
    public void processTransactionTerminated(TransactionTerminatedEvent transactionTerminatedEvent) {

            if (transactionTerminatedEvent.isServerTransaction())
                System.out.println("Transaction terminated event recieved"
                        + transactionTerminatedEvent.getServerTransaction());
            else {
                System.out.println("Transaction terminated "
                        + transactionTerminatedEvent.getClientTransaction());

                //System.out.println(transactionTerminatedEvent.getClientTransaction().getRequest());

            }
    }

    @Override
    public void processDialogTerminated(DialogTerminatedEvent dialogTerminatedEvent) {
        System.out.println("processDialogTerminated" +dialogTerminatedEvent);
    }

    public  void init() throws PeerUnavailableException, InvalidArgumentException, TransportNotSupportedException, ObjectInUseException, TooManyListenersException {
        SipFactory sipFactory = null;
        mSipStack = null;
        sipFactory = SipFactory.getInstance();
        sipFactory.setPathName("gov.nist");

        Properties properties = new Properties();
        //properties.setProperty("javax.sip.OUTBOUND_PROXY", "127.0.0.1:5060" + "/"+ "ws");
        properties.setProperty("javax.sip.STACK_NAME", "SIP_CLIENT");

        properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "32");
        properties.setProperty("gov.nist.javax.sip.DEBUG_LOG", "sip_client/out/log/debug.txt");
        properties.setProperty("gov.nist.javax.sip.SERVER_LOG", "sip_client/out/log/server.txt");
        //properties.setProperty("javax.sip.OUTBOUND_PROXY","127.0.0.1:5082/WS");
        properties.setProperty("javax.sip.IP_ADDRESS",mIPAddress);
        properties.setProperty("javax.sip.TRANSPORT",mProtocol);
        //properties.setProperty("gov.nist.javax.sip.USE_TLS_GATEWAY","true");
        properties.setProperty("gov.nist.javax.sip.TCP_POST_PARSING_THREAD_POOL_SIZE", "1");
        properties.setProperty("javax.sip.AUTOMATIC_DIALOG_SUPPORT", "off");
        properties.setProperty("gov.nist.javax.sip.AUTOMATIC_DIALOG_ERROR_HANDLING","false");
        //properties.setProperty("gov.nist.javax.sip.IS_BACK_TO_BACK_USER_AGENT","true");
        properties.setProperty("gov.nist.javax.sip.MESSAGE_PROCESSOR_FACTORY", NioMessageProcessorFactory.class.getName());
        properties.setProperty("gov.nist.javax.sip.CACHE_CLIENT_CONNECTIONS","false");
        mSipStack = (SipStackExt) sipFactory.createSipStack(properties);

        mHeaderFactory = sipFactory.createHeaderFactory();
        mAddressFactory = sipFactory.createAddressFactory();
        mMessageFactory = sipFactory.createMessageFactory();
        mUdpListeningPoint = mSipStack.createListeningPoint(mIPAddress, mUdpPort, mProtocol);

        mSipProvider = mSipStack.createSipProvider(mUdpListeningPoint);
        mSipProvider.addSipListener(this);

    }

    public void sendRegister(UserCredentials userCredentials,String serverIP,int serverPort) throws SipException, ParseException, InvalidArgumentException {

    StringBuilder sb = new StringBuilder();

    sb.append("REGISTER sip:firstname.lastname@example.com:5060;method=GET?Host=127.0.0.1&Location=/&transport="+mProtocol+" SIP/2.0\r\n");
    sb.append("CSeq: 1 REGISTER\r\n");
    sb.append("To: <sip:piyush@domain:5082>\r\n");
    sb.append("From: \"piyush\" <sip:piyush@domain:5082>;tag=o3qshhkifd\r\n");
    sb.append("Call-ID: gth3knqa3t3n0bj42osph5\r\n");
    sb.append("Max-Forwards: 69\r\n");
    sb.append("Via: SIP/2.0/"+mProtocol+" n8020ls4d00s.invalid;branch=z9hG4bK8197727\r\n");
    sb.append("Contact: <sip:email@example.com;transport="+mProtocol+">;+sip.ice;reg-id=1;+sip.instance=\"<urn:uuid:c8f8a859-5f68-48e4-88f4-49abf1ac036f>\";expires=600\r\n");

    sb.append("Allow: INVITE,ACK,CANCEL,BYE,UPDATE,MESSAGE,OPTIONS\r\n");
    sb.append("Content-Length: 0\r\n");
    sb.append("Supported: path,gruu,outbound\r\n");
    sb.append("Expires: 600\r\n");

    System.out.println("Register request over websocket "+ request);

        ClientTransaction ctx = mSipProvider.getNewClientTransaction(request);
        ctx.sendRequest();
        //timer.schedule(new MyTimerTask(), 1000, 3000);
    }

    @Override
    public void processDialogTimeout(DialogTimeoutEvent arg0) {
        // TODO Auto-generated method stub

    }

}

/* Output as follows -

Register request over websocket REGISTER sip:email@example.com:5060;method=GET?Host=127.0.0.1&Location=/&transport=UDP SIP/2.0
CSeq: 1 REGISTER
To: <sip:piyush@domain:5082>
From: "piyush" <sip:piyush@domain:5082>;tag=o3qshhkifd
Call-ID: gth3knqa3t3n0bj42osph5
Max-Forwards: 69
Via: SIP/2.0/UDP n8020ls4d00s.invalid;branch=z9hG4bK8197727
Contact: <sip:email@example.com;transport=UDP>;+sip.ice;reg-id=1;+sip.instance="<urn:uuid:c8f8a859-5f68-48e4-88f4-49abf1ac036f>";expires=600
Allow: INVITE,ACK,CANCEL,BYE,UPDATE,MESSAGE,OPTIONS
Supported: path,gruu,outbound
Expires: 600
Content-Length: 0

responseEvent.getResponse()SIP/2.0 401 Unauthorized
CSeq: 1 REGISTER
To: <sip:piyush@domain:5082>;tag=6e9d37d85ef64ab7aee1dfb44a2b1f94
From: "piyush" <sip:piyush@domain:5082>;tag=o3qshhkifd
Call-ID: gth3knqa3t3n0bj42osph5
Via: SIP/2.0/UDP n8020ls4d00s.invalid:5082;branch=z9hG4bK8197727
x-Error-Details: No auth header
WWW-Authenticate: Digest realm="domain",nonce="b97e036da02577c13598f26e4e3d27ec",qop="auth",algorithm=MD5,stale=false,opaque="00000001"
Content-Length: 0

responseEvent.getResponse()SIP/2.0 200 OK
CSeq: 2 REGISTER
To: <sip:piyush@domain:5082>;tag=68067566c18441ccb8a645c812aa23f1
From: "piyush" <sip:piyush@domain:5082>;tag=o3qshhkifd
Call-ID: gth3knqa3t3n0bj42osph5
Via: SIP/2.0/UDP n8020ls4d00s.invalid:5082;branch=z9hG4bK-37-d3e9f8fe24da7121a13553b1b7c0b54d
Contact: <sip:email@example.com;transport=UDP>;+sip.instance="<urn:uuid:c8f8a859-5f68-48e4-88f4-49abf1ac036f>";expires=599
Expires: 599
Content-Length: 0

responseEvent.getResponse()SIP/2.0 200 OK
CSeq: 2 REGISTER
To: <sip:piyush@domain:5082>;tag=68067566c18441ccb8a645c812aa23f1
From: "piyush" <sip:piyush@domain:5082>;tag=o3qshhkifd
Call-ID: gth3knqa3t3n0bj42osph5
Via: SIP/2.0/UDP n8020ls4d00s.invalid:5082;branch=z9hG4bK-37-d3e9f8fe24da7121a13553b1b7c0b54d
Contact: <sip:firstname.lastname@example.com;transport=UDP>;+sip.instance="<urn:uuid:c8f8a859-5f68-48e4-88f4-49abf1ac036f>";expires=599
Expires: 599
Content-Length: 0

Transaction terminated gov.nist.javax.sip.stack.SIPClientTransactionImpl@7c805a26
Transaction terminated gov.nist.javax.sip.stack.SIPClientTransactionImpl@5626892b

*/

SIP Register Request using JAIN SIP


Package System Broken AMD FGLRX Unmet Dependencies

Question: I uninstalled propriety ATI driver to check if it would fix wrong Plymouth resolution.  It did.  But now I cannot reinstall either propriety drivers listed.
Also package system has broken with this error:
The package system is broken
If you are using third party repositories then disable them, since they are a common source of problems.
Now run the following command in a terminal: apt-get install -f
The following packages have unmet dependencies:
<code>fglrx-amdcccle: Depends: fglrx but it is not installed
                Depends: libqtcore4 (>= 4:4.5.3) but 4:4.8.1-0ubuntu4.1 is installed
                Depends: libqtgui4 (>= 4:4.5.3) but 4:4.8.1-0ubuntu4.1 is installed
</code>
What should I do?
Comment: possible duplicate of [How do I resolve unmet dependencies after adding a PPA?](http://askubuntu.com/questions/140246/how-do-i-resolve-unmet-dependencies-after-adding-a-ppa)
Answer: Use broken package filter in Synaptic to locate failed package, then uninstall.  This will fix broken dependency but no idea how to get either propriety graphics drivers to reinstall.  Open to suggestions...
Answer: I have always had trouble with the drivers in the repositories for AMD. I recommend going directly to the AMD website at http://www.amd.com/us/products/technologies/amd-catalyst/Pages/catalyst.aspx
Click on the 'find a Driver' dialogue, fill in the details for your system, and download the file. Then you need to run it and follow the instructions to build the .deb files for your computer, and then install the drivers using your favourite package manager.
These instructions here are a little brief and lacking detail, but I think more complete instructions for this process are easily available on this forum and elsewhere on the web.
Comment: ...but of course follow Fleamour first to repair package dependencies, then you should be able to uninstall with no difficulty.


Why does my toilet feed service valve still leak?

Question: The metal pipe that comes out of the wall and feeds water into the cistern on my toilet is connected to the plastic cistern pipe (inlet valve pipe?) by a service valve. It is pretty much identical to this one:
http://www.toolstation.com/shop/Plumbing/Valves/Service+Valve+15mm/d20/sd2696/p44747
There is a leak in the connection between the female end of the service valve and the threaded plastic pipe to the cistern. The leak stops if I turn off the valve (so at least that's something) but starts again as soon as I turn it back on. Not a serious leak, just a drip, but it drips about a litre in 12 hours so without a big bucket under it, if I leave it on it will flood my bathroom while I'm at work.
I figured it was the washer that had gone, so I bought a pack of these:
http://www.toolstation.com/shop/Plumbing/Washers+Fixings/Fibre+Washer+38/d20/sd2703/p91174
I took the washer from the service valve to the shop when I bought them and compared them, so I got the exact same ones (or at least they look and feel identical). I have now tried every combination I can think of, and haven't been able to stop it from leaking. I have tried with a single washer, with two washers together, I have wrapped PTFE tape around the thread on the plastic pipe, I have even tried a washer wrapped in PTFE tape, but nothing seems to help.
My question is:
  - Is it worth replacing the whole valve? Could there be something wrong with the valve that isn't just the washer? The valve part works fine, because the leak stops when I turn it off. I did notice when I took the old washer out that there seemed to be tiny chips of what felt like concrete or something in there, not sure what that is or where it came from.
  - Could there be something wrong with the thread on the plastic pipe, or is this unlikely to be the issue?
  - Is it worth trying a rubber washer instead of the fibre one that was in there already?
  - Should I be tightening the valve onto the pipe really super hard, or should a few turns be enough if the washer is doing its job?
I have done a few bits of pieces of DIY before but I have not done much plumbing, so any suggestions would be welcome!
Comment: Considering the low price for the service valve you linked to, I'd just get a new one and try it. I'd also feel the pipe ends for any abrasion and sand them smooth with 220grit sandpaper if there are minor abrasions. Also, check to ensure the end of the pipe isn't cracked. A crack in the pipe at the end is a likely suspect for this problem.
Comment: The plastic pipe is more likely the problem than the valve. The whole system is dependent on the pipe end sealing against the washer. Like getterdun suggested, be sure this is smooth. Also ensure the valve surface under the washer is clean and smooth. A neoprene washer is worth a try. You cannot tighten this type of washer too much. The fiber type can handle more pressure, but still does not need to be super tight.
Comment: Note my toilet/cistern is a top-loader, much like this one http://www.plumbnation.co.uk/site/ideal-standard-create-edge-close-coupled-toilet-cistern-e3029/large-e3029.jpg
Comment: Thanks getterdun. I guess my main reason for not replacing the valve so far is that if I turn the valve off, there is no leak - if I replace the valve and it starts leaking at the other end (before the tap) then I will have to turn off the water to the whole flat :( How easy would it be to spot a cracked pipe with the naked eye? Or is there some test I could use (like wetting it and looking for bubbles etc)
Answer: Thanks for the comments getterdun and bcworkz.
I went to Toolstation and bought a new service valve and also a new inlet valve for the princely sum of about £11. As per your suggestion I checked the plastic pipe, and it looked a bit rough around the end and one of the teeth of the thread was badly worn, but I couldn't see a way to replace just the pipe so I replaced the whole thing (dismantled the cistern and everything as per a video on YouTube).
I couldn't get the old service valve off, couldn't get enough grip to turn the valve part opposite to the nut part, so I decided to leave the old one now but give it a really good wipe and test anyway with the new inlet valve and pipe. I also used a fresh fibre washer. At first when I turned the water back on it leaked quite a bit and I was slightly disheartened, but I remembered reading somewhere that fibre washers slowly expand as they get wet, so I just put a bucket under the leak and left it for an hour or so. Bingo! No more leak :)


Is my garage subpanel safe for 100 amps?

Question: Not an electrician. Just wondering how much my subpanel can safely power.
I have a 125-amp subpanel in my attached garage powered by two separate 6/2 NM-B cables with ground, run in the attic. Distance to main panel is about 65 ft. Breaker in main panel is 50 amp dual-pole. The subpanel has room for 8 slim breakers (4 spaces?). It appears spaces 1 & 3 are powered by the first hot wire and spaces 2 & 4 are powered by the second hot wire. Both 6 gauge neutrals are connected to the same bus that is isolated from ground in the subpanel. The two ground wires are connected to a ground bar which is mounted directly inside the subpanel.
Questions:

The two ground wires from each of the 6/2 cable runs appear to be 12 gauge. Everywhere I've read states these need to be at least 10 gauge. Are two 12 gauge wires OK?
Can this subpanel draw 85-90 amps as wired?

Thanks!
Comment: If I'm reading the question correctly, you have a MAJOR code violation going on. You can't feed a sub-panel with 2 cables (I assume you meant cables and not wires).  On the surface it may seem OK, like I've got 2 cables supplying 50 amps each, but it's NOT OK, reason being is that if one of the 50 amp supply breakers trips or you have a circuit failure , the entire load will be on the other breaker....not good.   But to rescue this, like @Harper-ReinstateUkraine asked, "what are you trying to power"?
Comment: What exactly is it you are trying to power?  By the way the short answer is "no, not even close", but if you can say your plans we may be able to figure a way to salvage it.  What is the cable type and is it run outdoors or underground?
Comment: Pictures of the panel, with the cover _carefully_ removed, and of all the labels inside the panel (on the inside of the swinging door and inside the panel itself) will help tremendously.
Comment: How hard would it be to replace the existing cables feeding the subpanel?
Comment: It sounds like you have  single 50A Dual-Pole breaker (fine) feeding the black wires of a pair of 6/2 w/ground cables (not fine) and the white wires are connected to the neutral bus, grounds to ground.

That's a 50A (@240V) feed, on inappropriate cabling. It's not a 100A feed, though you can run 100A@120V from it. But it's improperly cabled.
Comment: Paralleling both the hots and the neutrals to make a 100A+ feed is certainly out of the question, as that *would* risk overloading individual wires (and would leave no free wires for neutral so it would be a 240V-only feed).
Comment: @GeorgeAnderson The paralleling isn't a major issue right now as obviously only the neutrals are paralleled and one of them alone is big enough for the whole load. Currently no overload can result from one wire breaking or one breaker tripping. One neutral could be disconnected to eliminate the paralleling, leaving only the "separate cables" issue (still a significant violation).
Comment: @nobody As you stated earlier, only the neutrals are currently paralleled.
Comment: @ThreePhaseEel Not impossible, but the attic space is tight due to shallow slope of roof.
Comment: @Harper-ReinstateUkraine I'm trying to see what can safely be connected to this panel as wired. Cables are NM-B and run in attic.
Comment: Nothing can be connected to it right now!  However, "what you're planning to hook up" is the deciding factor in whether the existing wires can be saved.
Answer: Your panel was wired improperly in the first place. But we can save it.
What they did was combine two cables to get enough wires to do the job.  That's not allowed.  I would call it "cheap" but they actually spent a fortune compared to what they could have spent.
So let's fix it on the cheap, using the existing wires.
You will need two subpanels. You already have one, so you'll need one more.    One panel can be 120V and the other one 240V-only (no neutral).  Or both 120V.  Or both 240V-only.  Your call.
Each cable goes to a different subpanel.
The wires are only good to 55A and you can only plan to put 55A of load on them.   However, since 55A breakers are not sold, you can use a 60A breaker.  This is not permission to plan to use 60A of ampacity.
To wire a 120V-only panel
On the 120V panel(s), the white wire goes to neutral both in the subpanel and on the main panel.  On the main panel, the black wire lands on the breaker - the other half of the breaker is empty.*
At the subpanel, the hot wire is split to feed both hot lugs on the panel.  Lugs are only rated for 1 wire, so both lugs will need to be pigtailed and tied with a 3-wire splice.  120V loads will now work. Do not use MWBCs.
A 120V panel can support 6600 VA of calculated load. (120V x 55A).
To wire a 240V-only panel
The white wire at both ends gets taped with black or red tape to indicate its use as a hot.  It goes to both poles of the 240V circuit breaker, and to the two hot terminals on the subpanel.  At the subpanel, keep the neutral bar completely empty (this panel does not have neutral) and buy an accessory ground bar - this is to make clear to "the next guy" that there is no neutral here.
It'll need to be a nice big panel, because you'll be using spaces 2 at a time. Spaces are cheap.
You then wire up 240V-only (no neutral) loads, such as a heater, air conditioner, water heater, welder, compressor, or EVSE that is hardwired or uses a NEMA 6 family socket.   You cannot install a NEMA 14 socket, but EV's don't need neutral.
If you have an EVSE with a NEMA 14-50 plug, either send it back, or throw away the plug and install a NEMA 6-50 plug (notice when disassembling the 14-50 how there is no neutral wire in the cord, and the neutral pin connects to nothing?)  EV's have no use whatsoever for neutral, so the 14-50 socket is pointless and stupid.  I have no idea why EV suppliers love that plug so much.
A 240V panel can support 13200 VA of load. (55A x 240V).
Two of them can support 26400 VA of load, more than the 21600 VA you were asking for.
"They are 4-wire 120/240V loads, or I can't say."
Then you have no choice but to replace the entire cable run.
I would use 2-2-2-4 aluminum wire of a type such as SER which is rated for the same places NM cable is rated.  There is nothing wrong with aluminum at these large sizes, and the panel lugs are aluminum anyway.
Now here's the kicker. Price 2-2-2-4.  Now price 6/2 copper NM.  See how the 2-2-2-4 is about 1/5 the price of what they did put in? This is the trouble with using wire "you have laying around".  They could have sold the 6/2 on Craiglist for more than the 2-2-2-4 cost, and had plenty left over for a larger subpanel.
2-2-2-4 aluminum is good for 90A. Some people believe it is 100A wire - there's a reason they think that, but it's wrong for your application.
This will support 21600 VA.

* They don't make 1-pole breakers larger than 30A, so if you need a 120V breaker that is 50A or 60A, you will need to buy a 2-pole breaker and use only one pole.   If your setup is dual 120V subpanels, you can use the same breaker (but they'll trip together if you do).
Comment: This is the answer I didn't know I needed. Thank you.
Answer: No, it is not safe for 100A. Your 6Ga wire is rated for 55A maximum (if the cables are NM-B or UF-B, 65A in the unlikely even that they're SE or USE). It would be a code violation to attempt to parallel those wires to "double up" the current-carrying capacity (and anyway if you did parallel the two pairs of insulated wires in your two /2 cables, you'd be left with no insulated wires for neutral).
Furthermore, your current setup is a code violation. All wires in a run must be in the same conduit or cable. You may not have one of the hots in one cable and the other in another. You must use /3 cable or wires in a conduit to make a 4-wire feed to a subpanel. Additionally, it is code violation to parallel conductors, as you have with the neutrals. One of the 6Ga wires alone is sufficiently large so you could just disconnect one, but you'd still have the multiple cables problem.
To address the current violations, you could:

Replace the feed with a 6/3 cable
Replace the feed with individual wires in conduit (3 6Ga copper in EMT / 4 wires in non-metallic conduit, or larger, cheaper aluminum)
Disconnect one cable entirely if you can get by with only 50A @ 120V (no 240V loads).

To actually increase the amount of power available at the subpanel, you must replace the feed with larger wires (the specific size will depend on what type of wire/cable you choose, copper or aluminum, how much capacity you want, etc).
Comment: Does a 6/3 cable safely provide two 50A@120V circuits connected to the same 50A dual-pole breaker? All the breakers in the subpanel so far are single-pole 20A.
Comment: @RyanHaney from the first paragraph of the answer, "Your 6Ga wire is rated for 55A maximum", so yes, you can support 50A on #6 wire. _HOWEVER_, you're going to have a hard time fitting #6 wire onto a 15a or 20a socket. ("Hard" as in "impossible" - the wires are just too big to fit.) There are ways around this, and they've been addressed in other questions here if you'll search.
Comment: @FreeMan Nowhere did I even remotely suggest connecting #6 wire to 15a or 20a sockets.
Comment: @RyanHaney A load being "50A@120V" is *highly improbable*.  Typo?
Comment: I'm going to accept this answer as there are obviously code violations here and I need to get some general answers about what is allowed.


Need functions that both allocates memory for a string's creation, and inputs that string into an array of character pointers also allocated

Question: Here back again with another question!
#include <stdio.h>      // For standard input-output
#include <stdlib.h>     // For malloc
#include <string.h>     // For strcmp
#include <ctype.h>      // For isdigit
#define WordSize 20 // Macro defining maximum word size

char * input(void);

void addWord(char*,char**,int);

int main(void){
    // Define variables
    int Num_Words;
    // Prompt user for number of words, make sure to verify input
    printf("How many words do you wish to have: ?");
    while(scanf("%d", &Num_Words) !=1)
        {
            printf("Invalid entry, please try again!");
        }
    // Allocate memory for words (char **)!
    char ** NumWords = malloc(Num_Words * sizeof(int));

    // Get user input for each word, add pointer for each word to words

    char * ptr = malloc(WordSize * sizeof(char));
    addWord(ptr, NumWords, Num_Words);

    return 0;
}

char * input()
{
    char string;
    while(scanf("%s", &string) != 1)
        {
            printf("Please input valid string! \n");
            while(getchar() != '\n' ){}
        }

    char * array = (char *) malloc(sizeof(char) * string);
    *array = string;

    return array;
}

void addWord(char* word, char** words, int NumofWords)
{
    //TO-DO: Implement addWord

    for (int i = 0; i < NumofWords; i++)
        {
            printf("Enter word %d: \n ", i + 1);
            word = input();
            *words[i] = *word;
        }
    return;
}

Excuse the quotes, because some of them are mine and some are provided form the skeleton code to try and give direction. Again fairly new to coding and this is a kicker of a question, but the issue I am having at present is through the function inputWord and addWord as the iteration does not work and I get kicked out of the program at word 3. What I am supposed to do is ask the user for the number of words they wish to input (ditto), then from their do a dynamic allocation for the total number of words (ditto?) and then for each word cast a pointer to the user defined string , iterating to to fill the number of words defined earlier by the user. I don't really know what the problem/issue is? It compiles fine, but compiling doesn't mean functionality whatsoever. Any thoughts or areas I should look at.
Comment: `char string;` is a *single* character, but is followed by `while(scanf("%s", &string) != 1)` which wants an array. Later in the function `*array = string;` is quite wrong, also `sizeof(char) * string` as the argument for `malloc`. The whole function `inputWord()` is off.
Comment: I understand where of my issues were! When demonstrating the pointer-pointers, when assgining the memory, the sizeof() was incorrect and was allocating to the size of the integer versus the size of char *
Comment: I still need to go through and do a free memory function for the list of pointers and other function but I'll hash those issues out myself and look at what you brilliant minds discussed here so far. I'm just stumped on why I keep getting booted out during the itteration
Comment: OT: regarding: `while(scanf("%s", &string) != 1)`   when using the 'input format conversion' specifiers `%s` and/or `%[...]`  always include a MAX CHARACTERS modifier that is 1 less than the length of the input buffer because those specifiers always append a NUL byte to the input.  This avoids any possibility of a buffer overflow and the resulting undefined behavior
Comment: @SeanBright sorry about that! Still new to the whole process my bad and got super sidetracked yesterday, I'll upload the rest of the cde
Comment: @TobySpeight Phew! There we go! Hopefully that fits the minimum requirements, been a crazy day today hehe, but actually having things fleshed out in a simpler fashion takes the edge off too
Answer: the question:
Need functions that both allocates memory for a string's creation, and inputs that string into an array of character pointers also allocated
first, allocate the array of pointer:
char *arrayOfPointers = calloc( 100, sizeof( char* ) );

then use: getline()` to input the string into allocated memory into the array of pointers.
Comment: aaaah, getline! Completely forgot about that! Yeah that would make more sense, I updated my code as well because I realized that I was held off on a lot of code needed for people to actually try and compile my work, BUT I think that would be the missing bit


ChannelFactory: Channel Close() not closing connection (netstat shows ESTABLISHED)

Question: I have a WPF application that is communicating with a WCF server.
I am using one ChannelFactory to create channels for each call:
var channel = _channelFactory.CreateChannel();
var contextChannel = channel as ICommunicationObject;
try
  {
      channel.DoSomething();
  }
  catch (Exception)
  {
      contextChannel?.Abort();
      throw;
  }
  finally
  {
      contextChannel?.Close();
  }

There are many requests to the server when starting the application and at some points it grinds to an halt and I get timeouts.
Looking at netstat I see a few ESTABLISHED connection to the server,
When I change the  ServicePointManager.DefaultConnectionLimit to 10, I can process more calls to the server, but it still comes to a halt after some time with a timeout exception.
Setting ServicePointManager.DefaultConnectionLimit to int.MaxValue processes all my request, but I have about 720 ESTABLISHED connections to the server (netstat on the server gives me the same result).
I am confused about two things here:

It looks like WCF is not pooling connections, but creating a new connection for each request
Even after a I close the channel, the connection seems to remain established.

I also checked the ServicePointManager.FindServicePoint(new Uri("https://server:3000")); and it confirms that CurrentConnections are at the limit I set as the ServicePointManager.DefaultConnectionLimit.
I have reduced the ServicePointManager.MaxServicePointIdleTime to 500, this closes the connections faster, but it still creates a connection for each call I make.
How can I convince the channel factory to reuse exising channels when communicating with my server.
This is my binding:
new WebHttpBinding
{
    TransferMode = TransferMode.Streamed,
    ReceiveTimeout = TimeSpan.FromMinutes(1),
    SendTimeout = TimeSpan.FromMinutes(1),
    MaxReceivedMessageSize = 2147483647,
    MaxBufferPoolSize = 2147483647,
    ReaderQuotas =
        {
            MaxDepth = 2147483647,
            MaxStringContentLength = 2147483647,
            MaxArrayLength = 2147483647,
            MaxBytesPerRead = 2147483647,
            MaxNameTableCharCount = 2147483647
        },
    Security = new WebHttpSecurity() { Mode = WebHttpSecurityMode.Transport, Transport = new HttpTransportSecurity() { ClientCredentialType = HttpClientCredentialType.None } }
};

Answer: Turns out that some of the streams that the server returns were not closed properly, which caused the client to keep the connection open, even after Close() was called.
If Close() is called and the stream that was returned to the client has not been closed, the connection will not be reused and the client will get a TimeoutException at some point.
Thanks to Zhang Lan for giving the hint in the MSDN forums:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/a91a6d05-05ae-402e-bf7d-306289c4d0e2/wcf-with-streaming-mode-timeout-after-two-calls-when-client-and-service-are-not-on-same-machine?forum=wcf
Comment: Did you use streams on the client side? If so, did closing the streams solve the problem?
I've experienced i similar problem with open connections that I describe here https://stackoverflow.com/questions/59929665/can-creating-a-new-wcf-client-for-each-request-in-asp-net-core-lead-to-socket-ex
I have no control over the service I call but as far as I know there are no streams involved.
Comment: Yes, my problem was caused by streams. I have attempted to answer your question, I hope that helps.


Trouble calling js functions with prepack.io

Question: I have this function in a js file (not really spectacular):
function loadLazyImages() {
    var lazyImages = document.querySelectorAll('.js-lazyload');
}
loadLazyImages();

I also have a gulp task that concatenates and uglifies this file among others. This worked fine in the past, but now I'm trying out 'prepack' and there seems to be a problem:
not an object
TypeError
    at loadLazyImages (unknown:12:22)
    at unknown:15:1
C:\...\node_modules\prepack\lib\prepack-standalone.js:59
    throw new InitializationError();

The documentation states something about document and window not being defined but is rather vague when it comes tot solutions. Any insights?
Comment: I don't know much about prepack but it seems that from reading their issue tracker on GitHub you just can't do this yet (e.g. [see this issue](https://github.com/facebook/prepack/issues/24)).
Answer: Try run prepack with --trace option.


Does $\sum\limits_{n=1}^{\infty}\frac{\cos^{2}(n+1)}{n}$ converge?

Question: The original question, given to my Calculus II recitation class, was:
Determine if the series $$\sum\limits_{n=1}^{\infty}\frac{(-1)^{n}\cos^{2}(n+1)}{n}$$
converges absolutely, conditionally, or diverges. I can kind of see a comparison with the alternating harmonic series here, but making that formal is tough. With the absolute series $\sum\limits_{n=1}^{\infty} \frac{\cos^{2}(n+1)}{n}$, I'm not sure what test to apply.
What I've Tried: No tests (in the classical Calc II curriculum) work. I've tried expanding $\cos^{2}(n+1)$ into a power series within the series in question, but I'm not really sure where to go from there. My intuition tells me this series will diverge, since it seems "close" to the harmonic series; but $\cos(x)$ is less than $1$ infinitely often.
Comment: Fred, if this question is from a Calculus II course, my question is, how are you supposed to come up with an answer using the techniques available from Calculus II material? You may want to convey that to your professor. Which brings me to the second question. From which textbook is this exercise? Just curious
Comment: @imranfat This is from a practice sheet made by the instructor. I'm his TA for the course. Doing this on the board, I didn't immediately know what to do; and thinking about it on and off, I'm convinced it's a mistake, as I don't see any immediate way to apply the traditional Calculus II material. Regardless, it's an interesting question that's been bugging me.
Comment: Well, you can ask your professor what test he expects the students doe carry out. He doesn't have to show the work; you can share that with us. I am just curious...
Answer: Regarding the question on absolute convergence, the answer is no.
$$\sum_{n=1}^m\frac{\cos^2 (n+1)}{n} = \underbrace{\sum_{n=1}^m\frac{1}{2n}}_{\text{divergent harmonic series}} + \underbrace{\sum_{n=1}^m\frac{\cos 2(n+1)}{2n}}_{\text{convergent by Dirichlet test}}$$
Also we can use the same approach to prove convergence when $(-1)^n$ appears.
$$\sum_{n=1}^m\frac{(-1)^n\cos^2 (n+1)}{n} = \underbrace{\sum_{n=1}^m\frac{(-1)^n}{2n}}_{\text{convergent alternating series}} - \underbrace{\sum_{n=1}^m\frac{(-1)^{n+1}\cos 2(n+1)}{2n}}_{\text{convergent by Dirichlet test}}$$
Note that $(-1)^{n+1}\cos 2(n+1) = \cos [(n+1)\pi] \cos 2(n+1) = \cos [(n+1)(2 + \pi)]$
Comment: This is valid but difficult.  (In particular, I think a Calc II student might have trouble finding a bound for $\sum cos 2(n+1)$ so even if Dirichlet's test was part of his curriculum it might be tough.  I give a more direct and elementary argument below.
Comment: @Fred.  Yes you can split the partial sums as I added above.  As $m \to \infty$ the first sum on the RHS diverges and the second sum converges so the sum on the LHS diverges.
Comment: Thanks. I see you've distributed summation. Is this legal in this case? Also, I've wiki'd Dirichlet's test, but I can't see which two series you are using to fit the criterion.
Comment: @Fred:  I think you figured it out. The Dirichlet test applies because $1/(2n) \to 0$ in a decreasing fashion and the partial sums $\sum_{n=1}^{m} \cos 2(n+1)$ are bounded for all $m$. Same applies to $\sum_{n=1}^m \cos ((2+\pi)(n+1)$.
Answer: $\sum_{n=1}^{\infty}\frac{\cos^{2}(n+1)}{n}$ clearly diverges.  For any two consecutive integers, at least one of them is distant from a (non-integer) half-integer multiple of $\pi$ by at least $\frac{1}{2}$, which is more than $\frac{\pi}{8}$.  That number of the pair will have a cosine greater than $\cos(\frac{3\pi}{8})$ in absolute value, and $\cos(\frac{3\pi}{8})=\sin(\frac{\pi}{8})>\frac{1}{2}\sin(\frac{\pi}{4})=\frac{\sqrt{2}}{4}>\frac{1}{3}$.  Thus, any two consecutive terms $\frac{\cos^{2}(j+1)}{j} + \frac{\cos^{2}((j+1)+1)}{j+1}$ will contribute at least $\frac{1}{9(j+1)}$ to the sum.  Since $j\ge 1$, we have $\frac{1}{j+1}\ge\frac{1}{4j}+\frac{1}{4(j+1)}$, so $\frac{1}{9(j+1)} \ge\frac{1}{36j}+\frac{1}{36(j+1)}$, i.e. $$\frac{\cos^{2}(j+1)}{j} + \frac{\cos^{2}((j+1)+1)}{j+1} \ge \frac{1}{36j}+\frac{1}{36(j+1)}$$  But this means $$\sum_{n=1}^{\infty}\frac{\cos^{2}(n+1)}{n}\ge\frac{1}{36}\sum_{n=1}^{\infty}\frac{1}{n}$$ which diverges.
Answer: You could use Dirichlet's test. Observe $n^{-1}$ converges monotonically to zero and
\begin{align}
\left|\sum^N_{n=1}(-1)^n \cos^2(n+1) \right|\leq 1.
\end{align}
Hence the series converges.
Comment: True, but this test is not in Calculus II curriculum.
Comment: @CMonsour Yes. But I didn't say $\sum^N_{n=1}\cos^2(n+1)$ is bounded. Look carefully.
Comment: OK, I see what your claim is now.  (I had missed the $(-1)^n$ since the question title was about the absolute series.) It does seem like it might be a difficult bound for a Calc II student to prove.
Comment: Jacky.Very nice, clear and concise.Thanks!


How to remove and/or modify the elements that are loaded into custom sign in pages in Azure AD B2C?

Question: I've followed the steps at this link to setup a custom signin page for Azure AD B2C:
https://learn.microsoft.com/en-us/azure/active-directory-b2c/customize-ui-with-html?pivots=b2c-user-flow
Which are essentially:

Create a custom HTML file:

<!DOCTYPE html>

    <title>My Product Brand Name</title>

Upload it to a file hosting service

In Azure AD B2C > User Flows > [ your_sign_in_flow ], set the following:

Use custom page content: YES

Custom page URI:  [ paste the URL of your hosted file here ]

Click Save

Click Run User Flow to test the flow

That produces this login page:

Where the HTML of the api div is:

Sign in

Sign in with your social account

                  <button class="accountButton firstButton claims-provider-selection" id="AzureADPeople" role="link" autofocus="">Azure AD People</button>

OR

      <form id="localAccountForm" action="JavaScript:void(0);" class="localAccount" aria-label="Sign in with your email address">

            Sign in with your email address

              Email Address

            <input type="email" id="email" name="Email Address" title="Please enter a valid Email Address" pattern="^[a-zA-Z0-9!#$%&'+^_`{}~-]+(?:\.[a-zA-Z0-9!#$%&'+^_`{}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$" autofocus="" placeholder="Email Address" aria-label="Email Address">

                Password
                    <a id="forgotPassword" href="/<my-tenant-name>.onmicrosoft.com/B2C_1_signin1/api/CombinedSigninAndSignup/forgotPassword?csrf_token=****==&tx=StateProperties=****&p=B2C_1_signin1">Forgot your password?

              <input type="password" id="password" name="Password" placeholder="Password" aria-label="Password" autocomplete="current-password" aria-required="true">

            <button id="next" type="submit" form="localAccountForm">Sign in</button>

      </form>

In order to be able to customise this page, I need to know how to do the following:

Remove text elements if I don't want them displayed
Modify text elements if I want to change the text strings
Style text elements if I want them to have different font stylings
Wrap various elements in divs with particular classes to be able to apply a design
(eg display the different sign in options as inline-blocks side by side etc)

My question is:
Is it permissible to do all of this via JavaScript (and CSS to hide/style text elements)?
Technically I think I could do it, but I'm not sure if it is allowed or best practice.
This page has a list of guidelines for using JavaScript in Azure AD B2C custom pages:
https://learn.microsoft.com/en-us/azure/active-directory-b2c/javascript-and-page-layout?pivots=b2c-user-flow#guidelines-for-using-javascript
One of them is:

Don't take a dependency on Azure AD B2C code or comments.

But I'm not sure how elements can be customised without being able to reference the code within the api div.
For reference, the Page Layouts page does have a Version setting, which makes me think that, if we keep the same version selected, the contents of the api div would be unlikely to change (and therefore not break any JavaScript referencing particular divs etc).

Proof of Concept
I was able to create this custom signin page:

With this custom HTML page:
<!DOCTYPE html>

    <title>My Custom Login Page</title>

    <link rel="stylesheet" href="https://email@example.com/dist/css/uikit.min.css" integrity="sha256-f3SVFXP30MgahZ0Z7Lp1W02MuLgtiAtk8uFqTbGxNfY=" crossorigin="anonymous">

    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Josefin+Sans:wght@200&family=Noto+Sans+Ethiopic:wght@300&display=swap" rel="stylesheet">

Answer:
Don't take a dependency on Azure AD B2C code or comments.

This moreso is referring to our JS hooks and low level functionality, not the DOM.
You'll need CSS/JS to manipulate the DOM for your requirements.
Comment: Thank you for the confirmation, is there anyway to 'know' when the `api` div has finishing loading its content?   So that we can apply our transformations after the `api` div has loaded all its content?  As a workaround, as shown in my original post, I am currently using a 1 second `setTimeOut` after `document.ready`, but that is hacky and doesn't look very good.
Comment: Usually document.ready() is sufficient.
Comment: `$(document).ready(function() { // transformations here })` does not work.  It only works if I add a `setTimeout` of 1 second within the document ready function.  Are there any events available from the Azure injections into the `api` div?  Eg when the process has started and when it has finished?  If so, we could hide the `api` div with CSS, wait for the Azure injections to finish, and then run our transformation code and show the `api` div.
Comment: @user1063287 Not sure if you're still looking for an answer but the `defer` keyword worked for me: ``


Nvidia proprietary driver on Ubuntu 16.04 causing login loop

Question: I'm having the issue where whenever I install any proprietary nvidia driver on my Ubuntu it results in a login loop and I have to run sudo apt purge nvidia-361, reboot and it logs just like it should.
I'm using an Asus ROG G750JX from 2013 with an Intel i7 and a GTX 770M.
Does anyone know how to install the nvidia drivers and not result in a login loop?
Answer: Disable Secure Boot in BIOS and run
sudo apt install nvidia-361 nvidia-prime


Calculate the lengths of the heights descending from triangle vertices

Question: Given a triangle, calculate the lengths of the heights descending from triangle vertices  $A, B$ and $C$ respectively.
$$A(-1,-1,5),~~ B(0,3,-2),~~ C(3,-1,3)$$
I don't get it with which forma i should use and how to solve this question
Comment: Are you working in $\mathbb R^3$. Moreover look at the tags I added for correctness.
Answer: 1.) Use the distance formula to determine the side lengths:
$$d = \sqrt {(x-x_0)^2+(y-y_0)^2+(z-z_0)^2}$$
$$AB = \sqrt {(-1-0)^2+(-1-3)^2+(5-(-2))^2}=\sqrt{66}$$
$$AC = \sqrt {(-1-3)^2+(-1-(-1))^2+(5-3)^2}=\sqrt{20}$$
$$BC = \sqrt {(0-3)^2+(3-(-1))^2+(-2-3)^2}=\sqrt{50}$$
2.) Then use Heron's formula to calculate the area:
$$Area = \sqrt{s(s-a)(s-b)(s-c)}$$
Where $s = \frac {a+b+c} {2}$.
$$s=\frac {\sqrt{66}+\sqrt{20}+\sqrt{50}} {2}$$
$$Area=\sqrt{(\frac {\sqrt{66}+\sqrt{20}+\sqrt{50}} {2})((\frac {\sqrt{66}+\sqrt{20}+\sqrt{50}} {2})-\sqrt{66})((\frac {\sqrt{66}+\sqrt{20}+\sqrt{50}} {2})-\sqrt{20})((\frac {\sqrt{66}+\sqrt{20}+\sqrt{50}} {2})-\sqrt{50})} \approx 15.780$$
3.) Calculate each height using $Area=\frac12bh$:
$$H_A = 2\frac{Area}{BC}\approx2\frac{15.780}{\sqrt{50}}\approx 4.463$$
$$H_B = 2\frac{Area}{AC}\approx2\frac{15.780}{\sqrt{20}}\approx 7.057$$
$$H_C = 2\frac{Area}{AB}\approx2\frac{15.780}{\sqrt{66}}\approx 3.885$$
Answer: Hint:

calculate the sides lengths,
calculate the triangle area,
use $|\triangle ABC| = \frac{1}{2}h_a\cdot a$ to calculate $h_a$.

I hope this helps ;-)
Answer: Hint: first, calculate the length of each side, then use Heron's formula to determine the area of the triangle. Finally, use the formula $\text{area}=\text{side}\times\text{height}/2$ to determine the heights.


Remount componentDidMount() by path.name

Question: When the page loads I use componentDidMount() to document.createElement("script"); in the layout index.js of a ReactJS and GatsbyJS project as
componentDidMount () {
  const tripadvisorLeft = document.createElement("script");
  tripadvisorLeft.src = "https://www.jscache.com/wejs?wtype=selfserveprop&uniq=789&locationId=10467767&lang=en_NZ&rating=true&nreviews=0&writereviewlink=true&popIdx=true&iswide=true&border=false&display_version=2";
  tripadvisorLeft.async = true;
  document.body.appendChild(tripadvisorLeft);
}

This then requests the data to be displayed and works fine. However, when I <link to=... another page using gatsby-link (imagine the same issue applies for react-router), componentDidMount() has already run so it won't fetch the data again.
How can I ensure that this script is mounted after each path change, or better by a specific path?
Comment: React Router offers hooks like `onChange` and `onUpdate` which you can use to do something like what you are trying to achieve. [See this related stack overflow question](https://stackoverflow.com/questions/39351573/react-router-onchange-hook?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa)
Comment: Just to be sure, do you want the body of `componentDidMount` (i.e. fetching the script) to happen on each route change?
Comment: Ideally only on certain route paths, for example the `root` and `/reviews/` but at this stage everything would be a great starting point. Also not the entire functions of `componentDidMount` only the ` const tripadvisorLeft`
Comment: Thank you @ChiragRavindra. I am just looking this up for `gatsby-link`
Comment: Which version of `react-router` are you using?
Answer: You can use navigateTo from the gatsby-link package to roll your own Link component that executes your custom logic before navigating.
Link.jsx
import React from "react";
import { navigateTo } from "gatsby-link";

const RESOURCE_PATH = "https://www.jscache.com/wejs?wtype=selfserveprop&uniq=789&locationId=10467767&lang=en_NZ&rating=true&nreviews=0&writereviewlink=true&popIdx=true&iswide=true&border=false&display_version=2";
const refetchAndNavigate = (path) => () => {
  // refetch
  const tripadvisorLeft = document.createElement("script");
  tripadvisorLeft.src = RESOURCE_PATH;
  tripadvisorLeft.async = true;
  document.body.appendChild(tripadvisorLeft);

  // finally navigate
  navigateTo(path);
}

const Link = ({ to, ...propsToPass }) => (

);

export default Link;

I have not tested this code but idea will work.
Comment: Thank you for your question. I have had a play with your idea and think it's on track to what I need but some issues are blocking me. This would be remounting the script throughout the site? I have multiple scripts that require mounting as per their component, some with data being used via GraphQl to build the URL. This would not be possible in your example. Wondering if we could start a live chat and I could share a link to the source?
Comment: @Darren It sounds like you need access to props pass down into components in order to build the API in the first place. If that's the case you'll need to perform your fetching logic in `componentDidUpdate`. Also, have you looked into [React portals](https://reactjs.org/docs/portals.html)?
Comment: Thank you for your reply. Yes, I though about Portals but this will not help. I have never been so frustrated in looking for a solution. If you have a moment to check out the source https://github.com/discovr-bookings/mountainWhispers if that helps you see how I can implement your suggestion. You can also see deployed version here that shows the issue gracious-allen-d5eb54.netlify.com/varenna/reviews. Cheers.
Answer: You can add in the componentDidUpdate lifecycle method which is called whenever the component is updated:
componentDidUpdate(prevProps) {
  // check if path has changed
  if (prevProps.pathname !== this.props.pathname) {
    // call something to fetch data
  }
}

You can add more conditions to match only certain paths.
Check your gastby-link library to see how you can get the current pathname to pass in as props.
You can also try passing pathname={window.location.pathname} from a parent component that gets re-rendered when path changes.
Comment: Thank you. Did not work for me sorry. When loading the `script` via `componentDidUpdate` I do not get the scripts mounted, conditions added or not. Any ideas?
Comment: Can you try removing then re-inserting the `tripadvisorLeft` element in `componentDidUpdate`? Perhaps try `this.forceUpdate()` after the script runs too (make sure you add the path change check otherwise it'll go into infinite recursive rendering). Also check that `componentDidUpdate` is indeed getting called.
Comment: Thank you for your reply. I have tried in many ways but cannot get working - now back to using `componentDidMount`. Here is the source https://github.com/discovr-bookings/mountainWhispers/blob/master/src/components/properties/TripAdvisor.js if that helps you see how I can implement your suggestion. You can also see deployed version here that shows the issue https://gracious-allen-d5eb54.netlify.com/varenna/reviews/.
Comment: Did you try my suggestion above (re-inserting the script element)? Did `componentDidUpdate` get called? Also try `tripadvisorLeft.onload = () => this.forceUpdate()`. Add logging to check if `this.forceUpdate()` is being called etc.
Comment: Yes, tried but the scripts aren't getting called. Will try `forceUpdate` but sure this has been tried.
Comment: No, that isn't doing it either. `forceUpdate` logged in the console but I am now thinking the issue is not with the `script` but with the entire rendering of the component. When the script is called it alters the DOM but the when the component is re-rendered the DOM has changed and so the content is missing. I need to re-render the entire component, including the `script`.
Answer: Could you use a HOC to accomplish what you want. I just threw this together, it will need to be modified.
Create a component something like,
const withTracking = (WrappedComponent) => {
    return class withTracking extends React.Component {
        constructor(props) {
            super(props);

            this.trackit = this.trackIt.bind(this);
        }

        trackIt() {
            {
                const tripadvisorLeft = document.createElement("script");
                tripadvisorLeft.src = "https://www.jscache.com/wejs?wtype=selfserveprop&uniq=789&locationId=10467767&lang=en_NZ&rating=true&nreviews=0&writereviewlink=true&popIdx=true&iswide=true&border=false&display_version=2";
                tripadvisorLeft.async = true;
                document.body.appendChild(tripadvisorLeft);
            }
        }

        render() {
            return (

                    <WrappedComponent {...this.props} trackIt={this.trackIt} />

            );
        }
    }
};

Then in react router wrap it like,
<Route exact path="/pet-of-the-week" component={withTracking(TEST)}/>

And in the component use componentDidMount,
const TEST = (WrappedComponent) => {
    return class ClickLogger extends React.Component {
        constructor(props) {
            super(props);
        }

        componentDidMount() {
            this.trackIt();
        }

        render() {
            return (

something

            );
        }
    }
};

Answer: componentDidMount runs the first time (and only the first time!) the component is mounted in the DOM.
componentDidUpdate runs every time the component receives new props, but not for the initial render.
In order to operate on the DOM for the first render and for subsequent updates, you'll need to register your


Close form without reloading page when sending post request to backend API

Question: This is probably a simple one, but I have a React front end and Express back end, and I'm sending data to my API through a form on the front end. I have two buttons, one Submit and one Close. The Close button has a click event handler that closes the overlay without leaving the page. I would like my Submit button to work the same using the onSubmit handler. However, even though my post requests goes through successfully, it never closes the overlay despite using the same function.
I can make the app work by using a res.redirect on my back end to the home page, but I'd ideally like to not have the page reload. Additionally, when I have my back end send any kind of data back using res.send() or res.json(), it loads the JSON data in my browser instead of processing it in my front end (e.g. showing all posts in my Posts.js component).
Relevant code:
Post route
router.post('/', (req, res) => {

  Post.create(req.body)
    .then(newPost => {
        console.log("Success!")
        res.status(201).json(newPost);
        //res.redirect('http://localhost:3000');
    })
    .catch(err => {
      console.log(err);
      res.send(err);
    })
})

Form and Close overlay function
handleClose(e) {
    this.props.closeForm();
    e.preventDefault();
  }

  render() {
    const postForm =

      <form action="http://localhost:5000/api/posts" method="post" className="form-container">

New Blog Post

          Title
          <input type="text" placeholder="Blog Post Title" name="title" required />

          Location
          <input type="text" placeholder="Location" name="location" required />

          <textarea placeholder="Your post here" name="bodyText" required />

          <button type="submit" className="btn" onSubmit={this.handleClose} >Post</button>
          <button type="submit" className="btn cancel" onClick={this.handleClose}>Close</button>

      </form>

Answer: Two options

Recommended: Send the request by JavaScript using an Ajax call
Hacky solution: Insert an iframe tag in your page and have the form have it as a target

XHR
var xhr = new XMLHttpRequest();
xhr.open("POST", '/server', true);

//Send the proper header information along with the request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

xhr.onreadystatechange = function() { // Call a function when the state changes.
    if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
        // Request finished. Do processing here.
    }
}
xhr.send("foo=bar&lorem=ipsum");

iframe

<form action="http://localhost:5000/api/posts" method="post" target="formTarget">

</form>

Answer: Your issue has nothing to do with Node.js. Read about controlled components and axios.
To do it the react way, change your code to the following:
    import React from 'react';
    import axios from 'axios';

    class YourComponent extends React.Component {

        constructor(props) {
            super(props);
            this.state = {
                title: '',
                location: '',
                bodyText: ''
            };

            handleOnInputChange = (event)=> {
                const target = event.target;
                const value = target.type === 'checkbox' ? target.checked : target.value;
                const name = target.name;

                this.setState({
                  [name]: value
                });
            }

            handleSubmitForm = ()=> {
                const { title, location, bodyText } = this.state;

                axios.post('http://localhost:5000/api/posts', {
                    userName: name,
                    userLocation: location,
                    text: bodyText
                })
                .then(response=> {
                    //Do something with the response
                    console.log(response)
                })
                .catch(error=>{
                    //Do something with the error
                    console.log(error)
                })
            }
        }

        render(){

             <form className="form-container">

New Blog Post

                 Title
                 <input type="text" placeholder="Blog Post Title" name="title" required value={this.state.title} onChange={event => this.handleOnInputChange(event)} />

                 Location
                 <input type="text" placeholder="Location" name="location" required value={this.state.location} onChange={event => this.handleOnInputChange(event} />

                 <textarea placeholder="Your post here" name="bodyText" required onChange={event => this.handleOnInputChange(event}>{this.state.bodyText}</textarea>

                 <button type="button" className="btn" onSubmit={this.handleSubmitForm} >Post</button>
                 <button type="button" className="btn cancel" onClick={this.handleClose}>Close</button>

             </form>

        }
    }
    export default YourComponent

Comment: So in this scenario, we've basically moved the post logic from the backend into React. Is this common practice, and what kinds of things would we still need Express to handle?
Comment: Sorry @Mknerr, I'm not sure I understand what you mean by `we've basically moved the post logic from the backend into React`. The frontend app will make a POST request to the backend in order to process something I guess. How are you handling that in your react app?
Comment: I believe it's from this line: ``


Sum of Column until a value is reached

Question:

T's
Product
RS
Value
180000

TT/21-22/079
PROD/21-22/00064
RS27C150X75X6.5X10JR
1718

TT/21-22/079
PROD/23-24/04240
RS27C150X75X6.5X10JR
3550

TT/21-22/079
PROD/23-24/04241
RS27C150X75X6.5X10JR
2384

TT/21-22/079
PROD/23-24/04242
RS27C150X75X6.5X10JR
1600

TT/21-22/079
PROD/23-24/04956
RS27C150X75X6.5X10JR
4824

TT/21-22/079
PROD/23-24/04957
RS27C150X75X6.5X10JR
1600

TT/21-22/079
PROD/23-24/04958
RS27C150X75X6.5X10JR
2498

TT/21-22/079
PROD/23-24/04961
RS27C150X75X6.5X10JR
22439

TT/21-22/079
PROD/23-24/04962
RS27C150X75X6.5X10JR
7180

TT/21-22/079
PROD/23-24/05081
RS27C150X75X6.5X10JR
3450

TT/21-22/079
PROD/23-24/05082
RS27C150X75X6.5X10JR
3101

I am trying to write a VBA script to add the total in 4th column until total reaches less than or equal to E1, I want to select all rows until the total is less than or equal to required value.
I have a loop running to calculate sum of 4th column but it runs into error because the total will never reach near the required value.
The code runs fine when the value of E1 is less than totals of 4th column.
I know its simple, but I have tried to no avail.
Sub test()
    Dim TempReq As Long
    Set sht = Worksheets("TempReq")
    lrD = sht.Cells(Rows.Count, 4).End(xlUp).row

    For i = 1 To lrD
        j = 1
        TempReq = TempReq + sht.Cells(i, 4).Value
        If TempReq => sht.Cells(j, 5).Value Then
            Set rng = sht.Range("a1:d" & i)
        End If
    Next i
    rng.Select
End Sub

Comment: your code works fine, you just need to change the comparison sign around: `If TempReq => sht.Cells(j, 5).Value` should be `If TempReq <= sht.Cells(j, 5).Value`. Currently, the test keeps succeeding after you've reached the required value.
Comment: My apologies for moving your data around a bit, I'm not familiar enough with [Markup table](https://www.tablesgenerator.com/markdown_tables) yet to not have headers(?).
Answer: This should work:
Sub test()
    Dim TempReq As Long, sht As Worksheet, lrD As Long
    Set sht = Worksheets("TempReq")
    lrD = sht.Cells(Rows.Count, 4).End(xlUp).Row
    Dim i As Long, Rng As Range, maxValue As Long
    maxValue = sht.Range("E1").Value
    For i = 2 To lrD
        TempReq = TempReq + sht.Cells(i, 4).Value
        If TempReq > maxValue Then 'went over the limit
            Set Rng = sht.Range("A2:D" & i - 1)
            Exit For
        End If
    Next i
    If Rng Is Nothing Then 'didn't reach it
        Set Rng = sht.Range("A2:D" & i - 1)
        MsgBox "Maximum never reached"
    Else
        MsgBox "Maximum reached on row " & i - 1
    End If
    Rng.Select 'try not to use Select :)
End Sub

It notifies if the values were too small to reach the limit and where the last value  was at. You can of course use Debug.Print if you don't want to get a MsgBox.
Try to avoid using Select since you don't need to use Select to use the range variable you have. Also, declare all your variables, use Option Explicit to avoid this further on.
Comment: Thank you @Notus_Panda for the solution, this works well for the logic I have been trying for a bigger problem. Thanks again.
Comment: You're welcome! Just remember, I added headers but kept E1 as your maximum allowed value.
Comment: I see the changes you made to table.  I was just stuck at how to apply my logic because VBA is so object based and being a newbie I just didn't know how to.

Sum of Column until a value is reached


jquery/AJAX get function not working

Question: Ive been staring at this for an hour now and I cant figure out what Im doing wrong.  Im hoping for a second set of eyes.
The purpose of the function is to get all of the JPG images from a folder on the server and create an array of divs with the acquired images as the div's background image.  mostly this is because IM too lazy to write out all of the html, but also because it allows for quick changes without editing code.
The latest jQuery library is loaded, and supporting other jQuery functions on the page. I think the problem is in the line starting with $("body"). This function runs without error, but no divs are created.
$(document).ready(function() {
var loc = "images/slides";
var fileextension = ".jpg";
$.ajax({
    url: loc,
    success: function (data) {
        $(data).find("a:contains(" + fileextension + ")").each(function () {
            var filename = this.href.replace(window.location.host, "").replace("http:///", "");
            $("body").append($("

"));
        });
    }
});
});

Comment: "not working"? Please explain what is not happening that should. Is jQuery loaded? Are there any errors in the console?
Comment: In what way does this fail?  What does `data` contain and how does the code not behave as expected?  Don't just describe the end results of something you want us to build for you, do some debugging and describe your attempt.
Comment: What does the URL `images/slides` return?
Comment: the latest Jquery library is loaded, and supporting other Jquery functions on the page.  I think the problem is in the line starting with$("body").  This function runs without error, but no divs are created.
Comment: Had you echoed, in the console, the line of HTML you're writing out  you would have seen the problem.
Answer: "...image:url(&apos" + loc + filename +"&apos)..."

&apos? Do you mean '? I'm not sure that would render correctly. A ' is fine though, so this:
$("body").append($("

"));

Personally, I would use this syntax.
$('
', {'class': 'slide'}).css({
    backgroundImage: "url('" + loc + filename +"')"
}).appendTo('body');

NB, the key 'class' is encapsulated because not doing so causes IE to break
Comment: Thanks Popnoodles, your better syntax did it.  Thanks again

jquery/AJAX get function not working