Show content as per Taxonomy Term

Question: I am new to drupal and using drupal 7. I have created some taxonomies and using it as menus using Taxonomy Menu module. The Taxonomies are being shown as menus.
Now I want to change content of the page as per term of the taxonomy. I have searched the problem but found different modules doing this task like Taxonomy Display, Taxonomy Menu Block. But I don't want  to use any of the module and want to do it manually so that I can understand the inner working of Drupal themes.
Any help will be much appreciated.
Comment: Do you want to filter contents on node page on basis of term associated with current node?
Comment: @PushpinderRana Yup I want to change content of my main page on basis of term associated.
Comment: Using VIEWS you can achieve it. Associate a node with the term and create a new VIEW and add a relationship to get all the details based on the relationship.
Answer: You can do this by Views:

Create view of block type (admin/structure/views)
Add fields want to display on term page.
Go to "Contextual filters" settings under "Advanced" tab.
Add the filters: "Content: Has taxonomy term ID (with depth)" and "Content: Has taxonomy term ID depth modifier". You can configure this on this filter: → When the filter value is NOT in the URL: → Provide default value → Type: Taxonomy Term ID from URL → under that, check the box "Load default filter from node page, that's good for related taxonomy blocks." → now check the boxes of the taxonomies you want involved here.
Now you need to add the second filter in order to exclude the current node from the list. Click [+] button of the contextual filters section.
Select Content: Nid.
Chosse the option "when argument is not present" to "Provide default argument".
Choose the "Default argument type" to "Content ID from URL".
Go to "MORE" , and check the "Exclude" box.
Move the filter "Content: Nid" to the top position.
Add a block to your view and embed the block on your node pages.
Save your view

Show content as per Taxonomy Term


How to the set permission of content types for a specific user role?

Question: How to set the permission of content types for a specific user role?
Answer: If you want to set permission from admin panel then goto /admin/people/permission after find your content (view/edit) and set the user role (anonymous/ Authenticated/ Administration) permission. but if you want to set it problematically then visit https://docs.drupalcommerce.org/commerce2/developer-guide/products/theme-product  (Drupal 7 - A Simple Content Type: Permissions & Access)
Answer: For D7 you can use the Content Access module.
As an alternative (which I recommend), for D7 or D8, you can use the Group module.


Isoperimetric inequality with Green-capacitiy

Question: I was wondering what the progress is, in isoperimetric inequalities for Capacities, specifically with the Green kernel ( optional: and Riesz kernel with $a\in (2,\infty)$). Or if it is solved already, please feel free to post the answer or reference.
By Green-capacity I mean $$Cap_{G}(A)=\inf \{\int\int G(x,y)\mu(dx)\mu(dy):\mu~~\text{ a probability measure on A}\}]^{-1}$$ and $$G(x,y)=\frac{\Gamma(\frac{d}{2}-1)}{2\pi^{\frac{d}{2}}}|x-y|^{d-2}$$ for $A\subset \mathbb{R}^{d}$,with $d\geq 3$.
By isoperimetric I mean, $Cap_{G}(A)\geq Cap_{G}(A^{*})$ where $A^{*}$ is a ball with $vol(A^{*})=vol(A)$.
Thank you
Answer: Your   terminology is a bit confusing: Green capacity usually refers specifically to using Green's function for a proper subdomain of $\mathbb R^n$.
The case $\alpha=2$ (sometimes called the Newtonian capacity) is classical. What helps in this case is that the potential is a harmonic function on the complement of the support of the measure. This allows one to express capacity in terms of the Dirichlet integral $ \int |\nabla u|^2 $ of the potential over the complement of $A$. The Dirichlet integral is easier to rearrange than equilibrium measures. Basically, one takes the equilibrium potential for $A$, performs symmetric decreasing rearrangement (which does not increase the Dirichlet energy), observes that the rearranged function, though not harmonic, satisfies the appropriate boundary condition for $A^*$, and therefore the harmonic solution of the Dirichlet problem will have even smaller integral.
The above sketch  has some holes. One has to cut off the infinity by a large sphere, do the above, and let the radius of the sphere tend to infinity.
For rearrangement of Dirichlet integral, see G. Pólya, G. Szegö, "Isoperimetric inequalities in mathematical physics". For other things mentioned above, see Capacity article of EOM and its references.

To my knowledge, $\alpha>2$ remains open. I don't know of any papers on the subject published since An Isoperimetric Inequality for Riesz Capacities by Méndez-Hernández.


Intenção é fazer com que esses dois títulos  sejam editáveis, mas infelizmente estou conseguindo aplicar apenas no primeiro

Question:

window.onload = function() {
  function editTitle() {
    var choices = []
    var title = document.getElementsByTagName('h4')[0];

    var span = title.firstChild;

    span.onmouseover = function() {
      this.title = 'Clique para editar o texto';
      this.style.background = '#f5f5f5';
    }
    span.onclick = function() {
      var textoAtual = this.firstChild.nodeValue;
      var texto = this.firstChild.nodeValue;
      var input = '<input ="text" name="1" value="' + textoAtual + '">';
      this.innerHTML = input;
      var field = this.firstChild;
      this.onclick = null;
      this.onmouseover = null;

      field.select();
      field.onblur = function() {
        this.parentNode.innerHTML = this.value;
        editTitle();
      }
    }
  }
  editTitle();
}
h1 {
  font: normal 2.4em/1.6 georgia, "sansation", "bitstream vera serif", times, serif;
  color: #900;
}

* {
  margin: 0;
  padding: 0;
}

.informativo h1 {
  top: auto;
  float: right 1000px;
  font-weight: bold;
  font-size: 20px;
  color: black;
  font-family: arial;
  padding: 1px;
}

.informativo img {
  float: left;
  height: 156px;
  width: 220px;
}

.informativo p {
  font-size: 15px;
  font-family: arial;
  padding-bottom: 8px;
}

.informativo p2 {
  font-size: 10px;
  font-family: arial;
}

.informativo h2 {
  font-family: arial;
  font-size: 15px;
  padding: 5px;
}

.informativo h3 {
  font-family: arial;
  font-size: 20px;
}

.informativo h4 {
  font-family: arial;
  font-size: 15px;
  padding-bottom: 12px;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <title>Informativo de vencimento</title>

Bom dia,

      Prezado cliente; Informamos que seu próximo boleto vencera dia:

Altere a data aqui

Detalhe do titulo abaixo.

Altere o título aqui

    <p2>Caso não tenha recebido o boleto , entrar  em contato  por este mesmo email para  que  possamos envia-lo em tempo hábil para pagamento .

         </p2>

Comment: Por favor edita a tua pergunta com mais informação, colar o código apenas sem dizer onde precisas de ajuda, não vais receber muita ajuda.
Comment: `var title = document.getElementsByTagName('h4')[0]` não seria aqui o problema?
Answer: Acrescentei um for para iterar todos as tags

window.onload = function() {
  function editTitle() {
    var choices = []
    var titles = document.getElementsByTagName('h4');

    for (var i = 0; i < titles.length; i++) {
      var title = titles[i]

      var span = title.firstChild;

      span.onmouseover = function() {
        this.title = 'Clique para editar o texto';
        this.style.background = '#f5f5f5';
      }
      span.onclick = function() {
        var textoAtual = this.firstChild.nodeValue;
        var texto = this.firstChild.nodeValue;
        var input = '<input ="text" name="1" value="' + textoAtual + '">';
        this.innerHTML = input;
        var field = this.firstChild;
        this.onclick = null;
        this.onmouseover = null;

        field.select();
        field.onblur = function() {
          this.parentNode.innerHTML = this.value;
          editTitle();
        }
      }
    }
  }
  editTitle();
}
h1 {
  font: normal 2.4em/1.6 georgia, "sansation", "bitstream vera serif", times, serif;
  color: #900;
}

* {
  margin: 0;
  padding: 0;
}

.informativo h1 {
  top: auto;
  float: right 1000px;
  font-weight: bold;
  font-size: 20px;
  color: black;
  font-family: arial;
  padding: 1px;
}

.informativo img {
  float: left;
  height: 156px;
  width: 220px;
}

.informativo p {
  font-size: 15px;
  font-family: arial;
  padding-bottom: 8px;
}

.informativo p2 {
  font-size: 10px;
  font-family: arial;
}

.informativo h2 {
  font-family: arial;
  font-size: 15px;
  padding: 5px;
}

.informativo h3 {
  font-family: arial;
  font-size: 20px;
}

.informativo h4 {
  font-family: arial;
  font-size: 15px;
  padding-bottom: 12px;
}

Bom dia,

    Prezado cliente; Informamos que seu próximo boleto vencera dia:

Altere a data aqui

Detalhe do titulo abaixo.

Altere o título aqui

  <p2>Caso não tenha recebido o boleto , entrar  em contato  por este mesmo email para  que  possamos envia-lo em tempo hábil para pagamento .

     </p2>

Comment: Muito Obrigado Mesmo cara! mandou muito xD Agradeço de coração
Comment: Por nada, se a resposta solucionou sua questão, marque ele como como resolvida, obrigado.
Answer: Só para deixar registrado que o Html5 possui o atributo contenteditable que tornam elementos de texto editáveis:

h4 {
  outline: none;
}

Bom dia,

    Prezado cliente; Informamos que seu próximo boleto vencera dia:

Altere a data aqui

Detalhe do titulo abaixo.

Altere o título aqui

  <p2>Caso não tenha recebido o boleto , entrar  em contato  por este mesmo email para  que  possamos envia-lo em tempo hábil para pagamento .</p2>


Apache ReWrite Rule Questions

Question: A few questions:

I have several domains hosted on the same server and I created some ReWrite rules that for specific {REQUEST_URI} gets redirected elsewhere. I copied these rules to each and every Virtual Host. Can I just put these rules in a file and do something like:
<VirtualHost>
ServerAdmin email@example.com
DocumentRoot /var/www/html/<directory>
ServerName <domain>
ServerAlias www.<domain>
ErrorLog logs/www_<domain>-error_log
CustomLog logs/www_<domain>-access_log common
RewriteEngine on
Include rewrite_rules.conf

How can one create a rule that says if requests come in on specific domains to re-direct to a generic 'For Sale' page. Example, Same they type in www.Allertia.com and I want them to be directed to a For Sale Page.
Answer:
Yes, you can do that. The Include directive acts as if the contents of the named file were literally included.
Assuming you want the same "for sale" page to show up for all of the domains:
<VirtualHost *:80>
    ServerName forsale1.com
    ServerAlias www.forsale1.com
    ServerAlias forsale2.com
    ServerAlias www.forsale2.com
    ...

    RewriteEngine on
    RewriteRule .* /var/www/html/path/to/forsale.html
</VirtualHost>

This will not change the URL that appears in the browser. If you want to perform an HTTP redirect so that the URL in the browser does change, you could add [R] after the rewrite rule. (Or you could use Redirect or RedirectMatch which might be a little quicker, if your server is under high load)
Answer: You want something that matches against the incoming HTTP Host: header, so a rule such as this will work:
RewriteCond %{http_host} !^www.allertia.com
RewriteRule /  http://example.com/for-sale.html [R,L]

The issue you'll find is that if you say "Rewrite all requests for http://www.alertia.com to http://alertia.com/for-sale.html" you'll get a redirection loop.  So redirecting to an un-related domain is simplest.
However if you wish you can create a rule which says "For all requests not equal to /for-sale.html, do the rewrite":
RewriteCond %{http_host} www.allertia.com
RewriteRule !/for-sale.html$  http://www.allertia.com/for-sale.html [R,L]

Obviously you'll need to update the path for the "for sale" page.  You'll probably also want to include the rules twice:

http://allertia.com/
http://www.allertia.com/
Comment: @Steve Kemp - Do I need to create a Virtual Host for Allertia to achieve this or is there a generic way to have ReWrite rules evaluated and acted upon at a non Virtual Host level? I have a number of domains for sale and if I can avoid creating a Virtual Host for each one that would be best!
Comment: I was working on the assumption these rules were global - so you didn't need  to create a virtual host for them.
Comment: @Steve - Oh, sorry, where do global rules go in httpd.conf?
Comment: Add the rules I suggested to your "rewrite_rules.conf" file - the one you demonstrate using already in your config.
Comment: @Steve oh, #1 has nothing to do with #2 above. They are different questions. I don't understand where to put/how to use ReWrite rules without creating a virtual host for each domain. Can you explain?
Comment: Just have the rule in the block governing the directory (e.g. www or htdocs) and not in a virtual host and it will be global
Comment: @Devin - When I put the rules in my `` like `#RewriteEngine on
    #Rewritebase /
    # For-Sale - Domains
    #RewriteCond %{http_host} !^www.allertia.com [NC,OR]
    #RewriteCond %{http_host} !^allertia.com [NC,OR]
    #RewriteCond %{http_host} !^www.iph0wnd.com [NC,OR]
    #RewriteCond %{http_host} !^iph0wnd.com [NC,OR]
    #RewriteCond %{http_host} !^www.paymetowait.com [NC,OR]
    #RewriteCond %{http_host} !^paymetowait.com [NC]
    #RewriteRule /  http://6colors.net/for-sale/index.html [R,L]` N
Comment: @Devin -Nothing works, I think something circular might be going on. Or at least Safari thinks so
Comment: @Devin - the rules are not commented out, but they were when I copied this into the comment and the RewriteRule is: `RewriteRule / http://6colors.net/for_sale/index.html [R,L]`
Comment: So you uncommented it and it works?
Comment: Apache ignores global rules if any virtual hosts are defined.
Comment: `RewriteOptions Inherit` will allow you to use global rules with virtual hosts. http://httpd.apache.org/docs/current/mod/mod_rewrite.html#vhosts

Apache ReWrite Rule Questions


Straightedge-Only for Perpendicularity

Question: Given a triangle ABC and a midpoint M (of the line AB), is it possible to check whether
the line CM is perpendicular to AB with a straightedge only?  By this, I mean that points
can be added imprecisely into any open region, or along any open line segment, and the
straightedge can be used to draw the unique connecting lines (but no distances can be
measured) with a programmable procedure.
I was hoping that the colinearity of some generated points in the end could check this,
but now suspect that this is impossible.
This differs a little from "Steiner construction" becuase the "final constructed point"
is given, so only confirmation is needed.  In the problem here, I don't have the circle
for the Poncelet–Steiner theorem.
Answer: Whatever points and lines you draw, a shear transformation parallel
to $AB$ will preserve the collinearity of all collinear points,
and will preserve the distances $AM$ and $MB$,
but it will not preserve the angle of the line $CM$ with the line $AB$.
So whatever construction you perform with your straightedge,
there is another (sheared) construction indistinguishable from the first one
(as far as anything you can tell with a straightedge)
in which the line corresponding to $CM$ in the new construction is
not perpendicular to the line corresponding to $AB$.

Straightedge-Only for Perpendicularity


Second Order Nonlinear Differential Equation

Question: Could you help me solve this differential equation?
$$yy''=2(y')^2$$
Comment: Step 1: Post the problem, not a link to the problem.  Step 2: Post a useful title.  Step 3: Post your own efforts toward solving the problem.  Step 4: Profit.
Comment: divide through by $y'y$
Comment: I think the left side is $yy''$, not $yy'$.
Comment: Yeah, my typo. Tx
Comment: Not a duplicate of https://math.stackexchange.com/questions/2304269/solve-the-following-equation-y-yy3#2304284
Answer: Hint: note that
$$0 = 2(y')^2-yy'' = y^3\left( \frac 1 y \right)''$$
Comment: ok, but how might op see this on his or her own?
Answer: Hint...use $y''=y'\frac{dy'}{dy}$ so that you have either $y'=0$ or a separable variable differential equation...
Answer: Hint. Rewrite equation as: $$\tfrac{y{y}''-({y}')^2}{y^2} = \tfrac{({y}')^2}{y^2}$$
Then if we substitute $\omega (x)=\tfrac{{y}'}{y}$ our equation will be in the form: $${\omega}'(x)=\omega ^2(x)$$.
Answer: $yy'' = 2(y')^2$
divide through by $yy'$
$\frac {y''}{y'} = 2\frac {y'}{y}\\
\ln y' = 2\ln y + C\\
y' = Cy^2$
Can you solve that diff eq?
Continued....
$\frac {C y'}{y^2} = 1$
Remeber that C is arbitrary, so there is no need to keep track of its sigh, and I can replace $C$ with $\frac 1C$ if it suits me.
$\frac {C }{y} = t + D\\
 y = \frac {C}{t + D}$
Shall we check?  (Now we will need to keep track of signs)
$y' = -\frac {C}{(t + D)^2}\\
y'' = 2\frac {C}{(t + D)^3}\\
yy'' = 2\frac {C^2}{(t + D)^3} = 2(y')^2$


what is the most easy to read Algebraic Geometry book?

Question: All:
what is the most easy to read (most accessible) Algebraic Geometry book ?
(If possible, I am looking for an introduction book, maybe for undergraduate, and maybe similar to A Friendly Introduction to Number Theory).
Answer: I believe it's the "Introduction to Algebraic Curves" of William Fulton. He let you download the book from his site. Here is the link:
http://www.math.lsa.umich.edu/~wfulton/CurveBook.pdf
Answer: I am fans of both
Hartshorne - Algebraic Geometry  which is quite a classical text
For a more friendly introduction try
Eisenbug & Harris - The Geometry of Schemes.
Comment: Not only is Hartshorne not "the easier book about the subject": it is a horrendous book to try to begin with into algebraic geometry. Also the Eisenbud-Harris book: is way into graduate level, and it definetely cannot be regarded as an "introduction".
Comment: Hartshorne is the best reference but it isn't the easier book about the subject.


Visual issue with css3 animation and jquery (hover flip card)

Question: Read me: --> Im having troubles when I hover the flip card, if you move the cursor while hovering inside the div is triggering continuously and it makes an annoying effect, so here is what I need:
1) I want to hover the flip card and dont trigger animation again even you move the cursor inside while hovering.
2) I also need center p tag vertically in the flip card, margin-top is working and margin:auto is not working, I put the 2 examples in the snippet, check next classes:
.card .front p {
    margin-top: 100px;
}
.card .back p {
    margin: auto;
}

So why is not working margin:auto? I wont use margin-top, need the content at the center. Here is the working snippet code:

Updated question:
  I also need achieve the next: one time you hover the flip card the animation must be completed, even you hover out the div, and then flip to the original position again, I tried next but it doesnt work:

$(".container").hover(function(){
            $(this).find(".card").toggleClass('flipped')
        }, function(){
            setTimeout(function(){
                $(this).find(".card").toggleClass('flipped')
            }, 1000);
    });

$(document).ready(function () {
    $(".card").hover(function(){
            $(this).toggleClass('flipped')
        }, function(){
            $(this).toggleClass('flipped')
    });
})
.container {
    width: 200px;
    height: 260px;
    position: relative;
    margin: 0 auto 40px;
    -webkit-perspective: 800px;
    -moz-perspective: 800px;
    -o-perspective: 800px;
    perspective: 800px;
    display: inline-block;
}
#main{
    border: 1px solid black;
}
button{
    width: 30%;
    height: 10%;
    margin-top: 100px;
    cursor: default;
}

.card {
    width: 100%;
    height: 100%;
    position: absolute;
    -webkit-transition: -webkit-transform 1s;
    -moz-transition: -moz-transform 1s;
    -o-transition: -o-transform 1s;
    transition: transform 1s;
    -webkit-transform-style: preserve-3d;
    -moz-transform-style: preserve-3d;
    -o-transform-style: preserve-3d;
    transform-style: preserve-3d;
    -webkit-transform-origin: right center;
    -moz-transform-origin: right center;
    -o-transform-origin: right center;
    transform-origin: right center;
}

.card.flipped {
    -webkit-transform: translateX( -100%) rotateY( -180deg);
    -moz-transform: translateX( -100%) rotateY( -180deg);
    -o-transform: translateX( -100%) rotateY( -180deg);
    transform: translateX( -100%) rotateY( -180deg);
}

.card div {
    height: 100%;
    width: 100%;
    color: white;
    text-align: center;
    font-weight: bold;
    position: absolute;
    -webkit-backface-visibility: hidden;
    -moz-backface-visibility: hidden;
    -o-backface-visibility: hidden;
    backface-visibility: hidden;
    cursor:pointer;
}

.card .front {
    background: red;
}
.card .front p {
    margin-top: 100px;
}
.card .back p {
    margin: auto;
}

.card .back {
    background: blue;
    -webkit-transform: rotateY( 180deg);
    -moz-transform: rotateY( 180deg);
    -o-transform: rotateY( 180deg);
    transform: rotateY( 180deg);
}

Test

MyBack

Answer: The problem comes from the fact that because you are transforming the element that has got the hover, the pointer may get out of the box, causing an unwanted change of state from hover to none and back again.
You could catch the hover event on the main div. To align the elements, the simplest way is to use CSS Flexbox. margin: auto will not work since it sets margin-top and margin-bottom to 0 by default.
Here are the changes I've made :
$(document).ready(function() {
  $(".container").hover(function() {
    $(".card").toggleClass('flipped')
  }, function() {
    $(".card").toggleClass('flipped')
  });
})

.card .back {
  /*no changes*/
  display: flex;
  justify-content: center;
  align-items: center;
}

.card .front {
  /*no changes*/
  display: flex;
  justify-content: center;
  align-items: center;
}

And a working example :

$(document).ready(function() {
  $(".container").hover(function() {
    $(".card").toggleClass('flipped')
  }, function() {
    $(".card").toggleClass('flipped')
  });
})
h1 {
  text-align: center;
}

.container {
  width: 200px;
  height: 260px;
  position: relative;
  margin: 0 auto 40px;
  perspective: 800px;
  display: inline-block;
}

#main {
  border: 1px solid black;
}

button {
  width: 30%;
  height: 10%;
  margin-top: 100px;
  cursor: default;
}

.card {
  width: 100%;
  height: 100%;
  position: absolute;
  transition: transform 1s;
  transform-style: preserve-3d;
  transform-origin: right center;
}

.card.flipped {
  transform: translateX( -100%) rotateY( -180deg);
}

.card div {
  height: 100%;
  width: 100%;
  color: white;
  text-align: center;
  font-weight: bold;
  position: absolute;
  backface-visibility: hidden;
  cursor: pointer;
}

.card .front {
  background: red;
  display: flex;
  justify-content: center;
  align-items: center;
}

.card .back p {
  margin: auto;
}

.card .back {
  background: blue;
  transform: rotateY( 180deg);
  display: flex;
  justify-content: center;
  align-items: center;
}

Test

MyBack

How about it ?
Comment: Thats nice about the hover, but why isnt work margin auto to center the element?
Comment: margin: auto will not work since it sets margin-top and margin-bottom to 0 by default.
Comment: Thanks for answer, last question, could you please check my updated question?
Comment: We should conitnue this discussion in chat : https://chat.stackoverflow.com/rooms/158959/room-for-visual-issue-with-css3-animation-and-jquery-hover-flip-card


How to bulk delete selected content/nodes?

Question: I want to bulk delete data and along with it I need check-box where I should able to "select all" data to delete. I tried the Delete all module, which is helpful to delete all the content, but it's all or nothing.
Sometimes I may not want to delete all the content/nodes. Therefore, I would also like to be able to select which specific content/nodes gets deleted only.
Can anyone help me on this?
Comment: It's not really clear what are you asking. What do you mean by there is no checkbox to select? I suggest updating your question with more details so others can help you better.
Answer: Using the VBO module as suggested in the prior answer is indeed the way to go, BUT ... if you add the Rules module to that also the possibilities for what you can do are virtually only limited by your own imagination. Read on for more details on that ...
Step 1: Create a Rules Component
Have a look at this example of a Rules Component (in Rules export format):
{ "rules_delete_nodes_containing_a_specific_value_in_a_text_field" : {
    "LABEL" : "Delete nodes containing a specific value in a text field",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "node" : { "label" : "Node", "type" : "node" },
      "text_field_value" : { "label" : "Text Field Value", "type" : "text" }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_free_format_text" } },
      { "data_is" : {
          "data" : [ "node:field-free-format-text" ],
          "value" : "[text-field-value:value]"
        }
      }
    ],
    "DO" : [
      { "entity_delete" : { "data" : [ "node" ] } },
      { "drupal_message" : { "message" : "Deleted node with id \u0022[node:nid]\u0022 and title \u0022[node:title]\u0022 (which contained the string \u0022[text-field-value:value]\u0022 in field \u0022field_free_format_text\u0022)." } }
    ]
  }
}

Some more details to further explain the above above example:

This Rules Component will be used in the subsequent step.
In my case I have a text field with machine name field_free_format_text.

Note that I also added the Rules Condition Entity has field to make that field available for further processing in this Rules Component. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')". For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in that video.
Note that I've not added a Rules condition here about selected content types, that's possibly an extra condition you might want to add also. But if the selection list field is only used for the content types you're interested in, then the Entity has field condition should be sufficient already.
If you want, just grab (copy) the exported rule above, change all occurrences of the machine name of that field to match the machine name of your field, and then you can simply import this Rules Component in your own environment.
After you did this, you can navigate to admin/config/workflow/rules/components in your own site, and then use the hyperlink "execute" to qa-test it in your own site. After you use that link, use the button that says Switch to direct input mode. Then you'll be able to enter some Node identifier and hit the Execute mode. Depending on the node id you selected (if it has that field, and if the Rules Condition is satisfied), your node will be updated.
After you're confident your rule works perfect for all variations of your nodes, move on to the next step below.
Here is an example of the (2) Drupal messages I got when executing this Rules component for a node with ID = 48, in which I used the string "GetRidOfThisNode":

Deleted node with id "48" and title "Demo field_free_format_text replacement" (which contained the string "GetRidOfThisNode" in field "field_free_format_text").
Component rule: Delete nodes containing a specific value in a text field has been executed.

Variation of the display of that message could be that you use Rules to create a (similar) log record ...
Attention: you always get the 2nd message. But the first one only shows up if you have an actual match ... and hence the update gets performed also.
Step 2: Let VBO do the bulk of the work
This step is pretty easy ... Just create an appropriate view of all your nodes to be processed, and transform it into a Views Bulk Operations view. The clue to what you want VBO to do as an operation is ... you guessed it: Execute the Rules Component from Step 1.
If you're not familiar with how to do so, have a look at the video about Using Rules components with VBO". If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.
Of course there are multiple variations of the above approach, like processing by component type, narrowing down your Views output to only "a" specific value, etc. But that should be straight forward, and up to your own imagination.
Attention: to process many nodes at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...
Happy VBO-ing while Rules-ing!
Answer: The VBO answers are perfect and are likely what you need but my favoured approach for end users is an entity form with an entity reference field with the "check all" module and rules..
Simply because i can have other fields in the form passed to rules more easily if it's something more complicated than delete. Like moving nodes from one organic group to another for example.

Updated with more details and an example.

https://www.drupal.org/project/checkall I had to patch it a bit (can't remember which ones right now) and use form alters because it's still a bit glitchy.
https://i.stack.imgur.com/Ikwyv.png This is an entity form (with entity form block) on an admin page for an OG with multiple options that control conditional fields. Enabling "preview" in the entity form settings gives a conformation step like VBO.
The benefit is that you can give users whatever list of actions you want whereas with VBO, I think the parameter for the rules component is an autocomplete and sitewide which wasn't an option for me. The downside is that you can't have a table like VBO so you have to join fields in an entity reference view. In this example, it's the username and email together.
There are benefits to both but this was a great option for node and user management where the admin wouldn't be a part of the groups. I use this set up for OG management, OG content, bulk flagging, allowing privileged users assign other privileged users and moving / deleting regular users.
Comment: Your answer sounds "intriging" to me, can you expand it a bit about that check all module (+ add a module link on D.O)? Maybe also some types of examples?
Comment: Updated my answer with lots of detail for other users.. I'm pretty sure the screenshot tells the whole story for you.
Answer: You can bulk delete stuff using:
Views Bulk Operations (VBO)

Views Bulk Operations (VBO) This
module augments Views by allowing bulk operations to be executed on
the displayed rows. It does so by showing a checkbox in front of each
node, and adding a select box containing operations that can be
applied. Drupal Core or Rules actions can be used.

Video Tutorial
Comment: Thanks a lot for editing and also for the answer i will try with this


Proof of existance of Eulerian cycle in directed graph

Question: Claim
A directed graph has an Eulerian cycle if and only if every vertex has equal in degree and out degree, and all of its vertices with nonzero degree belong to a single strongly connected component.
I was looking for this proof in the Internet, but all i have found are the proofs for undirected graphs. I would be glad, if someone can give a link or name of the book, where i can find proof for this claim.
Comment: Check out the book *Digraphs* (2nd edition) by Bang-Jensen and Gutin: page 23, theorem 1.7.2 "Euler's theorem".
Answer: Pages 5-8 of Sascha Wolff's Lecture #1 "Round Trips" from his last-year block-course "Algorithmic Graph Theory" contain an illustrated proof both for undirected and directed case.
Comment: link is now dead :(


Division of two counted values

Question: Hi Guys I'm new to SQL I'm trying to divide the output value as explained with the code below
Tried this but it didn't work
SELECT COUNT(DATE_COMPLETE)/COUNT(SUB_SYS) AS FINAL
FROM VW_TWCOMPLETION

I'm using this code where SUB_SYS has value like A,B,C AND DATE_COMPLETE is a Date value like 11/19/2019 ,12/19/2019 , 13/19/2019
SELECT  SUB_SYS ,COUNT(SUB_SYS) AS TOTAL , COUNT(DATE_COMPLETE) AS COMPLETE
FROM VW_TWCOMPLETION
GROUP BY SUB_SYS
ORDER BY SUB_SYS

I want to Divide the output I get from the count as COMPLETE/TOTAL
How can I divide these output values?
Table Data

SUB_SYS

MG1-AS-PWER-05-0

MG1-AS-PWER-06-0

MG1-AS-SPAL-05-0

MG1-AS-SPAL-07-0

TOTAL

6

11

4

17

12

COMPLETE

0

6

0

2

1

0

FINAL I AM GETTING WITH BELOW CODE IS
0
0
0
0
0
Comment: "Tried this but it didn't work". What does that mean? Did you get an error message? Did you get the wrong result?
Comment: I got "0" instead of Multiple outputs.
Comment: Sample data is best served as [DDL](https://en.wikipedia.org/wiki/Data_definition_language) + [DML](https://en.wikipedia.org/wiki/Data_manipulation_language). Please [edit] your question to include it, your current attempt and your desired results. For more details, [read this.](https://dba.meta.stackexchange.com/questions/2976/help-me-write-this-query-in-sql)
Answer: you can try like below
   with cte as
  (
   SELECT  SUB_SYS ,COUNT(SUB_SYS) AS TOTAL , COUNT(DATE_COMPLETE) AS COMPLETE
   FROM VW_TWCOMPLETION
   GROUP BY SUB_SYS

  ) select SUB_SYS, (COMPLETE*1.0) /NULLIF(TOTAL,0) as final from cte ORDER BY SUB_SYS

Comment: Zaynul  i am getting this error "Msg 1033, Level 15, State 1, Line 7
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified."
Comment: @Mani check the updated answer or use order by in outer query not inside cte
Comment: the code is working but i am not getting any output its all 0.
btw i change it to COMPLETE/TOTAL
Comment: share your table's data in the question otherwise, no one can say you why you are not getting your expected output
Comment: hope this helps.

Division of two counted values


Returning a json object in select - causes slow down

Question: In the stored procedure, I'm using CTE table to return a data set as JSON. As the amount of data increased, I have noticed that one particular part of the stored procedure is causing the slowdown after running the execution plan.
There're 4 tables and they are linked using ID. For simplicity, I'm going to refer to them as Table1, Table2, Table3 and Table4.
Table1
(
    Id (int primary key),
    Colum1,
    Colum2,
    ---
)

Table2
(
    Id (int primary Key)
    Table1Id (foreign key) --To table 1 Id,(non-unique, non-clustered) index
    Colum1,
    Colum2,
    ---
)

Table3
(
    Id (int primary key),
    Table2Id (foreign key) -- To table 2 Id, has (non-unique, non-clustered) index
    Table4id (foreign key) -- To table 4 id, has (non-unique, non-clustered) index
    Colum1,
    Colum2,
    ---
)

Table4
(
    Id (int primary key),
    Colum1,
    Colum2,
    --
)

Table1 has roughly 55000 records and Table2 has 75000 records. I'm passing a JSON filter to the stored procedure to do some filtering and my final output gets return as a JSON object. However, not the filter nor the returning as json is causing slowdown. In my SELECT statement, I'm building an object within using subquery. That's what is causing the issue.
Here's is the query:
(
 SELECT

      Colum1,
      Colum2,
      Colum3,
      ...
      --Causes Slowness
      Object1 = (
                       SELECT t2.Id,
                              t2.Table1Id,
                              t2.Colum1,
                              t2.Colum2,
                              ...
                              -- Causes Slowness
                              Object2 = (
                                  SELECT t3.Id,
                                         t3.Table2id,
                                         t3.Table3Id,
                                         t4.Colum1 + ' ' + t4.Colum2 as newcolumn,
                                         ...
                                  FROM Table3 t3
                                  INNER JOIN Table4 t4
                                      ON t3.Table4Id = t4.Id
                                  WHERE t2.Id = t3.Table2Id
                                  ORDER BY CASE WHEN @OrderByAndOrder = 'colum1 asc' THEN u.Colum1 END ASC,
                                           CASE WHEN @OrderByAndOrder = 'colum1 desc' THEN u.Colum1 END DESC
                                  FOR JSON PATH, INCLUDE_NULL_VALUES
                                  )
                              FROM Table2 t2
                              WHERE t2.Table1Id = s.Id
                                AND
                              --Search by (;) colum1
                                (
                                        (ISJSON(@Filter) IS NULL) OR
                                        (JSON_VALUE(@Filter, '$.Colum1') = N'') OR
                                        (JSON_VALUE(@Filter, '$.Colum1') IS NULL) OR
                                        ((ISJSON(@Filter) IS NOT NULL) AND
                                            (JSON_VALUE(@Filter, '$.Colum1') <> N'') AND
                                                EXISTS( SELECT * FROM STRING_SPLIT(JSON_VALUE(@Filter, '$.Filter'), ';')
                                                        WHERE t2.[Colum1] LIKE CONCAT('%', [Value], '%')
                                                        AND [value] <> ''
                                                    )
                                            )
                                    ) )
                                ORDER BY
                                CASE WHEN @OrderByAndOrder = 'Colum1 asc' then t2.[Target] END ASC,
                                CASE WHEN @OrderByAndOrder = 'Colum1 desc' then t2.[Target] END DESC,
                                FOR JSON PATH, INCLUDE_NULL_VALUES
                          )
FROM Table1 (NOLOCK) mainTable
INNER JOIN Table2 t2
 ON mainTable.Id = t2.Table1Id
WHERE
mainTable.Id IN (SELECT Id FROM #Ids) --Could potentially join
AND
...
--same JSON filters on columns in mainTable

--Doing some more stuff with cte

Populating Object1 and Object2 within Object1 is causing significant load on this procedure. Is there anything I can do to improve the performance and keep the objects as is?
Comment: in that case, I would suggest looking into this https://www.mssqltips.com/sqlservertip/6037/sql-server-uncorrelated-and-correlated-subquery/ , which can provide a better view of why you having an issue with a correlated subquery, try switching the query for the  cross apply(inner join) or outer apply(left join) depending what you need.
Comment: I'm really not sure what you're expecting from a bounty here. It's effectively impossible for us to test, and improve your SQL when you won't provide us the full statement, or provide us with sample data. With no query plan either, there's nothing we can actually do here.
Comment: No suggestion at all?
Comment: do you have sample data? or could you post a whole proc with some data so we can play around and troubleshoot it, But your main issue is that you are running a select inside the select which is known for bad performance what you could is use OUTER APPLY
Comment: Unfortunately, I cannot post my data online nor I can put the whole proc. I do know my issue is caused by those selects. What I'm looking for is an alternate solution for it.
Comment: Have you been clearing the query plan cache prior to testing. You could also omit the @OrderByAndOrder bits and see if there is any performance related changes. When troubleshooting issues like this, it often helps to remove all parameters and narrow down to the smallest level of granularity that reproduces the problem. Clearing the query plan just removes the possibility of a bad plan being cached.
Comment: The bounty was set just to get some attention to the question. I understand I'm making this harder for all of you by not providing the full proc and test data, but all I'm looking for is an alternate solution (some type of join) that could accomplish the same result. That was I can do some internal testing.
Answer: Not sure it will do the trick, but you should try to add OPTION (RECOMPILE) at the end of you query.


How to add image field in a custom module form?

Question: In our custom module, mymodule we have a form MyModuleForm where we want to allow for an image to be uploaded or chosen from already uploaded images. Below is the MyModuleForm.php file, but cannot figure out why we are not able to upload the Image and save it. There is a menu link where the module's form is and when we navigate to the page we see a blank page with no field or widget to set the image.
Goal

To be able to make the Image Browser widget display so that we can use an existing image or upload one.
Store the image using MyModuleForm from the custom module.
We should be able to change the image as needed and save the configuration.
Set file status to permanent.
Add to file usage calculation.

How do we add an Image field on our MyModuleForm so that we can either use an existing image or upload a new one?
Here is what we tried but didn't work
MyModuleForm.php
class MyModuleForm extends ConfigFormBase {
  protected function getEditableConfigNames() {
    return [
      'mymodule.settings'
    ];
  }

  public function getFormId() {
    return 'mymodule_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('mymodule.settings');
    $form['my_file'] = [
      '#type' => 'managed_file',
      '#title' => 'my file',
      '#name' => 'my_custom_file',
      '#description' => $this->t('my file description'),
      '#default_value' => $config->get('my_file'),
      '#upload_location' => 'public://'
    ];

    return parent::buildForm($form, $form_state);
  }

  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Check if image is uploaded.
    if(isset($form_state['default_press_release_image'])) {
      // Set file status to permanent.
      $image = $form_state->getValue('my_file');
      $file = File::load($image[0]);
      $file->setPermanent();
      $file->save();
      // Add to file usage calculation.
      \Drupal::service('file.usage')->add;
    }

    $this->config('ns_default_images.settings')
      ->set('default_press_release_image', $form_state->getValue('default_press_release_image'))
      ->save();

    parent::submitForm($form, $form_state);
  }
}

Comment: This sounds like a route problem, what does your route configuration looks like? Please update the question accordingly
Answer: The default_value attribute accept an array in case of managed_file:
  $form['my_file'] = [
      '#type' => 'managed_file',
      '#title' => 'my file',
      '#name' => 'my_custom_file',
      '#description' => $this->t('my file description'),
      '#default_value' => [$config->get('my_file')],
      '#upload_location' => 'public://'
    ];

In The submit function you are using a field name different from the declared one in the buildForm().
The value of a managed_file should be an array even when the field is not multiple:
$form_state->getValue('default_press_release_image')[0];


Changing HTML code with Javascript show/hide

Question: I have tried a few different things, including a switch statement, appending using JQuery etc. and I can't get this to work with the button. What I am trying to do is change the words in P2 from:
Please push `<button id = "me" onclick = "toggle1('me');">this </button>` to show more information about me.

to:
Please push `<button id = "me" onclick = "toggle1('me');">this </button>` to hide more information about me.

I have to do the same thing with "courses" but I think if I could understand the first one, I could get how to do the second see/hide on my own.
I am so confused now :/
I think it has something to do with span tags, but I honestly am in my first week of HTML and have not learned what are probably really simple procedures for things like this yet.  I would appreciate any and all the help I can get to  help me figure this out.
<!DOCTYPE html>

   <title>About me</title>

 My Page

Stuff about me

Here is a link to learn more about HTML!

   Please push <button id = "me" onclick = "toggle1('me');">this </button> to see more information about me.

   Please push <button id = "courses" onclick = "toggle1('courses');">this </button> to see my list of courses."

More stuff about me...

    Course Name
    Date
    Time

    Programming Paradigms
    Tuesday / Thursday
    11:00-12:15

    Computer Organization
    Tuesday / Thursday
    9:30-10:45

    Linear Algebra
    Monday/Wednesday/Friday
    11:50-12:40

    Combinatorics
    Monday/Wednesday/Friday
    8:35-9:25

Comment: If you're using JQuery you can use methods like `.hide()` and `.show()`. By this same token `.toggle()` does both of those but flipping back and forth when called. Sooo `document.getElementById("p3").show()` instead of using `block`.
Comment: instead of changing the display property directly, you might consider setting up a css class that adds none. That way all you have to concern yourself with is adding or removing the class.
Comment: You can assign a class to P2 words by simply using a span and then you can use jQuery click function and html function to replace the text. http://api.jquery.com/click/ and http://api.jquery.com/html/
Comment: @SurgeonofDeath OP isn't using jQuery
Answer: You have a Syntax Error in your function toggle1. Remove unwanted braces. Try this:

But, if you are using jQuery, toggle is an inbuilt function. this is very simple as(Inline JS - Although Recommended as seperate Script): Remove your toggle1 function and change your two html onclick attributes:
Please push <button id = "me" onclick = "$('#p3').toggle()">this </button> to see more information about me.

Please push <button id = "courses" onclick = "$('#schedule').toggle()">this </button> to see my list of courses.

Comment: Thank you for your reply! I plan to edit the braces in just a moment. As for jQuery and toggle, is there a way to change see to hide or hide to see without that, since that's now how my code is set up so far? I guess I'm just really not understanding how to do that. If all else fails and I do have to use jQuery for simplicity, how do you implement the part that would change see and hide on toggle? Sorry if I'm asking too much, I just really want to understand. Thanks again for your time.
Comment: @Heather, are you asking about `show()` and `hide()`  instead of `toggle()`. That works. But, I don't think I understood your question.
Answer: It may be easier with jQuery, something along these lines...
`<script`>
function showhide() {
$( "#showhide" ).text( "hide" );
}
`</script`>

Please push this to show more information about me.

<button onclick="showhide()">Hi</button>


Separate Database For SQL Server Reports

Question: I have researched this on here (and other sites) quite a bit.
I feel like I am missing something simple. So please direct me to another posting or help answer my question.
Basically, we have out grown our current database server.
The main issue is high CPU usage because of poorly written reports on top of a poorly designed relational database. The other problem is due to the IO usage for both workloads running. Users experience locks and issues trying to save into the system during high usage times and when the reports are pointing to the same server. Indexing and maintenance is done frequently. There is little fragmentation in the indexes that would lead to increased IO or CPU. Locking (by the reports) has been minimized, however other queries still need to acquire locks to maintain compliance.
I am forced to split the two main workloads from it... Which by the way, should happen anyway, since one is an OLTP workload and the other is a reporting workload using SSRS.
Here are the three main options I have tried to create a separate reporting database also with the reasons why each one will not work.
Things tried already:

Full database copy – This is what we have been doing but it is slow and our reports will have 12 hour old data. This does not meet our business requirements or end user expectation.
Log Shipping – I tried to implement this but we lose the 15 minute restore option for our backups (Data Protection Manager). Being able to restore the database in 15 minute increments seemed more important than having a separate reporting database. This is a valid point made by my supervisor, though it is becoming an increasing problem due to the issues the users are experiencing with the OLTP side of the system. The other problem with log shipping is that the report server would be down while the restore happens on the reporting database.

3.Replication –  Transactional Replication is Microsofts recommended solution. It would keep our 15 minute backups in place as well as give us almost live reporting data.
Due to some of the code they use in our medical records system, it is not compatible with replication. The heavy use of truncate (not supported by replication) as well as the (questionable) ability to enable end users to create new database columns (changes to the
schema) via the web interface.
Any help out there? Thank you.
Comment: Have you tried mirroring?
Comment: Whilst not strictly an answer to your question, there is a 4th option - as the DBA, you have access to the SQL Profiler, and the SQL Query Tuner. Run the profiler for 20 minutes during some of these badly written reports, load that trace into the Query Analyzer, give it a long work time and let it do its work. It might come up with some surprising indexes or statistics you can add to the database that will help, and adding indexes shouldn't impact the code running on the DB (unless they're using HINTs, which they shouldn't).
Comment: You say that indexing and maintenance are done frequently, then go on to say that there is little fragmentation in the indexes. Have you thought about using Hallengren's index maintenance scripts so that indexes with little fragmentation and not unnecessarily reindexed? What kind of lag could be tolerated on the reporting side if you separate it from the OLTP side? Why can't you use the tlog backups generated by "Data Protection Manager" to restore to another database on a different server?
Answer: Since I seem to not have the ability to reply to answers posted, I am going to reply this way. Sorry for the confusion.
Mark Henderson: Yes, I have done quite a bit of optimizing these queries. Unfortunately, there is only so much I am able to do to get them performing better. Some of it has to do with the code of the 3rd party medical records system... Some of it has to do with the lack of resources I am given for the server to handle both workloads adequately. The indexing is worth checking back on, though I have done that quite a bit, I will continue to investigate.
CMcKeown: I was reading more about mirroring recently. The caveat with that seems to be similar to log shipping. While a snapshot happens, the reporting database will be offline and the users will be disconnected. Mirroring, as I understand it, will also require an availability group, which could require changes to the medical records application that I may not be given the ability to implement.
darin strait: Yes, I have scripts in place that only defragment or rebuild indexes that are only a certain percent fragmented for each. This was necessary due to the amount of growth in the database. The indexes on tables that are updated frequently fragment quicker than the other indexes... So, it was necessary to handle those separately.
We have had a few discussions over the lag time on the reporting data. At first up to 24 hours was fine, then we got some push back from the users, now many of the reports apparently need to have almost live data. I am trying to push for hourly or half hour windows at this point. Part of the problem is satisfying everyone, and if I'm not able to, then making the right people as happy as possible. I don't know why I have not considered using the log backups sent to DPM to populate the reporting database. Without really looking into it, the problems would seem to be the same with log shipping, in that the database would have to be offline while it is being restored. I also do not know if there is a good automated way for DPM to handle a task like that. It is worth investigating so I thank you for that idea.
darin strait: Thank you for the correction on the availability group and the Asynchronous Database Mirroring. However, from what I see the same issue applies with the snapshots as it does with the log shipping restores. The users will be disconnected while the snapshot is created. We are using enterprise edition, so this is an option. It may be a better option in the end, due to it not interfering with our current backup system. Thank you for the input, I will take it under serious consideration.
Comment: "mirroring" != "availability group". Availability groups are a SQL 2012 thing. You would be looking at something more like this-> http://msdn.microsoft.com/en-us/library/ms187110(v=sql.105).aspx
Comment: Also relevant: http://blogs.lessthandot.com/index.php/DataMgmt/DBAdmin/read-from-your-mirror-in-sql-server
Comment: Regarding mirroring - the mirrored database is in a perpetual state of 'Restoring', and therefore isn't usable (similar to Log Shipping), but what you can do is create a read-only snapshot of that database for reporting purposes.


Find all the elements of order $20$ in $(\mathbb{Z}\backslash 101\mathbb{Z})^{\times}$

Question:
Find the order of $2$ and $5$ module $101$. Futhermore, find all the elements of order $20$ in $(\mathbb{Z}\backslash 101\mathbb{Z})^\times$.

Since $\phi(101)=100=2^25^2$ then $2$ and $5$ only can have order $2,5,2^2,2\cdot 5$ or $,2^2\cdot 5$. After evaluating every power of $2$ and $5$ I got that $2$ and $5$ are primitive roots module $101$. Is there any shorter path to find the answers?
There exists $\phi(20)=8$ elements of order $20$. I know that $2^i$ is a primitive root if and only if $(i,100)=1$, so $(2^i)^5$ and $(5^i)$ are elements of order 20. Is there any shorter path to find all these elements?
Comment: @YotasTrejos 2 is indeed a primitive root modulo 101. However, note that this contradicts your first sentence after the statement of the problem; so you might want to check your thinking on that sentence. Also, 5 is not a primitive root modulo 101 (for one thing, it's a quadratic residue); in fact, its order is 25.
Comment: Do you mean $(\mathbb{Z} / 101 \mathbb{Z})$*? Cause otherwise, $2 * 51 \mod 101 = 1$ and 2 is not a generator
Comment: @NikolasWojtalewicz every nonzero element of $(\Bbb Z/101\Bbb Z)^+$ is a generator, including $2$.
Comment: Why is there a contradiction?
Comment: @GregMartin Right, since 101 is prime, and the order of an element must divide the order of the group, every non-zero element is a generator. Whoops :D
Answer: Since $2$ is a generator, $2$ has order $100$ and so $2^5$ has order $20$.
Therefore, the elements of order $20$ are $(2^5)^k$ where $\gcd(20,k)=1$.


hook_form_alter() only firing after cache clear

Question: I have a custom module that I'm using to add a Java applet to some of my admin forms. The applet is necessary to get details about the product being entered.
I'm noticing that after 15 minutes (or more) of site inactivity, my hook stops firing. If I clear the cache, the hook begins firing once again. However, this only seems to last 15 minutes or so.
Is it possible there is some admin form caching happening?
Possibly salient details:

I'm using Seven as the admin theme
I'm using D7 with Commerce Kickstart install profile (commerce_kickstart-7.x-1.8)
Comment: Provide code of your hook_form_alter() function
Comment: This might not be the best solution, but why not inside the hook_form_alter of the custom module you created you add drupal_flush_all_caches(); so that everytime you open the admin form the cache is clear and you always get the proper results. This should allow you to work while you figure out what is wrong.
Comment: Can you post the code of your hook_form_alter()? Or at least the form_id that you're checking for?
Comment: I'd echo what others have said: Can't answer the question without code. You might be altering the form in a way that bypasses Drupal's aggressive caching system.
Comment: I cant comment yet or this would be a comment. It sounds like your caching level is to high? http://api.drupal.org/api/drupal/includes%21form.inc/function/form_set_cache/7 while not an "answer" might help someone smarter than me answer it.
Answer: I think your problem stands in cascading caching logic : your form must be called by something (a block, a template, a function...) that must be itself cached.
What you have to think about is "When, and by who, is my cache warmed up, with which conditions ?" : the most logical answer is that when your cache is created for the first time, conditions in your hook_form_alterare not TRUE.
For example, are you searching, in your alter, for infos coming from the session, or user roles, or static variables...
We could do more with your code :)
Answer: I was facing the same problem. hook_form_alter() was not being called without clearing cache and thus the form incomplete. It was a form at admin panel (module config form).
Then I used the format hook_form_FORM_ID_alter() and the problem solved.
Answer: I'm noticing that after 15 minutes (or more) of site inactivity, my hook stops firing: If your javascript code does not work, as per my understanding that this is issue related to your javascript.
When the system is idle for few minute, javascript stopped working and generate the error. I was working in a project, I found the same issue and so I need to refresh browser to make it working after few minute if system is idle.
You can add some debug in your hook_form_alter and check that its working or not if system is idle for few minute.
Answer: move your  hook_form_alter() in theme template.php , works each time


SMTP module: The following From address failed

Question: all,
Here is something I don't quite understand.
First of all, my site-wide email address configured on Site Information page is firstname.lastname@example.com.
Then, I use smtp module to send emails out from my site. I configure SMTP settings with my yahoo email address firstname.lastname@example.com.
I tries to send a test email out to my other gmail address email@example.com, but failed. Email can never be sent out in this situation.
Here is watchdog log details:
<code>Type    smtp
Date    Monday, September 22, 2014 - 11:29
User    lyon
Location    http://localhost:8888/drupal-test/admin/config/system/smtp
Referrer    http://localhost:8888/drupal-test/admin/config/system/smtp
Message Error sending e-mail from firstname.lastname@example.com to email@example.com : The following From address failed: firstname.lastname@example.com
SMTP server error: From address not verified - see http://help.yahoo.com/l/us/yahoo/mail/original/manage/sendfrom-07.html

Severity    error
Hostname    ::1
Operations
</code>
SMTP configuration didn't go wrong, because in the following two situations, email can be sent out well:

configure site-wide email address to be the same one configured in SMTP settings: email@example.com.
configure SMTP settings with a gmail address, then configuring site-wide email address to be any email address will work well. (People on Internet says Gmail can override it).

I don't want the SMTP configuration to be tied with Gmail account, it should support any mail host. How can I overcome this problem?
I appreciate your help.
Comment: Why do you use Yahoo to send Gmail emails in the first place?  Any particular reason to do that?
Comment: I didn't use Yahoo to send Gmail emails. I configured SMTP with my Yahoo account, and was trying to send an email to my Gmail account.
Comment: But your "from" address is \@gmail.com not \@ymail.com, so only gmail's SMTP can be expected to send it without problems. In old days with no mail security (199x) you could use any SMTP to send mails with any "from". That is no longer true, people kinda didn't like it when someone was impersonating their clients, and now without SMTP admin's cooperation you cannot do that, you must use SMTP of company that is hosting your "from" address.
Comment: OK, thank you for this great tips. My question now is that if it is possible to overwrite drupal site-wide email address to be @ymail.com in code programmatically?
Comment: or do I have to configure site-wide email address to match smtp_username I put in SMTP configuration page?
Answer: I believe the problem lies with Yahoo not having your permission to send from the gmail account.  You could try setting up Yahoo to send from your gmail account but I'm not sure Yahoo will do that.
You could look into a mail service like MailJet, which is cheap and scalable.
Or, assuming you're using the drupal_mail function, simply set your $from variable in 'params' to 'firstname.lastname@example.com'.
Comment: thanks for answering my question. MailJet sounds good. But is there any way I could simply override the mail from address to be SMTP from address rather than using site-wide mail address programmatically?
Comment: Oh yes, the other option I forgot to write in... does that help?
Comment: Yes I am using `drupal_mail` function. And no, setting `$from` variable to 'email@example.com' didn't work out. I even set `$from` to be smtp_username variable I configured in smtp module, but still, when I `dpm` the $from variable in `smtp.mail.inc` file under smtp module, it keep showing the site-wide email address..
Comment: Ok.. Now I got it. You second option works on my own custom module. It was a problem in the test mail function of smtp module. `$from` is omitted in its `drupal_mail` function. see line #149 under smtp.admin.inc in smtp module. I will accept your answer, thanks for your time.
Comment: Ah right, good sleuthing and you're welcome =)


How to best sort xml records with xslt?

Question: Here's my source xml file, it has records like so:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

        <ID>12345</ID>

    <record>
        <name>Foo</name>
        <recTime>2020-03-30T23:59:36.62Z</recTime>
    </record>
    <record>
        <name>Bar</name>
        <recTime>2020-03-31T23:59:36.62Z</recTime>
    </record>
    <record>
        <name>Car</name>
        <recTime>2020-03-29T23:59:36.62Z</recTime>
    </record>

I want to transform it so that all the records are sorted by "recTime", like so:
<?xml version="1.0" encoding="UTF-8"?>

    <ID>12345</ID>

  <record>
    <name>Car</name>
    <recTime>2020-03-29T23:59:36.62Z</recTime>
  </record>
  <record>
    <name>Foo</name>
    <recTime>2020-03-30T23:59:36.62Z</recTime>
  </record>
  <record>
    <name>Bar</name>
    <recTime>2020-03-31T23:59:36.62Z</recTime>
  </record>

I'm playing with xslt, but I'm not familiar with it.  Here's what I have so far:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ss="abc:def.ghi">

<xsl:output method="xml" version="1.0" omit-xml-declaration="no" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:variable name="newline">
  <xsl:text>
  </xsl:text>
</xsl:variable>

  <xsl:template match="/">

      <xsl:value-of select="$newline"/>
      <xsl:copy-of select="/ss:*/ss:B" />
      <xsl:for-each select="/ss:*/ss:record">
        <xsl:sort select="ss:recTime"/>
        <record>
          <xsl:value-of select="$newline"/>
          <name><xsl:value-of select="ss:name"/></name>
          <xsl:value-of select="$newline"/>
          <recTime><xsl:value-of select="ss:recTime"/></recTime>
          <xsl:value-of select="$newline"/>
        </record>
    </xsl:for-each>

  </xsl:template>

</xsl:stylesheet>

Here's what it outputs:
<?xml version="1.0" encoding="UTF-8"?>

  <ID>12345</ID><record>
  <name>Car</name>
  <recTime>2020-03-29T23:59:36.62Z</recTime>
  </record><record>
  <name>Foo</name>
  <recTime>2020-03-30T23:59:36.62Z</recTime>
  </record><record>
  <name>Bar</name>
  <recTime>2020-03-31T23:59:36.62Z</recTime>
  </record>

It has a few problems:

The root element 'A' is missing the attribute msgVersion="revision2.0"
Element 'B' should not have a namespace, since it did not in the source xml
The xml formatting (spacing and new lines) isn't pretty, but that's not high priority

I also have a gut feeling I'm going things the hard way.  Any help would be appreciated.
Comment: *"Element 'B' should not have a namespace, since it did not in the source xml"* You are mistaken about that. Default namespaces are inherited. **All** the elements in the source XML are in the `"abc:def.ghi"` namespace.
Comment: Rather confusing that your headline asks about sorting, but the sorting part of this stylesheet seems to be working perfectly well, and the detailed questions are unrelated to sorting.
Comment: Sorry if that was confusing.  I realize I had the sort part working, but I wasn't sure if it was the best way.  That's why I asked "How to best sort" in the headline.  And sure enough, my attempt was not the best approach.
Answer: How about:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ss="abc:def.ghi">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="/ss:A">
    <xsl:copy>
        <xsl:apply-templates select="@* | ss:B"/>
        <xsl:apply-templates select="ss:record">
            <xsl:sort select="ss:recTime"/>
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

How to best sort xml records with xslt?


Browser back button page state on a custom button click

Question: I have two pages. on the first page user select some filters and press search button then user navigates to the second page. On the second page user will see a grid and he will perform some tasks there.
Now the user needs to go back to the first page on one click with out using the browser back button. since the user perform some tasks in the second page which posts backs occur user can not go to the first page from one click on the browser back button.
user also needs the state of the first page to be same as when he selects the filters and press search.
How can i achieve this?
Answer: Unfortunately there is no magic trick for this.  You'll have to programmatically remember the return URL and also any page state that you will need to set back up when they return.
It's not uncommon to see a querystring containing a UrlEncoded ReturnUrl parameter for this purpose.  If you can manage to get everything needed to restore state in the Url then you can simply redirect back to Request.QueryString["ReturnUrl"] upon completion.
If you want to avoid the querystring you'll either need to form post it, or store the needed data somewhere separate from the current request (like Session) for retrieval later.
Answer: This might help you, not exactly the back button pressed.
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack) //check if the webpage is loaded for the first time.
        {
            ViewState["PreviousPage"] =
        Request.UrlReferrer;//Saves the Previous page url in ViewState
        }
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        if (ViewState["PreviousPage"] != null)  //Check if the ViewState
                        //contains Previous page URL
        {
            Response.Redirect(ViewState["PreviousPage"].ToString());//Redirect to
        //Previous page by retrieving the PreviousPage Url from ViewState.
        }
    }

Comment: that doesn't maintain the state of the previous page, you just made a redirect to the previous, in that case when the page loads it will loose all selected filters


SonarQube incompatible with Gradle 7.0

Question: I'm running SonarQube Gradle Version 3.0 with Gradle 6.7.1, when I run gradle sonarqube I've got a Gradle FAILURE: :
Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.

App/build.gradle :
apply plugin: 'org.sonarqube'

build.gradle :
buildscript {

    ...

    dependencies {
        ...
        classpath "org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:3.0" // Added for SonarQube
    }
}

allprojects {
    repositories {
        ...
        maven {
            url "https://plugins.gradle.org/m2/" // Added for SonarQube
        }
    }
}

gradle-wrapper.properties :
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7.1-all.zip

Comment: I'm pretty sure this is not the reason for your builds failure. It is just a warning that a feature currently working will not work in an upcoming version of Gradle. This is pretty common when working with new versions of Gradle, because plugin authors need some time to adapt their plugins when features get deprecated.
Answer: [UPDATE] 26 Dec 2020
I have tried using gradle-6.7.1 and still SonarQube incompatible with Gradle 7.0, alternatively I use Codacy to get feedback on code. *By default Android can use Lint

SonarQube incompatible with Gradle 7.0


OSX El Capitan 10.11.3 Bluetooth not available

Question: I am having some issues to get back to function my bluetooth (OS X El Capitan V.10.11.3, after the update), just presents a message as NOT AVAILABLE. I tried This solution without any response.
Later, I tried to reboot the SMC like the following:

How to Reset SMC in a MacBook Air, MacBook Pro Retina, or MacBook
  Pro's (with non-removable batteries)
Step #1. Turn off your MacBook (any of the above version). Step #2.
  Attach the power adapter to your Mac. Step #3. Press
  Control+Shift+Option keys and power button together for some time and
  then release the keys. Ctrl, Shift, Option, and Power Key Combination
  Step #4. Start the boot as usual.

From here.
Also not working with my issue.
It's really frustrating, damn macs.
Comment: Always El Capitan, I imagine 10.11.2 or 10.11.1. I just bought the macbook on december.
Comment: I would try contacting the apple store, to fix or replace it for free.
Comment: Which was the previous version of your OSX? Just so I know not to update, in case I can run into the same problem.
Answer: Had this problem since 2015 usually after waking the computer, Bluetooth would show as unavailable and I have tried just about everything suggested by answers I found online. The only solution I have come across that works 100% for me is by going to System Preferences -> General -> unchecking Allow Handoff between this Mac and your iCloud devices
It has been a month of observing this problem that occured daily and never had an issue afterwards. Hope this might help some of you out there.


Problema Apache - 2 dominios

Question: boa tarde...
Estou tentando configurar 2 dominios em 1 servidor:
_Debian Linux
_Apache2
Criei o seguinte arquivo: pclinx.conf , logo apliquei a2ensite , icou habilitado e reiniciei o apache2.
<VirtualHost *:80>
ServerAdmin webmaster@localhost
ServerName www.pclinx.com.br
ServerAlias *.pclinx.com.br
DocumentRoot /var/www/html/pclinx

<Directory />
   Options FollowSymLinks Indexes
   AllowOverride AuthConfig
</Directory>
<Directory /var/www/html/pclinx>
   Options Indexes FollowSymLinks MultiViews
   AllowOverride all
   Order allow,deny
   Allow from all
</Directory>
</VirtualHost>

Em /var/www/html/pclinx tem um arquivo index.html .... mais não consigo visualizar o index.
Site: www.pclinx.com.br
Podem me ajudar por favor?
Answer:
Você pode tentar assim, em  VirtualHost colocar  o IP do Servidor, acesse o log do Apache2 que está no /var/log/, para ver que erro ocorre.

<VirtualHost IP_DO_SERVIDOR:80>
ServerAdmin webmaster@localhost
ServerName www.pclinx.com.br
ServerAlias *.pclinx.com.br
DocumentRoot /var/www/html/pclinx

<Directory />
   Options FollowSymLinks Indexes
   AllowOverride AuthConfig
</Directory>
<Directory /var/www/html/pclinx>
   Options Indexes FollowSymLinks MultiViews
   AllowOverride all
   Order allow,deny
   Allow from all
</Directory>
</VirtualHost>

Se precisar de um gerenciador de Hospedagem use o ISPConfig3, script para instalar no Ubuntu: https://gist.github.com/jniltinho/4b50de4a24a162add15f
Answer: Acabei de configurar aqui para simular o seu problema. Fiz desta forma:
<VirtualHost *:80>
    DocumentRoot /var/www/html/pclinx/
    DirectoryIndex index.html index.php
    ServerName www.pclinx.com.br
        <Directory /var/www/html/pclinx/>
        Options Indexes FollowSymLinks MultiView
        AllowOverride all
        Order allow,deny
        allow from all
        </Directory>
</VirtualHost>

Sugiro você apagar o que tentou e por isto ao invés. Caso não consiga fazer funcionar, poste aqui as últimas linhas do seu log do apache.
Não esqueça de reiniciar o apache depois de efetuar a mudança.

Problema Apache - 2 dominios


Getting "invalid character value for cast" error while inserting data into table. Java

Question: <code>try {
                    Connection conn=DriverManager.getConnection("jdbc:ucanaccess://E:\\testing.accdb");
                    String sql="insert into Books (Book_ID,Book_Name,Subject_ID,Author) values (?,?,?,?) ";
                    PreparedStatement pst=conn.prepareStatement(sql);
                    pst.setString(1, textField_BN.getText());
                    pst.setString(2, textField_SID.getText());
                    pst.setString(3, textField_BID.getText());
                    pst.setString(4, textField_A.getText());
                    pst.executeUpdate();

                    JOptionPane.showMessageDialog(null, "Data Saved");

                } catch (Exception e) {
                    e.printStackTrace();
                }
</code>
I made a connection using Ucanaccess, it is successful and printing tables. However, I tried writing an insert query that would input rows into the table it is giving me the error

UCAExc:::4.0.4 data exception: invalid character value for cast   at
  net.ucanaccess.jdbc.UcanaccessPreparedStatement.setString(UcanaccessPreparedStatement.java:742)
Comment: you have `(Book_ID,Book_Name,Subject_ID,Author)` so it should be `pst.setString(1, textField_BID.getText());
                pst.setString(2, textField_BN.getText());
                pst.setString(3, textField_SID.getText());
                pst.setString(4, textField_A.getText());` - once you fixed this, we can check for further issues but right now the ordering doesn'T match your table def
Comment: Does your _Book_ID_ and _Subject_ID_ are string value?
Comment: and you don't understand the meaning of `invalid character value for cast at ... setString`? I mean, we don't know which string you try to insert nor do we know which line it is ... check the values and the table schema. And shouldn't `textField_BID.getText()` not be the first value of the insert? I mean, `pst.setString(1, textField_BID.getText());`
Comment: It looks like `textField_SID.getText()` should come at the first place.
Comment: @Benoit no, but `textField_BID.getText()` should come first
Comment: It worked guys, thank you
Answer: Look at line 742 in your java class, see what field it is setting and then validate you are passing in a string. the cast exception happens because of invalid data type being passed into the prepared statement that expects a different data type based on your schema. If you have to add some debugging to print the values of each object value you are setting and also check your schema to make sure your java data types being set in the prepared statement match up.
"invalid character value for cast" error on INSERT via UCanAccess


Rules: how to display the value of variables?

Question: I use the Devel module on Drupal 7 to debug some rules of my site but I can't debug without knowing the value of variables I created.
In the case, I have a loop where I sum different values and at the end of the loop I store that in a second variable that I compare to fixed parameters.
Is there something that can show me every value of the rules variables?
In the default log I have only events but I don't know anything else...
Thanks!
Answer: Two options:

At admin/config/workflow/rules/settings, set "Show debug information" to "Always."
In the rule's actions, add the action "Show a message on the site" (under the System group, I believe). Pass it the variable(s) you want to debug.
Comment: Thank you very much, the second method used with php code is very good!


Why "delta" chords?

Question: Why are major seventh chords called delta chords and written with a delta symbol, like CΔ7 or CΔ? Do engravers consistently use Δ to mean a seventh chord (such that Δ7 is redundant) or do some use Δ simply to mean major?
Answer: The triangle symbol Δ originally meant "triad" (meaning major triad) [1]. However, nowadays it is - at least to my knowledge, and when used without any other qualifiers - exclusively used to denote a major seventh chord, even though that usage is a bit sloppy. I recommend you use Δ7 for denoting a major seventh chord. This will avoid any possible confusion, and it is also the symbol I come across most often.
[1] The Chord Scale Theory & Jazz Harmony, B. Nettles and R. Graf
Comment: @ColeJohnson: No, there's absolutely nothing wrong with it. It's just one of several options.
Comment: Is there anything wrong with using "Cmaj7" instead of "CΔ7"? IIRC, Rocksmith uses "Cmaj7".
Comment: CΔ9 and CmΔ9 are also common. Major 7th. major 9th.
Comment: I respectfully disagree with the "exclusively used to denote a major seventh chord" statement. In modern days, it stands for "major seventh". For example, the music typesetting software I use, Lilypond, notates a minor triad with an added mayor seventh simply as "mΔ".
Comment: @AlexLopez: Thx for you comment, and I don't think we disagree. What I meant was that the triangle used alone without anything else always denotes a major 7th chord, even though I would discourage such a usage and would use Δ7 instead. In combination with a lowercase "m", it clearly denotes a minor triad with a major 7th. I'll edit my answer to clarify.
Comment: Cheers, Matt :-) And by reading again my own words I just realised there's ambiguity in them too! Using words as opposed to notation, it seems difficult to distinguish between a major triad with an added major seventh and a triad (major or minor) with an added major seventh.
Comment: @ColeTobin `maj7` is the far older way to denote a major seventh chord.
Answer: △ without further qualifications in most contexts means "some type of major chord".
The point of these chord charts is to indicate to the player the most important information about the harmony of a given song.  Usually, where the symbol "△" is used, we're talking about a jazz context.  In this context, which specific major chord to use is left to the tastes of the performer, and so when one sees C△ in a lead sheet it might be rendered variously as C△7, C△9, C6/9 etc.
In the same way we often don't feel the need to tell the player which inversion to use, in jazz we often don't feel the need to tell the player which specific type of major chord to use.
Similarly, we often don't specific inversions; take for example a dominant chord (instead of a major chord), most of the time we see G7 any inversion of will do, but sometimes we really want the F at the bottom, in which case one would write G/F.
The same goes for major chords; if it's really important then be specific (e.g. C△9/G), and if it isn't then let the player decide what specific chord and inversion to use and just write C△
Comment: You can maybe get away with "...in most contexts means major quality chord," but I have never seen an instance of a **C△** that could be a **C7**, which is a major quality chord.
Comment: @DavidBowling, C7 is not considered a "major quality chord" among most serious musicians, particularly jazz musicians. They consider there to be 3 types of chords: major, minor, and dominant. Thus C7 would be a dominant quality chord, not a major quality chord.
Comment: @ScottM -- You are confusing _chord quality_ with _chord function_. Chord _quality_ refers to the underlying triad and can be major, minor, augmented, or diminished, but not dominant. Chord _function_ can be dominant, and a 7th is not required for a chord to be dominant. Standard chord nomenclature names: root, triad quality, highest degree of the structure when built in 3rds above the root, finally alterations or added pitches. This is how Nettles and Graf describe chord symbols.
Comment: perhaps quality is the wrong word, I very nearly just said "flavour".  A C7, C9, C7♭9 etc. are all a "dominant" chords and "Δ" is a "major flavour chord", for want of a better term. I don't know what exact term to use, but basically anything that "functions" as a major chord.  I don't know if dominant chords count as major quality, if they do then that's the wrong word to use.
Comment: The main point is that C△ does not necessarily mean C△7 as the accepted answer suggests.  In fact, there are many cases when another major chord would be preferable, or even just a triad sometimes!
Comment: @DavidBowling I've edited the answer, and avoided the term quality for the reason you've outlined. I haven't used function because I think that has its own problems, so I've simply said "major type" and illustrated what that means by example.
Comment: @DavidBowling, I'm merely stating how chords are viewed (and yes, chord terms are used, even potentially incorrectly) among the majority of working musicians, particularly in jazz, where these chords occur most frequently.
Comment: @ScottM -- Well, I am a jazz musician, and I have never heard any other serious musician say that a **C7** is not a major quality chord. Chord quality refers to the underlying triad. You are correct that jazz musicians tend to group chords into major, minor, and dominant (but here **sus** chords tend to fall under the dominant category, while augmented chords frequently fall under either major or dominant, showing that this is only a loose categorization). My original point was that delta chords _never_ mean dominant 7th chords.
Comment: @DavidBowling, I agree with your original point.

Why “delta” chords?


Is there a way to install SSL certificate on EC2 instances running IIS using ebextentions?

Question: I'm trying to find a simple way to install SSL on EC2 instances running IIS without having to RDP into each server. Can it also be configured to add and install the cert upon spinning up instances during auto scaling? I have been looking around for a while, but could not find a simple way to do this.
Comment: Yes, you could build into the AMI, or you could use a configuration management system. Alternatively, you could put an ELB in front of your instances and let it handle the SSL.
Comment: I already have SSL on ELB. I also know how to create an AMI... but how can I install SSL on EC2 ?
Answer: You could create an AMI and include the SSL configuration in the AMI.
A better option might be to use an ELB and AWS Certificate manager to terminate SSL. The ELB then talks http to your IIS servers. The SSL certificate is free from AWS for use in your ELB, but you can't use it outside the ELB. More documentation here.
Comment: Then you need to follow the advice in the first part of my answer. I can see that you would want to do that for regulatory or compliance reasons, but from a technical point of view it's likely unnecessary. AWS doesn't allow network sniffing, and they have full access to everything that isn't encrypted before it hits AWS anyway.
Comment: Just get a server working and create an AMI from that. There's no need for anything additional, but you'll need to recreate the AMI each time the certificate expires. Alternately you could put the certificate on S3 (with appropriate permissions) and use a startup script to download it when the server starts.
Comment: I already have an SSL on ELB, but I want to make the connection between ELB and EC2 instance secure, hence I need to install SSL on the EC2 instance.
Comment: Do you happen to have a tutorial of how to create an AMI and include the SSL configuration in the AMI? Amazon's documentation isn't exactly clear on that


I can't add a new list item in Bootstrap tab

Question: I am using the following code for creating a tabbed interface:

Chart 1

Chart 2

Chart 3

As soon as I add,

Chart 4

before the
, the CHart 4 text appears as simple text, with no tab boundary. Why is this happening?
Comment: Its working fine, You didnt added  tag for tab4.. try with that it will work fine   Chart 3
Comment: It would be a simple text as the Tab needs a `` tag around it also.
Answer: This is because Bootstrap 3 tabs were having styles for , without  it doesn't match the conditions to get the tab navigation styling. Here is the sample Bootstrap 3 CSS code for Tabs:
.nav-tabs > li > a {
  margin-right: 2px;
  line-height: 1.428571429;
  border: 1px solid transparent;
  border-radius: 4px 4px 0 0;
}

.nav-tabs > li > a:hover {
  border-color: #eeeeee #eeeeee #dddddd;
}

.nav-tabs > li.active > a,
.nav-tabs > li.active > a:hover,
.nav-tabs > li.active > a:focus {
  color: #555555;
  cursor: default;
  background-color: #ffffff;
  border: 1px solid #dddddd;
  border-bottom-color: transparent;
}

Try like this Demo:

Chart 1

Chart 2

Chart 3

Chart 4

Comment: Sounds like stupid but this is the correct answer cause CSS declared it has to be with an `` tag to work.
Comment: Thank you for the answer. But what if I don't need the  bit? I will put an onclick listener that will hide divs based on which tab is pressed. Why should I use  then?
Comment: Then you have to customize your tab, where in bootstrap they wrote style with  only, so edit it / create your own css according to your requirement


How to use checkbox values in code?

Question: In my Oracle APEX application page I have checkbox item with multiple values. The source of checkbox is like this:
STATIC:One,Two,Apple

In page process I need to use the value from checkbox in PL/SQL code. As far as I understand I get colon separated values. Question is how to use those values and test if Value is One, then do this. If Two is checked as well, then do something more.
Answer: Depending on situation you can use:
Convert string with delimiter to table (you can use this as subquery):
select regexp_substr('1:2:3','[^:]+', 1, level) ID from dual
connect by regexp_substr('1:2:3', '[^:]+', 1, level) is not null;

ID
--
 1
 2
 3

Check one value using instr:
where instr('1:2:3', '2') > 0

If value of the second argument of the function is contained inside the first argument - function returns its position, otherwise - 0.
Answer: For performance I prefer the INSTR function, e.g. INSTR(':'||:p_item||':',':Two:') > 0

How to use checkbox values in code?


MySQL - Delete duplicate records but keeps XX records

Question: My problem is that I want to delete duplicated records but keeps XX latest records. For example:

id
ean
price
price_type
country
valid_to

1
12345678
19.99
b2c
US
2022-03-30

2
12345678
18.99
b2c
US
2022-03-28

3
12345678
17.99
b2c
US
2022-03-26

4
11122233
146.99
b2b
US
2022-03-30

5
11122233
150.99
b2b
US
2022-03-28

6
11122233
170.99
b2b
US
2022-03-26

7
11122233
180.99
b2b
US
2022-04-01

Desired results - keeps 2 latest records:

id
ean
price
price_type
country
valid_to

1
12345678
19.99
b2c
US
2022-03-30

2
12345678
18.99
b2c
US
2022-03-28

4
11122233
146.99
b2b
US
2022-03-30

7
11122233
180.99
b2b
US
2022-04-01

Which query statement should I make to do this? Thank you!
Comment: What is precise MySQL version?
Comment: @Akina MySQL 5.7
Answer: it is support MSSQL 8.0 version or above
use ROW_NUMBER with PARTITION and get your result
Get only 2 record of each ean
SELECT * FROM (
SELECT id,ean,price,price_type,country,valid_to,
ROW_NUMBER() OVER(PARTITION BY valid_to ORDER BY ean,valid_to) AS RNO
FROM tablename
)main
WHERE RNO < 3

if you want to delete then use this
DELETE FROM tablename WHERE id IN (
    SELECT Id FROM (
            SELECT id,
            ROW_NUMBER() OVER(PARTITION BY valid_to ORDER BY ean,valid_to) AS RNO
            FROM tablename
        )main
        WHERE RNO > 2
        )

Comment: OP needs not select but delete
Comment: @Akina added both code delete and select.
Comment: what happened can you explain please @Akina.
Comment: it's working find because first getting id after delete it so working fine.
Comment: Oops, I miss that you use double subquery.
Comment: so what you thinks it's right or wrong.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/243227/discussion-between-piyush-kachhadiya-and-akina).
Comment: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=ef1a0e8faf610bc352ff06b1934789d8
Answer:
What is precise MySQL version? – Akina
MySQL 5.7 – nphuly

DELETE t0
FROM test t0
JOIN ( SELECT t1.id, COUNT(*) cnt
       FROM test t1
       JOIN test t2 ON t1.ean = t2.ean AND t1.valid_to <= t2.valid_to
       GROUP BY t1.id ) t3 ON t0.id = t3.id
WHERE t3.cnt > 2

https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=3284d0a012272813c1fbd6121bfd51b3


Query size of local memory accessible to subgroups in Vulkan

Question: Is there a way to know how much local memory every compute unit has access to? For example in OpenCL I could call
cl_ulong size;
clGetDeviceInfo(deviceID, CL_DEVICE_LOCAL_MEM_SIZE, sizeof(cl_ulong), &size, 0);

Vulkan should have something equivalent to this.
Answer: The GLSL compute shader abstraction's equivalent to OpenCL local memory is shared memory: memory accessible to all work items in a work group (defined by shared-qualified variables). As such, you may query GL_MAX_COMPUTE_SHARED_MEMORY_SIZE to get the amount of shared memory.


How to install sendmail client only, without the MTA?

Question: Is there any way to install the sendmail client, only, without installing the sendmail MTA at all?
What I mean by this is the sendmail -t command that is frequently used by processes such as cron to submit outgoing email. Most such programs expect some kind of sendmail API compatible program called sendmail to which they can send their outgoing mail.
Currently on my mail server, I don't have any sendmail binary, and as such I see things like this in cron:
(CRON) info (No MTA installed, discarding output)
Actually, I do have an MTA installed - one that I wrote myself (so not Postfix, exim, etc.) - but I don't have any sendmail program written to interface to that. I'm wondering if it's possible to install and use the sendmail program in isolation to just receive anything given to it and then open an SMTP connection localhost:25 and feed that into the MTA using an SMTP transaction. This way, I don't need to write my own sendmail program that has the same interface to do that.
Is this possible? I would assume something like this already exists, so I don't want to reinvent the wheel. Default installation of sendmail also installs the sendmail MTA, which I don't want; I don't want to install any MTA package that would clobber or interfere with the real MTA already on the system.
In the research I've done, there seems to be very little separation between the two. All the tutorials seem to assume you're using one of the "standard" MTAs. If the answer is "no", then equivalently is there documentation on the full sendmail binary API that needs to be implemented for program compatibility?
Answer: Option 1: Install (simple) "sendmail look alike"
As I understand you can use ssmtp (or msmtp) program/package to get "sendmail look alike" capable to pass messages to SMTP server (e.g. localhost:25).
https://wiki.archlinux.org/title/SSMTP
https://packages.debian.org/source/stable/ssmtp
Option 2: Use sendmail without starting sendmail daemon
Install sendmail package but block starting sendmail daemon.  Modern sendmail installations by default pass messages submitted by sendmail command via SMTP to localhost:25.
[It has been introduced to avoid security risks of installing sendmail as set root uid]
Comment: Thanks, looks like msmtp is the currently maintained alternative, and importantly it is sendmail interface compatible so it can just be symlinked. I guess it seems like sendmail itself can't be use to provide the sendmail interface in a non-invasive way, ironically...
Comment: ....or mutt, or nullmailer, or about 20 lines of bash script.
Comment: @InterLinked You can use sendmail too. Install it  but do not start sendmail daemon (block starting sendmail daemon).  Modern sendmail by default passes messages submitted by sendmail command to SMTP daemon localhost:25.


Como validar um maskedtextbox em branco?

Question: No caso o maskedtextboxTEL (00)0000-0000 devolveria um error provider e só prosseguiria após o preenchimento do mesmo.
Answer: Você pode utilizar o método String.IsNullOrWhiteSpace.
Código
 if (String.IsNullOrWhiteSpace(txt_Telefone.Text))
 {
    errorProvider1.SetError(txt_Telefone, "Preencha o telefone ! ");
 }

Comment: Acho que não vai funcionar, se for uma mask, vai ter vim o .Text preenchido com (00) 0000-0000
Comment: hmm.. pior que e mesmo em ... acha devo manter a resposta ? afinal não deixa de estar validando um conteúdo em branco né .o pior que o autor da pergunta parece ter abandonado o site =´(. Eu levei em consideração mais pelo titulo da pergunta dele mesmo.
Comment: Vamos esperar pra ver o que o autor da pergunta falou.


Googlescripts mergesort

Question: function MergeSort() {
var low = 1;
var mid = 2;
var high = 3;
var i, m, k, l;
temp[MAX] = new array();
l = low;
i = low;
m = mid+1;

while( 1 < = mid && m <= high ) {
    if(array[1] < = arr[m]) {
        temp[i] = arr[1];
        i++;
    }
    else {
        temp[i] = arr[m];
        m++;
    }
    i++;
  }
  if(1>mid) {
      for(k=m;k<=high;k++){
          temp[i]=arr[k];
          i++;
      }
  }
  else {
      for(k=1;k<=mid;k++) {
      temp[i]=arr[k];
      i++;
  }
}

for(k=low;k<=high;k++) {
    arr[k]=temp[k];
}

}
Coming from another language I am totally clueless, could someone point me in the right direction for taking a set of numbers and putting them in order via mergeSort? Thanks.
Answer: Here is an working example for Merge sort.
var array = [5, 2, 4, 7, 1, 3, 2, 6];

function merge(A, p, q, r){
   var n1 = q - p + 1;
   var n2 = r - q;
   var i = 0, j = 0, L = [], R = [];
   while (i < n1){
       L.push(A[p + i++]);
   }
   while(j < n2){
       R.push(A[q + j++ + 1]);
   }

   L.push(Number.MAX_VALUE);
   R.push(Number.MAX_VALUE);

   i = 0;
   j = 0;

   var k = p;
   while(k <= r){
       if(L[i] <= R[j]){
          A[k] = L[i];
          i = i + 1;
       }else{
          A[k] = R[j];
          j = j + 1;
   }
   k = k + 1;
}
}

function mergeSort(A, p, r){
if(p < r){
    var q = Math.floor((p + r) / 2);

    mergeSort(A, p, q);
    mergeSort(A, q + 1, r);
    merge(A, p, q, r);
}
}

function testMergeSort(){
   var p = 0;
   var r = (array.length) - 1;
   Logger.log("BEFORE: " + array);
   mergeSort(array, p, r);
   Logger.log("AFTER: " + array);
 }

Hope that helps!

Googlescripts mergesort