How does this for() work?

Question: I've come across the following for in some code:
for (i = M, j = N; i; )

i,j,M,N are all integers; what does the for do?
Comment: as long as i is <> 0 it will work.
Comment: it's equal to `i = M, j = N; while(i)`
Comment: `i` and `j` will be initialized once to the respective values (here `,` is just a separator and you can give as many statements separated by `,` in sections (init1,init2,init3; condition check; adjustment1,  adjustment2, adjustment3). Here `init` part gets executes only once. And for every condition check the adjustments and body part(if any) gets executed.
So in your case, as long as `i != 0`, the body and adjustments(no adjustments in your case) will gets executed.
**Note**: if nothing is given in condition part, by default it is considered as `true (!=0)`
Answer: it's the same as
i = M;
j = N;

while (i != 0) {
  ...
}

Comment: Made a pedantic edit since you don't know the type of `i` and `j`: the OP must have declared them elsewhere.
Comment: Further pendantanc point. It would be `while (i)` not `while (i != 0)`
Comment: I chose (i != 0) to make it more clear what happens but of course you are right. I wouldn't write (i != 0) aswell
Answer: This for loop's exit condition is i, i is an int, it is implicitly convertible to bool which means that the loop will run until i == 0 (because 0 evaluates to false, any other value evaluates to true). The loop itself doesn't modify i though so if the body of the loop doesn't either then you have an infinite loop.
Answer: The loop can be rewritten to
i = M;
j = N;
while(i) {
    //...
}

Answer: Short Answer:
for (i = M, j = N; i; )

The above for loop, initializes i to M, j to N, and loops till i is non-zero (or false). In case, the value of i is not changed within the for loop, the loop will execute indefinitely.
Long Answer:
In a for loop, there are three parts (from C++ standard guidelines)
for (clasue-1 ; expression-2; expression-3 )

where (emphasize on bold text)

The expression >expression-2 is the controlling expression that is
  evaluated before each execution of the loop body.
The expression expression-3 is evaluated as a void expression
  after each execution of the loop body.
If clause-1 is a declaration, the scope of any variables identifiers
  it declares is the remainder of the declaration and the entire loop,
  including the other two expressions. it is reached in the order of
  execution before the first evaluation of the controlling expression.
Both clause-1 and expression-3 can be omitted.

So in your case,
clause-1 is

i = M, j = N

which is the declaration/initialization of i and j to be used within the for loop.
expression-2 is

i

As expression-2 is supposed to be a boolean expression, the value of i governs the exit condition. Usually a value of 0 is considered false while all other values are true. So the loop will execute until the value of i is 0.
So your loop translates to

i = M; j = N;
while(i) { // statements.  }
Answer: In C and C++ you can use int as a Boolean variable. Actually, in C it does not even exist a bool.
The most common form of a for loop looks like this:
for(init; condition; increment)

It has three statements, so the second statement is simply something that can be evaluated to true or false, which an integer can.
Answer: for (i = M, j = N; i; ) {
    // body
}

is the same as:
i = M;
j = N;
while (i != 0) {
    // body
}

If M != 0 and i doesn't change inside the for loop body you have an infinite loop.

How does this for() work?


OpenGL slows for 5k points

Question: I am writing a SLAM library and want to visualize its work with OpenGL. I need to draw some 100k points and a few hundred rectangles and I would expect that OpenGL can handle it easily. However, after the number of points reaches 5k my program slows down.
I am new to OpenGL, so I guess I am not doing things in a proper way. I used this tutorial for learning.
As the program works, it spits out certain events from which only a few are relevant:

Point Created (size_t id, float x,y,z;)
Point Updated (szie_t id, float x,y,z;)
Position Estimated (Quaternion Q, Vector3D T)

The part of the program that visualizes these events (simplified) works as follows.
We assign a GL_ARRAY_BUFFER to each point. In order not to allocate a new buffer every time we get a new point, I decided to keep a repository of buffers. As a new point arrives we assign to it a "free" buffer from the repository. Only if the repo is empty, we allocate a new buffer with glGenBuffers.
std::stack<GLuint> point_buffer_stack;
std::map<size_t, GLuint> active_points;

void OnPointCreated(size_t id,  float x, float y, float z ){
  GLuint point_buffer_id;
  if(point_buffer_stack.empty()){
    glGenBuffers(1, &point_buffer_id);
  }
  else {
    point_buffer_id = point_buffer_stack.top();
    point_buffer_stack.pop();
  }
  active_points[id] = point_buffer_id;

  OnPointUpdated(id, x, y, z);

}

void OnPointUpdated(size_t id, float x, float y, float z){
  GLuint point_buffer_id = active_points[id];
  float buffer[3] = {x,y,z};
  glBindBuffer(GL_ARRAY_BUFFER, point_buffer_id);
  glBufferData(GL_ARRAY_BUFFER, sizeof(buffer), buffer, GL_STATIC_DRAW);
}

void OnPointDeleted(size_t id){
  GLuint point_buffer_id = active_points[id];
  point_buffer_stack.push(point_buffer_id);
  active_points.erase(id);
}

Draw the frame only when the position is updated:
void OnPositionUpdated (const glm::mat4 & projection){
  glm::mat4 model_view_projection;
  /* Compute  model_view_projection and set the corresponding UniformMatrix4fv for using in the  vertex shader */

  // Draw points
  glEnableVertexAttribArray(0);
  for(const auto & id_vertex: active_points){
    glBindBuffer(GL_ARRAY_BUFFER, id_vertex.second);
    glVertexAttribPointer(
      0,                  // layout from vertex shader.
      3,                  // 3D
      GL_FLOAT,           // type
      GL_FALSE,           // normalized?
      0,                  // stride
      (void *) 0            // array buffer offset
      );
    glDrawArrays(GL_POINTS, 0, 1);
  }
  glDisableVertexAttribArray(0);

  /*Draw a rectangle that shows the current position by drawing two triangles */

  glfwSwapBuffers(window);
  glfwPollEvents();
}

On my Asus Zenbook with Intel® Xe Graphics, Ubuntu 20.04, OpenGL starts to lag behind the camera at ~5k points. After some time I get an insufficient memory error from OpenCV (which is built with OpenGL support).
Is this expected? What am I doing wrong? How to solve this issue?
For the reference, the initialization of OpenGL is done as follows:
glfwInit();
glfwWindowHint(GLFW_SAMPLES, 4);
glfwWindowHint(GLFW_DOUBLEBUFFER, GLFW_TRUE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

window = glfwCreateWindow(1920, 1080, "SLAM 3D visualization", NULL, NULL);

Answer:
We assign a GL_ARRAY_BUFFER to each point.

That's your problem. This means you are allocating an entire buffer object for all of 12 bytes of memory. Putting each point in its own buffer also means that you must render each point with a separate draw call.
None of that is a recipe for performance.
Create a single large buffer for all the points you intend to use, and render them all with a single draw call. If you need to change parameters or something between points, make them a separate vertex attribute. Or failing that, make them uniforms to your shader and render all of the points that use one set of parameters, change the uniforms, then render the next points that use the new parameters, etc.

OpenGL slows for 5k points


jqGrid - refreshing grid issue

Question: I am having trouble refreshing the grid on a submit to allow the new data to be shown and then adding a new item again.
The code to explain
jqGrid itself
 $("#grid").jqGrid({
        datatype: "local",
        data: List,
        width: 1405,
        shrinkToFit: 1105,
        rowNum: List.length,
        colNames: ['id', 'Delete'],
        colModel: [
            { name: 'id', index: 'id', editable: false, hidden: false, hidedlg: true },
            {
                name: 'actions', index: 'actions', width: 100, sortable: false, editable: false, formatter: imageFormat,
                formatoptions: {
                    keys: true,
                    editbutton: false,
                    delOptions: { url: getURL('controller') + 'actionmethod?id=' + $('#id').val() }
                }

            }
        ],

An external button to add a row
$("#Add").click(function () {

   $("#grid").jqGrid('editGridRow', "new", { height: 480, width: 400, reloadAfterSubmit: true, recreateForm: true });

});

And basically the afterSubmit event...
$("#grid").bind("AfterSubmit", function (event, status, postData) {

    $("#grid").jqGrid('GridUnload');

    // This basically calls the code on the top
    loadGrid();

   // close the add item dialog...
});

The problem is:
if I remove the line: $("#grid").jqGrid('GridUnload')
The grid will not refresh correctly (doesnt add the new row on the UI) however, it will add it to the database on the server end and I can keep adding new rows successfully to the database but without no refresh.
When I say, "it will add it to the database" I mean if I reload the whole page, the items will show
If I keep the line: $("#grid").jqGrid('GridUnload')
The grid will refresh properly on the first time only and add the row into the database. Afterwards I can keep adding but the submit window doesnt close nor do the grid refresh.
I have tried using
$("#grid").trigger('gridReload') - but without any success (maybe I a using it wrong)
Thanks
Comment: @oleg - Apparently your the man to call with these jqGrid issues. If I have done this wrong (commenting your name in the question) I apologise
Comment: can you post jsfiddle ?
Comment: Probably not as its not all my code.
Comment: do you use firebug if yes please check whether you are getting any js errors in console tab after grid refreshes first time but not for subsequent insertions.
Comment: Good idea, will have a look thanks, @AtulNar
Answer: I think your mistake in here:

I have tried using
$("#grid").trigger('gridReload') - but without any success (maybe I a
  using it wrong)

The method is "reloadGrid", so using
$("#grid").trigger('reloadGrid')

should be fine for you needs to refresh the grid data only.
Comment: Thanks for the spot, but it doesn't actually do anything (but it should..) do I need to put in anything after?
Comment: Sorry, copy-paste mistake, corrected it.
If this does not triggers the data reload, check the js console for errors, or check the URL monitor if the URL is correct or if the server returns correct response code (200 or similar).

jqGrid - refreshing grid issue


TextView from database not detect in adapter

Question: public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

    private Context context;
    private List<Result> results;

    public RecyclerViewAdapter(Context context, List<Result> results) {
        this.context = context;
        this.results = results;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_view, parent, false);
        ViewHolder holder = new ViewHolder(v);

        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Result result = results.get(position);
        holder.textViewId.setText(result.getId());
        holder.textViewName.setText(result.getName());
        holder.textViewPhone.setText(result.getPhone());
        holder.textViewAddress.setText(result.getAddress());
        holder.textViewStatus.setText(result.getStatus());
    }

    @Override
    public int getItemCount() {
        return results.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        @BindView(R.id.textId) TextView textViewId;
        @BindView(R.id.textName) TextView textViewName;
        @BindView(R.id.textPhone) TextView textViewPhone;
        @BindView(R.id.textAddress) TextView textViewAddress;
        @BindView(R.id.textStatus) TextView textViewStatus;
        @BindView(R.id.button) Button button;
        @BindView(R.id.checkBox) CheckBox checkBox;

        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
            itemView.setOnClickListener(this);

            String status = textViewStatus.getText().toString();
            if(status.equals("Check")){
                checkBox.setChecked(true);
            }else{
                checkBox.setChecked(false);
            }
        }

I've retrieved the data from MySQL database to the text view in recyclerview show name status phone..., the status will show check and not check, I added checkbox in the adapter to set the checkbox check if the textview status is check, but the string status compare it to the textview value android:text in XML not the value from database, it can only detect the value from database if I add listener... how can i do it without onClick listener?
Comment: What you actually want ?
Answer: Why not place this block of code in the onBindViewHolder method instead:
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    ...
    String status = holder.textViewStatus.getText().toString();
    if(status.equals("Check")){
       holder.checkBox.setChecked(true);
    }else{
       holder.checkBox.setChecked(false);
    }
}

Answer: Because you get Text from TextView in a constructor of Viewholder which is called before your onBindViewHolder() in which you set Text in TextView and also constructor called only one time after creating RecyclerView.
So, Please add this code in onBindViewHolder() method to get the correct response.
String status = textViewStatus.getText().toString();
            if(status.equals("Check")){
                checkBox.setChecked(true);
            }else{
                checkBox.setChecked(false);
            }


Can I reroute this air duct?

Question: I'm quite new to dealing with HVAC duct-work.
We would like to install a suspended ceiling in this room. Since the finished ceiling will be higher than this duct-work, we're going to build drywall bulkheads around them.
In order to reduce the wasted space (and having to build more bulkheads), we were thinking of running the two 7-inch ducts from the end of the main duct. This way we can build a single bulkhead around the main duct and continue it, containing the two smaller ducts, to the exterior wall where they turn apart and run upstairs. Both 7-inch lines lead to registers in the floor immediately above, approximately 10 feet apart, on the same wall.
Are there any good reasons not to do this (such as loss of pressure in one of the lines)? Would it be better to replace those two lines with a larger conduit and branch it when it reaches the wall?
Comment: Note, that's a damper control on the right duct in your picture (most likely in the closed position). You'll need to leave that accessible, which can be done with a small access panel in the drywall.
Comment: I'm no expert, but it was my impression from my reading that taps shouldn't be in the end cap to allow the system to pressurize properly.
Answer: I don't see a problem with that, other than the existing duct doesn't look wide enough to fit both. You'll have to get/build a reducer that goes from something slightly wider (that can support both circular ducts coming out of it) to the existing square duct size. Most metal shops can build this sort of thing for you - I had a couple 45-degree elbows built to re-route some ducts in my basement, it cost me around $50 I think.
<code> | |   | |
 | |   | |    <--  existing two round ducts (one moved)
 | |   | |
+---------+
|        /
|       /    <-- new reducer
+------+
|      |
|      |     <-- existing square ducts
|      |
</code>
The main thing is to keep the number of elbows to a minimum. In fact, in your case it may work better as it looks like you'll reduce the number of elbows by one.

Another option would be to extend the main duct, and split the two round ducts off at the end. Not sure how long those are now, but the box stores carry a few regular square duct sizes you can buy and assemble/install yourself.
Comment: Thanks @gregmac. Actually, we had considered extending the existing square duct since it only has to run about 10 feet before it reaches the wall.

Can I reroute this air duct?


apt-get install pgpool2 fails on trusty

Question: I am trying to install pgpool2 on trusty, but when using apt-get to do so it fails, like so:
# uname -a
Linux vagrant-ubuntu-trusty-64 3.13.0-51-generic #84-Ubuntu SMP Wed Apr 15 12:08:34 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux

# apt-get install pgpool2
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 pgpool2 : Depends: libmemcached6 (>= 0.44) but it is not installable
E: Unable to correct problems, you have held broken packages.

Answer: The solution is to install pgpool2 like so:
$ apt-get install pgpool2=3.3.2-1ubuntu1 libpgpool0=3.3.2-1ubuntu1
For some reason the default packages for pgpool2 are broken, but when you specify these versions it installs properly.
Comment: Don't forget you can accept your4 own answer to show others this was the solution that worked
Comment: `apt-get install pgpool2` works now

apt-get install pgpool2 fails on trusty


Replace oven timer with switch

Question: I have a Moulinex Series O35 convection oven. The timer has stopped working, and after taking it apart, I found that the timer was broken (one of the connections had broken off).
I'm wondering if I can simply replace the timer with a standard switch from the hardware store.
Is it possible and safe just to put a switch where the timer was and replace the timer's connections with the switch's?
The timer's serial number is e210866
Comment: With a timer, if you forget, the timer will turn off.  With a simple switch, it will not turn off.
Comment: You don't show a picture or explain exactly how it is broken, but might be possible to repair/fix.  If lucky, might also be an inexpensive part to replace.
Comment: Have you searched the internet for a direct replacement part? That should be the first step before even considering cobbling something together that may or may not work.
Answer: If you do not replace the timer-switch with the same timer-switch you will have made modifications to the oven that void its safety listing, whatever that may be for your locality.
That will shift any liability from a failure of the oven that causes a house fire or the like from the manufacturer to you. It will also provide your insurer with an excuse not to pay a claim.
Answer: Theoretically you could. But keep in mind that:

The switch needs to be capable of switching the full current & voltage. A quick search finds mixed answers - French manufacturer, all prices of anything (mostly used) in Euros, which would imply ~ 240V/50Hz. On the other hand, searching for the switch finds markings of 120V or 125V, 15A, 60 Hz. So not clear exactly what you've got, but pretty sure the timer or switch needs to be rated to handle the full power requirements of the oven.
A typical switch isn't going to be a direct (same form factor) replacement, so insulation of wires/connectors, making sure nothing can fall in/around the switch into the oven controls, etc. is critical for safety.
As noted in a comment, if you use an ordinary switch then there is the "got on a call and forgot to turn off the oven" followed by "what's that smell?" followed by "smoke alarm" is a real possibility.

So conceptually, "yes", but practically, "no".
Comment: The e210866 timer is available for $13 from a [well-known internet marketplace](https://www.ebay.com/itm/154591837244?hash=item23fe643c3c:g:ewwAAOSwWWdeIxJs).
Comment: Given that a switch might not be the best option after all, is there something more reasonable that I could find at a local hardware store, or will I have to resort to ordering the same timer part online?
Comment: I don't know that oven, but usually that spot needs heat resistant components, a standard timer will not. You could permanently connect the wires, bypassing the timer, and then the oven is manually turned on and off.

Replace oven timer with switch


Why is the drywall wet in one corner?

Question: I'm repainting a room and noticed that the paint was chipping off (and was even bubbly) in one of the corners just above the baseboard. It wasn't wet but to me it looked like evidence of past moisture. I chipped some of that top layer off without looking too much into it. I spackled the corner and when I started sanding it the next day, I noticed that the spackle didn't dry and almost all of it fell out while sanding. I also noticed that the wall was cold (wouldn't call it wet to the touch). I've decided that I will need to cut out a piece of the drywall in that corner to inspect what is happening inside. The room is on the second floor and that corner is protruding in the air as seen in the photos.

House is located in southeast PA. At the moment it's cold around here (usually just around 32). Hasn't rained in a week or so. No evidence of wetness outside so I'm wondering if there is a weep hole that Is allowing the cold air to get in. I'm hoping to not leave the wall open for longer than I have to and that is why I'm posting here before I start.

I will check the insulation in the two walls as the walls converge to the corner.
I will also check to feel any cold holes. If I find that there is air coming in, would it be enough to get some kind of a wood caulk or sealer, and seal the corner joint from the inside?

Edit: Opened up the drywall - no evidence of wetness. I did notice a draft from the corner I guess. applied some insulating foam to that so hopefully that will help in the future. Thanks for the advice!
Comment: No, you meant protruding. Any wetness is likely from higher up on that wall (or the roof). Please post a photo of the entire area. Please put any new information in your answer, not down here.
Comment: Wouldn't it be a fair assumption that because the corner is more exposed to the outside cold than any other part of the room, it's causing small but constant levels of low condensation on the surface?  It would be enough to cause superficial damage, but not damage to the surface below.
Comment: Hello, and welcome to Home Improvement. Would you fix the images, and give us more info (e.g. your location and climate)? And, you should probably [take our tour](//diy.stackexchange.com/tour) so you'll know the details of contributing here.
Comment: From your description it sounds like a leak has run down the sheetrock. A leak will cause the paper and or paint to blister and peal. If allowed to dry it is usually ok on a wall but if it bellies (wet insulation pushing it causes a bulge it will always have the bulge. Be careful messing with damp Sheetrock because the paper is really easy to tear when wet,
Comment: I'm not sure. I need to inspect to roof first from what I'm reading here. The wetness is only on the bottom edge so if it is coming from the top, I guess it might be pooling down at the bottom edge because the rest of the wall has no evidence of water damage. I'm ok with tearing out and replacing the drywall especially since I plan on repainting the room anyways.
Comment: If you're willing to tear out drywall, I'd suggest that this may be your best course of action. Cut back until you find a stud on each side of the corner, then, using a straight edge, cut up the _center_ of the stud on each side. That will allow you to pull the insulation (if it's in batts) or push it around some to see what's going on. Look for evidence of water coming down from the roof. If you see that, start inspecting the attic. The leak may not be at the corner, but higher up the roof, then it runs down the inside to that corner and drips down the wall.
Comment: Yeah that's what I'm thinking it is. Checked the attic above this room and I don't see any water there. I will tear out a piece of drywall and then go as far as needed. I am thinking it's a stream of cold air that's getting to the drywall. That's why I was thinking of maybe applying some kind of wooden caulk to that joint to shield the drywall and paint from. Getting damaged.
Comment: https://www.youtube.com/watch?v=zixxZJeBLUI
Answer: I'd go with FrK and Steve Sether, since you found no signs of water and this is a bump-out. Condensation is most likely.
It could be a lack of insulation, but more likely it's an air leak. This could be permanently fixed if a Spray Foam's tube easily feeds up into there from a gap in the siding's corner or from drilling a small hole in the room's corner.
You'll need Big Gap Filler spray foam, shot for about 5-seconds to get the area filled.

Why is the drywall wet in one corner?


Multiple return values in Lua

Question: Ran into this problem earlier.
For a multi return value  function
fn=function() return 'a','b' end

the call
print(fn()) returns a b
but the call
print(fn() or nil) returns only a
why? or should not matter since the first call was successful right?
Answer: Quoting from Programming in Lua §5.1 – Multiple Results

Lua always adjusts the number of results from a function to the circumstances of the call. When we call a function as a statement, Lua discards all results from the function. When we use a call as an expression, Lua keeps only the first result. We get all results only when the call is the last (or the only) expression in a list of expressions.

In the case of your example, the return value of fn() is used as an expression (the left operand of or operator), so only the first value is kept.

Multiple return values in Lua


templated function pointer as template parameter

Question: I just stumbled on a small problem that bugged me while dealing with templates. Here is an example:
template<class _returnType, _returnType (*_function)()>
_returnType aliasGetter() { return _function(); }
int getCoolNumber() { return 42; }
int main()
{
    std::cout << aliasGetter<int, &getCoolNumber>(); //42
}

this code works (http://cpp.sh/ if you want to try it), however since I give a function pointer as template parameter I shouldn't need _returnType, it's right there in the function signature, the problem is, no matter how hard I try, I can't find a way to get rid of this additional template parameter.
How can I make aliasGetter take only one template parameter (a pointer to the getter to alias)?
If that's not possible, why not?
Comment: @WhiZTiM That would require passing the function pointer to the call at run-time.
Comment: What about using a single template parameter and rely on Template Argument Deduction?
Comment: You need it because your second template parameter depends on it. You may build up something with https://functionalcpp.wordpress.com/2013/08/05/function-traits/ but I doubt that you will save a template paramter.
Answer: In C++17, it will become possible, thanks to template auto:
template <auto F> std::invoke_result_t<F> aliasGetter() { return F(); }

Before C++17, it's not possible. You need to specify the type of the non-type template parameter - there's no way around that. You can't make a factory for this either since you can't pass a function pointer through a function template and have it end up as a non-type template argument.

The shortest workaround in C++14 is to, sigh, use a macro:
template <class T, T F> std::result_of_t<T()> aliasGetter() { return F(); }
#define TEMP_ALIAS(x) decltype(x), x

std::cout << aliasGetter<TEMP_ALIAS(&getCoolNumber)>();

which gets you the type of your function pointer without you having to manually type it twice.
Comment: I knew it was possible with C+17 thanks to the new syntax you described, however, I thought that maybe, it can be done without this magic trick (that's why I tagged C++14). It's still a good and clear answer though
Comment: `std::result_of` is [deprecated](http://en.cppreference.com/w/cpp/types/result_of) on C++17, use `std::invoke_result` instead.


Impulse on different screen sizes Spritekit Xcode

Question: Hi I'm making a game where you tap to give an upward impulse to the ball of lets for example say a cgvector (4,0).
This if for both 4inch and 3.5 inch retina displays.
Will the impulse move the ball the same amount in pixels or same amount relative to the screen size different. I need the ball to move the same amount relative to the size or else the game will become easier on i5's . I have an idea of how to achieve it.
Could someone with knowledge of how impulse works clear this up?
Only asking because i recently played it on a i5 and got higher scores than usually on the i4
Thanks
Answer: physics simulation does not depend on screen size, however the scene may be scaled (see scaleMode) which can affect how much of the scene you can see on each device.
Comment: i.e. it will move the same pixels?
Comment: and it WAS actually easier?
Comment: a body with a given velocity will move at the same speed (in points, not pixels) regardless of screen size


Change dynamically image according to the selected combobox using javascript

Question: I am working one task i.e change image according to select the combobox item name. My task look like:

In this picture I have made one combobox in that having item name like photo1, photo2 and photo3.
So my question is that, after select the combobox selected item according to the selected item image will be change automatically and replace the heart image. So for this task I have used the html page and one external JavaSCript.
In html page whole UI is described while in external JavaScript other functionality are described.
Above show the html page code i.e.

function addAnchor(group) {
             group.add(anchor);
    }

    function loadImages(sources, callback) {
             var images = {};
             var loadedImages = 0;
             var numImages = 0;
             for(var src in sources) {
                 numImages++;
             }
             for(var src in sources) {
                 images[src] = new Image();
                 images[src].onload = function() {
                       if(++loadedImages >= numImages) {
                            callback(images);
                       }
                 };
                 images[src].src = sources[src];
              }
        }

        function initStage(images) {
                 var stage = new Kinetic.Stage({
                        container: "container",
                        width: 691,
                        height: 440
                    });

    var yodaGroup = new Kinetic.Group({
                        x: 0,
                        y: 0,
                        draggable: false
                    });
                    var layer = new Kinetic.Layer();

    function addProduct( imgObj ){
           var layer = new Kinetic.Layer();
            var imageObj = new Image();
            imageObj.onload = function() {
              var image = new Kinetic.Image({
                x: stage.getWidth() / 2 - 53,
                y: stage.getHeight() / 2 - 59,
                image: imageObj,
                width: 106,
                height: 118,
       draggable: true
              });
                // add the shape to the layer
              layer.add(image);

              // add the layer to the stage
         stage.add(layer);

         image.on("mouseover", function(){
        var imagelayer = this.getLayer();
        document.body.style.cursor = "move";
        this.setStrokeWidth(1);
        this.setStroke("#000000");
     layer.draw();
      writeMessage(messageLayer, "Drag Image Into Position Double Click To Remove");
    });

    var messageLayer = new Kinetic.Layer();
      stage.add(messageLayer);

    // yoda
       var yodaImg = new Kinetic.Image({
           x: 0,
           y: 0,
           image: images.yoda,
           width: 691,
           height: 450,
           name: "image"
       });
          yodaGroup.add(yodaImg);
               stage.draw();
         }

        window.onload = function() {
               var sources = {

        //From here the static images has coming. I want to do dynamic // image as   per the combobox is selected item name is changed.

                   yoda: "images/heart.jpg"
               };
               loadImages(sources, initStage);
        };

            <select name="Choice">
               <option value="Pic1.jpg">Photo 1</option>
               <option value="Pic2.jpg">Photo 2</option>
               <option value="Pic3.jpg">Photo 3</option>
            </select>

So here is my code and just I want to do the call the dynamic image as per the combobox selected item name is changed in windows load which I have comment from where the image is calling by JavaScript
Comment: Where is the default heart image in your posted code?
Answer: If you want to change the  image path according to the selected option of the select box,
HTML :
<select name="kitchen_color" id="kitchen_color" onchange="setImage(this);">
  <option value="https://www.google.ru/images/srpr/logo4w.png">Google</option>
  <option value="http://yandex.st/www/1.645/yaru/i/logo.png">Yandex</option>
  <option value="http://limg.imgsmail.ru/s/images/logo/logo.v2.png">Mail</option>
</select>

JavaScript :
function setImage(select){
  var image = document.getElementsByName("image-swap")[0];
  image.src = select.options[select.selectedIndex].value;
}

Comment: Great. But TharinduLucky when I am doing same code. it shows the path in the alert but does not shows the image in the image div.                                 function setImage(select){
  var image = document.getElementById("container");

  image.src = select.options[select.selectedIndex].value;
  alert(image.src);
}
Comment: Thanks TharinduLucky. It is working. But after that it is coming one more error and that is the image is coming but it is not replace the same image infact it is creating new div and displaying in that.
Comment: To make your life easier, I put it in this snippet.. http://js.do/code/selectbox-image I don't see it's creating any divs


How to plot multiple xarray DataArray objects into one figure using the xarray plotting capability?

Question: I have the following xarray DataSet with 3 dimensions (time, latitude, longitude) and 2 variables (__xarray_dataarray_variable__, regions). The regions variable can be either nan, 0, 1, 2, 3, 4, or 5 indicating the region Id for the lat/lon. The __xarray_dataarray_variable__ variable is of integer.
<xarray.Dataset>
Dimensions:                        (latitude: 106, longitude: 193, time: 92)
Coordinates:
  * latitude                       (latitude) float32 -39.2 -39.149525 ... -33.9
  * longitude                      (longitude) float32 140.8 140.84792 ... 150.0
  * time                           (time) datetime64[ns] 1972-01-01 ... 2017-07-01
Data variables:
    __xarray_dataarray_variable__  (time, latitude, longitude) int32 dask.array<shape=(92, 106, 193), chunksize=(2, 106, 193)>
    regions                        (latitude, longitude) float64 nan nan ... nan

I would like plot a figure which contains 6 lines and where the Y axis is the spatial mean value of __xarray_dataarray_variable__ and X axis is the time. Each line is for one region Id.
da = ds["__xarray_dataarray_variable__"]

# Region 0
da_region_0 = da.where(ds.regions == 0)
da_region_0_mean = da_region.mean(['longitude', 'latitude'])  # Get spatial mean

# We can follow the example to get da for region 1 - region 5.
... ...
p_mean = da_region_0_mean.plot.line(x='time')  # This is only plotting a figure for each region but not all 6 regions.

How can I plot one single figure that contains lines for all 6 regions instead of individual figures for each using the xarray plot capability?
Comment: Did you try creating a figure and supplying its axis to each of your line plots? That should help if you want to overlay multiple xarray plots in one figure
Answer: I think I understand what you are looking for.  This is the way that I would approach it.  I'll set up some data in the style of yours first:
import matplotlib.pyplot as plt
import numpy as np
import xarray as xr

data = np.random.random((6, 3, 11))
da = xr.DataArray(data, dims=['longitude', 'latitude', 'time'], name='foo')

region_data = np.random.choice(range(6), size=(6, 3))
region = xr.DataArray(region_data, dims=['longitude', 'latitude'], name='region')

ds = xr.merge([da, region])

This Dataset, ds, looks like:
<xarray.Dataset>
Dimensions:  (latitude: 3, longitude: 6, time: 11)
Dimensions without coordinates: latitude, longitude, time
Data variables:
    foo      (longitude, latitude, time) float64 0.7016 0.1519 ... 0.1446 0.2396
    region   (longitude, latitude) int64 5 1 1 5 0 1 0 0 2 3 0 4 4 3 3 1 2 1

To compute the regional means, we can first stack the longitude and latitude dimensions of the Dataset:
stacked = ds.stack(xy=('longitude', 'latitude'))

This will enable us to easily use groupby to group by region number when computing the mean:
regional_means = stacked.foo.groupby(stacked.region).mean('xy')

To plot, we can use xarray.DataArray.plot.line along with the hue keyword argument to produce a single panel with time series lines for each region:
lines = regional_means.plot.line(hue='region', add_legend=False)
labels = range(6)
plt.legend(lines, labels, ncol=2, loc='lower right')

Here we have opted to create our own legend to give us as much control as possible over its position and format.  This produces a plot like this:

More line plotting examples can be found here.


connecting to WAMP SQL database using PHP object

Question: I want to call a php file in the WAMP server from my android app. The php file is then expected to connect to the WAMP sql database. I have written the following code. I need the structure as below because of the format of the data im planning to upload.
So now the problem is as soon as I make a ConfigGraphsDAO object in uploadRequest method, the fileId is returning null. but if i comment that line the fileId is return as 2. Can someone explain to me what I am doing wrong please. Thanks  a lot
The php file called from my app is called UploadController.php and its as follows
require_once 'config.php';
require_once 'DAO.php';
$fileId=1;
class UploadController {
    private static function uploadRequest() {
       global $config;
       $configGraphDAO = new ConfigGraphsDAO();
       $fileName = (isset($_POST[self::$PARAM_FILE_NAME])) ? $_POST[self::$PARAM_FILE_NAME] : null;
       $GLOBALS['fileId']=$GLOBALS['fileId']+1;
       echo self::$PARAM_FILE_ID . "=" . $GLOBALS['fileId'];
    }
}

ConfigGraphsDAO.php is as below.
class ConfigGraphsDAO extends DAO{
//I plan to do something here. But right now its all empty
}

DAO.php is as follows
abstract class DAO {
  public function __construct() {
    $this->connect();
  }

  private function connect() {
    global $config;
    $this->con = mysql_connect($config["DB_HOST"], $config["DB_USER"], $config["DB_PASSWORD"],$config["DB_NAME"] );
    if (!$this->con) {
        throw new Exception("Failed to connect to database." . mysql_error());
    }
}
}

config.php is as follows.
$config = array();
$config["DB_HOST"] = "localhost"; //"http://172.26.191.215"; //"localhost"; //
$config["DB_NAME"] = "ocean";
$config["DB_USER"] = "root";
$config["DB_PASSWORD"] = "";
$config["UPLOAD_DIR"] = "context_repo";
$config["DASH_SERVER_ADDR"] = "http://172.26.191.215/ocean";

Comment: Where is `$PARAM_FILE_NAME` defined?
Comment: I think you need to read the manual on the subject of [Abstract classes](http://php.net/manual/en/language.oop5.abstract.php) Mainly this `Classes defined as abstract may not be instantiated`. And this `When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child;`
Answer: include ConfigGraphsDAO.php also in the required files list
Comment: Thanks. That was the problem. So like in java when we are using another php file is it necessary to put it like "require_once 'ConfigGraphsDAO.php';" at the beginning.


Outlook VSTO - Adding file path/hyperlink to MailItem WordEditor from Outlook VSTO

Question: I am having following problem.  I have a window that opens and allows me to select some files.
Then I can right-click on that window and choose to attach paths of selected files to a new mail dialog.
The workflow is like this:

I open my windows and select couple of files
Right-click, choose to add selected files paths to MailItem
Logic will check if there is an ActiveInspector
3.1. If there is one, I get its CurrentItem as MailItem (so, new mail dialog exists and does not need to be created)
3.2. If there is none, I call CreateItem(Microsoft.Office.Interop.OLItemType.olMailItem) to create
    new mail dialog and then I call MailItem.Display(false) to display
    the mail item dialog
Next I loop through list of selected files paths and add them to the new mail dialog.  This works great.

PROBLEM If I open my window for the 2nd time to select more files and add their paths to the same mail dialog I opened earlier, they are not added.
Here is the code:
public void AddFilePaths(List<string> paths)
{
    if (paths.Count > 0)
    {
        var inspector = MyAddIn.Application.ActiveInspector();
        MailItem mi = null;
        bool newMailItem = false;

        if (inspector != null)
        {
            // If new mail dialog is already open, just get it.
            // This is called on my 2nd attempt to add paths to new mail.
            // This MailItem is the same one created on 1st call in below
            // else block.  I confirmed that by adding some dummy email
            // Body in below else block, then checking for it here on
            // 2nd call.  I think this proves that correct
            // Inspector/MailItem is returned here.
            mi = MyAddIn.Application.ActiveInspector().CurrentItem as MailItem;
        }
        else
        {
            // create new mail dialog and display it
            // this is called on my 1st call to add paths to new mail
            mi = MyAddIn.Application.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
            mi.Body = "Dummy email body";
            newMailItem = true;
        }

        if (newMailItem)
        {
            mi.Display();
            inspector = MyAddIn.Application.ActiveInspector();
        }

        if (inspector != null)
        {
            foreach (var path in paths)
            {
                AddPathToActiveInspector(path);
            }
        }
    }
}

The code above calls this method to add path to the current ActiveInspector WordEditor:
public void AddPathToActiveInspector(string path)
{
    var inspector = MyAddIn.Application.ActiveInspector();
    dynamic we = inspector.WordEditor;
    dynamic word = we.Application;
    const string nl = "\n";

    // I have noticed that if I am debugging, this line will throw error
    // "COMException was unhandled by user code", "An exception of type
    // System.Runtime.Interop.Services.COMException occurred in
    // System.Dynamic.dll but was not handled by user code:
    // Message: This command is not available
    // InnerException: null
    // I have also seen following error on 2nd attempt: "The TypeText
    // method or property is not available because the document is
    // locked for editing."
    word.Selection.TypeText(nl);

    string address = path;
    string subAddress = "";
    string screenTip = "";
    string displayText = path;
    word.ActiveDocument.Hyperlinks.Add(word.Selection.Range, ref address, ref subAddress, ref screenTip, ref displayText);
    word.Selection.TypeText(" ");
}

Comment: So what happens if you step through your code? Does it actually run? Are you sure there is only one Inspector? What do you do with inline replies
Comment: Thanks Dmitry, please see my updated question.  I have traced the code and I get correct inspector/MailItem which I confirmed by adding dummy MailItem.Body message when MailItem is created (on 1st call), then checking Body for that text on 2nd call.  I added that to my code comment above.  I have also found that an COMException is thrown but only while debugging (???).  I added comment in my code for that, too.  In my Replies and forwards section (inline replies), nothing is checked and I'm including original message text (if that is what you meant with inline replies.  Much appreciated
Answer: I would simply create a new email message each time you are adding your paths to avoid the possibility of adding paths to a wrong email message which could happen if you have opened multiple emails.

Add a reference to Microsoft.Office.Interop.Word to your project
Add using Microsoft.Office.Interop.Word on top of your class file

Here is the code:
public void AddFilePaths(List<string> paths)
{
    if (paths.Count > 0)
    {
        MailItem  mi = ThisAddIn.Application.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
        mi.Display();
        if (mi!= null)
        {
            foreach (var path in paths)
            {
                AddPathsToNewEmailMessage(path);
            }
        }
    }
}

The code above calls this method to add the path to the new email message WordEditor:
public void AddPathsToNewEmailMessage(string path)
{
    object link = url;
    object result = "url";
    object missing = Type.Missing;
    string nl = "\n";

    var inspector = ThisAddIn.Application.ActiveInspector();
    MailItem currMessage = inspector.CurrentItem;
    Word.Document doc = currMessage.GetInspector.WordEditor;
    Word.Selection sel = doc.Windows[1].Selection;
    doc.Hyperlinks.Add(sel.Range, ref result, ref missing, ref missing, ref link, ref missing);
    sel.EndKey(Word.WdUnits.wdLine);
    sel.InsertAfter(nl);
    sel.MoveDown(Word.WdUnits.wdLine);
}


How to create tabbed page in Xamarin.Forms similar to that of Facebook app

Question: I am working with Xamarin.Forms and I would like to create a navigation method similar to that of the Facebook app and also other newer versions of different apps. Here are two pictures, one of Facebook app on Android and the other is of KakaoTalk, also on Android.

I've tried several different ways to implement this. For example I wrapped the MainPage (TabbedPage) inside a NavigationPage. I also tried wrapping the MainPage (ContentPage) inside a NavigationPage then calling
PushAsync(new TabbedPage());

inside the MainPage via the Navigation property. I also tried wrapping the children of the MainPage (TabbedPage) inside separate NavigationPages. None of these attempts resulted in the desired effect.
I would like the following to happen. When a user taps on a Button or something that navigates to another page I'd like a ContentPage to pop in front of everything (tab bar included) except for the Navigation bar (or Action Bar). Obviously this happens via the PushAsync() method which also results in a small back arrow appearing in the Nav bar. My understanding is that a PushAsync() call pushes the chosen page onto the navigation stack provided by the NavigationPage. Therefore if a TabbedPage is wrapped inside a NavigationPage a new ContentPage would not be able to pop in front of the tabs like in the two applications mentioned above.
This, plus the fact that the tab bars of said apps don't get inside the ActionBar (in Android) in landscape mode leads me to believe that what I'm trying to achieve is best done not using TabbedPage but something that acts like a tab bar, e.g. a horizontal stack of Buttons perhaps.
Has anyone implemented this correctly and in an elegant way using Xamarin.Forms? So again, I would like to make this tab like navigation with the tabs staying underneath the ActionBar in landscape mode and a new Page appearing in front of the tabs (hiding them) when pushed onto the navigation stack. Do you think this can be done with Custom Renderers? Of course in iOS these are done with tabs but in Android I'm not sure.
What I would like is not necessarily code examples, but a best practice on this issue. So again, this is in Xamarin.Forms with a common PCL project and an Android and iOS project. Thank you in advance for your answers and advices!
P.S.: I've obviously searched this site before (Google as well) but I've found no real articles on this issue.
Answer: I have used ToolbarItems order=primary for navigation bar menu button and ToolbarItems order=secondary for tab bar on top.I have PCL the code written is in XAML. :)
http://codeworks.it/blog/?p=232
Answer: You can create a custom controller using the grid. it will remove the hassle of writing custom renderers.
Answer:
My understanding is that a PushAsync() call pushes the chosen page onto the navigation stack provided by the NavigationPage. Therefore if a TabbedPage is wrapped inside a NavigationPage a new ContentPage would not be able to pop in front of the tabs like in the two applications mentioned above.

This is not true actually. According to Xamarin API Doc, the Navigation property is context-aware, i.e. it will find all its parents until there is a NavigationPage.
In Android, only one NavigationPage is allowed and therefore even you call PushAsync() inside the TabbedPage, it will still push via your wrapping NavigationPage.
Comment: Yeah, well, this is true :D Thank you for this. Actually, I've found the answer since. I use a ViewPager in Android and tabs in iOS. I don't think there is a common code solution for this problem that behaves the way I wanted it.
Comment: @GáborBirkás Can you post the code of the solution you found as the official answer to the question? Many people like me have the same problem, and your solution seems interesting. Is it a custom renderer? Can you post it here or as a basic github sample project?


Why my dictionary is not updating in Python?

Question: I have below code,
The output is coming very weird.
wsman_invoke_attr = {}
l = [u'BIOS.Setup.1-1:Slot3', u'BIOS.Setup.1-1:Slot2', u'BIOS.Setup.1-1:Slot1', u'BIOS.Setup.1-1:Slot5', u'BIOS.Setup.1-1:Slot4']
w = []
k = {"a":w}
for i in l:
    wsman_invoke_attr["InstanceID"] = i
    w.append([wsman_invoke_attr])
    k["a"] = copy.deepcopy(w)

    wsman_invoke_attr.clear()
print k

The output is coming as {'a': [[{'InstanceID': u'BIOS.Setup.1-1:Slot4'}], [{'InstanceID': u'BIOS.Setup.1-1:Slot4'}], [{'InstanceID': u'BIOS.Setup.1-1:Slot4'}], [{'InstanceID': u'BIOS.Setup.1-1:Slot4'}], [{'InstanceID': u'BIOS.Setup.1-1:Slot4'}]]}
where as I am looking for
{'a': [[{'InstanceID': u'BIOS.Setup.1-1:Slot3'}], [{'InstanceID': u'BIOS.Setup.1-1:Slot4'}], [{'InstanceID': u'BIOS.Setup.1-1:Slot2'}], [{'InstanceID': u'BIOS.Setup.1-1:Slot5'}], [{'InstanceID': u'BIOS.Setup.1-1:Slot1'}]]}

Where is it going wrong?
Comment: The "fix" for the code is replacing `k["a"] = copy.deepcopy(w)` with `w = copy.deepcopy(w); k["a"] = w` but the better solution is to restructure to a list comprehension as per viraptor
Answer: You seem to be doing a lot of things that are not necessary. Clearing the temporary dictionary and deepcopy are not necessary here. Here's a simpler solution:
instances = [[{'InstanceID': iid}] for iid in l]
k = {'a': instances}

As for the issue in your code - when you do wsman_invoke_attr.clear() you're still holding a reference to the dictionary you used before, so you're clearing all of them at the same time. Then you add a new name to all of them again.


changing image color in java

Question: I am trying to change color of image. Hence I used the following code
public class Picture {

String img_name;
BufferedImage buf_img;
int width;
int height;

public Picture(String name) {
    this.img_name = name;

    try {
        buf_img = ImageIO.read(new File(img_name));
    } catch (IOException ex) {
        Logger.getLogger(Picture.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public Picture(int w, int h) {
    this.width = w;
    this.height = h;
    buf_img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
}

public int width() {
    width = buf_img.getWidth();
    return width;
}

public int height() {
    height = buf_img.getHeight();
    return height;
}

public Color get(int col, int row) {
    Color color = new Color(buf_img.getRGB(col, row));
    return color;
}

public void set(int col, int row, Color color) {
    buf_img.setRGB(col, row, color.getRGB());
}

public void show() {
    try {

        File saveAs = new File("D:\\temp\\" + new Random().nextInt() + ".png");
        ImageIO.write(buf_img, "png", saveAs);

        Desktop.getDesktop().open(saveAs);
    } catch (IOException ex) {
        Logger.getLogger(Picture.class.getName()).log(Level.SEVERE, null, ex);
    }
   }

 }

public class ColorSeparation {

public static void main(String[] args) {

    // read in the picture specified by command-line argument
    Picture picture = new Picture("D:\\qwe1.jpg");
    int width = picture.width();
    int height = picture.height();

    // create three empy pictures of the same dimension
    Picture pictureR = new Picture(width, height);

    // separate colors
    for (int col = 0; col < width; col++) {
        for (int row = 0; row < height; row++) {
            Color color = picture.get(col, row);
            int r = color.getRed();
            int g = color.getGreen();
            int b = color.getBlue();
            pictureR.set(col, row, new Color(r, 0, 0));

        }
    }

    // display  picture in its own window
    pictureR.show();

  }

}

It is working as expected.
.
Now I want to set color of entire image to rgb 255, 153, 51. I tried to set
pictureR.set(col, row, new Color(255, 153, 51)). But the resulted output is the below image.
How can I get correct image? Please help.
Comment: That looks a lot like an image where you have "set color of entire image to rgb 255, 153, 51" to me.
Comment: Post the `Picture`  class. Better still, post a [mcve]
Comment: @Reimeus I have updated the question now
Answer: Your initial example is misleading you. Your code in the first example is setting varying shades of red (pulled from the original red channel), creating a "redscale" image, not "colorizing" the image like you think it is.
int r = color.getRed();
pictureR.set(col, row, new Color(r, 0, 0));

Your second example is setting a fixed color for each and every pixel, so you get a uniform orange.
pictureR.set(col, row, new Color(255, 153, 51))

You need to colorize the image by varying all three channels, just like you varied the red value initially. See this question for an example using compositing, which is a different angle from what you're using now.
The easiest implementation for you, given your sample code, would be to calculate the relative luminence of each pixel (effectively it's grayscale value) and use that to adjust the "orange" value you are setting. The standard weighting for luminence is
L = 0.2126*R + 0.7152*G + 0.0722*B

so something like
pictureR.set(col, row, new Color(255 * L/255, 153 * L/255, 51 * L/255));

Comment: The color co ordinates are exceeding the limit giving Exception in thread "main" java.lang.IllegalArgumentException: Color parameter outside of expected range: Red Green Blue
Comment: @swapnilgandhi Correct, L is in the range 0-255 so muliplying it by the pixel values exceeds the RGB value range (also 0-255). I have updated my answer to convert L to a percentage (divide it by 255) while setting color channels. You may want to use a non-uniform weighting (like the weights in the `L` formula) in your solution, depending on your desired result.
Comment: Luminence didnt work, but the other thing did. Thanks a lot.

changing image color in java


Table element is cutting off while inserting

Question: below is my html

 ...........

I need to insert the below html string right after the tbody, myTbody1
var html = '

             Col1
             Col2
             Col3
             Col4
             Col5
             Col6
             Col7
             Col8
             Col9

             Data
             Data
             Data
             Data
             Data
             Data
             Data
             Data
             Data

'

I tried to do like below and it inserts at right place but it is cutting the first two tags tbody and table from the html string.
$(html).insertAfter($(this));

where $(this) equals tbody.myTbody1
Any help is appreciated.
Answer: As specified, tbody can only contain tr elements. Since the HTML you're passing is invalid jQuery just works with the valid portion that's created in the DOM.
To make a nested table like that you'll have to add a tr and td element as children of the tbody and put the inner table inside the td.
Comment: Hey Josh, if I use insertAfter, IE inserts the html into the tbody as a child, but I want to insert after the tbody, any idea?
Answer: You can nest tables easily, using the JQuery provided by Shahil, but you need to surround the entire nested table in the 'tr' opening and closing tags. Your second code example should read
var htmlToInsert = '

             Col1
             Col2
             Col3
             Col4
             Col5
             Col6
             Col7
             Col8
             Col9

             Data
             Data
             Data
             Data
             Data
             Data
             Data
             Data
             Data

'

I would then use the JQuery $('.myTBody1').html(htmlToInsert);
Finally, make sure your
 tags have matching
 closing tags.
For more information, visit JQuery API - .html()


Identifying dependent pairs of events

Question: Which of the following pairs of events are dependent?
options:
A)Drawing a heart from a deck of cards, replacing it, and then drawing another heart.
B)Tossing three coins at the same time and getting tails on all three.
C)Randomly choosing a captain and an assistant captain from a team of 18 players.
D)Choosing a class president from one group of students and a vice-president from a different group of students.
My work:
First let's define what a dependent event is: Two events are dependent if the outcome of the first event affects the outcome of the second event, so that the probability is changed. So out of those four choices (A,B,C,D) the correct choice that displays the dependent event is A) Drawing a heart from a deck of cards, replacing it, and then drawing another heart.
Is this choice correct?
Comment: is this correct?
Answer: No, replacing the card makes the deck return to its original state with no change in probability whatsoever. The correct choice should be (c), because for instance the probability of Player $1$ being vice captain is $\frac{1}{18}$ only if he/she is not chosen as captain, in which case the probability of him/her being vice captain will be zero.
Comment: so C represents the dependent event?
Comment: @TanvirJoshi Yes, it does.
Comment: ok,i also had one last question i needed help on ,can you chat
Comment: on stack exchange
Comment: heres the question:For the set of whole numbers from 1 to 20 inclusive,Tammy knows that some numbers are odd .She is going to write each number on a different ball and place the balls in a box. If one ball is randomly selected from the box,what is the probability,to the nearest tenth,that the number written on it is divisible by 5 or is an odd number? i got 1/20 as my answer is that correct?
Comment: No, I'm getting $\frac 35$.

Identifying dependent pairs of events


How to clean tuple and insert them in a csv file?

Question: I'm printing out from a db to a csv file like this:
result = cursor.fetchall()
writer = csv.writer(writeFile, dialect='myDialect')
   for x in result:
      x = list(x)
      for z in x:
         z = re.sub(r'[^\w\s]',' ',z)
      x = tuple(x)
      writer.writerow(x)

I want to clean each string in my tuples removing punctuations. I've found this regex which is working well.
However it's not working as my csv file is still full of punctuations.
Comment: That replaces `z` but `x` remains untouched. You don't need inner loop and need to replace `x`, if I'm not wrong.
Answer: The iteration variable z holds just a copy of each value in x, so changes made to z are not reflected in x. You should use enumerate to iterate through x so that you can modify items in x via an index:
for i, z in enumerate(x):
    x[i] = re.sub(r'[^\w\s]',' ',z)


Cannot log in to public open Wifi connection

Question: As a long time user of Ubuntu (10y+) I have noticed the relationship between Ubuntu and public Wifi hotspots (without wifi security) that require login  through a web page have not always been easy...
At times, I was able to be automatically redirected to a web page for logging in, but I have been experiencing the same problem for a while: after connecting to the open wifi network, the browser does not redirect to the login page! I have just updated to 16.04 and I was disappointed to see it did not fix the problem.
I tried deleting the connection from Network Manager but this doesn't change anything. The behaviour is the same with any browser (Chromium, Firefox, Opera, etc). I have dual-boot on this machine and no problem connecting to those network in Windows...I don't really know what else to try...
Is anyone else experiencing this issue? Any help to troubleshoot (or solve) the problem is highly appreciated. Please let me know if you need command outputs for diagnostics.
Update: Today, I did manage to connect to one of these wifi networks, but received a warning first :

However, I tried to connect to a Starbucks network afterwards and still have the same problem. Thaller below pointed to a possible problem in the NetworkManager.conf file: could anyone maybe post a normal file so I can see what's wrong with mine?
Comment: Sounds like a browser problem and not an Ubuntu problem. Have you tried other browsers, say Chrome(ium) for example?
Comment: Just edited my post:the issue is present with any browser
Comment: Does it work with those browsers in Windows? Or it just opens in IE?
Comment: @CelticWarrior, yes the Windows versions of those browsers allow to be redirected and log in.
Comment: Check the answer below. Also some captive portals use things like ActiveX which is Microsoft proprietary for Windows. If that's the case the login page may not load properly or not at all.
Comment: See also https://unix.stackexchange.com/questions/89630/how-to-sign-into-an-open-wireless-network
Answer: Here is what I have found works for forcing the captive portal (i.e., login page for WIFI connections on public hotspots):

Make the connection to the WIFI.

Open a terminal and type route -n. You should receive a display such as:
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         10.1.0.1        0.0.0.0         UG    600    0        0 wlo1
10.1.0.0        *               255.255.248.0   U     600    0        0 wlo1
link-local      *               255.255.0.0     U     1000   0        0 wlo1```

Type the default Gateway (i.e., 10.1.0.1) into your browser's address bar, you will receive the WIFI login page.
Comment: @grisaitis - core utilities has `ip`, which has option `route`. Usage: `ip route`
Comment: What about a solution using only core utilities? I don't have `route`, and of course can't install it because I don't have internet on that device.
Comment: One small suggestion... I had to pass the -n option with my route command (i.e. route -n) to get the necessary ip.  Without it, the Default Gateway was shown as a domain name that couldn't be resolved.  The -n option forces route to display the results as numeric ip addresses.
Comment: None of the IP addresses that showed up were reachable. This did not work for me. (Ubuntu 20.04 LTS)
Comment: This is useful info. Ubuntu tried to connect to nmcheck.gnome.org for me for some reason.
Comment: @grisaitis you can also try the following: `more /etc/resolv.conf`. I found that trick [here](https://mattoppenheim.com/2020/09/30/getting-the-login-screen-on-hotel-wifi-using-linux/).
Answer: Enter http://nmcheck.gnome.org in your browser. (I added the "hotspot login" of Ubuntu 18 to my favorites and it showed that address, every time I clicked on it.) It worked for me.
Comment: This is an underrated answer. Works perfectly for me and is extremely simple - I just added it to my bookmarks toolbar, so now resolving this is just a click away.
Comment: Similar to this answer, http://icanhazip.com worked great
Comment: I was able to get to this while experiencing issues, but it didn't help my connectivity for https pages or prompt the login portal.
Answer: I have the same problem and I am going to add the following to my /etc/NetworkManager/NetworkManager.conf file:
[connectivity]
uri=http://nmcheck.gnome.org/check_network_status.txt

(source)
Comment: Is this an answer to the question?
Comment: Remember to restart the network manager with `service network-manager restart` after.
Comment: This did it for me! – Tested at Starbucks, with Ubuntu-Gnome 16.04
Comment: Did not work for me (on Antergos-Gnome).
Comment: I am running Kubuntu 22.04. Adding this, and running `sudo systemctl restart NetworkManager.service` succeeded in getting me a log in popup when connecting to these public wifi services. However, my DNS is not working, so when I click "Log in", nothing happens. My resolv.conf contains entries 184.108.40.206 and 184.108.40.206.
Answer: For me,
sudo dpkg-reconfigure resolvconf

completely solved the problem. I hope it will help you.
Comment: Could you please [edit] and expand your answer a bit, e.g. by describing what the command does ans why this might solve the problem in the question? Thanks and welcome to Ask Ubuntu.
Comment: This worked for me too. Resolv.conf seems to be a configuration which tells your browser/network connect where to look first for domain name resolvers (DNS). These captive portals redirect your requests for "http://somesite.com" to -> [captive login page].
Comment: Worked like a charm!!!
Answer: Guruprasad L's blog post's answer for me.

Create file /etc/NetworkManager/conf.d/20-connectivity-debian.conf (you'll need root or sudo).
Add the following lines as recommended by Guruprasad:
[connectivity]
uri=http://network-test.debian.org/nm
response=NetworkManager is online
interval=300

Restart the network manager with service network-manager restart (will need sudo or root again).
Answer: NetworkManager is a bit involved in this. When you configure connectivity-checking (see man NetworkManager.conf), then it will try periodically to download a website to see whether it has internet access. This is also used to detect a captive portal. Based on this, NetworkManager has a Connectivity state, which might be one of Local, Portal, Full.
Appart from that, NetworkManager does nothing. When using gnome3, gnome-shell looks at that connectivity state and might open a portal-login page, that is a browser with some website. Maybe there are other components that perform a similar task like NetworManager's connectivity check or gnome-shell's portal-login.
In the end, you can also do without these two. When you are behind a captive portal you can open a browse to a HTTP site (not HTTPS), the portal will redirect you to a login page.
Maybe you are not redirected because you are trying to open a HTTPS site. The portal usually blocks that entirely, because attempting to redirect it would anyway result in a certificate warning.
Comment: Thanks, thaller. I realized my NetworkManager.conf is only 5 lines long and I suspect this is not normal...I've probably been dragging it through all these release upgrades and the file remained the same. Is there a way to re-generate this file to the default version?
Comment: There is no certificate warning: the browser doesn't react on its own and if type something in the address bar, it keeps thinking forever...
Answer: Running route -n should have a first entry that looks something like:
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         172.31.0.1      0.0.0.0         UG    20600  0        0 wlan0

If you can ping the gateway (e.g. ping 172.31.0.1) and if you know the URL for the captive portal (from connecting on your phone or another computer), you should be able to link these two to get to a login screen. Edit your hosts file sudo vi /etc/hosts and add an entry like:
172.31.0.1 gialto.wifi/hotspot/novotelmedellinguest

(Replace gialto.wifi/hotspot/novotelmedellinguest with the full address of the wifi login)
Then uncheck "enable networking" in the wifi settings in the upper right of your desktop and recheck it. Finally enter the full address in your browser (make sure to start with http:// if your browser is attempting to do a search instead of a lookup).
Answer: For future answers searchers, I had the exact same problem suddenly in Chromium for Ubuntu 16.04, but trying to navigate to a site in Firefox showed me the login page for the network.
Answer: This will likely be of no help to anyone, but I got xfinitywifi working on my Windows partition, then fiddled around with the MAC address until it suddenly started working. I can't replicate it currently.
Answer: I had the same problem. The login page of the networks just never showed up and the login screen window was broken. The cause was a dangling wireguard connection. After disabling that connection, all was fine.
Answer: I was getting a domain name resolution error when my browser tried to open the login page. If you have another internet source available, like a phone, you can look up the ip address using a service like https://www.nslookup.io/
I then replaced the domain name in my web browser url with the ip address and everything worked.
Answer: This solution worked for me on an Ubuntu computer with a camera and required a phone (Android) that had been connected and logged into the Wi-Fi network.
On the Ubuntu computer establish a Bluetooth network connection to the phone —i.e., tether it. Install the wifi-qr package on the Ubuntu computer. Untether it. On the phone, bring the QR code to share the network password up on the screen. On the computer, in a terminal, run wifi-qr s and scan the QR code using the computer's camera. Repeat if necessary.


Import an es6 module in a protractor test file

Question: I'm trying to import an es6 module in my protractor test files, but I can't get it working (I used the is-docker package 3.0.0 as an example). Here is what I tried:

First I got this error:

Error: Error [ERR_REQUIRE_ESM]: require() of ES Module [...]/node_modules/is-docker/index.js from [...]/e2e/app.e2e-spec.ts not supported.
Instead change the require of index.js in [...]/e2e/app.e2e-spec.ts to a dynamic import() which is available in all CommonJS modules.

I updated my tsconfig used by protractor:

{
  // ...
  "compilerOptions": {
    "module": "esnext",
    "target": "esnext",
    // ...
  }
}

This resulted in the following error:
SyntaxError: Cannot use import statement outside a module

So I added a package.json in my e2e folder containing the protractor test files:

{
  "type": "module"
}

This resulted in the following error:
E/configParser - Error [ERR_REQUIRE_ESM]: require() of ES Module [...]/e2e/protractor.conf.js from /usr/local/lib/node_modules/protractor/built/configParser.js not supported.
protractor.conf.js is treated as an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which declares all .js files in that package scope as ES modules.
Instead rename protractor.conf.js to end in .cjs, change the requiring code to use dynamic import() which is available in all CommonJS modules, or change "type": "module" to "type": "commonjs" in [...]/e2e/package.json to treat all .js files as CommonJS (using .mjs for all ES modules instead).

    at ConfigParser.addFileConfig (/usr/local/lib/node_modules/protractor/built/configParser.js:135:26)
    at Object.initFn [as init] (/usr/local/lib/node_modules/protractor/built/launcher.js:93:22)
    at Object.<anonymous> (/usr/local/lib/node_modules/protractor/built/cli.js:227:10)
    at Object.<anonymous> (/usr/local/lib/node_modules/protractor/bin/protractor:5:1)

I can't follow the error instructions and change the requiring code to use dynamic import(), because the error is inside protractor code:
addFileConfig(filename) {
    // ...
    let filePath = path.resolve(process.cwd(), filename);
    let fileConfig;
    try {
        fileConfig = require(filePath).config;
    }
    // ...
}

Comment: Moving to cypress, already migrated one application. The difficult part was working without waitForAngular() functionality. In protractor we sometimes did conditional testing, but without waitForAngular that's difficult: https://docs.cypress.io/guides/core-concepts/conditional-testing
Comment: did you manage to fix it?
Comment: No, couldn't find a solution. Decided to stop trying eventually, because we're moving away from protractor soon because it's end of life.
Comment: Same thing we are doing, curious to know moving to what, we decided playwright
Answer: Root cause
Start from Angular@13, it removed the support for CommonJS and UMD - Detail
Workaround
As the warning suggested, use the dynamic import() from CJS.
No changes in package.json or tsconfig.json
For ProtractorHarnessEnvironment, replace it with SeleniumWebDriverHarnessEnvironment
async function getSeleniumWebDriverHarnessEnvironment() {
  const lib = await import("@angular/cdk/testing/selenium-webdriver");
  return lib.SeleniumWebDriverHarnessEnvironment;
}

For Angular Material Component Harness, apply the same:
async function getMatTableHarness() {
  const lib = await import("@angular/material/table/testing");
  return lib.MatTableHarness;
}

If above approach doesn't work, try use the following replace import() (as explained by this blog)
const dynamicImport = async (packageName: string) =>
  new Function(`return import('${packageName}')`)();

References

How to import ES6 modules in CommonJS
Difference between ES Modules and CommonJS Modules
Import ES modules in TypeScript project


how do I conditionally display angular mat-tabs on smaller screen?

Question: I want to place contents in tabs, but only on smaller screen. Otherwise the contents should just fall back to div blocks ( or to other layout defined in css ).
For smaller screen ( @media only screen and (max-width:600px) ), tab should appear
<mat-tab-group >
  <mat-tab label="First">
 Content 1
</mat-tab>
  <mat-tab label="Second">
 Content 2
</mat-tab>
  <mat-tab label="Third">
 Content 3
 </mat-tab>
</mat-tab-group>

Now for larger screen, it has to fall back to three div blocks

 Content 1

 Content 2

 Content 3

How do I achieve this using a single block of code in angular / angular material tabs ?
Answer: You should be able to do this using the CDK Layout BreakpointObserver and breaking your content down into separate components. For example:
import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout';
import { Component } from '@angular/core';
import { Observable } from 'rxjs';
import { map, shareReplay } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  isHandset$: Observable<boolean> = this.breakpointObserver.observe(Breakpoints.Handset)
    .pipe(
      map(result => result.matches),
      shareReplay()
    );

  constructor(
    private breakpointObserver: BreakpointObserver,
  ) { }

}

<ng-container *ngIf="(isHandset$ | async) === true; then thenTemplate; else elseTemplate"></ng-container>

<ng-template #thenTemplate>
    <mat-tab-group>
      <mat-tab label="First">
 <app-content-1></app-content-1>
</mat-tab>
      <mat-tab label="Second">
 <app-content-2></app-content-2>
</mat-tab>
      <mat-tab label="Third"><div <app-content-3></app-content-3>
 </mat-tab>
    </mat-tab-group>
</ng-template>

<ng-template #elseTemplate>

 <app-content-1></app-content-1>

 <app-content-2></app-content-2>

 <app-content-3></app-content-3>

</ng-template>

Please note that each piece of content will need to be abstracted out into its own sub-component. Some info that I think could be useful, you can find the exact dimensions of each breakpoint and what it is called at this link.
Edit: Flipped ng-if
Comment: Thanks! Thats close to what I wanted.


Dynamic Hierarchical Javascript Object Loop

Question:    var treeData = {"name" : "A",  "children" : [
                         {"name" : "B", "children": [
                                 {"name" : "C", "children" :[]}
                          ]}
                   ]};

THE ARRAY BEFORE SHOULD BE EMPTY. THE ARRAY AFTER SHOULD BE POPULATED DEPENDING ON THE NUMBER OF NODES NEEDED THAT WILL BE DEFINED FROM A DYNAMIC VALUE THAT IS PASSED.
I would like to build the hierarchy dynamically with each node created as a layer/level in the hierarchy having its own array of nodes. THIS SHOULD FORM A TREE STRUCTURE. This is hierarchy structure is described in the above code.There should be a root node, and an undefined number of nodes and levels to make up the hierarchy size. Nothing should be fixed besides the root node.  I do not need to read or search the hierarchy, I need to construct it.
The array should start {"name" : "A",  "children" : []} and every new node as levels would be created {"name" : "A",  "children" : [HERE-{"name" : "A",  "children" : []}]}. In the child array, going deeper and deeper. Basically the array should have no values before the call, except maybe the root node. After the function call, the array should comprise of the required nodes of a number that may vary with every call depending on the results of a database query. Every child array will contain one or more node values. There should be a minimum of 2 node levels, including the root.
It should initially be a Blank canvas, that is no predefined array values.
Answer: Here is the example of function to create your nodes dynamically:
function createNode(name) {
   return({name: name, children: []});
}

function addChild(node, child) {
    node.children.push(child);
    return node;
}

var treeData = createNode("");
var subChild = createNode("");
addChild(subChild, createNode("A31"));
addChild(treeData, subChild);

But I suggest to use prototypes instead.
To find any node by 'path' with any level:
function findNodeByPath(root, path) {
   var curr;
   while(root && ((curr = path.splice(0,1)[0]) !== undefined)) {
        if (root.children) root = root.children[curr];
        else root = undefined;
   }
   return root;
}

function findNodeByName(root, namePath, create) {
   var curr;
   while(root && ((curr = namePath.splice(0,1)[0]) !== undefined)) {
        if (root.children) {
            var found = undefined;
            for (var i = 0; !found && i < root.children.length; i++)
                if (root.children[i].name == curr) found = root.children[i];
            if (create && !found) {
                found = createNode(curr);
                addChild(root, found);
            }
            root = found;
        }
        else root = undefined;
   }
   return root;
}

var A31 = findNodeByPath(treeData, [0, 0]); // Will return the node with name A31
addChild(A31, createNode("A31 child 1"));
addChild(A31, createNode("A31 child 2"));

// second child will be accessible by:
var secondChildOfA31 = findNodeByPath(treeData, [0, 0, 1]);

// also to find node by the name:
var secondChildOfA31 = findNodeByName(treeData, ["", "A31", "A31 child 2"]);

// will create all intermenient nodes with respective names:
var veryDeepChild =  findNodeByName(treeData, ["foo", "bar", "baz", "quux", "moo"], true);

function createOuterNode(name, childNode) {
    return {name: name, children: childNode? [childNode] : []}
}

// Example to create nodes in the question:
var CNode = createOuterNode("C");
var BNode = createOuterNode("B", CNode);
var ANode = createOuterNode("A", BNode);

// Example using LOOP:
var list = ["A", "B", "C"];
var outer = undefined;
for (var i = list.length - 1; i >= 0; i--) outer = createOuterNode(list[i], outer);

// outer will contain A node with child B with child C
console.log(outer);

Comment: Hey thanks. I would like the var treeData to represent the entire hierarchy created and its data. Is this done in the code you have shown me.I am sorry but I am still novice.
Comment: In the example I provided, executed code will leave treeData in exact state that you specified in the question (but I hardly can guess why do you need to create such simple array 'dynamically' instead of using quite a readable JSON-like declaration)
Comment: Lol. Well it should not be that simple. I was initially using JSON, but I needed the hierarchy to be able to 'grow'. The code in my original question describes the general structure and workings of how the hierarchy should look and work. But I need it to work as if the number of levels and the depth of each of the levels in the hierarchy is not known. The code I provided, and the code You provided, both allow for this 3 levels in the hierarchy. The structure should remain the same as described above, but the levels and size of the hierarchy should be dynamic.
Comment: How do I alter the code to allow for any number (in my case it should'nt be more than 5) of levels depending on the data source to be be generated. treeData should again represent the entire hierarchy produced.  How do I do this? through a Loop? Can You help with this please? I would really appreciate it :) PS. I am sorry that I was unclear before on how it should work.
Comment: See my updated answer for the example of infinite tree traversal using path array. You can modify the function to use child names instead of indexes
Comment: I am a bit confused with this updated code. Does this still produce the same 3 levels. What defines the number of levels in the hierarchy and the depth of each of the levels?
Comment: this example has 4 levels indeed. Just add more indexes to the path parameter. `findNodeByPath(root, [])` returns `root`; `findNodeByPath(root, [N])` returns Nth node on 1st level; `findNodeByPath(root, [a, b, c, d, e])` returns `root.children[a].children[b].children[c].children[d].children[e]` (on 5th level) and so on
Comment: I am attempting to see it work, but I am having trouble modifying the function to use the child name instead of the indexes as you told me to. How do I do this. I am sorry to be a bother. I kinda new to this level of code.
Comment: Do I have to make any changes to indexes or anything to allow this to work with my code. Just as it is above, it doesn't work. Do I hae to change an index format of anything? How do I change indexes to child names so that I can see how it works?
Comment: I haven't seen your code; if you will take the code from my example (one in the grey fields) and execute it, it will work. Probably you still have to read something on tree traversal [here](http://stackoverflow.com/questions/722668/traverse-all-the-nodes-of-a-json-object-tree-with-javascript) or [here](https://www.google.com/search?q=dynamic%20tree%20traversal%20in%20javascript) to properly use it.
Comment: The first code you gave me, that is the createnode(), worked great, except for the fact that there were a fixed 3 levels. This new code is giving problems to integrate with the code I am using. The code That I am using can be seen here: http://bl.ocks.org/1312406. You will see the oirginal var treeData here.
Comment: To create node in any position of hierarchy, you have to find its parent with findNodeByPath() or findNodeByName() and then call createNode(). Also I'm going to update my example with 'create' param for findNodeByName() - take a look
Comment: I am finding it very difficult to integrate this code with that of bl.ocks.org/1312406. The first example that you gave me worked great for the 3 levels. I have been trying to alter that code to achieve the dynamic hierarchy building that I want.
Comment: Can something of this nature work: That is using Loops here.                             function createNode(name) {
   return({name: name, children: []});
}

function addChild(node, child) {
    node.children.push(child); //loop here
    return node;
}

var treeData = createNode("");
var subChild = createNode("");
addChild(subChild, createNode("A31")); //Loop here
addChild(treeData, subChild);
Comment: To create nodes from blocks example you can use my code: `var root=createNode("A"); findNodeByName(root, ["A1"], true); findNodeByName(root, ["A2"], true); findNodeByName(root, ["A2", "A31", "A311"], true); findNodeByName(root, ["A2", "A31", "A312"], true);`. Intermediate nodes A2 and A31 will be added too.
Comment: smh.This does not seem to work with me. I am sorry for that. Like my previous comment: Can I include loops in the first code you gave me (function createNode(name)) to dynamically generate nodes in the hierarchy.
Comment: Please update your question with examples of array 'before' and 'after' function call and I will try to figure out what do you want to do
Comment: I have made the changes to the original question. Check it out. Please let me know if you understand this. I will try to explain it better. I really need help, I have been at this for days now.
Comment: Look, you tell that "THE ARRAY AFTER SHOULD BE POPULATED DEPENDING ON THE NUMBER OF NODES NEEDED THAT WILL BE DEFINED FROM A DYNAMIC VALUE THAT IS PASSED". But to pouplate the array, the number of nodes is just not enough, where should we take information about node names and parent-child relationships? Please explain. If we have only number, should we interpret it as depth? If yes, how should we guess names of sub-nodes?
Comment: The node names will be derived from a database, which I know how to do. But my problem is building the hierarchy. My actual use for this code will be applied to show the levels in differnet school programme. So I am trying to figure out the depth yes, as you said, and how to build it dynamically because the levels for programmes may vary. One programme may have 3 levels (certificate, diploma, bachelor's degree-in the case of a BSC degree), while another may have only 2 levels(certificate and diploma-in the case of a diploma). Pleas help.
Comment: Please take a look at createOuterNode() function in the example and onwards. Also give some example from data from a database.
Comment: Thanks, I will try this now, but I need for the entire hierarchy created to be represented by the var treeData, so I can call it. How do I do this?
Comment: In my example with the loop, root node always changes, just change outer to treeData. But it will be much more helpful if you will provide an example of input data (or I will die while trying to guess what exactly you need to accomplish)
Comment: Like I said in my previous comment, the data to be displayed on the hierarchy are to be levels of school courses. For example the structure of one particular programme may be 'UCL year1' as root node, 'UCL year2' as 2nd node and 'UCL Final Year' as last node. The depth and number of nodes will vary.
Comment: It is not enough. Do you have an array with such structure:
[[node2label, parentNodeLabel], [node2label, parentNode2Label]]?
Comment: I have update my question to include the code that I am using. This uses Mysql, php and javascript. I hope this shows you how the data will be populated to the hierarchy. Of course this is my first rough version that misses much detail.
Comment: As you can see from the above code, the var treeData must hold the hierarchy, and its data is populated from the database through php.
Comment: Oh, your code is completely broken on server-side. I would happily help you but I can't spend more time. I suggest to create new question and provide these details:

- some rows from Products table

- how javascript tree should look like for these Products

And, of course, whole page you have posted above.
Comment: [[rootnode, node1[node2[node3[node4]]]] I think this represents what I am trying to do. Tell me what you think :)
Comment: Ok well I really appreciated your help (Y)


sort order in sql with 2 columns

Question: I have table like this:
+----+------+-----------+-------------------+
| ID | Name | sortorder | overridesortorder |
+----+------+-----------+-------------------+
| 1  | kkkk | 4         | null              |
+----+------+-----------+-------------------+
| 2  | yyyy | 3         | null              |
+----+------+-----------+-------------------+
| 3  | zzzz | 2         | 4                 |
+----+------+-----------+-------------------+
| 4  | gggg | 1         | 3                 |
+----+------+-----------+-------------------+

I need to display the order like below, sorting the table with above two sort order columns:
+----+-------+-----------+-------------------+
| ID | Name  | sortorder | overridesortorder |
+----+-------+-----------+-------------------+
| 1  | kkkk  | **4**     | null              |
+----+-------+-----------+-------------------+
| 3  | zzzz  | 2         | **4**             |
+----+-------+-----------+-------------------+
| 2  | yyyy  | **3**     | null              |
+----+-------+-----------+-------------------+
| 4  | gggg  | 1         | **3**             |
+----+-------+-----------+-------------------+

Comment: https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-query
Comment: Please limit your DBMS version tags. There are things that will work on SQL Server 2014 that won't work on SQL Server 2008. Nothing that matters for this question, but still a good habit to get into.
Answer: Is this what you want?
select t.*
from t
order by coalesce(overridessortorder, sortorder) desc;

Answer: Get the maximum value of the two columns and order by it with that
SELECT ID, Name, sortorder, overridesortorder,
(SELECT Max(o)
FROM (VALUES (sortorder), (overridesortorder)) AS value(o)) as order_value
FROM [TABLE] ORDER BY order_value

Comment: The example always has the override higher, but there is no guarantee there.
Comment: i have another rows. Both rows(sortOrder,Overridesortorder) values are null. I need to display remaining rows order by Name column. Please help.
Answer: This is what you are looking is
select *
from table
order by isnull(overridesortorder, sortorder) desc, overridesortorder

Answer: SELECT ID, Name, sortorder, overridesortorder
FROM t
ORDER BY COALESCE(overridessortorder, sortorder) DESC, sortorder DESC;

This will combine the two columns, using the override where it is not null, then sort order where it is null, and then sort the result based on the original sort order column to break ties. If you want to break ties based on the override, you just switch that second sort.
Answer: I am adding few more rows
in this case if the sortorder and overridesortorder is null i need to display order by Name
ID  Name    sortorder   OverriderSortOrder  order_value
3   zzzz    2   4   4
1   kkkk    4   NULL    4
2   yyyy    3   NULL    3
4   gggg    1   3   3
5   hhhh    NULL    NULL    NULL
6   bbbb    NULL    NULL    NULL
7   jjjj    NULL    NULL    NULL
8   cccc    NULL    NULL    NULL

sort order in sql with 2 columns


How to check that two conditions of 5 are true?

Question: I want to check that 2 of 5 fields are filled, but I don't know how.
If I put this in conditions, that only checks one of the conditions is true:
OR

field1 is not empty
field2 is not empty
field3 is not empty
field4 is not empty
field5 is not empty

there is an easier way that the following?

field1 is not empty
field2 is not empty

OR

field1 is not empty
field3 is not empty

OR

field1 is not empty
field4 is not empty

OR

field1 is not empty
field5 is not empty

OR

field2 is not empty
field3 is not empty

OR

field2 is not empty
field4 is not empty
(...)
Answer: 2 For loops
    for(int i=0;i<5;i++){
     for(int j=i+1;j<5;j++){
      if(field[i]==true&&field[j]==true)
       return true;
     }
    }

EDIT:
You replace the statements for your needs.
And you must store the fields in an array.
Credits to zolyboy for the i+1 thing :)
Comment: j variable should start from i not from 0
Comment: why to test field[1] == true && field[2] == true and after that field[2] == true && field[1] == true ? it's totally the same thing, if you put instead of 0 i+1 then you will not do the same multiple times
Answer: In SQL I would to it this way:
select if(if(field1='',0,1)+ if(field2='',0,1)+ if(field3='',0,1)+ if(field4='',0,1)+ if(field5='',0,1)=2) true else false end ...

In other language it could be something like:
int a = (field1.equals(""))0:1;
int b = (field2.equals(""))0:1;
int c = (field3.equals(""))0:1;
int d = (field4.equals(""))0:1;
int e = (field5.equals(""))0:1;

boolean result= (a+b+c+d+e==2)?true:false;

With above code you can easily use it for 3 of 5, 4 of 5, 7 of 10 conditions etc...


How do I get museum items / collections?

Question: I've been playing Puzzle Craft for four months now and am close to completing the app (or maxing the levels, at least). However, I have not yet found a single 'collection' (the items shown in the museum). How might I find these?
Answer: You can only find the collectible items in chests. There is a building to upgrade the chest appearing, which will improve the chest to mythic when maxed.
The type of chest only determine the type of collection items you can found. When you have mythic chests its only matter of luck.
You can build/upgrade your chapel in order to improve your chances of finding collection in chests.


Is there any way to skip Combo Chicken lessons?

Question: I am really enjoying Guacamelee, but I have a bit of a problem with fine motor skills, so executing combos correctly is SUPER difficult for me sometimes.
Right now I seem to be stuck with Combo Chicken, trying to do a combo that is pretty impossible for me so far.
Is there any way for me to get past this without getting the combo correct? Or has my inability to get this right effectively made the game unplayable as I cannot progress?
Comment: I'm not familiar with the game, but you may be able to use an Autohotkey script if you're playing on pc.
Comment: I assume if it's like any other game, you won't be able to progress until you beat it (unless the Combo Chicken Lessons are optional).  There seem to be a few [videos](https://www.youtube.com/watch?v=4LVTkuZhuEQ) out there that you might be able to watch to get the combo down, and then keep practicing.
Answer: According to this wiki, Combo Chicken cannot be skipped (emphasis mine):

Combo Chicken can be started as soon as you reach Santa Luchita, but cannot be finished until Juan has learned all Special Moves.

For what it's worth, this is widely considered an annoying part of the game, and fairly repetitive and difficult (so I wouldn't blame it entirely on a lack of fine motor skills).
However, I found these threads which make a couple of suggestions on how to beat it, which include:

Pushing Poncho back against the wall - this should help with targeting him and landing the combos
Taking your time - the buttons don't need to be pressed immediately, so taking some extra time to make sure you have the directions correct can help ensure the combo lands correctly

I also found these videos which may be of some help in figuring out exactly what the combo is, and providing some insight into how to land them correctly.
Based on my personal experience with Guacamelee, this part of the game is, erm, challenging. I fancy myself as having played a few fighting games in my day, but this part of the game definitely took some time. For me, I just kept practicing, and deliberately trying to push the correct buttons in the correct sequence (that was my main problem). So I would recommend beyond the advice from the sources above, just try to be really deliberate in your actions, take your time, and you should be able to pass it after a couple of tries!
Comment: Kept working at it, and finally managed to beat it last night. Those tips really helped!
Answer: This cannot be skipped mainly due to the fact that it ties into the poncho'd out achievement/trophy. My best suggestion is to find some of the tutorial videos and see if it in any way can help you with your issue.


How to chain on custom validations using Yup

Question: I want to add a .test() method to a validationSchema. The test is to look for common email domain  misspellings. For instance, to check if gmail was misspelled "gmial" or "gnail".
const validationSchema = Yup.object({
         email: Yup.string().lowercase()
        .email('You have entered an invalid email')
        .required('This field is required')
        .test('test-name', 'Did you mean @gmail??????', function(value){
            if (value.includes('gmial' || 'gnail'))
                return this.createError('')
    })
<Formik>
      <Form>

          Email
          <Field type='text' id='email' name='email' />
          <ErrorMessage name='email' component={TextError} />

      </Form>
</Formik>

Answer: Return a boolean result in your test.
const validationSchema = Yup.object({
  email: Yup.string()
    .lowercase()
    .email('You have entered an invalid email')
    .required('This field is required')
    .test('Gmail?', 'Did you mean @gmail?', (value) => value.includes('gmial' || 'gnail')),
});