Bootstrap confirmation requires two clicks before shows up?

Question:

var myJSON = {
  "customers": [{
      "id": 100,
      "first": "Mike",
      "last": "Johnson",
      "email": "email@example.com",
      "position": "Consultant"
    },
    {
      "id": 101,
      "first": "John",
      "last": "Dunn",
      "email": "firstname.lastname@example.com",
      "position": "Programmer"
    },
    {
      "id": 109,
      "first": "Lisa",
      "last": "Morgan",
      "email": "email@example.com",
      "position": "Secretary"
    },
    {
      "id": 233,
      "first": "Kris",
      "last": "Bradley",
      "email": "firstname.lastname@example.com",
      "position": "Programmer"
    },
    {
      "id": 57,
      "first": "Dave",
      "last": "Hart",
      "email": "firstname.lastname@example.com",
      "position": "Supervisor"
    }
  ]
};

$(document).ready(function() {
  generateTbl();
});

function generateTbl() {
  var jsonData = myJSON.customers,
    buildTbl = "

Customer ID	First Name	Last Name	Email	Position	Delete

";

  for (var key in jsonData) {
    buildTbl += "
" + $.trim(jsonData[key].id) + "	";
    buildTbl += "" + $.trim(jsonData[key].first) + "	";
    buildTbl += "" + $.trim(jsonData[key].last) + "	";
    buildTbl += "" + $.trim(jsonData[key].email) + "	";
    buildTbl += "" + $.trim(jsonData[key].position) + "	";
    buildTbl += "<button type='button' class='btn btn-default btn-sm customer_delete'></button>
";
  }
  buildTbl += "

";
  $('#customers_data').empty().append(buildTbl);
  buildDataTable('customers', [5], 5);
}

function buildDataTable(tblID, columnsArray, displayLength) {
  $('#' + tblID).DataTable({
    dom: 'Bfrtip',
    buttons: [
      'copy', 'csv', 'excel', 'pdf', 'print'
    ],
    "iDisplayLength": displayLength,
    "aoColumnDefs": [{
      'bSortable': false,
      'aTargets': columnsArray
    }]
  });
}

$('#customers_data').on('click', '#customers :button.customer_delete', deleteCustomer);

function deleteCustomer() {
  var recordID = $(this).closest('tr').attr('id'), // Get record ID.
    targetTr = $(this).parents('tr');

  $(this).confirmation({
    rootSelector: '[data-toggle=confirmation]',
    placement: 'bottom',
    singleton: true,
    title: 'Do you want to remove this account?',
    onConfirm: function() {
      if (recordID) {
        var table = $('#customers').DataTable(); // Select DataTable by ID.
        table.row(targetTr).remove().draw(); // Remove record from DataTable.
      }
    }
  });
}
<!DOCTYPE html>

  <title>Hearing Application</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/dataTables.jqueryui.min.css" />
  <link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.4.2/css/buttons.dataTables.min.css" />

Welcome to Main Page

As you can see in my example first time you click on delete button dialog is not showing. Second time will show. What could be the reason why dialog is not showing on the first click? I'm not sure if that has to do anything with dynamically built table? If anyone knows solution for this please let me know.
Comment: Which confirmation plugin are you using?  It sounds like the call to `confirmation()` is performing the initialization, not opening automatically.  You may need to look at the api for the plugin and find if there is a logical way to open the confirmation after the initialization
Comment: @Taplar Version it's right in the example. I believe it's 1.0.7.
Comment: If it is this plugin, http://bootstrap-confirmation.js.org/, then you should be able to do `$(this).confirmation('show');` after you initialize it.  You can find details about it under the Methods on that page.
Comment: @Taplar Do you know `cdn` from that source for confirmation?
Comment: I assumed it was that plugin as your rootSelector key and value match the examples on that site
Comment: I copied your snippet to an answer and added that command and it does fix your issue.
Comment: @Taplar I just tried and still requires two clicks in my example above.
Answer: You should be creating your confirmation before the button click, but if you must do it this way add in a $(this).confirmation('show') after you create the confirmation.. This piece of code makes it work:

var myJSON = {
  "customers": [{
      "id": 100,
      "first": "Mike",
      "last": "Johnson",
      "email": "firstname.lastname@example.com",
      "position": "Consultant"
    },
    {
      "id": 101,
      "first": "John",
      "last": "Dunn",
      "email": "firstname.lastname@example.com",
      "position": "Programmer"
    },
    {
      "id": 109,
      "first": "Lisa",
      "last": "Morgan",
      "email": "firstname.lastname@example.com",
      "position": "Secretary"
    },
    {
      "id": 233,
      "first": "Kris",
      "last": "Bradley",
      "email": "email@example.com",
      "position": "Programmer"
    },
    {
      "id": 57,
      "first": "Dave",
      "last": "Hart",
      "email": "email@example.com",
      "position": "Supervisor"
    }
  ]
};

$(document).ready(function() {
  generateTbl();
});

function generateTbl() {
  var jsonData = myJSON.customers,
    buildTbl = "

Customer ID	First Name	Last Name	Email	Position	Delete

";

  for (var key in jsonData) {
    buildTbl += "
" + $.trim(jsonData[key].id) + "	";
    buildTbl += "" + $.trim(jsonData[key].first) + "	";
    buildTbl += "" + $.trim(jsonData[key].last) + "	";
    buildTbl += "" + $.trim(jsonData[key].email) + "	";
    buildTbl += "" + $.trim(jsonData[key].position) + "	";
    buildTbl += "<button type='button' class='btn btn-default btn-sm customer_delete'></button>
";
  }
  buildTbl += "

";
  $('#customers_data').empty().append(buildTbl);
  buildDataTable('customers', [5], 5);
}

function buildDataTable(tblID, columnsArray, displayLength) {
  $('#' + tblID).DataTable({
    dom: 'Bfrtip',
    buttons: [
      'copy', 'csv', 'excel', 'pdf', 'print'
    ],
    "iDisplayLength": displayLength,
    "aoColumnDefs": [{
      'bSortable': false,
      'aTargets': columnsArray
    }]
  });
}

$('#customers_data').on('click', ':button.customer_delete', deleteCustomer);

function deleteCustomer() {
  var recordID = $(this).closest('tr').attr('id'), // Get record ID.
    targetTr = $(this).parents('tr');

  $(this).confirmation({
    rootSelector: '[data-toggle=confirmation]',
    placement: 'bottom',
    singleton: true,
    title: 'Do you want to remove this account?',
    onConfirm: function() {
      if (recordID) {
        var table = $('#customers').DataTable(); // Select DataTable by ID.
        table.row(targetTr).remove().draw(); // Remove record from DataTable.
      }
    }
  });
  $(this).confirmation('show');
}
<!DOCTYPE html>

  <title>Hearing Application</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/dataTables.jqueryui.min.css" />
  <link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.4.2/css/buttons.dataTables.min.css" />

Welcome to Main Page

Comment: Can you provide an example of how to create confirmation before I do on click? I think that actually will prevent some of the problems that I have.
Answer: Added the line to the code to show it does show the confirmation on the first click.

var myJSON = {
  "customers": [{
      "id": 100,
      "first": "Mike",
      "last": "Johnson",
      "email": "firstname.lastname@example.com",
      "position": "Consultant"
    },
    {
      "id": 101,
      "first": "John",
      "last": "Dunn",
      "email": "firstname.lastname@example.com",
      "position": "Programmer"
    },
    {
      "id": 109,
      "first": "Lisa",
      "last": "Morgan",
      "email": "email@example.com",
      "position": "Secretary"
    },
    {
      "id": 233,
      "first": "Kris",
      "last": "Bradley",
      "email": "firstname.lastname@example.com",
      "position": "Programmer"
    },
    {
      "id": 57,
      "first": "Dave",
      "last": "Hart",
      "email": "email@example.com",
      "position": "Supervisor"
    }
  ]
};

$(document).ready(function() {
  generateTbl();
});

function generateTbl() {
  var jsonData = myJSON.customers,
    buildTbl = "

Customer ID	First Name	Last Name	Email	Position	Delete

";

  for (var key in jsonData) {
    buildTbl += "
" + $.trim(jsonData[key].id) + "	";
    buildTbl += "" + $.trim(jsonData[key].first) + "	";
    buildTbl += "" + $.trim(jsonData[key].last) + "	";
    buildTbl += "" + $.trim(jsonData[key].email) + "	";
    buildTbl += "" + $.trim(jsonData[key].position) + "	";
    buildTbl += "<button type='button' class='btn btn-default btn-sm customer_delete'></button>
";
  }
  buildTbl += "

";
  $('#customers_data').empty().append(buildTbl);
  buildDataTable('customers', [5], 5);
}

function buildDataTable(tblID, columnsArray, displayLength) {
  $('#' + tblID).DataTable({
    dom: 'Bfrtip',
    buttons: [
      'copy', 'csv', 'excel', 'pdf', 'print'
    ],
    "iDisplayLength": displayLength,
    "aoColumnDefs": [{
      'bSortable': false,
      'aTargets': columnsArray
    }]
  });
}

$('#customers_data').on('click', '#customers :button.customer_delete', deleteCustomer);

function deleteCustomer() {
  var recordID = $(this).closest('tr').attr('id'), // Get record ID.
    targetTr = $(this).parents('tr');

  $(this).confirmation({
    rootSelector: '[data-toggle=confirmation]',
    placement: 'bottom',
    singleton: true,
    title: 'Do you want to remove this account?',
    onConfirm: function() {
      if (recordID) {
        var table = $('#customers').DataTable(); // Select DataTable by ID.
        table.row(targetTr).remove().draw(); // Remove record from DataTable.
      }
    }
  });

  //added this line to show the confirmation immediately after initialization
  $(this).confirmation('show');
}
<!DOCTYPE html>

  <title>Hearing Application</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/dataTables.jqueryui.min.css" />
  <link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.4.2/css/buttons.dataTables.min.css" />

Welcome to Main Page


JQuery Accordion SubMenu/Nested not working

Question: I am using JQuery Accordion and it works as it should and opens and closes fine....BUT I want to add an accordion submenu and this doesn't work nor styles either.
My libraries:

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/start/jquery-ui.css" type="text/css" rel="Stylesheet" />

I added this test:

TEST MAIN MENU

Sub header

sub content here

and "Sub header" is not styled as a header nor it wraps up the div below it like "TEST MAIN MENU" does...

On the  I have this:

All I need is to make "
Sub header
" a collapsable div too.
Answer: If you want accordion within an accordion then this is your solution.
By the way, when you say "#accordion" in js code, jQuery will try to find an element with id="accordion" and apply the styles to it. In the html that you have currently posted you have no such element.
Answer: You can't have a submenu in an accordion.
"and "Sub header" is not styled as a header", Where is the CSS? What do you mean not styled as a header?
Can you give an example of what it is you want?
Comment: This answer contains 2 questions. And why do you say that you cannot have a submenu? Please justify.
Comment: Ref: Can you give an example of what it is you want? ... I basically want to add a DIV inside the the current collapsable div ... So you click on parent header .... div opens ... and you get another Header ... you click and you can see the content.
Comment: @Pencho: Ya sure, you can have an accordion in an accordion, but it isn't really a sub-accordion and it doesn't really make sense to use an accordion for this. Maybe my answer was a little badly formulated. He seems to be looking for a collapse-able menu rather. Post your fiddle as answer?


How to pass dictionary values from a django query, as a filter value in another query?

Question: query 1:
nearestzips = PostalCode.objects.distance(PostalCode.objects.get(code='user.zipcode').location).order_by('distance')[:9]

print nearestzips
>>>[<PostalCode=97202>, <PostalCode=97201>, <PostalCode=97215>, <PostalCode=97239>, <PostalCode=97214>]

query 2:
latest_entries = Entry.objects.filter(zipcode__in=nearestzips.values())

print latest_entries
>>>TypeError: Cannot use a multi-field GeoValuesQuerySet as a filter value.

I am trying to take 'nearestzips' which contains 5 postal codes, and query entries that match those postal codes, but I am getting the error above.  any advice?
Answer: Rather than use .values(), use a .values_list() with whatever field you want to match on:
latest_entries = Entry.objects.filter(zipcode__in=nearestzips.values_list('myField', flat=True))

Comment: I will try this, but do you think this is the cause of my error?
Comment: I believe this answer should work, if not, wrapt the `values_list` in a `list()` call to turn it into a real python array/list.
Comment: Yes, this is the cause of your error. There shouldn't be a reason to wrap the `values_list` into `list()` when `flat=True` is passed in, because this will return a standard list, not a queryset.
Comment: would 'myField' just be 'PostalCode' ?
Comment: nevermind, it's 'code', but i get another error. programmingerror: invalid reference to FROM-clause entry for table "cities_postalcode" HINT perhaps you meant to reference the table alias"u0"
Comment: I'd need to see your models to understand what you're trying to access here. It should be whatever `ModelField` on `PostalCode` that you want to filter by. It would also help to see the `Entry` model since that presumably has a foreign key to `PostalCode`. Please update the original question with the code for those models.


Redirect mlflow 404 to custom error page URI instead of returning "The requested URL was not found on the server" error

Question: I am deploying MLflow on a Kubernetes cluster and using NGINX Ingress Controller as reverse proxy and load balancer.
I would like to customise the MLflow ingress, so that accessing a link that doesn't exist will return a custom error page instead of "Not Found" &
"The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again."
Currently, a couple of custom error pages are hosted on a separate deployment and would like to redirect to those pages instead.
The nginx ingress controlller default backend looked appropriate however I'd prefer a URI redirect to introducing another component and hosting the custom error pages there.
Here is an ingress example:
<code>kind: Ingress
apiVersion: networking.k8s.io/v1
metadata:
  name: mlflow-ingress
  labels:
    helm.sh/chart: chart-0.1.0
    app.kubernetes.io/instance: mlflow
  annotations:
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/ssl-passthrough: "true"
    nginx.ingress.kubernetes.io/use-regex: "true"
    nginx.ingress.kubernetes.io/rewrite-target: /$1
    nginx.ingress.kubernetes.io/proxy-body-size: 150m
    layer.quantumblack.com/description: "Log your experiments and metrics"
    layer.quantumblack.com/name: "MLFlow"
    layer.quantumblack.com/service_type: "mlflow"
    layer.quantumblack.com/url: "https://example.com/mlflow/"
    nginx.ingress.kubernetes.io/custom-http-errors: "404, 500, 502, 503, 504"
    nginx.ingress.kubernetes.io/server-snippet: |
      error_page 404 502 "https://example.com/404";
      error_page 403 "https://example.com/403";

</code>
With this setup, going to https://example.com/mlflow/#/experiments/0 will redirect to the custom error page but going to https://example.com/mlflow/1234 will return the aforementioned error.
I tried the example above and it redirects as long the server has problems (e.g. nginx 404 not found or 502 bad gateway) but doesn't satisfy the use case mentioned above.
Answer: You need to configure your Nginx Custom Errors.
I'll share you some links:
https://stackoverflow.com/a/60205943/21404450
https://www.callumpember.com/Easy-Kubernetes-Nginx-Ingress-Custom-Error-Pages/


How to show a modal dialog before beforeunload shows its own?

Question: I do understand that it's not possible to replace the beforeunload dialog with a custom one, and that if we need to set a custom message to the user, we'll have to return a string in our beforeunload handler:
{Custom message here set by returning a string in our beforeunload handler}
Are you sure you want to leave this page?
[Leave this page] [Stay on this page]

So, how about showing a custom modal dialog (maybe jQuery) before the actual beforeunload dialog is shown by the browser?
My current code uses Fancybox:
window.onbeforeunload = function() {
    $.fancybox({ 'type':'iframe', 'href':'/PopupOnExit.php' });
    return "Special offer! Stay on this page for more details.";
};

However, this shows the browser's dialog first, and only after clicking either "Stay" or "Leave" buttons does the browser show my modal dialog.
Is there any way to make my modal dialog show before the the browser's dialog?
Comment: I edited the question with the browser dialog which I'm referring to
Answer: The DOM modifications take effect only when your script ends execution. In this case, the native dialog is fired first for obvious security reason.
Note that due to the many security problem introduced by this unspecified feature (see the MDN doc), it will maybe be removed (the soonest the best in my opinion), the old reason to have it (save the data) being obsolete in the age of ajax.
Comment: The removal of the `beforeunload` event will be a sad day. No custom pop-up comes close to native ones
Answer: unload and onBeforeUnload are very not cross-browser events. Be careful.
It's not work in Opera and sometimes in Chrome.


How to make system wide alias for "ls -l"?

Question: I would like to have
alias ll="ls -l"

to be system wide.
How is that done on Ubuntu?
Answer: Add it in to /etc/bashrc. This will (or should) get called on login by every user who uses bash.
Comment: My machine (Ubuntu 12) doesn't have /etc/bashrc or any references to it in /etc/profile, ~/.bashrc or elsewhere.  The place I found that was best to do this, decoupled from the system's files and thus better for maintaining customizations with something like Puppet, is to place a file in /etc/profile.d/
Comment: I believe the correct location is actually `/etc/bash.bashrc` FWIW
Answer: # echo "alias ll='ls -l'" >> /etc/bash.bashrc

and make sure that this file is executed whenever an user enters a shell by adding the following in ~/.bashrc:
# Source global definitions
if [ -f /etc/bash.bashrc ]; then
    . /etc/bash.bashrc
fi

Comment: This answer was helpful. In Ubuntu 14.04, when I opened my `.bashrc` file, near the end, there's a pre-created section similar to the `if [...]` @quanta mentions, except is uses `.bash_aliases`.  All I had to do is echo the alias into `echo "alias ll-'ls -l'" >> ~/.bash_aliases` since `.bashrc` already had something setup in this environment.  And I closed/re-opened putty.
Answer: If your user's $HOME/.bashrc contains the usual
if [ -f /etc/bashrc ]; then
        . /etc/bashrc
fi

Then put it in /etc/bashrc. If it doesn't then put it in /etc/profile from where it will at least be read for login shells.


How to prove these conditions right or wrong?

Question:
 To solve the questions, I can write easily that

The area of ADC and BDC triangles equal and similarly EBD and CED triangle areas are equal.

From this conditions how to show  the following conditions  are true or not?
Answer: A. [midpoint theorem]
B. [Equal base and equal altitude]
C. (It is Not necessarily true). When C is obtuse, the foot of the perpendicular from E to AC will lie outside of ⊿ABC. This mean CF is less than 0.5 of AC and AF is then larger than 0.5 of AC. In short, AF > FC. This further implies the claim is not true [according to equal base and equal altitude]. See illustration below.

D. This is not true in general unless AD = DC. Then, AD = DC = DB. This further means angle C must be 90 degrees.
E. This is not true obviously. [Edit: True because area = AC * altitude / 2 = AC * DF.]
Comment: Actually, E is true: the line perpendicular to the line $(AC)$ and passing through $B$ intersects $(AC)$ at $H$. Then the area of $ABC$ is $\frac{1}{2}AC\cdot BH$. But $(DF)$ and $(BH)$ are parallel so, Thales' theorem implies that $\frac{DF}{BH}=\frac{AD}{AB}=\frac{1}{2}$. So $DF=\frac{BH}{2}$, which proves $E$.
Comment: @Taladris You are right. I forgot the factor 0.5 in calculating the area of a triangle. I am going to have my post edited shortly.


Why does this anonymous type not deserialize properly using JsonConvert.DeserializeAnonymousType?

Question: I have the JSON string:
{"response":{"token":"{\"token\":\"123\",\"id\":191}"}}

And then I have the following code to Deserialize it, but it is returning null:
 var def = new
       {
           token = new { token = string.Empty, id= string.Empty }
        };

  var deserializedToken = JsonConvert.DeserializeAnonymousType(token, def);

deserializedToken is null
Here is a more detailed example that I can't get to work:
var def = new
            {
                code = string.Empty,
                message = string.Empty,
                url= string.Empty,
                token = new {token = string.Empty}
            };

            var response = JsonConvert.DeserializeAnonymousType(data, def);

            var innerDef = new { token= string.Empty, id= string.Empty };

            var deserializedInner = JsonConvert.DeserializeAnonymousType(response.token.token, innerDef);

Answer: There are two problems here, as far as I can tell:

You don't have a response property to deserialize
The "token:123 id:191" part is actually just a string - the value of the outer token property

So if you change your code to:
var def = new
{
    response = new { token = "" }
};

var deserializedToken = JsonConvert.DeserializeAnonymousType(json, def);
Console.WriteLine(deserializedToken);

then you'll end up with:
{ response = { token = {"token":"123","id":191} } }

If you want to deserialize the token/id part as well, you can do that with:
var innerDef = new { token = "", id = "" };
var deserializedInner = JsonConvert.DeserializeAnonymousType
    (deserializedToken.response.token, innerDef);
Console.WriteLine(deserializedInner);

That then prints:
{ token = 123, id = 191 }

Comment: @xaisoft: Well what's the JSON to go with that? To be honest, I think it may be worth asking as a new question, just to keep everything clearer.
Comment: Okay so that explains the internalized question I kind of had all along. I've seen the deserializer skip *over* properties if it can find a match. Maybe better stated, I've seen it deserialize into objects that are lower than the root. If I had any more votes for the day you'd have mine; but that doesn't much matter for you probably. I'm sure by an hour in you're out of up votes. :D
Comment: I got it to work with your that example, but I put a more detailed on that I can't get to work.
Answer: string jsonToken = @"{'response':{'token':{'token':'123','id':191}}}";
var def = new
{
    response = new
    {
        token = new { token = string.Empty, id = 0 }
    }
};

var deserializedToken = JsonConvert.DeserializeAnonymousType(jsonToken, def);


How does one calculate the confidence intervals of range odds ratios?

Question: Suppose in a logistic regression a one unit increase in a linear dependent variable corresponds to an odds ratio of 1.61. The 95 % confidence interval ranges from 1.19 to 2.54.
JMP calculates the confidence intervals for "range odds ratios" exponentially so that a 11 unit increase corresponds to an interval from 1.19^11 to 2.54^11. See http://www.jmp.com/support/help/Logistic_Fit_Platform_Options.shtml
Is this correct?
Comment: When you ask is it correct do you mean (a) have I read the documentation correctly, or (b) is what JMP does the right way to do this?
Answer: Assuming the range of your variable is 11, then that is in principle right.
However, I would not do it that way: the 1.19 and 2.54 are rounded numbers, so they are slightly off. Those rounding errors tend to become surprisingly big if you raise it to a large number like 11.


My google maps looks weird

Question: I have this page here and the google maps looks weird, and when I say weird the information on the map is too big and cuts off (the the information that looks like it in a square word bubble similar to something you would see in a comic book.)
My Question is, how would I move the map over to view the full information
is there away to set a position on the map?
Here is my google maps code:

View Larger Map

Thanks,
J
Comment: A bit of context would help here...
Comment: what you want is to change the center maps positn? or to change the marker? i created this demo for us to be working. http://jsfiddle.net/LyLXt/
Comment: I am looking to move the map down more so the information box will fit...is there away to position the map so the information box will not be cut off?
Answer: You need to move it down a little.

open the "View Larger Map" link
resize it to the size you will be using
move the map down so there is room for the InfoWindow above the marker.
Capture the "Paste link in email or IM"
Paste that link in the address bar
Get the "embed code" ("Paste HTML to embed in website")
Put the embed code in your HTML.

adjusted jsfiddle

View Larger Map

My google maps looks weird


How to use one field with different settings

Question: I have a field that determines which category my content belongs to, stored in a taxonomy vocabulary. The field is used in both the content type and the user profile. Users may select a category, but they can select only one and definitely not more. The content however can belong to more categories, in my case 2. So the field settings should be different, but that is impossible when using a single field. Whenever i change the maximum number of values in useraccounts to 1, the field in the nodetype changes to 1 also.
I use the same field to be able to make some views (starting from a user's perspective) to display content based on the users choice.
I see three possible solutions:

Somehow use a field alias, enabling me to define the same field in 2 different ways. But i haven't found a mod for field aliases;
Define two seperate fields with seperate settings. But i can't filter my output in a View based on the value of another field. Also, using a contextual filter won't work because there is no value to pass in the URL;
Set the max value to 1 and add the same node twice, one for each category. Which is not the way to go, obviously.

Any clues to avoid option #3 ? I use D7 btw.
Thanx,
Cas
Answer: Set the maximum number of values to unlimited.
Then using hook_form_alter change the categories select to only allow 1 value on the user profile form:
function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {

    //drupal_set_message("Form ID is : " . $form_id);

    switch($form_id) {

        case 'user_profile_form':

            //dpm($form);
            $form['field_category'][LANGUAGE_NONE]['#multiple'] = false;
            break;

    }
}

If need be you could also add an additional validation handler here to add some custom server side validation to make sure that the user is not selecting more than 1 department.
Comment: Thanx Felix, this works fine for me. I had to change the widget from checkbox/radio to a select list because the #multiple identifier only works on select lists. But that is even better. I never made a custom module using a hook and had to dive into that, so you helped me in more than one way!
Comment: Glad to hear it - now you can make custom modules anything is possible :)
Answer: You don't specify exactly how the field is used on the User and Node Entities, but I'm assuming a User is able to pick a category of content to like/see/follow/associate with using a Term reference field, and Nodes are able to say they belong to two of these categories in the same way.
I would go with two different fields, because you really have two different use cases for a reference to one or more Terms in the same Vocabulary. I don't think it would make sense to filter users and nodes based on the same field in Views anyway, because it wouldn't work the way I think you want it to work.
Using the same Field on two different content types does not in any way actually link them together, or even imply they can be linked together. It just means those two content types needed the same settings for a Field, so why not create two instance of the same Field settings to make sure they'll always be the same.
In other words; "That's not a bug, it's a feature!"
When creating a View, one of the first things you do is to select the "base table", ie you're creating a Node (actually known as "Content" in Views) or User type View. Assume you want to display "every" item of this type (SQL's SELECT * FROM foo). If you create a Node/Content View without filters, you'll get all Nodes. You may link in User data (through the author or another field) through Relationships (SQL JOIN bar ON foo.x=bar.y), but you'll never see all users listed just once or a single row with just a User, since their data is just joined to the Nodes. The same is true for Nodes if you start with a User based View.
Filtering on the same field for more than one content type is useful when your content types are similar or closely structurally related somehow, and are both of the same base type (bundles of say Nodes). This way you can truly list all of these items just by making a Node View and filtering out other bundles, without any joins, so they're both first class items. Then you can get a subset of both types of content by adding a single filter on the [Term reference] field.
However, if the same field is used on Nodes and Users, you'd have to tell Views which instance of that field to filter on by, selecting the Relation to use (if any), ie which table (node or user) to use. (View generates one alias for each table a field is used on automatically, but it can still only compare a filtering value to one of them with one filter, and aliases still use Relationships/JOINs.)
This means you either get a subset based on which Nodes are in a category, or which Nodes were authored by Users that have selected that category.
This is because filters currently (until Views 7.x-3.8) only filter based on a fixed value (using one of several operators),  and not the value of another field.
Just to cover a corner case; if you also add another filter, filtering on the same Category value, but using "the other" table as the Relationship (User in a Node View or vice versa) you'll end up only with Nodes in the same category as its author has selected, or only Users which have created Nodes in the category they like. This type of very narrow subset of Users or Nodes would also be generated if you picked any other two fields (one from each of User and Node) to filter on, since the "Content" Field being instances of the same Field settings does not really matter for the result set you'll get back.
Since you want different settings for Term references, create two separate Fields. One for Nodes, allowing two Terms, let's call it "Categories". One for Users allowing one Term, let's call it just "Category".
This will actually make it slightly easier to navigate in the Views UI as you can clearly see which one of the Fields belongs to Nodes or Users later on.
Now, if you're looking to fetch Nodes based on which Category the current User has picked we'll have to figure out exactly what that relationship looks like.
A list of Nodes is not directly relatable to Users, unless the user happens to be the author or there are explicit User/Node reference fields linking them together, so let's break this down in steps.
Start with a Content View, add at least the Title field and the "Content: Categories" field just so we know shat we're getting back from the query. Sort by the Node title or whatever makes sense in your case.
Nodes hold the term ids in our Categories field, but we need the actual Term data, that's one Relationship in the right direction. Add a "Content: Categories" Relationship. Make it Required since we don't want Nodes without Categories set shown. By now your result set will include all Nodes with two Categories set twice, because of the JOIN this created. That's fine.
The Terms are also being referenced by a field on Users, and adding the previous Relationship between Nodes and Terms now allows us to go one step further. Add the "Taxonomy term: User using Category" Relationship and make it required as well. By now the result set will have multiplied the number of times a Node is shown by how many Categories it has, and again by the number of users which have set one of those Terms in their own Category Field. That's also fine.
You can now add a "User: Name" field to see who has chosen the same category used by the Node (note that it's using the Relationship chain).
Now we have established a link from Nodes to Users. Time to limit things to the User we're interested in: the one currently logged in. By now you'll be able to filter the result set based on any User data available through the Relationship chain, including the logged in status. So add a "Current user" filter and set it to "Logged in".
By now, your query is pretty much unreadable, but it works! ;)
In this case we're lucky User can only select one Category, since that prevents multiplying the number of times a Node is shown by the number of matches between the Category and Categories fields. But if you do need User to be able to select multiple categories later, make sure you tell Views to only return unique/distinct matches.
If some of my assumptions are wrong, please comment and I'll update the answer accordingly.
Comment: Thank you for this elaborate clearing! Because my View already worked when the user selects only one category i was helped with the above tweak through hook_form_alter but your text helped me understand Views/Queries a little better. I will certainly return to it when i need to.


What is the shortest distance from the ellipse $x^2+\frac{y^2}{4} =1$ and the point (2,2).

Question: What is the shortest distance from the ellipse $x^2+\frac{y^2}{4} =1$ and the point (2,2).
I know that this is the projection of (2,2) onto the ellipse. How do I go about finding the shortest distance between this point and the curve?
Comment: -1. No effort to try to solve the problem yourself. No effort to check if there is already a solution on this site.
Answer: Define point $P(2,2)$.  The tangents to the curve $$x^2+\frac14y^2=1$$ will have a slope of $m=-\dfrac{4x}{y}$ or $-\dfrac{2x}{\sqrt{1-x^2}}$.  At some $x$ value, the point of tangency will be $Q(x,2\sqrt{1-x^2})$.  We want $m$ and $PQ$ to be perpendicular, and thus their values will be of negative reciprocal.
As such, we have $$\frac{\sqrt{1-x^2}}{2x}=\frac{2\sqrt{1-x^2}-2}{x-2}\implies x\approx0.69661$$
(use a numerical method).
Now that you have your point $Q$, you can find the length of $PQ$.
Comment: Concerning your last equation, let $\sin \left(2 \tan ^{-1}(u)\right)$ to end with $u^4+7 u^3+u-1=0$ which can be solved with messy radicals. Otherwise, Householde method starting at $x_0=\frac{1}{\sqrt{2}}$  leads to an approximate $x=\frac{3 \left(116636+91089 \sqrt{2}\right)}{1021156}\approx 0.72111$ while the exact solution is ... the same. Cheers :-)
Answer: You can think about this as a constrained optimization problem.  You want to minimize the function $f(x,y) = (x-2)^2 + (y-2)^2$ [the square of the distance from $(x,y)$ to $(2,2)$], subject to the constraint that $x^2+y^2/4=1$.
Answer: Knowing that the gradients of level curves are perpendicular to them then seek for $(x,y)$ such that
$$[2x,\frac{1}{2}y]=\lambda[2(x-2),2(y-2)].$$
This models how the normal to the ellipse is aligned to the normal of a circle centered at $(2,2)$.
The next plot may help you to think towards the solution
$\qquad\qquad\qquad\quad$


How to remove the "Save" button from checkout cart summary form?

Question: On the first checkout page (checkout/xx/checkout), there is a view which displays line items for the order.  The view appears to be named "Shopping cart summary (Commerce Order)"
When I add the standard Delete button to the view (for deleting line items), it causes a Save button to appear below the line items.
How do I remove that Save button?
Update:
I tried a form-specific hook_form_alter(), but didn't find the Save button in the $form array. It appears to be a form embedded in another form.  Reading answer from @Yogesh made me realize that maybe I had the wrong $form_id and can debug with a general hook_form_alter() and look for a nested call for the embedded form.
Answer: One way of doing this is implementing hook_form_alter and hiding save button. Check example below:
function [MODULE_NAME]_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id = 'YOUR_FORM_ID') {
    // Set access to FALSE will prevent rendering form element on form.
    // Check the hierarchy of 'Save' button, before using #access.
    $form['actions']['save']['#access'] = FALSE;
  }
}

Comment: I tried this with a form_alter hook that I thought was specific to the form and couldn't find the button in the `$form` array. It appears to be a form embedded in another form.  Maybe I should try a general form_alter hook in case I had the wrong `$form_id`.
Comment: Specifically, the form to alter is `views_form_commerce_cart_summary_default`, and the element to alter is `$form['actions']['submit']`.  It's embedded into the parent form (`commerce_checkout_form_checkout`) as _rendered markup_.
Comment: I had $form['actions']['submit']['#access'], so submit instead of save (maybe because I'm using the workflow module)


How to config webpack to load custom fonts into storybook?

Question: I'm new to webpack and I'm trying to load custom fonts into stroybook v4 following this tutorial https://medium.com/@mushti_dev/hey-e6faa20b910a
The workspace structure looks like this (create-react-app + storybook)
my-project/
  .storybook
     config.js
     preview-hrad.html
     webpack.config.js
  fonts
    MyCustomFont.woff
  src
    components
       Title.js
    containers
    styles
       MyCustomFont.woff
    index.js
  stories

When loading the font from the styles folder in src, the config is as follows:
webpack.config.js
const path = require('path');

module.exports = async ({ config }) => {
  // fonts
  config.module.rules.push({
    test: /\.(png|woff|woff2|eot|ttf|svg)$/,
    use: [
      {
        loader: 'file-loader',
        query: {
          name: '[name].[ext]',
        }
      }
    ],
    include: path.resolve(__dirname, '../')
  });

  return config;
};

preview-head.html

Title.js
import React from 'react';

const Title = ({ title }) => {
  return (

{title}

  );
};

export default Title;

My question is how to load MyCustomFont.woff from the fonts folder ?
I tried to update the webpack config with  name: 'fonts/[name].[ext]', and the css style with src: url('fonts/MyCustomFont.woff') format('woff'); but I'm having hard time matching the correct font path.
Answer: I just ran into this issue on storybook v6.1, then realised there are actually two font areas to setup:

iframe preview fonts (components preview fonts in preview-head.html)
storybook dashboard fonts (dashboard navigation fonts in manager-head.html)

What I did:

make a copy of preview-head.html and rename to manager-head.html
ensure the font url specified in @font-face is relative to static folder path specified in npm scripts with -s
I did not change webpack config in main.js

my folder structure

|- .storybook/
   |- ...
   |- preview-head.html
   |- manager-head.html
|- src/
   |- ...
   |- fonts/
      |- font-name.otf

preview-head.html and manager-head.html

package.json

{
  ...
  "scripts": {
    ...
    "storybook": "start-storybook ... -s ./src",
    "build-storybook": "build-storybook -s ./src"
  }
}

Comment: This suggestion changes if I am using create-react-app? Because I haven't being able to make it work. Also checking https://github.com/mydatahack/mdh-design-system-storybook-typescript but can't make it work yet.
Comment: @AlexisDuran in your `*-head.html` file you can try something like this:
`
` then in your `package.json` you should have `"storybook": "start-storybook -p 6006 -s ./src"` and `"build-storybook": "build-storybook -p 6006 -s ./src"`
Comment: I ending up by use S3 to allocate my fonts and then from there everything was smooth. Hopefully either yours or my response help someone in the future!


Magento Programaticallly add product, Image is not selected as small-image

Question: I'm trying to add a product programmatically in magento. Everything works file except images.
The images are uploaded and showing up on product page. however, it doesn't set as small-image or thumbnail.
At admin back-end side, it looks like this,

I use following code ,
<code>$fullpath = 'upload/one.jpg';
$product->addImageToMediaGallery($fullpath, 'image', false);
$product->addImageToMediaGallery($fullpath, 'small_image', false);
$product->addImageToMediaGallery($fullpath, 'thumbnail', false);
</code>
I tried below code also with no luck,
<code>$product->addImageToMediaGallery($fullpath, array('image', 'thumbnail', 'small_image'), false, false);
</code>
Answer: Try adding
<code>$product->setImage($fullpath);
$product->setImage($fullpath);
$product->setThumbnail($fullpath);
$product->save();
</code>
I didn't test it but took the idea from here: http://webkul.com/blog/magento-set-product-default-image-product-images/
Comment: Still Not working..  No any error but image is shown like this, http://s14.postimg.org/fcm5zql1d/prblm.jpg, http://s15.postimg.org/7m8l300h7/prblm2.jpg
Comment: can you provide some more code, especially lines before and after your already provided code? (how is the object in $product created?) Then I would try it by myself in a test installation and tell you if I could manage. Oh and try to clear cashes and reindex, maybe that could lead to problems too?


How to display Multi select Listbox as dropdown in ASP.NET web forms

Question: I have the below code implemented, but the desired output is not rendered.
The list boxes are used to filter the grid view. I can filter the grid view but the filters (list boxes) are being rendered as it is. I need them to be inside the dropdown.
I have included the links to relevant resources in the head section, yet the control is rendered as a list box. I have seen this code work for many tutorials, why is it not working for me? Any help is appreciated
<code><asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">

    <link href="StyleSheet.css" rel="stylesheet" type="text/css">

    <link rel="stylesheet" href="//code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css">
    <link rel="stylesheet" href="/resources/demos/style.css">
    <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
    <script src="https://code.jquery.com/ui/1.13.1/jquery-ui.js"></script>
    <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
    <script src = "/scripts/jquery.min.js"></script>
    <script src = "/bootstrap/js/bootstrap.min.js"></script>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js"></script>
    <link href="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css" rel="stylesheet" type="text/css" />
    <script src="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js" type="text/javascript"></script>

    <script type="text/javascript">

        $(document).ready(function () {

            $("[id$=TextBox_From]").datepicker(
                {
                    dateFormat: 'mm/dd/yy', autoclose: true
                }
            );
            $("[id$=TextBox_To]").datepicker(
                {
                    dateFormat: 'mm/dd/yy', autoclose: true
                }
            );

            var FromDate = new Date(Session["start_date"]);

            $("[id$=TextBox_From]").datepicker('setDate', FromDate);
            var ToDate = new Date(Session["end_date"]);
            $("[id$=TextBox_To]").datepicker('setDate', ToDate);

            $("[id$=lstrpa_ticket_id]").multiselect({ includeSelectAllOption: true, enableCaseInsensitiveFiltering: true, enableFiltering: true });
            $("[id$=lstPortal_ID]").multiselect({ includeSelectAllOption: true, enableCaseInsensitiveFiltering: true, enableFiltering: true });
            $("[id$=lstRegion]").multiselect({ includeSelectAllOption: true, enableCaseInsensitiveFiltering: true, enableFiltering: true });
            $("[id$=lstMarket]").multiselect({ includeSelectAllOption: true, enableCaseInsensitiveFiltering: true, enableFiltering: true });
            $("[id$=lstClient]").multiselect({ includeSelectAllOption: true, enableCaseInsensitiveFiltering: true, enableFiltering: true });
            $('#lstAgency').multiselect({ includeSelectAllOption: true, enableCaseInsensitiveFiltering: true, enableFiltering: true });
            $("[id$=lstrequest_type]").multiselect({ includeSelectAllOption: true, enableCaseInsensitiveFiltering: true, enableFiltering: true });
            $("[id$=lstts_type]").multiselect({ includeSelectAllOption: true, enableCaseInsensitiveFiltering: true, enableFiltering: true });
            $("[id$=lstcompleted_success]").multiselect({ includeSelectAllOption: true, enableCaseInsensitiveFiltering: true, enableFiltering: true });
            $("[id$=lsttime_taken_validation]").multiselect({ includeSelectAllOption: true, enableCaseInsensitiveFiltering: true, enableFiltering: true });
            $("[id$=lsttime_taken_preQA]").multiselect({ includeSelectAllOption: true, enableCaseInsensitiveFiltering: true, enableFiltering: true });
            $('[id*=lst1]').multiselect({ includeSelectAllOption: true, enableCaseInsensitiveFiltering: true, enableFiltering: true });
        });

    </script>
</code>
In the above code for some places I tried different ways to identify list box control in different ways for checking, yet both failed:
<code>$("[id$=lstPortal_ID]").multiselect

$('#lstAgency').multiselect
</code>
The control is rendered as :

The desired output is like this
Answer: Please check jQuery library is referenced multiple times,that may be the reason i guess.


Expected amount of repeats in a random sequence of integers

Question: I'm looking at a series of random integers generated by a CSPRNG and noticed that there are more repeats (that is a number is in the sequence 2 or more times e.g. 9,3,8,5,6,3 - 3 is a repeat) than I expected.
I generated 10,000 numbers, each between 1 and 100,000, this resulted in 9,516 unique numbers. Does this seem correct, and if so, how would I calculated the expected about of unique numbers for n random numbers of a range 1 to x?
Comment: As Bernhard says in his answer, this does seem about correct. Random numbers are counter-intuitive in their behaviour. They "cluster" more than we tend to expect.
Comment: This question is a refinement of the Coupon Collector problem, which has been much studied.  The usual problem asks how many trials you'll need before you can expect to see all the numbers, but of course you can also ask for the expected number of coupons you'll see after $n$ trials, number of multiples, and so on.  Easy to get references on line; here, for example, is one:  http://www.math.ucla.edu/~pak/courses/pg/l10.pdf
Answer: When sample $n$ times from the set $\{1,\dots, x\}$, then the expected number of unique values is $x[1-(1-1/x)^n]$. With $n=10000$ and $x=100000$, this gives
approximately $9516.303$.
Comment: Thank you - I've run several sequences with different x and n values and put the same into your formula - very close match each time!
Answer: The probability a given single number does not appear at least once is $\left(1-\frac{1}{100000}\right)^{10000} \approx e^{-1/10}$
so the expected number not appearing is $100000$ times this, near $90483.7$,
making the expected number of unique numbers about $9516.3$, surprising close to what you observed.
Comment: Thank you - I accepted the other answer just because I understood the formula, but I can see you have the same answer. Tried upvoting you but could not as new here.
Answer: Your question is strongly related to the birthday paradox. Calculating the expected value of unique numbers could be done, e.g., by using combinatorial arguments. But as to your question: Yes, such a number indeed seems to be plausible.


Sample three Bernoulli variables given the 2 by 2 by 2 table

Question: I want to sample three Bernoulli variables given their 2 by 2 by 2 table:

where the last column is the probabilities with sum being equal to 1.
What I am thinking now is to use a multivariate normal distribution, then use cut-points to create Bernoulli variables.
Do you know any better way, directly sample from Bernoulli distributions?
Comment: But based on the probabilities on the last columns you can directly sample from the appropriate Bernoulli distributions
Answer: Suppose that you want to sample a Bernoulli trial for $X$, then you have to know the probability of success $\mathbb{P}(X=1)$
You can calculate this probability by summing over the other two variables.
$$\mathbb{P}(X=1)=\sum_{Y_{0},Y_{1}=0,1}\mathbb{P}(X=1,Y_{0},Y_{1})$$
$$=\mathbb{P}(X=1,Y_{0}=0,Y_{1}=0)+\mathbb{P}(X=1],Y_{0}=1,Y_{1}=0) +$$
$$ \mathbb{P}(X=1,Y_{0}=0,Y_{1}=1) + \mathbb{P}(X=1,Y_{0}=1,Y_{1}=1)$$
$$= \pi_{100} + \pi_{110} + \pi_{101} +\pi_{111}$$
Hence, $X\sim Bern(\pi_{100} + \pi_{110} + \pi_{101} +\pi_{111})$ similarly for the rest.
If you want to take into account the association between the random variables, then I suppose you can use a Multinomial distribution.
Where for example the event $(0,0,0)$ will have probability $\pi_{000}$ similarly you can think for the rest. So,  (not 100% sure but seems logical to me) for sampling Bernoulli trials you can think in the following way:

You conduct a single Multinomial sampling with probabilities $(\pi_{000},\pi_{001},\pi_{010},\pi_{100},\pi_{011},\pi_{101},\pi_{110},\pi_{111})$

You identify the result that you produced, for example if it is $(1,0,1)$ you can regard it as $X=1$, $Y_{0}=0$ and $Y_{1}=1$.

In R you could do something like:
probs = rdirichlet(1,rep(1,8))
Mult = matrix(0,1000,8)
for(i in 1:1000){
  Mult[i,] = rmultinom(1,1,prob)
}
X = sum(apply(Mult,2,sum)[c(4,6,7,8)]) # how many 1 draws
Y_0 = sum(apply(Mult,2,sum)[c(3,5,7,8)])
Y_1 = sum(apply(Mult,2,sum)[c(2,5,6,8)])

Comment: So, you want to calculate simultaneously the Bernoulli trials for all the variables ??


Display additional Column in the SQL query

Question: I have a SQL select query which returns the Customer Contact Email Address information to send the Customer Statements given below

    SELECT hp.party_name
      ,hzl.location_id "Bill To Number"
      ,hzps.party_site_name "Customer Bill To Name"
      ,hcp.email_address "Customer Email Address"
FROM
    hz_parties hp,
    hz_cust_accounts hca,
    hz_cust_acct_sites_all hcsa,
    hz_cust_site_uses_all hcsu,
    hz_party_sites hzps ,
    hz_locations hzl,
    hz_cust_account_roles hcar,
    hz_contact_points hcp,
    hz_relationships hr
WHERE 1=1
and hp.party_id             = hca.party_id
and hca.cust_account_id     = hcsa.cust_account_id
and hcsa.cust_acct_site_id  = hcsu.cust_acct_site_id
and hcsa.party_site_id      = hzps.party_site_id(+)
and hzps.location_id        = hzl.location_id(+)
and hcsu.site_use_code      = 'BILL_TO'
and NVL(hcar.status,'A')    ='A'
and hcar.cust_account_id    = hca.cust_account_id
and hcar.cust_acct_site_id  = hcsa.cust_acct_site_id
and hcar.relationship_id    = hcp.relationship_id
and hcp.contact_point_type  = 'EMAIL'
and nvl(hcp.end_date,SYSDATE+5) > SYSDATE
and hcp.relationship_id     = hr.relationship_id
and hr.relationship_code    = 'CONTACT_OF'
and hr.object_id            = hp.party_id;

Result of the above query is

PARTY_NAME  Bill_To_Number  Customer_Bill_To_Name   Customer_Email_Address
Party 1         1006746009  CUSTOM PRODUCTS         firstname.lastname@example.com
Party 1         1006746009  CUSTOM PRODUCTS         email@example.com
Party 2         1006746010  PAINT COMPANY           firstname.lastname@example.com
Party 2         1006746010  PAINT COMPANY           firstname.lastname@example.com
Party 3         1006746011  ADVANCED MATERIALS  firstname.lastname@example.com
Party 4         1006746012  ADVANCED PRODUCTS   email@example.com

I need to modify the query to display one more additional column using in the select statement(i.e., Dummy) with values either 'A' or 'B'. Logic to derive the value is, if a Customer having multiple emails for the first record it should be 'A' and for the second record it should be 'B'.
In the above output Party1 and Party2 are having multiple email ids so Dummy column should have A for first record and B for second record as given below

    PARTY_NAME  Bill_To_Number  Customer_Bill_To_Name   Customer_Email_Address   Dummy
Party 1         1006746009  CUSTOM PRODUCTS         email@example.com     A
Party 1         1006746009  CUSTOM PRODUCTS         email@example.com      B
Party 2         1006746010  PAINT COMPANY           firstname.lastname@example.com   A
Party 2         1006746010  PAINT COMPANY           firstname.lastname@example.com       B
Party 3         1006746011  ADVANCED MATERIALS  email@example.com       A
Party 4         1006746012  ADVANCED PRODUCTS   email@example.com A

Note: party_name column is the Primary key column.
Any help would me much appreciated.
Comment: how you determine which is a or b datatables have nor inherit order
Comment: Your query doesn't include any `order by`, so what determines "first" vs "second" record? If you're trying to determine primary/secondary e-mail, this should probably be a property of the contact record.
Comment: there is no particular condition to determine which record should have A and which record should have B.
Answer: Number the rows for each party_name/location_id/party_site_name combination and then convert that number to a character:
SELECT hp.party_name
      ,hzl.location_id "Bill To Number"
      ,hzps.party_site_name "Customer Bill To Name"
      ,hcp.email_address "Customer Email Address"
      ,CHR(
         64
         + ROW_NUMBER() OVER (
             PARTITION BY hp.party_name, hzl.location_id, hzps.party_site_name
             ORDER BY hcp.email_address
           )
       ) AS Dummy
FROM   hz_parties hp
       INNER JOIN hz_cust_accounts hca
       ON hp.party_id             = hca.party_id
       INNER JOIN hz_cust_acct_sites_all hcsa
       ON hca.cust_account_id     = hcsa.cust_account_id
       INNER JOIN hz_cust_site_uses_all hcsu
       ON hcsa.cust_acct_site_id  = hcsu.cust_acct_site_id
       LEFT OUTER JOIN hz_party_sites hzps
       ON hcsa.party_site_id      = hzps.party_site_id
       LEFT OUTER JOIN hz_locations hzl
       ON hzps.location_id        = hzl.location_id
       INNER JOIN hz_relationships hr
       ON hr.object_id            = hp.party_id
       INNER JOIN hz_contact_points hcp
       ON hcp.relationship_id     = hr.relationship_id
       INNER JOIN hz_cust_account_roles hcar
       ON  hcar.cust_account_id    = hca.cust_account_id
       and hcar.cust_acct_site_id  = hcsa.cust_acct_site_id
       and hcar.relationship_id    = hcp.relationship_id
WHERE  hcsu.site_use_code      = 'BILL_TO'
and    (hcar.status = 'A' OR hcar.status IS NULL)
and    hcp.contact_point_type  = 'EMAIL'
and    (hcp.end_date > SYSDATE OR hcp.end_date IS NULL)
and    hr.relationship_code    = 'CONTACT_OF';

fiddle
Comment: I have just used the derivation part from your query in the query I have posted. It is working as expected. Thanks
Comment: @Anji007 Move the `INNER JOIN` for `hcp` before the join for `hcar`.
Comment: Yes, that is worked. Many thanks for your help.


Stubbing Time.now with RSpec

Question: I am trying to stub Time.now in RSpec as follows:
it "should set the date to the current date" do
    @time_now = Time.now
    Time.stub!(:now).and_return(@time_now)

    @thing.capture_item("description")
    expect(@thing.items[0].date_captured).to eq(@time_now)
end

I am get the following error when doing so:
 Failure/Error: Time.stub!(:now).and_return(@time_now)
 NoMethodError:
   undefined method `stub!' for Time:Class

Any idea why this could be happening?
Comment: Just as it says. `Time` does not have a method called `stub!`.
Answer: Depending on your version of RSpec you might want to use the newer syntax:
allow(Time).to receive(:now).and_return(@time_now)

See RSpec Mocks 3.3
Comment: It's worth pointing out that this line must be in a 'before' block to work. It had no effect when I tested it inside of an 'it' block.
Comment: How can I mock `DateTime.now.in_time_zone`? I need to run the test on the first of the month, monday, hour 0.
Comment: Avoid using mocks or you will have hard time making any change in implementation.
Answer: You'd better use travel_to from ActiveSupport:
require 'rspec'
require 'active_support'
require 'active_support/testing/time_helpers'

Time.zone = 'UTC'

RSpec.describe 'Testing time' do
  include ActiveSupport::Testing::TimeHelpers

  it 'stubs current time' do
    travel_to Time.zone.parse('1970-01-01 08:00:30') do
      some_method_that_uses_current_time
    end
  end
end

Neither Rails nor other gems are needed.
Comment: @AurelBranzeanu The example has been updated to work with plain Ruby and RSpec (as the tags of the question imply). The `include` has been added as well. Thanks!
Comment: Not quite working: `NoMethodError: undefined method `travel_to' for #<RSpec::ExampleGroups...`

You should include ActiveSupport::Testing::TimeHelpers:
Answer: You can use timecop. Freeze the time before the test and  unfreeze it after.
describe "some tests" do
  before do
    Timecop.freeze(Time.now)
  end

  after do
    Timecop.return
  end

  it "should do something" do
  end
end

or define a specific time with
let(:time_now) { Time.now }

and used in Timecop.freeze(time_now) and in tests
Answer: You can always use timecop:
@time_now = Time.now

Timecop.freeze(@time_now) do
  @thing.capture_item("description")
  expect(@thing.items[0].date_captured).to eq(@time_now)
end

Comment: or with a before block: `before { Timecop.freeze(Time.now) }`

Stubbing Time.now with RSpec


Is sum, product and composition of uniformly continuous functions also uniformly continuous?

Question: I know that sum and composition are and product isn't but need prove of it or counter-example.
I have tried do it from definition but failed.
Answer: Hint: $x$ is uniformly continuous but $x^2$ is not.
Comment: ok but what about sum and composition?
Answer: I wonder if your question is more about how to use definitions and write proofs than about uniform continuity, since the proof for compositions is a quite straightforward application of the definition.
Suppose $g$ is uniformly continuous; then for every $\varepsilon>0$, no matter how small, there exists $\eta>0$ so small that whenever $|x-y|<\eta$ then $|g(x)-g(y)|<\varepsilon.$
But suppose $f$ is also uniformly continuous; then for every $\eta>0$, no matter how small, there exists $\delta>0$ so small that whenever $|s-t|<\delta$, then $|f(s)-f(t)|<\eta$.
So $|s-t|<\delta$ entails $|f(s)-f(t)|<\eta$ and $|f(s)-f(t)|<\eta$ entails $g(f(s))-g(f(t))|<\varepsilon.$
Given $\varepsilon>0$ there exists $\eta>0$ and given $\eta>0$ there exists $\delta>0$. Therefore, given $\varepsilon>0$ there exists $\delta>0$.
For sums, suppose we know that for every $\varepsilon>0$ there exists $\delta>0$ such that whenever $|x-y|<\delta$ then $|f(x)-f(y)|<\varepsilon$. This says something is true of EVERY positive number (in the role of $\varepsilon$). If it's true of EVERY positive number, then it's true of $\varepsilon/2$, since that is a positive number. So we can say there is some $\delta_1>0$ such that whenever $|x-y|<\delta_1$ then $|f(x)-f(y)|<\varepsilon/2$ (this number $\delta_1$ generally needs to be smaller than the value of $\delta$ mentioned earlier in this paragraph). Similarly, there is some number $\delta_2>0$ such that whenever $|x-y|<\delta_2$ then $|g(x) - g(y)|<\varepsilon/2.$ Now we can think about the sum $f+g.$  Let $\delta_3 = \min\{\delta_1,\delta_2\}.$
\begin{align}
& \text{If }|x-y|<\delta_3 \text{ then } |x-y| < \delta_1 \text{ and so } |f(x)-f(y)|< \frac\varepsilon 2. \\[10pt]
& \text{If }|x-y|<\delta_3 \text{ then } |x-y| < \delta_2 \text{ and so } |g(x)-g(y)| < \frac\varepsilon 2. \\[10pt]
& \text{From this it follows that} \\[10pt]
& | (f+g)(x) - (f+g)(y)| = \left| \Big(f(x) - f(y)\Big) + \Big(f(x)-g(y)\Big) \right| \\[10pt]
\le {} & |f(x)-f(y)| + |g(x)-g(y)| < \frac\varepsilon 2 + \frac\varepsilon 2 = \varepsilon.
\end{align}
Comment: You got me. That give me thought how do proof like this in generally. Thanks for your time.


What's the rhythm for 6/8?

Question: Looking into 6/8 on the Internet, I've learnt that the beat is not 6 eighth/quaver notes but 2 dotted quarter/crotchet notes.
So that's cool, but I've also read about beats in a measure being either strong or weak, and I've seen a few sites mention that, for 6/8 time, the beats go
s w w s w w
which is 6 beats, not 2. This is confusing.
How do I resolve this apparent discrepancy? What is the rhythm (or beat pattern) for 6/8?
Comment: When you count music with complex rhythms, there are often strong beats and weak beats, different options to count.  Generally how fast the music is decides on which you count for 6/8.  You can feel the strong 2 pulses or the weak 6 pulses.  Whichever makes more sense for that piece.  It's kind of like asking if a table is 75cm tall or 0.75m .  The answer is yes to both, and that there's a "metre" pun that I'm missing somewhere here.
Comment: Possible duplicate of [Does 3/4 time signature differ from 6/8?](http://music.stackexchange.com/questions/25035/does-3-4-time-signature-differ-from-6-8)
Comment: @guidot -  It's true that the two questions cover some of the same territory, but I disagree that they're duplicates.  This one is specifically about 6 beats vs 2 within 6/8 - no mention of 3/4, where the other one was trying to clear up confusion about the fact that the measures superficially resemble each other in the two time signatures.  Quite a different emphasis.
Comment: Keep in mind that tempo matters; with a slow 6/8, it might be easier to count out all 6 beats than trying to feel it in 2.
Answer: The main use of 6/8 time is to indicate a rhythm organized as a measure of two eighth-note triplets. Count ONE-two-thee-FOUR-five-six, etc; the ONE gets slightly more stress than the FOUR. An identical structure would be writing a 2/4 measure with all triplets, but that's supposedly harder to read. Historically, 6/8 has been used for this pattern. Some marches (Simper Fidelis and The Washington Post March for example) and many jigs (and gigues) have this pattern.
The 6/8 time signature is an example of a compound time signature.
Comment: I would be wary about using the word triplet to describe this three note group. Any type of tuplet (duplet, triplet, quadruplet, quintuplet, etc) is a description of a group of notes played in the space of another group of notes. A triplet describes a group of three notes played in the space of, most commonly, two notes.
Comment: 6/8 time is 6 eighth notes but the common practice is to group them into two groups of three so that you would only count, and it also be conducted, in two. So essentially one beat is the length of a dotted quarter, which equals three eighths. So the three eighth notes are played in the space of three eighth notes so they are technically not triplets.
Answer: The BEATS in 6/8 go 1,2,1,2....
The NOTES (if they're a constant stream of 8ths) go swwsww swwsww...   The s (strong) notes come on the beats.
I imagine you wouldn't be in the slightest worried about a bar of 4/4 containing 8 x 8th notes.  That's 8 notes, but 4 beats.   It's just that 6/8 has the bottom number 8, so you want to count 8ths.
Think of 6/8 as 2/ ....  well, that's the problem.  There isn't a bottom number that indicates a dotted half beat.  I can show you in notation:
Answer: It is easiest when trying to count. Although 3/4 and 6/8 look superficially similar how they are counted differs much.
Think of 3/4 as a waltz rhythm. How do you dance the waltz, it is 1,2 1,2 1,2? Think about how the dancers move when they dance the waltz.
A compound Time Signature now has pulses with dots next to them but the underlying number of pulses remains the same.
So remember 6/8 time is Compound Duple Time it is, in fact, more similar to 2/4 time than 3/4. The only difference between 6/8 and 2/4 is that instead of crotchet beats you now have dotted crotchet beats.
So 6/8 time you will count 1,2,3 1,2,3 with the emphasis usually on the first beat.
Now about triplets. Triplet does not change the beats, you still have exactly the same amount of beats you just play a certain amount of notes instead of the regular.
So in 2/4 with triplets, you would still have your two main crotchet beats you will only really play three notes in the time of one beat. (For quaver triplets at least.)
In 2/4 time with triplets, you would count 1,2 and just play the three notes in a beat but with 6/8 time it is just 1,2,3 1,2,3. So there are differences in the way you would approach playing those rhythms.
Answer: To amplify on Laurence's answer as well as the fourth paragraph of Neil's:
There's a whole 'family' of time signatures (called Compound) in which the basic beat is a dotted something.  In 6/8 it's a dotted quarter.  But most time signatures in which the top number is a multiple of 3 work the same way (provided the bottom number is 4 or larger).  For example, 3/8 is one beat per measure, 6/8 is two, 9/8 is three, and 12/8 is four.  Similarly, if the tempo is fast enough to justify it, 12/4 is four beats per measure, dotted half per beat, 6/4 is two beats, again dotted half per beat.
Likewise, 3/16 is one beat per measure, basic beat being a dotted eight.  Etc. Etc.
The real key to the whole concept is in the fourth paragraph of Neil's answer, if you extend it to include /4  and /16 signatures as well as /8.

What's the rhythm for 6/8?


Change JS code in order to work with GTM (arrow function and spread expression)

Question: I use this JS code to get title value from a elements in a series of li :
var res = [...document.querySelectorAll(".breadcrumb li:not(:first-of-type) > a")].map(el => el.getAttribute("title")).join(" - ");
alert(res)

I have to use it in Google Tag Manager but it doesn't work because GTM doesn't support ECMASCRIPT6.
How arrow function and spread expression can be changed to make it works with tag manager?
Comment: something like ..... `Array.from(document.querySelectorAll(...)).map(function(el){ return el})` ??
Comment: Try Babel online. https://babeljs.io/
Answer: You can call Array.prototype.slice on the NodeList to convert to an array. The arrow function can just be replaced with a regular function:
var res = []
  .slice
  .call(document.querySelectorAll(".breadcrumb li:not(:first-of-type) > a"))
  .map(function (el) {
    return el.getAttribute('title')
  })
  .join(' - ')


How do you set the document title in React?

Question: I would like to set the document title (in the browser title bar) for my React application. I have tried using react-document-title (seems out of date) and setting document.title in the constructor and componentDidMount() - none of these solutions work.
Comment: If you just want to change the title you can edit title in index.html file which contain inside the public folder
Comment: @IshanFernando this is not a solution when you have multi-language support. We don't need a temporary page title from index.html flashing while a page is loading.
Comment: I confirm, react-document-title works great with react 16.5
Answer: For React 16.8+ you can use the Effect Hook in function components:
import React, { useEffect } from 'react';

function Example() {
  useEffect(() => {
    document.title = 'My Page Title';
  }, []);
}

To manage all valid head tags, including <title>, in declarative way, you can use React Helmet component:
import React from 'react';
import { Helmet } from 'react-helmet';

const TITLE = 'My Page Title';

class MyComponent extends React.PureComponent {
  render () {
    return (
      <>
        <Helmet>
          <title>{ TITLE }</title>
        </Helmet>
        ...
      </>
    )
  }
}

Comment: Seems like overkill to set one single  tag.
Comment: This should definitely be the top answer. It's an excellent declarative way to manage the title and other meta attributes
Comment: like @Reactgular said this is overkill. Generally it's not advisable to bring in dependencies to solve problems that can be easily solved with what's already available. Sure the API might be nicer than `document.title` but you've just introduced potentially more complexity for no palpable benefit by adding relying on a library for something like this.
Comment: Is there no way to modify the template for static code like this? Have we really come to a point where static content needs to be scripted?
Comment: this will 'flash' the contents of the index.html in the first second, right?
Comment: @Reactgular agreed. I've updated the answer to point out that Helmet can be used to manage all head tags, not only title. And added an example of using Effect hook in React 16.8+
Comment: Usage of helmet in React 16 has an issue https://github.com/nfl/react-helmet/issues/548
Comment: @nxmohamad Yes, the "flash" issue can be resolved by removing the title tag altogether from the index.html file. Only downside being you have to make sure to give a title on every page or else it defaults to the domain name.
Comment: You may not need useEffect() if you are using functional components. `document.title = props.title` can be set and updated with a props change. It can even be set inside of render.
Answer: import React from 'react'
import ReactDOM from 'react-dom'

class Doc extends React.Component{
  componentDidMount(){
    document.title = "dfsdfsdfsd"
  }

  render(){
    return(
       test
    )
  }
}

ReactDOM.render(
  <Doc />,
  document.getElementById('container')
);

This works for me.
Edit: If you're using webpack-dev-server set inline to true
Comment: Change the content of the title tag in your index.html
Comment: This works but the document title is still "React App" while the page is loading - any idea how to fix that?
Comment: Better to do it declaratively like in @quotesBro's answer
Comment: Is this way OK for SEO?
Comment: @AlexVestin Not a good idea if you need different titles for different views in your React application
Comment: Why can't I update the document title in other components if my index.js file sets the title to start?
Comment: From reactjs version 16.3 'componentWillMount' is not recommended instead use 'UNSAFE_componentWillMount' & this is also not advisable in strict mode
Comment: where do I put `inline:true`?
Answer: For React 16.8, you can do this with a functional component using useEffect.
For Example:
useEffect(() => {
   document.title = "new title"
}, []);

Having the second argument as an array calls useEffect only once, making it similar to componentDidMount.
Comment: Until page loads it is React APP, then changes to "new title" very ugly.
Comment: How can this be tested with jest and enzyme?
Comment: +1. Note that if the title is *computed* in some way -- which it probably is, otherwise you would just set it in `...` and not touch it in your React component -- then the second argument should probably be `["new title"]` rather than `[]`, so that React knows to re-execute this hook if/when the computed title changes.
Answer: As others have mentioned, you can use document.title = 'My new title' and React Helmet to update the page title.  Both of these solutions will still render the initial 'React App' title before scripts are loaded.
If you are using create-react-app the initial document title is set in the <title> tag /public/index.html file.
You can edit this directly or use a placeholder which will be filled from environmental variables:
/.env:
REACT_APP_SITE_TITLE='My Title!'
SOME_OTHER_VARS=...

If for some reason I wanted a different title in my development environment -
/.env.development:
REACT_APP_SITE_TITLE='**DEVELOPMENT** My TITLE! **DEVELOPMENT**'
SOME_OTHER_VARS=...

/public/index.html:
<!DOCTYPE html>

         ...
         <title>%REACT_APP_SITE_TITLE%</title>
         ...

         ...

This approach also means that I can read the site title environmental variable from my application using the global process.env object, which is nice:
console.log(process.env.REACT_APP_SITE_TITLE_URL);
// My Title!

See: Adding Custom Environment Variables
Comment: I believe this is the most reasonable solution unless you want to change the title within a component
Comment: Make sure to put the .env files at the same level of your package.json file. :)
Comment: I tried this but %REACT_APP_SITE_TITLE% is displayed as title.
I have kept .env in same level as package.json and using react-scripts 3.4.1
Comment: @YuvrajPatil This is only applied at build time. If you need to inject them at runtime, https://create-react-app.dev/docs/title-and-meta-tags#generating-dynamic-meta-tags-on-the-server
Answer: Since React 16.8. you can build a custom hook to do so (similar to the solution of @Shortchange):
export function useTitle(title) {
  useEffect(() => {
    const prevTitle = document.title
    document.title = title
    return () => {
      document.title = prevTitle
    }
  })
}

this can be used in any react component, e.g.:
const MyComponent = () => {
  useTitle("New Title")
  return (

     ...

  )
}

It will update the title as soon as the component mounts and reverts it to the previous title when it unmounts.
Comment: Shouldn't this solution set the dependencies to [] so that its only ran on mount and unmount?
Comment: Correct me if I'm wrong, but this only works with Function components, and not Class components.
Comment: Best answer for modern React! The idea to reset the title is great.
Comment: Great hook, works great in function components.
as Alex already told us, it is not working in a class component, I just made a test to make sure.
Comment: This is the best solution till now. Great stuff. Keep up
Answer: import React from 'react';

function useTitle(title: string): void => {
  React.useEffect(() => {
    const prevTitle = document.title;
    document.title = title;

    return () => {
      document.title = prevTitle;
    };
  }, []);
}

function MyComponent(): JSX.Element => {
  useTitle('Title while MyComponent is mounted');

  return
My Component
;
}

This is a pretty straight forward solution, useTitle sets the document title and when the component unmounts it's reset to whatever it was previously.
Comment: This is the correct way to do it. But, it sure would be nice not to have to. The concept is reusable enough to just be on npm.
Comment: title should be in the useEffect dependency array
Answer: If you are wondering, you can set it directly inside the render function:
import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component {
    render() {
        document.title = 'wow'
        return
Hello

    }
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
)

For function component:
function App() {
    document.title = 'wow'
    return
Hello

}

But, this is a bad practice because it will block the rendering (React prioritize the rendering first).
The good practice:
Class component:
class App extends React.Component {
    // you can also use componentDidUpdate() if the title is not static
    componentDidMount(){
        document.title = "good"
    }

    render() {
        return
Hello

    }
}

Function component:
function App() {
    // for static title, pass an empty array as the second argument
    // for dynamic title, put the dynamic values inside the array
    // see: https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
    useEffect(() => {
        document.title = 'good'
    }, []);

    return
Hello

}

Comment: This is a typical error that appears in many react code bases: DON'T DO THAT ! Every render methods should be pure functions (no side effects), if you need to perform a side effect: useEffect for functional components, or component events in classes (more info: https://www.reddit.com/r/reactjs/comments/8avfej/what_does_side_effects_mean_in_react/dx1xo1l)
Comment: +1 to Elias' comment. Even if you have the right way listed, this answer might cause people to put it in the `render` func.
Answer: you should set document title in the life cycle of 'componentWillMount':
componentWillMount() {
    document.title = 'your title name'
  },

update for hooks:
useEffect(() => {
    document.title = 'current Page Title';
  }, []);

Comment: componentWillMount() is deprecated in latest react version 16
Comment: In this case, as in most of time cases, when you have to remove deprecated componentWillMount, move your code to componentDidMount
Answer: React Portals can let you render to elements outside the root React node (such at <title>), as if they were actual React nodes. So now you can set the title cleanly and without any additional dependencies:
Here's an example:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class Title extends Component {
    constructor(props) {
        super(props);
        this.titleEl = document.getElementsByTagName("title")[0];
    }

    render() {
        let fullTitle;
        if(this.props.pageTitle) {
            fullTitle = this.props.pageTitle + " - " + this.props.siteTitle;
        } else {
            fullTitle = this.props.siteTitle;
        }

        return ReactDOM.createPortal(
            fullTitle || "",
            this.titleEl
        );
    }
}
Title.defaultProps = {
    pageTitle: null,
    siteTitle: "Your Site Name Here",
};

export default Title;

Just put the component in the page and set pageTitle:
<Title pageTitle="Dashboard" />
<Title pageTitle={item.name} />

Comment: I loved this solution until I realized that it merely appends `fullTitle` to the content already  found in index.html's `Default Title`.
Comment: Wow, looks so promising, React Helmet and document.title both work, but this is awesome :) Thanks
Comment: Just remove default title in your module (not in `constructor`!)

```

import React from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';

const titleNode = document.getElementsByTagName("title")[0];
titleNode.innerText = '';

export default class Title extends React.PureComponent {
  static propTypes = {
    children: PropTypes.node,
  };
  constructor(props) {
    super(props);
    this.el = titleNode;
  }
  render() {
    return ReactDOM.createPortal(
        this.props.children,
        this.el,
    );
  }
}

```
Answer: Helmet is really a great way of doing it, but for apps that only need to change the title, this is what I use:
(modern way React solution - using Hooks)

Create change page title component

import React, { useEffect } from "react";

const ChangePageTitle = ({ pageTitle }) => {
  useEffect(() => {
    const prevTitle = document.title;
    document.title = pageTitle;
    return () => {
      document.title = prevTitle;
    };
  });

  return <></>;
};

export default ChangePageTitle;

Use the component

import ChangePageTitle from "../{yourLocation}/ChangePageTitle";

...

return (
    <>
      <ChangePageTitle pageTitle="theTitleYouWant" />
      ...
    </>
  );

...

Answer: For React v18+, custom hooks will be the simplest approach.
Step 1: Create a hook. (hooks/useDocumentTitle.js)
import { useEffect } from "react";
export const useDocumentTitle = (title) => {

    useEffect(() => {
        document.title = `${title} - WebsiteName`;
    }, [title]);

    return null;
}

Step 2: Call the hook on every page with a custom title according to that page. (pages/HomePage.js)
import { useDocumentTitle } from "../hooks/useDocumentTitle";

const HomePage = () => {
    useDocumentTitle("Website Title For Home Page");

    return (
        <>

Example Text

        </>
    );
}

export { HomePage };

Works well for dynamic pages as well, just pass the product title or whatever content you want to display.
Answer: You have multiple options for this problem I would highly recommend to either use React Helmet or create a hook using useEffect. Instead of writing your own hook, you could also use the one from react-use:
React Helmet
import React from 'react';
import { Helmet } from 'react-helmet';

const MyComponent => () => (
  <Helmet>
    <title>My Title</title>
  </Helmet>
)

react-use
import React from 'react';
import { useTitle } from 'react-use';

const MyComponent = () => {
  useTitle('My Title');

  return null;
}

Answer: Simply you can create a function in a js file and export it for usages in components
like below:
export default function setTitle(title) {
  if (typeof title !== "string") {
     throw new Error("Title should be an string");
  }
  document.title = title;
}

and use it in any component like this:
import React, { Component } from 'react';
import setTitle from './setTitle.js' // no need to js extension at the end

class App extends Component {
  componentDidMount() {
    setTitle("i am a new title");
  }

  render() {
    return (

        see the title

    );
  }
}

export default App

Answer: You can use the following below with document.title = 'Home Page'
import React from 'react'
import { Component } from 'react-dom'

class App extends Component{
  componentDidMount(){
    document.title = "Home Page"
  }

  render(){
    return(

 Title is now equal to Home Page

    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

or You can use this npm package npm i react-document-title
import React from 'react'
import { Component } from 'react-dom'
import DocumentTitle from 'react-document-title';

class App extends Component{

  render(){
    return(
      <DocumentTitle title='Home'>

Home, sweet home.

      </DocumentTitle>
    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

Happy Coding!!!
Answer: I haven't tested this too thoroughly, but this seems to work. Written in TypeScript.
interface Props {
    children: string|number|Array<string|number>,
}

export default class DocumentTitle extends React.Component<Props> {

    private oldTitle: string = document.title;

    componentWillUnmount(): void {
        document.title = this.oldTitle;
    }

    render() {
        document.title = Array.isArray(this.props.children) ? this.props.children.join('') : this.props.children;
        return null;
    }
}

Usage:
export default class App extends React.Component<Props, State> {

    render() {
        return <>
            <DocumentTitle>{this.state.files.length} Gallery</DocumentTitle>
            <Container>
                Lorem ipsum
            </Container>
        </>
    }
}

Not sure why others are keen on putting their entire app inside their <Title> component, that seems weird to me.
By updating the document.title inside render() it'll refresh/stay up to date if you want a dynamic title. It should revert the title when unmounted too. Portals are cute, but seem unnecessary; we don't really need to manipulate any DOM nodes here.
Answer: You can use ReactDOM and altering <title> tag
ReactDOM.render(
   "New Title",
   document.getElementsByTagName("title")[0]
);

Comment: -1 because a separate `ReactDOM.render` cannot interact with any existing state. So this approach have no benefit over `document.title = ...`, unless you only use React to maintain title, which is ... very unusual. In a normal react app, something like `React.createPortal` is needed. Or just simply set `document.title`.
Answer: the easiest way is to use react-document-configuration
npm install react-document-configuration --save
Example:
import React from "react";
import Head from "react-document-configuration";

export default function Application() {
    return (

Hello Developers!

    );
};```

Answer: you can create TabTittleHelper.js and
export const TabTittle = (newTitle) => {
document.title=newTitle;
return document.title;
};

later you writed all screens
TabTittle('tittleName');

Answer: I am not sure if it is a good practice or not, but In index.js headers I put:
document.title="Page Title";

Answer: I use a simple hook:
export default function usePageTitle(title: string) {
    document.title = `${title} - effOne Hub`;
}

That I then call from each page renderer
export default function About() {
    usePageTitle('About');

    ...

    return <>Page Content</>
}

Comment: You don't cleanup the title and "set it back" when component is cleared, not a hook per-se :)
Answer: const [name, setName] = useState("Jan");
  useEffect(() =>
    {document.title =   "Celebrate " +  {name}.name  ;}
  );

Comment: It is easier to accept an answer like this if you explain your code example and put it into the context of the question.
Comment: `useEffect`  was also suggested in [this answer](https://stackoverflow.com/a/56385973/3744182) by [Jordan Daniels](https://stackoverflow.com/users/9009196/jordan-daniels) among others.  Might you please [edit] your answer to explain a little how your answer differs from theirs?
Answer: If you're a beginner you can just save yourself from all that by going to the public folder of your react project folder and edit the title in "index.html" and put yours. Don't forget to save so it will reflect.


How to Loop Through List and Print Each Item But Include Previous with Each Line

Question: So I have this code right now but the problem is it will loop through the entire list and print is as one.
Here is the data I am reading.
[('Bob', '1\n2\n3'), ('Joe', '4\n5\n6')]
formatted_conversations = []
for conv in conversations:
    speaker, message = conv
    if len(formatted_conversations) == 0 or formatted_conversations[-1].split(" : ")[0] != speaker:
        formatted_conversations.append(speaker + " : " + message)
    else:
        formatted_conversations[-1] += "\n" + message
conversations=[]
for c in formatted_conversations:
    conversations.append(c.split(" : "))

So right now what happens is it automatically prints Bob 1,2,3 as one.
But I need it to print like this
Bob: 1
Bob: 1
2
Bob: 1
2
3
Joe:4
Joe:4
5
Joe: 4
5
6

So essentially it prints as 3 vs 1 and it adds the previous list each time and switches when it sees the new person with the :
Comment: Change `\n` to space when concatenating to the previous item?
Comment: that prints as Bob 1 2 3 all on one line. I need them to be separate but include the previous message
Comment: If you print each list element on its own line you'll get that.
Comment: what I am trying to get is it to print Bob 1 first, then Bob 1 and 2, then Bob 1, 2 and 3 but all on a new line
Answer: To include the old one append the last row
formatted_conversations.append(formatted_conversations[-1])

The new code:
formatted_conversations = []
for conv in conversations:
    speaker, message = conv
    if len(formatted_conversations) == 0 or formatted_conversations[-1].split(" : ")[0] != speaker:
        formatted_conversations.append(speaker + " : " + message)
    else:
        formatted_conversations.append(formatted_conversations[-1])
        formatted_conversations[-1] += "\n" + message
conversations=[]
for c in formatted_conversations:
    c = c.split(" : ")
    print(c[0] , ":" , c[1])
    conversations.append(c[0] + ":" + c[1])

output:
Bob : 1
Bob : 1
2
Bob : 1
2
3
Joe : 4
Joe : 4
5
Joe : 4
5
6

Comment: that just prints it all on the same line as one. So it just says bob 1 2 3
Comment: now it prints each one on a line and prints the message on separate lines
Comment: what did you even change in my code? it looks the exact same
Comment: The last for loop is changed to print the data (and save it in conversations in the right way, also this line was added formatted_conversations.append(formatted_conversations[-1])
Answer: I dont know your data format, I would do it something like this:
data = [('Bob', '1\n2\n3'), ('Joe', '1\n2\n3')]

def print_repeated(prefix, data):
    data = data.split("\n")
    last_print = f"{prefix}: {data[0]}"
    print(last_print)
    for item in data[1:]:
        last_print += "\n" + str(item)
        print(last_print)

print_repeated(data[0][0], data[0][1])

for name, values in data:
    print_repeated(name, values)

This outputs:
Bob: 1
Bob: 1
2
Bob: 1
2
3
Joe: 4
Joe: 4
5
Joe: 4
5
6

Comment: so it's reading off a script written in google docs. For Bob 1 2 , the number 2 must be on a new line, so not side by side like in your output.
Comment: @jeeeez I modified it to follow your expected output
Comment: @jheeez Are you trying to print the string, or join the string into one?
Comment: it's reading a google word doc off a script and taking a screenshot per line. So it sc Bob 1, then Bob 1 \n/ 2, then checks for the next character Joe: 1 , Joe 1 and 2 etc. but my current code straight up takes the screenshot of Bob: 1 2 3 in one without taking sc of Bob 1 first, then bob 1 2
Comment: here's my updated data that it's reading `[('Bob', '1\n2\n3'), ('Joe', '1\n2\n3')]
`
Comment: @jeeeez And you want to print that data to the console in the format described in the question?
Comment: the data I just commented needs to print just like you show in your output in your answer.
Answer: After concatenating the message to the string, append formatted_conversations[-1] to the result list so you get all the incremental conversations.
conversations = [('Bob', '1\n2\n3'), ('Joe', '4\n5\n6')]
formatted_conversations = []
for speaker, messages in conversations:
    output = speaker + ': ' + messages[0]
    formatted_conversations.append(output)
    for message in messages.split('\n')[1:]:
        output += '\n' + message
        formatted_conversations.append(output)

print(*formatted_conversations, sep="\n")

Output is:
Bob : 1
Bob : 1
2
Bob : 1
2
3
Joe : 4
Joe : 4
5
Joe : 4
5
6

Comment: I updated my post to show the layout I need. Tom's answer output example is showing how I need the result to be.
Comment: OK, then go back to use `\n` as the separator. The algorithm is the same.
Comment: the data should be [bob 1] [bob 1, 2] [bob 1, 2 3] like that
Comment: I ran my script and it produces the exact output you show in the question.
Comment: Please edit the question and show the input and desired output with proper formatting. Use a code block to format it.
Comment: the data looks like this `[('Bob', '1\n2\n3'), ('Joe', '1\n2\n3')]
`
Comment: I've updated the answer to reflect that input.


Publicação de Projeto ASP.NET MVC

Question: Bom dia senhores, trabalho com desenvolvimento de sistemas, mas até então nunca precisei fazer uma publicação em internet de uma aplicação minha, pois sempre trabalhei com projetos prontos, qual a melhor forma e onde fazer um publicação do meu projeto onde eu possa acessar ele pelo www.meusite.com.br? Poderiam me detalhar?
Comment: recomendo que você primeiro faça uma pesquisa sobre o assunto, faça as suas tentativas e depois retorne aqui com algum problema específico... caso ocorra algum...
Comment: Depende muito dos recursos e permissões disponíveis na hospedagem e a versão do asp.net que está utilizando.
Comment: @LeandroAngelo, gostaria apenas de publicas em uma hospedagem gratuita apenas para testes da aplicação, pois por exemplo, gostaria de testar meu app no celular, por isso o publish do meu projeto asp.net mvc
Comment: Mesmo dentro do asp.net existe muitas formas diferentes de fazer isso como publicação direta através do VS par ao Azure, através do GIT, através de um FTP, criando uma pasta local e copiando manualmente, etc. Depende, do projeto e do ambiente do servidor. Conforme comentado pelo pessoal é preciso que gere um problema mais específico para que possam ajuda-lo.  :)
Comment: Se é só pra testar, vc pode habilitar o IIS no seu computador, e acessar... Pode até criar um domínio dinâmico (no-ip, dyndns) e torná-lo público... Acho que é mais viável aprender a publicar no próprio computador, depois pública em uma hospedagem... E serviços gratuitos pra hospedar ASP.net acho difícil... Normalmente só demonstração
Answer: Creio que a principio você poderia usar o AZURE para publicar sua aplicação Web.
Crie uma conta gratuita no AZURE e crie sua aplicação web lá.
Após isso você pode fazer a publicação da sua aplicação Web já setando no publish do projeto para que seja hospedado na sua conta do azure.
Este link pode de ajudar a entender melhor:
https://docs.microsoft.com/pt-br/aspnet/core/tutorials/publish-to-azure-webapp-using-vs?view=aspnetcore-2.1
Comment: Consegui realizar o que eu queria pelo Azure, criei uma conta grátis e realizei o publish diretamente para o azure! eles me liberam uma URL onde conecto minha aplicação, consegui perfeitamente realizar o teste em meu celular.
Comment: Que bom que tenha conseguido progredir com o seu objetivo. :)
Answer: Olá,
Bom primeiramente você tem que ter um provedor para hospedar seu projeto e que vai redirecionar para seu dominio "www.meusite.com.br".
Se você não optar o Azure e contratar qualquer outro provedor de hospedagem, a maneira mais fácil é você dar um "publish" da sua aplicação aspnet para um diretorio windows, ali ele vai colocar seus arquivos pronto para publicação.
Para publicar, você precisa ter um endereço de FTP que o seu provedor contratado irá fornecer, e com este acesso, através de um programa de FTP, basta conectar e enviar seus arquivos obtido pelo "Publish" para o diretório do seu provedor.
Resumidamente este é o caminho mais simples. Claro que se foi desenvolver para hospedar no azure, o caminho é diferente, segue no citado na resposta acima, mas o Visual Studio conecta automaticamente e publica sua aplicação lá, basta conectar na sua conta pelo Visual Studio, isso é bem simples, mas ao dar o publish indicar que será no Azure.
Claro que ao contratar a hospedagem, deve ser configurado para asp.net, e informar o framework que esta sua aplicação, então primeiro verifique o framework que seu provedor disponibiliza e de build da sua aplicação para este framework.

Publicação de Projeto ASP.NET MVC


Selector for an element alone in a row?

Question: We have flex container with 2 child elements.
When we resize window, and one of flex item wraps, we have each element on its own row.
Is it any selector like :when-alone-in-row?
.flex-parent {flex-flow: row wrap}
    .flex-child
    .flex-child

Comment: No, there is not.
Comment: It depends on what is is you are trying to acheive when there is only one item on the row. There are techniques that *might* help here but at the moment this looks like an XY Problem.
Comment: You might be able to get something similar to what you're asking with CSS media queries
Comment: *Show* your HTML, don't describe it to us; language is far too ambiguous in most cases to adequately describe structure. Please see: the "*[MCVE]*" (and "*[ask]*") guidelines.
Comment: @DavidThomas we are in css/css3/flexbox section, I think it's clear to understand that .flex-parent - class of item with proper css attr, and .flex-child - it's child elements of flex-parent.
Answer: If it always collapses at the same screen size you could use media queries to adjust the styles when they are on their own row.
If not, it might be worth also using media queries for the collapsing, so you can better control your rows / columns.
Comment: trying to make responsive content-independence code, queries good only for device-dependency code
Comment: Ah, okay. Understood. Sorry, I couldn't help more.
Answer: No, there is no selector similar to :when-alone-in-row.
However, when you want to select the first and last elements from a group of siblings (which would be the case here since you're dealing with only two flex items), you can use the :first-child and :last-child pseudo classes.
Of course, the styles applied by these selectors will work even when both items are on the same line, unless they're applied in a media query.
Comment: When flex-wrap works - it knows width of items and knows when do wrap, and status of each-element wrap position. I want to use that knowledge :)

Using :first-child/:last-child/:nth-child would be "backend" solution as queries (they don't know how much content in element) without knowing of client responsive layout, it's "hardcode", for now I want maximum of responsive code.
Comment: Well then you may have to use JavaScript.
Comment: I prefer to use clear CSS... flex again goes trash like display:table and other "good" solutions :(

Selector for an element alone in a row?