问:
How to store reactive outputs values in a vector to be used in a function?
This is an extension of the question

How to isolate the output of a reactive (function) and save to a data.frame?

Basically I want to construct a table based on a vector with predetermined  and added values. I want to show as tableoutput the original vector and a column with the roll mean of the previous 4 values of this vector. For instance, if the user added the value 200, I will have

```<code>d <- c(rep(100,4),200)
</code>```

and using zoo::rollapply() I have the roll mean of the previous 4 values of d

```<code>md <- rollapply(d , mean , fill = NA, width = list(-1:-4))
</code>```

the expected result

```<code>cbind(d,md)

       d  md
[1,] 100  NA
[2,] 100  NA
[3,] 100  NA
[4,] 100  NA
[5,] 200 100
</code>```

In my shiny app I am not able to use my function, the app close when I add a value. But if I use other function like input$c1 + 5 it works. I think that the problem is that I do not know how to capture the updated vector and use it to run a function that needs a vector as input. Furthermore, to run the app I needed to match the same number of rows in the new column.

Here is my UI code:

```<code>library(shiny)

fluidPage(
  sidebarPanel(textInput("c1","example"),

           actionButton("update", "Update Table")
  ),

 mainPanel(tableOutput("example")

 )
)
</code>```

and the server

```<code>library(shiny)
library(zoo)

function(input, output) {

  #Example
  d <- c(rep(100,4))
  m <- c(rep(100,4))

  md <- reactive(
 rollapply(values$df , mean , fill=NA , width=list(-1:-4))
 )

  values <- reactiveValues(df = data.frame('D' = d, 'M_D'= m))
  newEntry <- observe({
    if(input$update > 0) {
        values$df <- isolate(rbind(values$df,data.frame('D' =input$c1,
   'M_D' = md())))
    }
  })

  output$example <- renderTable({values$df})

}
</code>```

答:
So I would say were using too many different shiny mechanisms and they were tripping over each other. I made the following changes:

changed observe to observeEvent so as to confine the calculations to when you pres the update button.

did away with the isolate usage as it is not needed in an observeEvent as opposed to an observe.

got rid of the reactive md() function as you already have that data stored in a reactiveValues list.

made the rollingapply operate only on the relevant columns instead of the entire data frame.

cleaned up the syntax a bit - got rid if extraneous quotes, c() in  c(rep(...)), etc.

compressed it a bit.

added the as.numeric to the input$c1 processing otherwise it was causing that column to convert to a factor and change its values.

So here is the code:

```<code>library(shiny)
library(zoo)

u <- fluidPage(
  sidebarPanel(textInput("c1","example"),
               actionButton("update", "Update Table")
  ),
  mainPanel(tableOutput("example")
  )
)
s <- function(input, output) {

  #Example
  d <- rep(100,4)
  m <- rep(100,4)

  values <- reactiveValues(df = data.frame(D=d, M_D=m))

  newEntry <- observeEvent(input$update,{
    d_new <- c(values$df$D,as.numeric(input$c1))
    m_d_new <- rollapply(d_new, mean , fill=NA , width=list(-1:-4))
    values$df <- data.frame(D=d_new,M_D=m_d_new)
  })
  output$example <- renderTable({values$df})
}
shinyApp(u,s)
</code>```

Which yields the following after entering 200 and pressing Update Table a few times:

Body:
This is an extension of the question

How to isolate the output of a reactive (function) and save to a data.frame?

Basically I want to construct a table based on a vector with predetermined  and added values. I want to show as tableoutput the original vector and a column with the roll mean of the previous 4 values of this vector. For instance, if the user added the value 200, I will have

d <- c(rep(100,4),200)

and using zoo::rollapply() I have the roll mean of the previous 4 values of d

md <- rollapply(d , mean , fill = NA, width = list(-1:-4))

the expected result

cbind(d,md)

       d  md
[1,] 100  NA
[2,] 100  NA
[3,] 100  NA
[4,] 100  NA
[5,] 200 100

In my shiny app I am not able to use my function, the app close when I add a value. But if I use other function like input$c1 + 5 it works. I think that the problem is that I do not know how to capture the updated vector and use it to run a function that needs a vector as input. Furthermore, to run the app I needed to match the same number of rows in the new column.

Here is my UI code:

library(shiny)

fluidPage(
  sidebarPanel(textInput("c1","example"),

           actionButton("update", "Update Table")
  ),

 mainPanel(tableOutput("example")

 )
)

and the server

library(shiny)
library(zoo)

function(input, output) {

  #Example
  d <- c(rep(100,4))
  m <- c(rep(100,4))

  md <- reactive(
 rollapply(values$df , mean , fill=NA , width=list(-1:-4))
 )

  values <- reactiveValues(df = data.frame('D' = d, 'M_D'= m))
  newEntry <- observe({
    if(input$update > 0) {
        values$df <- isolate(rbind(values$df,data.frame('D' =input$c1,
   'M_D' = md())))
    }
  })

  output$example <- renderTable({values$df})

}

Body:
So I would say were using too many different shiny mechanisms and they were tripping over each other. I made the following changes:

changed observe to observeEvent so as to confine the calculations to when you pres the update button.

did away with the isolate usage as it is not needed in an observeEvent as opposed to an observe.

got rid of the reactive md() function as you already have that data stored in a reactiveValues list.

made the rollingapply operate only on the relevant columns instead of the entire data frame.

cleaned up the syntax a bit - got rid if extraneous quotes, c() in  c(rep(...)), etc.

compressed it a bit.

added the as.numeric to the input$c1 processing otherwise it was causing that column to convert to a factor and change its values.

So here is the code:

library(shiny)
library(zoo)

u <- fluidPage(
  sidebarPanel(textInput("c1","example"),
               actionButton("update", "Update Table")
  ),
  mainPanel(tableOutput("example")
  )
)
s <- function(input, output) {

  #Example
  d <- rep(100,4)
  m <- rep(100,4)

  values <- reactiveValues(df = data.frame(D=d, M_D=m))

  newEntry <- observeEvent(input$update,{
    d_new <- c(values$df$D,as.numeric(input$c1))
    m_d_new <- rollapply(d_new, mean , fill=NA , width=list(-1:-4))
    values$df <- data.frame(D=d_new,M_D=m_d_new)
  })
  output$example <- renderTable({values$df})
}
shinyApp(u,s)

Which yields the following after entering 200 and pressing Update Table a few times:


来源: stackexchange

问:
Validating a String in a Class List C#
Im making a project in C# Console Application and it is a Sports Club Management Software for school. I created a Class List Athletes and I got several paramenters, one of it is the Athlete's ID... My question is, when I choose the "Add Athlete" option, how can I check if there´s already an ID in the whole list. You probably thinking: "Ohh... Well its preety ez, just a do while, and a for method in it and use the Contain method..." Well Ive tryed that and I didn't quite got it... Ive been programming for some months now... Its not that I am a very skilled programmer but :/ ...

This is what I tryed doing:

```<code>    do
    {
        for (int i = 0; i < Athletes.Count; i++)
        {
            if (Athletes[i].id.Contains(id))
            {
                Console.WriteLine("ID already exists, please insert another ID!");
                Console.WriteLine();
                Console.Write("Id: ");
                id = Console.ReadLine();
            }
        }
    } while (Athletes[i]);
</code>```

the thing is, as you can see, I cant use the [i] in the do while what makes it impossible to go through the list. I thought about getting a boolean but Im not really into booleans. Its probably a preety ez to fix problem but I really cant figger it out. Thanks guys. :)

答:
Try using Linq:

```<code>  using System.Linq;

  ...

  // Keep asking id...
  while (true) {
    if (!Athletes.Any(athlete => athlete.ID == id))
      break; // ... until id is not found

    Console.WriteLine("ID already exists, please insert another ID!");
    Console.WriteLine();
    Console.Write("Id: ");

    id = Console.ReadLine();
    //TODO: validate id here
 }
</code>```

Please notice, that you have to validate the user input: what if user write, say "bla-bla-blas" as id?

ContentLicense: CC BY-SA 3.0

Title: Validating a String in a Class List C#

Body:
Im making a project in C# Console Application and it is a Sports Club Management Software for school. I created a Class List Athletes and I got several paramenters, one of it is the Athlete's ID... My question is, when I choose the "Add Athlete" option, how can I check if there´s already an ID in the whole list. You probably thinking: "Ohh... Well its preety ez, just a do while, and a for method in it and use the Contain method..." Well Ive tryed that and I didn't quite got it... Ive been programming for some months now... Its not that I am a very skilled programmer but :/ ...

This is what I tryed doing:

    do
    {
        for (int i = 0; i < Athletes.Count; i++)
        {
            if (Athletes[i].id.Contains(id))
            {
                Console.WriteLine("ID already exists, please insert another ID!");
                Console.WriteLine();
                Console.Write("Id: ");
                id = Console.ReadLine();
            }
        }
    } while (Athletes[i]);

the thing is, as you can see, I cant use the [i] in the do while what makes it impossible to go through the list. I thought about getting a boolean but Im not really into booleans. Its probably a preety ez to fix problem but I really cant figger it out. Thanks guys. :)

Body:
Try using Linq:

  using System.Linq;

  ...

  // Keep asking id...
  while (true) {
    if (!Athletes.Any(athlete => athlete.ID == id))
      break; // ... until id is not found

    Console.WriteLine("ID already exists, please insert another ID!");
    Console.WriteLine();
    Console.Write("Id: ");

    id = Console.ReadLine();
    //TODO: validate id here
 }

Please notice, that you have to validate the user input: what if user write, say "bla-bla-blas" as id?


问:
When should I use old( key, value) on blade template ? Is it necessary in latest laravel version?
I noticed that in the older laravel blade template it was recommended to use old (key, value) to retrieve old values when form validation fails. (controller method handling the validation will post back to the form with the as-is data in request object)

Is it still necessary to use it in the latest laravel version ?

When should one use the old (key, value) function on the form fields on laravel blade template?

答:
In Laravel there is a convention that most "get me some value" like functions provide a way to cover case "there is no value to get", therefore signature of most getter like functions looks like:

```<code>get('key', $default = null)
</code>```

So in your case you would want to use old('key', default) in:

create form when you as programmer set valid default value (not placeholder), perhaps date of some action for "today/now" old('publish_at', Carbon::now()).

edit form old('publish_at', $post->publish_at), which means that on first load of edit form input field is pre-populated with data from database

Body:
In Laravel there is a convention that most "get me some value" like functions provide a way to cover case "there is no value to get", therefore signature of most getter like functions looks like:

get('key', $default = null)

So in your case you would want to use old('key', default) in:

create form when you as programmer set valid default value (not placeholder), perhaps date of some action for "today/now" old('publish_at', Carbon::now()).

edit form old('publish_at', $post->publish_at), which means that on first load of edit form input field is pre-populated with data from database


问:
Display XSL Formatted XML on a Control
I have XML files formatted with XSL. They look great on IE.

Now how do I do the same with Flex (not AIR)? I would like to use something like TextArea and not data grid.

Thanks.

答:
I think I can use JavaScript to do the transformation. So my Flex application passes the XML and XSL URLs to a JavaScript. The JavaScript does the XML-XSL transformation. And it should pass the transformed HTML back to Flex, so my Flex application can popup a TextArea (or similar) to display it.

I think I am getting close. But the problem at the moment is, the transformed HTML seems to be null/empty. Any ideas?

```<code>function loadXMLDoc(dname)
{
  if (window.XMLHttpRequest)
  {
    xhttp=new XMLHttpRequest();
  }
  else
  {
    xhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xhttp.open("GET",dname,false);
  xhttp.send("");
  return xhttp.responseXML;
}

function displayResult(xmlURL, xslURL)
{
  //prepare xml and xsl
  xml=loadXMLDoc(xmlURL);
  xsl=loadXMLDoc(xslURL);

  //get flash
  var isIE = navigator.appName.indexOf("Microsoft") != -1;
  var flashName = "index";
  var flashObject = (isIE) ? window[flashName] : document[flashName];

  // code for IE
  if (window.ActiveXObject)
  {
    ex=xml.transformNode(xsl);
    flashObject.GetTransformedHTML(ex);
  }
  // code for Mozilla, Firefox, Opera, etc.
  else if (document.implementation && document.implementation.createDocument)
  {
    xsltProcessor=new XSLTProcessor();
    xsltProcessor.importStylesheet(xsl);
    resultDocument = xsltProcessor.transformToFragment(xml,document);
    document.getElementById("example").appendChild(resultDocument);
  }
}
</code>```

Thanks.

ContentLicense: CC BY-SA 2.5

Title: Display XSL Formatted XML on a Control

Body:
I think I can use JavaScript to do the transformation. So my Flex application passes the XML and XSL URLs to a JavaScript. The JavaScript does the XML-XSL transformation. And it should pass the transformed HTML back to Flex, so my Flex application can popup a TextArea (or similar) to display it.

I think I am getting close. But the problem at the moment is, the transformed HTML seems to be null/empty. Any ideas?

function loadXMLDoc(dname)
{
  if (window.XMLHttpRequest)
  {
    xhttp=new XMLHttpRequest();
  }
  else
  {
    xhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xhttp.open("GET",dname,false);
  xhttp.send("");
  return xhttp.responseXML;
}

function displayResult(xmlURL, xslURL)
{
  //prepare xml and xsl
  xml=loadXMLDoc(xmlURL);
  xsl=loadXMLDoc(xslURL);

  //get flash
  var isIE = navigator.appName.indexOf("Microsoft") != -1;
  var flashName = "index";
  var flashObject = (isIE) ? window[flashName] : document[flashName];

  // code for IE
  if (window.ActiveXObject)
  {
    ex=xml.transformNode(xsl);
    flashObject.GetTransformedHTML(ex);
  }
  // code for Mozilla, Firefox, Opera, etc.
  else if (document.implementation && document.implementation.createDocument)
  {
    xsltProcessor=new XSLTProcessor();
    xsltProcessor.importStylesheet(xsl);
    resultDocument = xsltProcessor.transformToFragment(xml,document);
    document.getElementById("example").appendChild(resultDocument);
  }
}

Thanks.


问:
Alignment of price's location using CSS (Woo commerce Store)
Problem with the alignement of price with the name(heading)

CSS Code

```<code>.mgrt-product-title .price {
 padding-left: 749px;
 font-weight: bold;
 color:#000;
}
</code>```

You can check the present alignment here - my store. How to align prices to be all in the same line?

答:
Here you need to make changes in padding, as your padding is to left depending on the size of the text your location of price varies. Keep padding from right and it will be set</p>

```<code>.mgrt-product-title .price {
 float :right;
 padding-right: 100px;
 font-weight: bold;
 color:#000;
 }
</code>```

Body:
Problem with the alignement of price with the name(heading)

CSS Code

.mgrt-product-title .price {
 padding-left: 749px;
 font-weight: bold;
 color:#000;
}

You can check the present alignment here - my store. How to align prices to be all in the same line?

Body:
Here you need to make changes in padding, as your padding is to left depending on the size of the text your location of price varies. Keep padding from right and it will be set

.mgrt-product-title .price {
 float :right;
 padding-right: 100px;
 font-weight: bold;
 color:#000;
 }


问:
Best approach for loading balancing SQL Server 2016 Database and Reporting Services Loads
So I'm working on a small .NET project that has 4 Production servers:

Web

App

Database ((SQL Server 2016 Enterprise)

Reporting (Sql Server Reporting Services 2016)

After a recent outage, we installed a secondary replica SQL Server DB instance on our Report server as a High Availability Cluster. We intend in the near future to install SSRS on our original Database server, so we have complete failover if either server goes down.

I think there is an opportunity to more efficiently utilize the computing resources of both servers through load balancing database connections and SSRS loads.

Database load balancing ideas:

Write connections will have to be directed to the primary node in the cluster, but read-only connections can go to either, with an increasing preference for the secondary replica as the write connection load on the primary database node increases.

Database calls can originate from SSRS and from my .NET application, and well be sent to the High Availability Listener.

Database operations tend to be I/O heavy, and relatively light-medium CPU intensive.

SSRS load balancing ideas:

Report requests have 2 stages: data retrieval, and UI rendering. Both components could (theoretically) be individually load balanced to either server.

SSRS Report rending (not including data retrieval, but including any grouping and data processing within SSRS) is relatively medium-high on CPU utilization, and minimal IO.

I know there are load balancing solutions available that can load balance database calls and SSRS in isolation, but are there any products/solutions that can load balance database and SSRS loads together? That is evaluate the total load on each server and select the best server to execute each additional request the load balancing solution receives?

Here is a quick diagram:

In this picture, the SSRS load balancer and High Availability Listener are both on the App server. The primary database node is on top, labeled as 'Database 2', and the secondary replica is on the bottom sever in the diagram, labeled as 'Database 1'. Both database servers have SSRS installed.

-PS: We are currently budget limited to just these 4 Production servers, and we're trying to make the best use of these as we can :) These servers are all VMs, and the database servers have 4 vCPUs and 64 GB of RAM. The App Server also has 4vCPUs and 32 GB of RAM.

答:
This isn't too detailed in afraid but I've got nothing but great things to say about SSRS scale out deployments.

Let the reporting services engine decide what's best to balance load. It will work around the sql engine.
If you have a hardware load balancer for the front end, even better. I don't want to spam blog posts here but I wrote about that set up in more detail. Let me know if you want the link.
In my opinion any third party app would just complicate your environment.

Thanks, Craig


答:
Do you mean that Athletes is a List<Athlete> or something of that nature?  You can check if any member of a generic list meets a given predicate with .Any().  For example:

```<code>if (Athletes.Any(a => a.id == id))
</code>```

If Any() returns true then that means at least one member of the list satisfies the condition.

Title: Validating a String in a Class List C#

Body:
Do you mean that Athletes is a List<Athlete> or something of that nature?  You can check if any member of a generic list meets a given predicate with .Any().  For example:

if (Athletes.Any(a => a.id == id))

If Any() returns true then that means at least one member of the list satisfies the condition.


问:
jQuery Serialize working intermittently with Bootstrap radio button group
I'm trying to serialize a radio-button when the Bootstrap .btn label is clicked.

HTML:

```<code><div class="btn-group" data-toggle="buttons">
    <label label-default="" class="btn btn-primary">
        <input id="option1" name="options" type="radio" value="1">Option 1</label>
    <label label-default="" class="btn btn-primary active">
        <input id="option2" name="options" type="radio" value="1">Option 2</label>
    <label label-default="" class="btn btn-primary">
        <input id="option3" name="options" type="radio" value="1">Option 3</label>
</div>
</code>```

jQuery:

```<code>$(".btn").on('click', function(){
  console.log("Name: " + $(this).children('input').attr('name') );
  console.log("Value: " + $(this).children('input').val() );
  console.log("Serialized: " +  $(this).children('input').serialize() );
})
</code>```

The name and value are always present in my output but the serialization works intermittently (sometimes returning the serialzed value and sometimes returing an empty string) and I can't figure out why.

Demo here: http://www.bootply.com/86422#

Thanks!

答:
jQuery .serialize() and .serializeArray() will only parse buttons which are checked. These are known as "successful controls", as mentioned in the jQuery documentation.

If you'd like to use a Bootstrap button group where all buttons are unchecked (as seen in your question), then you should consider "What if a user never checks any of the buttons?".

Therefore, you should include a hidden button which is checked by default, so that at least one of the buttons in your button group is parsed by .serialize() or .serializeArray().

<form>

    <input class="hidden" type="radio" name="color" value="none" checked>

        <input type="radio" name="color" value="blue" />
        Blue

        <input type="radio" name="color" value="green" />
        Green

</form>
```

Body:
I'm trying to serialize a radio-button when the Bootstrap .btn label is clicked.

HTML:

        <input id="option1" name="options" type="radio" value="1">Option 1

        <input id="option2" name="options" type="radio" value="1">Option 2

        <input id="option3" name="options" type="radio" value="1">Option 3

jQuery:

$(".btn").on('click', function(){
  console.log("Name: " + $(this).children('input').attr('name') );
  console.log("Value: " + $(this).children('input').val() );
  console.log("Serialized: " +  $(this).children('input').serialize() );
})

The name and value are always present in my output but the serialization works intermittently (sometimes returning the serialzed value and sometimes returing an empty string) and I can't figure out why.

Demo here: http://www.bootply.com/86422#

Thanks!

Body:
jQuery .serialize() and .serializeArray() will only parse buttons which are checked. These are known as "successful controls", as mentioned in the jQuery documentation.

If you'd like to use a Bootstrap button group where all buttons are unchecked (as seen in your question), then you should consider "What if a user never checks any of the buttons?".

Therefore, you should include a hidden button which is checked by default, so that at least one of the buttons in your button group is parsed by .serialize() or .serializeArray().

<form>
  <div class="form-group">

    <!--
      This hidden checked button (with value 'none')
      will ensure that `serialize` parses at least one
      input in the button group.
    -->
    <input class="hidden" type="radio" name="color" value="none" checked>

    <div class="btn-group" data-toggle="buttons">
      <label class="btn btn-default">
        <input type="radio" name="color" value="blue" />
        <span>Blue</span>
      </label>
      <label class="btn btn-default">
        <input type="radio" name="color" value="green" />
        <span>Green</span>
      </label>
    </div>

  </div>
</form>

ContentLicense: CC BY-SA 4.0


问:
Microsoft Bot Framework Privacy/Encryption
On looking at privacy for the bot I built using Microsoft Bot Framework I noticed this:

to provide the I/O service, the Bot Framework transmits your message and message content (including your ID), from the chat service you used to the bot.

I'm concerned about any messages that are sent to my bot being sent in the clear.
Has anyone considered and/or implemented encryption in order to maintain the privacy of the messages in their bot? Or does anyone have any other solution?

答: When you register your chatbot, it requires an https endpoint. So, your message won't be sent in the clear. Additionally, you must generate an API key and a private password key for secure access to your chatbot so that only the Bot Connector can communicate. Make sure you secure your private keys so no one else can access your chatbot.</p>


问:
jquery shows hidden div only a few milliseconds
The div nav--contentoverlay and div test only show a few milliseconds and then disappear.How do they show until the next click on one of both?

$(function() {

    $(".js--toggle").click(function() {

/* this functions ($(".test … and $("body … don't work as expected */

        $(".test,.nav--contentoverlay").addClass("js--transition__open");
        $("body").css("overflow", "hidden");
        });
        $(".test,.nav--contentoverlay").click(function() {
            $(".test,.nav--contentoverlay").removeClass("js--transition__open");
            $("body").css("overflow", "auto");
        });

    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.test {
        width: 320px;
        height: 480px;
        background: white;
        position: absolute;
        top: 50%;
        left: 50%;
        margin: -240px 0 0 -160px;
        border: 1px solid #666;
        z-index: 999;
        visibility: hidden
    }

    .nav--contentoverlay {
        position: fixed;
        z-index: 1;
        bottom: 0;
        top: 0;
        left: 0;
        right: 0;
        background: black;
        opacity: 0.4!important;
        z-index: 7;
        visibility: hidden;
    }

    .js--transition__open {
        visibility: visible;
        opacity: 1;
        transition: opacity 0.5s ease;
    }</code>```

<!doctype html>

    <title>test</title>
    <meta charset="utf-8">
    <link rel="shortcut icon" href="favicon.ico">

test

Test

```

答:
.js--toggle is a link, so the page is following the link (refreshing the page) when you click on it. You need to disable the default action of the link by passing the event to your function in the click handler and using preventDefault()

$(function() {
  $(".js--toggle").click(function(e) {
    e.preventDefault();
    /* this functions ($(".test … and $("body … don't work as expected */
    $(".test,.nav--contentoverlay").addClass("js--transition__open");
    $("body").css("overflow", "hidden");
  });
  $(".test,.nav--contentoverlay").click(function() {
    $(".test,.nav--contentoverlay").removeClass("js--transition__open");
    $("body").css("overflow", "auto");
    console.log('closed');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.test {
  width: 320px;
  height: 480px;
  background: white;
  position: absolute;
  top: 50%;
  left: 50%;
  margin: -240px 0 0 -160px;
  border: 1px solid #666;
  z-index: 999;
  visibility: hidden
}

.nav--contentoverlay {
  position: fixed;
  z-index: 1;
  bottom: 0;
  top: 0;
  left: 0;
  right: 0;
  background: black;
  opacity: 0.4!important;
  z-index: 7;
  visibility: hidden;
}

.js--transition__open {
  visibility: visible;
  opacity: 1;
  transition: opacity 0.5s ease;
}</code>```

<!doctype html>

  <title>test</title>
  <meta charset="utf-8">
  <link rel="shortcut icon" href="favicon.ico">

test

Test

```

Body:
The div nav--contentoverlay and div test only show a few milliseconds and then disappear.How do they show until the next click on one of both?

$(function() {

    $(".js--toggle").click(function() {

/* this functions ($(".test … and $("body … don't work as expected */

        $(".test,.nav--contentoverlay").addClass("js--transition__open");
        $("body").css("overflow", "hidden");
        });
        $(".test,.nav--contentoverlay").click(function() {
            $(".test,.nav--contentoverlay").removeClass("js--transition__open");
            $("body").css("overflow", "auto");
        });

    });

.test {
        width: 320px;
        height: 480px;
        background: white;
        position: absolute;
        top: 50%;
        left: 50%;
        margin: -240px 0 0 -160px;
        border: 1px solid #666;
        z-index: 999;
        visibility: hidden
    }

    .nav--contentoverlay {
        position: fixed;
        z-index: 1;
        bottom: 0;
        top: 0;
        left: 0;
        right: 0;
        background: black;
        opacity: 0.4!important;
        z-index: 7;
        visibility: hidden;
    }

    .js--transition__open {
        visibility: visible;
        opacity: 1;
        transition: opacity 0.5s ease;
    }

<!doctype html>

    <title>test</title>
    <meta charset="utf-8">
    <link rel="shortcut icon" href="favicon.ico">

test

Test

Body:
.js--toggle is a link, so the page is following the link (refreshing the page) when you click on it. You need to disable the default action of the link by passing the event to your function in the click handler and using preventDefault()

$(function() {
  $(".js--toggle").click(function(e) {
    e.preventDefault();
    /* this functions ($(".test … and $("body … don't work as expected */
    $(".test,.nav--contentoverlay").addClass("js--transition__open");
    $("body").css("overflow", "hidden");
  });
  $(".test,.nav--contentoverlay").click(function() {
    $(".test,.nav--contentoverlay").removeClass("js--transition__open");
    $("body").css("overflow", "auto");
    console.log('closed');
  });
});

.test {
  width: 320px;
  height: 480px;
  background: white;
  position: absolute;
  top: 50%;
  left: 50%;
  margin: -240px 0 0 -160px;
  border: 1px solid #666;
  z-index: 999;
  visibility: hidden
}

.nav--contentoverlay {
  position: fixed;
  z-index: 1;
  bottom: 0;
  top: 0;
  left: 0;
  right: 0;
  background: black;
  opacity: 0.4!important;
  z-index: 7;
  visibility: hidden;
}

.js--transition__open {
  visibility: visible;
  opacity: 1;
  transition: opacity 0.5s ease;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!doctype html>
<html lang="en">

<head>
  <title>test</title>
  <meta charset="utf-8">
  <link rel="shortcut icon" href="favicon.ico">
</head>

<body>
  <div class="page">
    <div class="contentholder">
      <nav class="nav--global">
        <ul>
          <li><a href="" class="js--toggle" title="">test</a></li>
        </ul>
      </nav>
    </div>
  </div>

  <nav class="nav--contentoverlay"></nav>
  <div class="test">Test</div>
</body>

</html>


问:
Understanding Basic Python Logic and Flow of Operations (a, b = b, a+b)
I am trying to understand the code provided on the Python.org tutorial in section 3.2

```<code>a, b = 0, 1
>>> while b < 10:
...     print(b)
...     a, b = b, a+b
</code>```

The code above results in the sequence as follows:

```<code>1
1
2
3
5
8
</code>```

My questions are as follows:

Why do the numbers appear vertically and not horizontally like a print statement generally does?  I know you can force the numbers to appear horizontally but want to understand why that is not the default.

Most importantly, how is the python logic working?  I understand its the fibonacci sequence but you're only asking the code to print "b".  It should just print a+b over and over again, should it not (resulting in 1 being printed over and over again)?  I don't understand how the logic within python progresses the sequence.

Any help is much appreciated.  Thank you.

答:
The python print statement by default generates a newline after each print.
This causes each printed item to appear on its own line. If you print a literal newline, you get two blank lines:

```<code>>>> print "\n"

>>>
</code>```

Most importantly, how is the python logic working? I understand its
  the fibonacci sequence but you're only asking the code to print "b".
  It should just print a+b over and over again, should it not (resulting
  in 1 being printed over and over again)?

This line:

```<code>a, b = b, a+b
</code>```

evaluates the expressions b and a+b. If b=1 and a=0, then this results in the tuple (1, 1). That tuple is then split into its two components and assigned respectively to the variables a and b. So at the end of the first iteration, a and b each get the value 1. This is ultimately equivalent to the successive operations

```<code>tmp = b
b = a + b
a = tmp
</code>```

but notice that here we have to create a temp variable to hold the original value of b. This is because the one-liner evaluates both of the expressions on its right-hand side before it assigns to the variables named on the left-hand side.

Body:
I am trying to understand the code provided on the Python.org tutorial in section 3.2

a, b = 0, 1
>>> while b < 10:
...     print(b)
...     a, b = b, a+b

The code above results in the sequence as follows:

1
1
2
3
5
8

My questions are as follows:

Why do the numbers appear vertically and not horizontally like a print statement generally does?  I know you can force the numbers to appear horizontally but want to understand why that is not the default.

Most importantly, how is the python logic working?  I understand its the fibonacci sequence but you're only asking the code to print "b".  It should just print a+b over and over again, should it not (resulting in 1 being printed over and over again)?  I don't understand how the logic within python progresses the sequence.

Any help is much appreciated.  Thank you.

Body:
The python print statement by default generates a newline after each print.
This causes each printed item to appear on its own line. If you print a literal newline, you get two blank lines:

>>> print "\n"

>>>

Most importantly, how is the python logic working? I understand its
  the fibonacci sequence but you're only asking the code to print "b".
  It should just print a+b over and over again, should it not (resulting
  in 1 being printed over and over again)?

This line:

a, b = b, a+b

evaluates the expressions b and a+b. If b=1 and a=0, then this results in the tuple (1, 1). That tuple is then split into its two components and assigned respectively to the variables a and b. So at the end of the first iteration, a and b each get the value 1. This is ultimately equivalent to the successive operations

tmp = b
b = a + b
a = tmp

but notice that here we have to create a temp variable to hold the original value of b. This is because the one-liner evaluates both of the expressions on its right-hand side before it assigns to the variables named on the left-hand side.


问:
Php: Function to replace all chars except valid RFC 3986
Looking for a simple validation script that will replace all chars in a string except RFC 3986 valid chars

A-Z, a-z, 0-9, -, ., _, ~, :, /, ?, #, [, ], @, !, $, &, ', (, ), *, +, ,, ; and =. Also any other character needs to be encoded with the percent-encoding (%hh)

答: rawurlencode()</p>

Body: rawurlencode()


问:
Cannot get GELF Appender to add Sleuth Span Id
I am trying to get the Sleuth Span-Id and Trace-Id included as additonalFields in my logback-sping.xml GELF appeneder but am having no luck.  They show up fine in the actual log file output in the Console, but in Graylog they don't show up.  NOTE : the profile works just fine.

```<code><property name="CONSOLE_LOG_PATTERN" value="%date{ISO8601} [${springProfile}] [${springAppName:-},%X{X-B3-TraceId:-},%X{X-B3-SpanId:-},%X{X-Span-Export:-}] [%level] [${PID}] [%X{bindName}] [%thread] [%logger{10}] : %msg%n %ex{20}"/>

<springProfile name="integration,qa,prod">
    <appender name="GELF" class="biz.paluch.logging.gelf.logback.GelfLogbackAppender">
        <graylogHost>${graylogProtocol}:${graylogHost}</graylogHost>
        <graylogPort>${graylogPort}</graylogPort>
        <facility>${springAppName}</facility>
        <additionalFields>profile=${springProfile},traceid=%X{X-B3-TraceId:-},spanid=%X{X-B3-SpanId:-}</additionalFields>
        <extractStackTrace>true</extractStackTrace>
        <filterStackTrace>true</filterStackTrace>
        <maximumMessageSize>8192</maximumMessageSize>
        <timestampPattern>yyyy-MM-dd HH:mm:ss,SSSS</timestampPattern>
    </appender>
</springProfile>
</code>```

Also tried this:

```<code>        <additionalFields>profile=${springProfile},traceid=${X-B3-TraceId},spanid=${X-B3-SpanId}</additionalFields>
</code>```

No luck.

答:
Additional fields are static. They might get pre-processed by applying system properties but don't extract values from the MDC (%X).

Use mdcFields for this purpose:

```<code><mdcFields>X-B3-TraceId,X-B3-SpanId</mdcFields>
</code>```

mdcFields does not support field naming of included MDC fields (e.g. traceid=X-B3-TraceId does not work).

Documentation: http://logging.paluch.biz/examples/logback.html

Body:
I am trying to get the Sleuth Span-Id and Trace-Id included as additonalFields in my logback-sping.xml GELF appeneder but am having no luck.  They show up fine in the actual log file output in the Console, but in Graylog they don't show up.  NOTE : the profile works just fine.

<property name="CONSOLE_LOG_PATTERN" value="%date{ISO8601} [${springProfile}] [${springAppName:-},%X{X-B3-TraceId:-},%X{X-B3-SpanId:-},%X{X-Span-Export:-}] [%level] [${PID}] [%X{bindName}] [%thread] [%logger{10}] : %msg%n %ex{20}"/>

<springProfile name="integration,qa,prod">
    <appender name="GELF" class="biz.paluch.logging.gelf.logback.GelfLogbackAppender">
        <graylogHost>${graylogProtocol}:${graylogHost}</graylogHost>
        <graylogPort>${graylogPort}</graylogPort>
        <facility>${springAppName}</facility>
        <additionalFields>profile=${springProfile},traceid=%X{X-B3-TraceId:-},spanid=%X{X-B3-SpanId:-}</additionalFields>
        <extractStackTrace>true</extractStackTrace>
        <filterStackTrace>true</filterStackTrace>
        <maximumMessageSize>8192</maximumMessageSize>
        <timestampPattern>yyyy-MM-dd HH:mm:ss,SSSS</timestampPattern>
    </appender>
</springProfile>

Also tried this:

        <additionalFields>profile=${springProfile},traceid=${X-B3-TraceId},spanid=${X-B3-SpanId}</additionalFields>

No luck.

Body:
Additional fields are static. They might get pre-processed by applying system properties but don't extract values from the MDC (%X).

Use mdcFields for this purpose:

<mdcFields>X-B3-TraceId,X-B3-SpanId</mdcFields>

mdcFields does not support field naming of included MDC fields (e.g. traceid=X-B3-TraceId does not work).

Documentation: http://logging.paluch.biz/examples/logback.html


问:
Nested Permutations from Model
I'm writing a program that takes a permutations "model" of strings, and outputs all permutations according to that model. The model looks something like this:

```<code>model = Mix([
    [
        "this",
        PickOne(["is", "isn't"])
    ],
    PickOne([
        Mix([
            "absolutely",
            "great"
        ])
    ])
])
</code>```

Within the outputted permutations,

list objects will output the containing objects in sequence

Mix objects will output the containing objects in every possible order with ever possible max length (including zero)

PickOne objects will output only one of its containing objects at a time

So, the desired output of the above example would be:

```<code>[
    ["this", "is"],
    ["this", "isn't"],
    ["this", "is", "absolutely"],
    ["this", "is", "great"],
    ["this", "isn't", "absolutely"],
    ["this", "isn't", "great"],
    ["absolutely"],
    ["great"],
    ["absolutely", "this", "is"],
    ["great", "this", "is"],
    ["absolutely", "this", "isn't"],
    ["great", "this", "isn't"],
    []
]
</code>```

So far, I've implemented the permutations for the Mix class like this:

```<code>class Mix(list):
    def __init__(self, *args, **kwargs):
        super(Mix, self).__init__(*args, **kwargs)
        self.permutations = []
        for L in range(0, len(self)+1):
            for subset in itertools.combinations(self, L):
                subset_permutations = itertools.permutations(subset)
                self.permutations.extend(subset_permutations)
</code>```

and my PickOne class is simply this

```<code>class PickOne(list):
    pass
</code>```

which I'm planning on just testing for in my main function and handling accordingly (if type(obj) is PickOne: ...).

itertools provides simplification and efficiency for simpler use-cases, however I'm at a loss on how it will help me for this implementation (beyond what I already implemented in Mix). Any ideas of how itertools can be used to help in a Pythonic implementation of the above?

答:
I'm having some troubles wrapping my head around all those combinations, but I think your Mix class also has to yield the product of all those permutations. I've created a similar model to test this. This might work a bit different than yours, but it should be easy to adapt:

```<code>class CombModel:
    def __init__(self, *options):
        self.options = options

class Atom(CombModel):
    def __iter__(self):
        for x in self.options:
            yield x

class All(CombModel):
    def __iter__(self):
        for prod in itertools.product(*self.options):
            yield prod

class One(CombModel):
    def __iter__(self):
        for x in self.options:
            for y in x:
                yield y

class Mix(CombModel):
    def __iter__(self):
        for n in range(len(self.options) + 1):
            for perm in itertools.permutations(self.options, n):
                for prod in itertools.product(*perm):
                    yield prod
</code>```

The CombModel only provides a var-arg constructor for all the sub-classes. Atom is a "leaf" in the model and it's there so that I can "iterate" even over single strings or integers. This saves some if/else logic in all the other classes. All is what seem to be plain lists in your model, yielding the product of the different options. One and Mix correspond to your PickOne and Mix.

Using this rather simple model comb = Mix(All(Atom(1), Atom(21, 22)), One(Atom(31, 32), Atom(4))) I get the these combinations:

```<code>()
((1, 21),)
((1, 22),)
(31,)
(32,)
(4,)
((1, 21), 31)
((1, 21), 32)
((1, 21), 4)
((1, 22), 31)
((1, 22), 32)
((1, 22), 4)
(31, (1, 21))
(31, (1, 22))
(32, (1, 21))
(32, (1, 22))
(4, (1, 21))
(4, (1, 22))
</code>```

Your model translates to this:

```<code>model = Mix(
    All(
        Atom("this"),
        One(Atom("is"), Atom("isn't"))
    ),
    One(
        Mix(
            Atom("absolutely"),
            Atom("great")
        )
    )
)
</code>```

And gives those combinations:

```<code>()
(('this', 'is'),)
(('this', "isn't"),)
((),)
(('absolutely',),)
(('great',),)
(('absolutely', 'great'),)
(('great', 'absolutely'),)
(('this', 'is'), ())
(('this', 'is'), ('absolutely',))
(('this', 'is'), ('great',))
(('this', 'is'), ('absolutely', 'great'))
(('this', 'is'), ('great', 'absolutely'))
(('this', "isn't"), ())
(('this', "isn't"), ('absolutely',))
(('this', "isn't"), ('great',))
(('this', "isn't"), ('absolutely', 'great'))
(('this', "isn't"), ('great', 'absolutely'))
((), ('this', 'is'))
((), ('this', "isn't"))
(('absolutely',), ('this', 'is'))
(('absolutely',), ('this', "isn't"))
(('great',), ('this', 'is'))
(('great',), ('this', "isn't"))
(('absolutely', 'great'), ('this', 'is'))
(('absolutely', 'great'), ('this', "isn't"))
(('great', 'absolutely'), ('this', 'is'))
(('great', 'absolutely'), ('this', "isn't"))
</code>```

Note that those are still nested lists (or tuples, actually), but those can easily be flattened afterwards. Also, there are a few pseudo-duplicates (that would be duplicates when flattened) due to the "zero or more" nature of Mix. But apart from that, this looks rather close to your expected output.

On closer inspection, it might indeed be necesary to flatten first, so that PickOne will select only one from the Mix and not the entire Mix...

```<code>class All(CombModel):
    def __iter__(self):
        for prod in itertools.product(*self.options):
            yield flat(prod) # flatten here

class One(CombModel):
    def __iter__(self):
        for x in self.options:
            for y in flat(x): # flatten here
                yield y

class Mix(CombModel):
    def __iter__(self):
        for n in range(len(self.options) + 1):
            for perm in itertools.permutations(self.options, n):
                for prod in itertools.product(*perm):
                    yield flat(prod) # flatten here
</code>```

After weeding out the duplicates, the result is this:

```<code>()
('absolutely',)
('absolutely', 'this', 'is')
('absolutely', 'this', "isn't")
('great',)
('great', 'this', 'is')
('great', 'this', "isn't")
('this', 'is')
('this', 'is', 'absolutely')
('this', 'is', 'great')
('this', "isn't")
('this', "isn't", 'absolutely')
('this', "isn't", 'great')
</code>```

Title: Nested Permutations from Model

Body:
I'm writing a program that takes a permutations "model" of strings, and outputs all permutations according to that model. The model looks something like this:

model = Mix([
    [
        "this",
        PickOne(["is", "isn't"])
    ],
    PickOne([
        Mix([
            "absolutely",
            "great"
        ])
    ])
])

Within the outputted permutations,

list objects will output the containing objects in sequence

Mix objects will output the containing objects in every possible order with ever possible max length (including zero)

PickOne objects will output only one of its containing objects at a time

So, the desired output of the above example would be:

[
    ["this", "is"],
    ["this", "isn't"],
    ["this", "is", "absolutely"],
    ["this", "is", "great"],
    ["this", "isn't", "absolutely"],
    ["this", "isn't", "great"],
    ["absolutely"],
    ["great"],
    ["absolutely", "this", "is"],
    ["great", "this", "is"],
    ["absolutely", "this", "isn't"],
    ["great", "this", "isn't"],
    []
]

So far, I've implemented the permutations for the Mix class like this:

class Mix(list):
    def __init__(self, *args, **kwargs):
        super(Mix, self).__init__(*args, **kwargs)
        self.permutations = []
        for L in range(0, len(self)+1):
            for subset in itertools.combinations(self, L):
                subset_permutations = itertools.permutations(subset)
                self.permutations.extend(subset_permutations)

and my PickOne class is simply this

class PickOne(list):
    pass

which I'm planning on just testing for in my main function and handling accordingly (if type(obj) is PickOne: ...).

itertools provides simplification and efficiency for simpler use-cases, however I'm at a loss on how it will help me for this implementation (beyond what I already implemented in Mix). Any ideas of how itertools can be used to help in a Pythonic implementation of the above?

Body:
I'm having some troubles wrapping my head around all those combinations, but I think your Mix class also has to yield the product of all those permutations. I've created a similar model to test this. This might work a bit different than yours, but it should be easy to adapt:

class CombModel:
    def __init__(self, *options):
        self.options = options

class Atom(CombModel):
    def __iter__(self):
        for x in self.options:
            yield x

class All(CombModel):
    def __iter__(self):
        for prod in itertools.product(*self.options):
            yield prod

class One(CombModel):
    def __iter__(self):
        for x in self.options:
            for y in x:
                yield y

class Mix(CombModel):
    def __iter__(self):
        for n in range(len(self.options) + 1):
            for perm in itertools.permutations(self.options, n):
                for prod in itertools.product(*perm):
                    yield prod

The CombModel only provides a var-arg constructor for all the sub-classes. Atom is a "leaf" in the model and it's there so that I can "iterate" even over single strings or integers. This saves some if/else logic in all the other classes. All is what seem to be plain lists in your model, yielding the product of the different options. One and Mix correspond to your PickOne and Mix.

Using this rather simple model comb = Mix(All(Atom(1), Atom(21, 22)), One(Atom(31, 32), Atom(4))) I get the these combinations:

()
((1, 21),)
((1, 22),)
(31,)
(32,)
(4,)
((1, 21), 31)
((1, 21), 32)
((1, 21), 4)
((1, 22), 31)
((1, 22), 32)
((1, 22), 4)
(31, (1, 21))
(31, (1, 22))
(32, (1, 21))
(32, (1, 22))
(4, (1, 21))
(4, (1, 22))

Your model translates to this:

model = Mix(
    All(
        Atom("this"),
        One(Atom("is"), Atom("isn't"))
    ),
    One(
        Mix(
            Atom("absolutely"),
            Atom("great")
        )
    )
)

And gives those combinations:

()
(('this', 'is'),)
(('this', "isn't"),)
((),)
(('absolutely',),)
(('great',),)
(('absolutely', 'great'),)
(('great', 'absolutely'),)
(('this', 'is'), ())
(('this', 'is'), ('absolutely',))
(('this', 'is'), ('great',))
(('this', 'is'), ('absolutely', 'great'))
(('this', 'is'), ('great', 'absolutely'))
(('this', "isn't"), ())
(('this', "isn't"), ('absolutely',))
(('this', "isn't"), ('great',))
(('this', "isn't"), ('absolutely', 'great'))
(('this', "isn't"), ('great', 'absolutely'))
((), ('this', 'is'))
((), ('this', "isn't"))
(('absolutely',), ('this', 'is'))
(('absolutely',), ('this', "isn't"))
(('great',), ('this', 'is'))
(('great',), ('this', "isn't"))
(('absolutely', 'great'), ('this', 'is'))
(('absolutely', 'great'), ('this', "isn't"))
(('great', 'absolutely'), ('this', 'is'))
(('great', 'absolutely'), ('this', "isn't"))

Note that those are still nested lists (or tuples, actually), but those can easily be flattened afterwards. Also, there are a few pseudo-duplicates (that would be duplicates when flattened) due to the "zero or more" nature of Mix. But apart from that, this looks rather close to your expected output.

On closer inspection, it might indeed be necesary to flatten first, so that PickOne will select only one from the Mix and not the entire Mix...

class All(CombModel):
    def __iter__(self):
        for prod in itertools.product(*self.options):
            yield flat(prod) # flatten here

class One(CombModel):
    def __iter__(self):
        for x in self.options:
            for y in flat(x): # flatten here
                yield y

class Mix(CombModel):
    def __iter__(self):
        for n in range(len(self.options) + 1):
            for perm in itertools.permutations(self.options, n):
                for prod in itertools.product(*perm):
                    yield flat(prod) # flatten here

After weeding out the duplicates, the result is this:

()
('absolutely',)
('absolutely', 'this', 'is')
('absolutely', 'this', "isn't")
('great',)
('great', 'this', 'is')
('great', 'this', "isn't")
('this', 'is')
('this', 'is', 'absolutely')
('this', 'is', 'great')
('this', "isn't")
('this', "isn't", 'absolutely')
('this', "isn't", 'great')


问:
Comparing objects and enum class?
I have enum class, something like this:

```<code>public enum ProductCategory {
    FOOD("FOOD"),
    BEVERAGE("BEVERAGE"),
    DEFAULT("DEFAULT");

    private final String label;

    private ProductCategory(String label) {
        this.label = label;
    }

    public String getLabel() {
        return label;
    }
}
</code>```

And I want to write method that will compare two objects based on the ProductCategory. So if two objects have the same category (for example: FOOD), the method will return true.

```<code>public boolean searchFilterFunction(Object firstObject, Object secondObject) {
    if(firstObject==null || secondObject==null)
        return false;

    //code?
    return true;
}
</code>```

Enum class is in one package, and the method I want to write is in another. Can someone give me some hint?

答:
I want to write method that will compare two objects based on the ProductCategory

Java objects do not have an associated ProductCategory.

If your custom objects have one, you can write a method for checking it as if it were a primitive type:

```<code>public boolean searchFilterFunction(Product one, Product two) {
    return one != null
        && two != null
        && one.getProductCategory() == two.getProductCategory();
}
</code>```

Title: Comparing objects and enum class?

Body:
I have enum class, something like this:

public enum ProductCategory {
    FOOD("FOOD"),
    BEVERAGE("BEVERAGE"),
    DEFAULT("DEFAULT");

    private final String label;

    private ProductCategory(String label) {
        this.label = label;
    }

    public String getLabel() {
        return label;
    }
}

And I want to write method that will compare two objects based on the ProductCategory. So if two objects have the same category (for example: FOOD), the method will return true.

public boolean searchFilterFunction(Object firstObject, Object secondObject) {
    if(firstObject==null || secondObject==null)
        return false;

    //code?
    return true;
}

Enum class is in one package, and the method I want to write is in another. Can someone give me some hint?

Body:
I want to write method that will compare two objects based on the ProductCategory

Java objects do not have an associated ProductCategory.

If your custom objects have one, you can write a method for checking it as if it were a primitive type:

public boolean searchFilterFunction(Product one, Product two) {
    return one != null
        && two != null
        && one.getProductCategory() == two.getProductCategory();
}


问:
PDO query run only first time
I'm trying to get info from database but the query runs only for the first row!
I have tried many things but it didn't work; I don't know why.
The get method is on table that is filled by the database

The issue is in the first query 'SELECT CouID FROM CoursesC WHERE StuID = :ID '
if I change the query to 'SELECT CouID FROM CoursesC' it works fine!

I'm presenting the data into a <select> inside a modal

FORM CODE

```<code><form action="<?php $_SERVER['PHP_SELF']?>" method="GET" id="contact">

<table  id="studenttable">

  <tr>
  <th></th>
  <th>Student ID</th>
  <th>Student Name</th>
  <th>Student Passed Credits</th>
    <th>Action</th>
  </tr>
  <?php

    require('check.php');
$query = $conn->prepare('SELECT * FROM student WHERE AdvID=:id' );
$query->bindParam(":id",$_SESSION['userid']);
$query->execute();
$row = $query->fetch();

while($row = $query->fetch(PDO::FETCH_ASSOC)){
 ?>
  <tr>
  <td> <input type ="checkbox" name="checked[]" value="<?php echo $row['StuId'];?>"> </td>
  <td><?php echo $row['StuId']; ?></td>
  <td><?php echo $row['Name']; ?></td>
  <td> </td>
  <td>

  <button  type="submit" name="submit" value="<?php echo $row['StuId'];?>" class="btn icon-btn btn-info" ><span class="glyphicon glyphicon-info-sign"></span>More Information</button>
  </td>
  </tr>
<?php
}
      do {
    while ($query->fetch())
        ;
    if (!$query->nextRowset())
        break;
} while (true);
    $conn=null;
    $query->closeCursor();
?>

</table>

</form>

<?php
if (isset($_GET['submit'])){
    global $CC;
    $count=1;
    global $data;
    $T=$_GET['submit'];
?>
<script>
    $('#CC').html("");
    $('#CC1').html("");
</script>
<?php
    require('check.php');
    $q= $conn->prepare('SELECT CouID FROM CoursesC WHERE StuID = :ID ');
    $q->bindValue(':ID', $_GET['submit'] );
    $q->execute();
    $data = $q->fetch();
    while($data = $q->fetch(PDO::FETCH_ASSOC)){
        $CC=$data['CouID'];
?>
<script>
    $('#CC').append("<option><? echo $count++; echo "- "; echo $CC;?></option>");
</script>
<?php
    }
    $q->closeCursor();
    $A=$CC;
    /*echo "<script> alert('<?php $T ?>')";*/

    $q1= $conn->prepare('SELECT CouID FROM Courses');
    $q1->execute();
    $data1 = $q1->fetch();
    while($data1 = $q1->fetch(PDO::FETCH_ASSOC)){
        if($CC!=$data1['CouID']){
?>
<script>
    $('#CC1').append("<option><? echo $count++; echo "- "; echo $data1['CouID'];?></option>");
</script>
<?php
        }
    }
    $q1->closeCursor();
?>
<script>
    $(window).load(function(){
        $('#myModal').modal('show');
    });
</script>
<?
}
?>
<?php
    if (isset($_GET['submit'])){
        global $CC;
        $count=1;
        global $data;
        $T=$_GET['submit'];
?>
<script>
     $('#CC').html("");
     $('#CC1').html("");
</script>
<?php
        require('check.php');
        $q= $conn->prepare('SELECT CouID FROM CoursesC WHERE StuID = :ID ');
        $q->bindValue(':ID', $_GET['submit'] );
        $q->execute();
        $data = $q->fetch();
        while($data = $q->fetch(PDO::FETCH_ASSOC)){
            $CC=$data['CouID'];
?>
<script>
     $('#CC').append("<option><? echo $count++; echo "- "; echo $CC;?></option>");
</script>
<?php
        }
        $q->closeCursor();
        $A=$CC;
        /*echo "<script> alert('<?php $T ?>')";*/

        $q1= $conn->prepare('SELECT CouID FROM Courses');
        $q1->bindParam(":id", $_GET['submit']);
        $q1->execute();
        $data1 = $q1->fetch();
        while($data1 = $q1->fetch(PDO::FETCH_ASSOC)){
            if($CC!=$data1['CouID']){
?>
<script>
     $('#CC1').append("<option><? echo $count++; echo "- "; echo $data1['CouID'];?></option>");
</script>
<?php
            }
        }
        $q1->closeCursor();
?>
<script>
    $(window).load(function(){
        $('#myModal').modal('show');
    });
</script>
<?
    }
?>
<?php
    if (isset($_GET['submit'])){
      global $CC;
        $count=1;
        global $data;
        $T=$_GET['submit'];
    ?>
    <script>
     $('#CC').html("");
     $('#CC1').html("");
    </script>
    <?php
    require('check.php');
    $q= $conn->prepare('SELECT CouID FROM CoursesC WHERE StuID = :ID ');
    $q->bindValue(':ID', $_GET['submit'] );
    $q->execute();
    $data = $q->fetch();
    while($data = $q->fetch(PDO::FETCH_ASSOC)){
        $CC=$data['CouID'];
?>
<script>
     $('#CC').append("<option><? echo $count++; echo "- "; echo $CC;?></option>");
</script>
<?php
    }
    $q->closeCursor();
    $A=$CC;
    /*echo "<script> alert('<?php $T ?>')";*/

    $q1= $conn->prepare('SELECT CouID FROM Courses');
    $q1->bindParam(":id", $_GET['submit']);
    $q1->execute();
    $data1 = $q1->fetch();
    while($data1 = $q1->fetch(PDO::FETCH_ASSOC)){
        if($CC!=$data1['CouID']){
?>
<script>
     $('#CC1').append("<option><? echo $count++; echo "- "; echo $data1['CouID'];?></option>");
</script>
<?php
        }
    }
    $q1->closeCursor();
?>
<script>
    $(window).load(function(){
        $('#myModal').modal('show');
    });
</script>
<?
}
?>
</code>```

答:
Try changing this line:

```<code>$q= $conn->prepare('SELECT CouID FROM CoursesC WHERE StuID = :ID ');
$q->bindValue(':ID', $_GET['submit'] );
</code>```

to

```<code>$q= $conn->prepare('SELECT CouID FROM CoursesC WHERE StuID IN( :ID ) ');
$q->bindValue(':ID', implode(",",$_GET['checked']) );
</code>```

Your form is returning an array of IDs, not just one, so you must use 'IN' instead of '='.

Also, don't use <?php $_SERVER['PHP_SELF']?>. Use the name of page, in case you're deploying this outside of your project!

Title: PDO query run only first time

Body:
I'm trying to get info from database but the query runs only for the first row!
I have tried many things but it didn't work; I don't know why.
The get method is on table that is filled by the database

The issue is in the first query 'SELECT CouID FROM CoursesC WHERE StuID = :ID '
if I change the query to 'SELECT CouID FROM CoursesC' it works fine!

I'm presenting the data into a <select> inside a modal

FORM CODE

<form action="<?php $_SERVER['PHP_SELF']?>" method="GET" id="contact">

  Student ID
  Student Name
  Student Passed Credits
    Action

  <?php

    require('check.php');
$query = $conn->prepare('SELECT * FROM student WHERE AdvID=:id' );
$query->bindParam(":id",$_SESSION['userid']);
$query->execute();
$row = $query->fetch();

while($row = $query->fetch(PDO::FETCH_ASSOC)){
 ?>

   <input type ="checkbox" name="checked[]" value="<?php echo $row['StuId'];?>">
  <?php echo $row['StuId']; ?>
  <?php echo $row['Name']; ?>

  <button  type="submit" name="submit" value="<?php echo $row['StuId'];?>" class="btn icon-btn btn-info" >More Information</button>

<?php
}
      do {
    while ($query->fetch())
        ;
    if (!$query->nextRowset())
        break;
} while (true);
    $conn=null;
    $query->closeCursor();
?>

</form>

<?php
if (isset($_GET['submit'])){
    global $CC;
    $count=1;
    global $data;
    $T=$_GET['submit'];
?>

<?php
    require('check.php');
    $q= $conn->prepare('SELECT CouID FROM CoursesC WHERE StuID = :ID ');
    $q->bindValue(':ID', $_GET['submit'] );
    $q->execute();
    $data = $q->fetch();
    while($data = $q->fetch(PDO::FETCH_ASSOC)){
        $CC=$data['CouID'];
?>

<?php
    }
    $q->closeCursor();
    $A=$CC;
    /*echo "
<?php
        }
    }
    $q1->closeCursor();
?>

<?
}
?>
<?php
    if (isset($_GET['submit'])){
        global $CC;
        $count=1;
        global $data;
        $T=$_GET['submit'];
?>

<?php
        require('check.php');
        $q= $conn->prepare('SELECT CouID FROM CoursesC WHERE StuID = :ID ');
        $q->bindValue(':ID', $_GET['submit'] );
        $q->execute();
        $data = $q->fetch();
        while($data = $q->fetch(PDO::FETCH_ASSOC)){
            $CC=$data['CouID'];
?>

<?php
        }
        $q->closeCursor();
        $A=$CC;
        /*echo "
<?php
            }
        }
        $q1->closeCursor();
?>

<?
    }
?>
<?php
    if (isset($_GET['submit'])){
      global $CC;
        $count=1;
        global $data;
        $T=$_GET['submit'];
    ?>

    <?php
    require('check.php');
    $q= $conn->prepare('SELECT CouID FROM CoursesC WHERE StuID = :ID ');
    $q->bindValue(':ID', $_GET['submit'] );
    $q->execute();
    $data = $q->fetch();
    while($data = $q->fetch(PDO::FETCH_ASSOC)){
        $CC=$data['CouID'];
?>

<?php
    }
    $q->closeCursor();
    $A=$CC;
    /*echo "
<?php
        }
    }
    $q1->closeCursor();
?>

<?
}
?>

Body:
Try changing this line:

$q= $conn->prepare('SELECT CouID FROM CoursesC WHERE StuID = :ID ');
$q->bindValue(':ID', $_GET['submit'] );

to

$q= $conn->prepare('SELECT CouID FROM CoursesC WHERE StuID IN( :ID ) ');
$q->bindValue(':ID', implode(",",$_GET['checked']) );

Your form is returning an array of IDs, not just one, so you must use 'IN' instead of '='.

Also, don't use <?php $_SERVER['PHP_SELF']?>. Use the name of page, in case you're deploying this outside of your project!


问:
Monitor network performance for ffmpeg streaming
I'm building up a complex network emulation and I'm trying to catch some important performance measurements.
I have mininet running on a server and I' streaming videos from one mininet host to another (with -nodisp option cause I have no GUI).

Is it possible to catch some performance measurements from ffmpeg, maybe writing them on a file?

I would like to find delay, bandwidth, maybe jitter, and so on.

Thanks everyone in advance

答:
Just in case someone's interested, I resolved this way:

I moved to mp4box instead of ffmpeg to create dash chunks/manifest/.. (much better support and stability)

I've written a no-GUI python video player

I read my python player log files


问:
Why are result sets so large?
Why are result sets from data bases so large?  I typically get result sets that are around a million rows, each of which contains a couple of numerics, a varchar(75), a big int...whatever.  Probably not much more than 100 bytes per row.  And yet it takes up 6 GB!  Is this typical behavior?  My stack is Postgres + JDBC + Spring - I don't have any experience with other technologies.  </p>

答:
The java.sql.ResultSet itself will typically only have a couple dozen rows of data buffered at any time (configurable).

Now if you load all those rows into memory as Java objects, then you'll see large amounts of memory used. A String, for instance, has two bytes per char, two objects headers, an offset, two lengths and a cached hash value. BigInteger is similar. It all adds up. Use a profiler.

You might have better luck with a cached row set. That or don't load the entire set of results at once.

Title: Why are result sets so large?


问:
Spring security spring boot 4.x
I am stuck at an issue here. I am using spring boot with primefaces for my application. I am using spring security for authentication. Somehow I am getting access denied. Addition to it the users are already established in the mongodb and if i use spring redirection everything works great.

```<code>http.csrf().csrfTokenRepository(csrfTokenRepository()).and().authorizeRequests().antMatchers("/login**").access("permitAll")
            .antMatchers("/logout**").access("permitAll")
            .antMatchers("/secure/homePage.xhtml").access("hasRole('ADMIN') or hasRole('USER')")
            .anyRequest().authenticated().and().formLogin().loginPage("/login").defaultSuccessUrl("/secure/homePage.xhtml")
            .failureUrl("/login.xhtml?error").usernameParameter("email").and().logout().logoutUrl("/logout.xhtml")
            .logoutSuccessUrl("/login.xhtml").invalidateHttpSession(true).clearAuthentication(true).and()
            .exceptionHandling().accessDeniedPage("/accessDenied.xhtml");
</code>```

Btw, I have the following in my login page:

```<code><input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</code>```

答:
There is something fishy about your end points.

They are /secure/homePage.xhtml. These are usually pointing to a controller method and in the controller you supply the path to the view. then a specific view resolver will go and deliver the page.

```<code>@Bean
ViewResolver viewResolver() {
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setViewClass(org.springframework.faces.mvc.JsfView.class);
    resolver.setPrefix("/WEB-INF");
    resolver.setSuffix(".xhtml");
    return resolver;

}

@Controller
public class HelloWorldController {

    @RequestMapping("/helloWorld")
    public String helloWorld(Model model) {
        model.addAttribute("message", "Hello World!");
        return "helloWorld";
    }
}
</code>```

In this example, you will have a helloWorld.xhtml in /WEB-INF/

Title: Spring security spring boot 4.x

Body:
I am stuck at an issue here. I am using spring boot with primefaces for my application. I am using spring security for authentication. Somehow I am getting access denied. Addition to it the users are already established in the mongodb and if i use spring redirection everything works great.

http.csrf().csrfTokenRepository(csrfTokenRepository()).and().authorizeRequests().antMatchers("/login**").access("permitAll")
            .antMatchers("/logout**").access("permitAll")
            .antMatchers("/secure/homePage.xhtml").access("hasRole('ADMIN') or hasRole('USER')")
            .anyRequest().authenticated().and().formLogin().loginPage("/login").defaultSuccessUrl("/secure/homePage.xhtml")
            .failureUrl("/login.xhtml?error").usernameParameter("email").and().logout().logoutUrl("/logout.xhtml")
            .logoutSuccessUrl("/login.xhtml").invalidateHttpSession(true).clearAuthentication(true).and()
            .exceptionHandling().accessDeniedPage("/accessDenied.xhtml");

Btw, I have the following in my login page:

<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>

Body:
There is something fishy about your end points.

They are /secure/homePage.xhtml. These are usually pointing to a controller method and in the controller you supply the path to the view. then a specific view resolver will go and deliver the page.

@Bean
ViewResolver viewResolver() {
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setViewClass(org.springframework.faces.mvc.JsfView.class);
    resolver.setPrefix("/WEB-INF");
    resolver.setSuffix(".xhtml");
    return resolver;

}

@Controller
public class HelloWorldController {

    @RequestMapping("/helloWorld")
    public String helloWorld(Model model) {
        model.addAttribute("message", "Hello World!");
        return "helloWorld";
    }
}

In this example, you will have a helloWorld.xhtml in /WEB-INF/


问:
Getting Memory Corruption (Malloc) while using new operator and calling constructor of a structure in C++
I was trying this problem  and I am not concerned with the logic or algorithm of this program right now. My concern is I am getting the segmentation fault. For that I tried using gdb which showed me a "malloc : memory corruption". This problem has been haunting me as many times I use new operator and get segmentation fault. I am not able to figure out why?. But tracing output on a test case made me think something is wrong with the while loop. Please help me to correct my mistake.

Here is my code link, I was struggling to properly insert code on stackoverflow so used ideone. It also has the test case for which It gives segmentation fault.

I am getting following error message.
* Error in `./mergeoverlapping': malloc(): memory corruption: 0x0000000000a8e130 *

Aborted

(program exited with code: 134)
Press return to continue

```<code>#include <bits/stdc++.h>
using namespace std;
// debug statement
#define TRACE
#ifdef TRACE
#define trace1(x) cerr << #x << ": " << x << endl;
#define trace2(x, y)                                                           \
  cerr << #x << ": " << x << " | " << #y << ": " << y << endl;
#define trace3(x, y, z)                                                        \
  cerr << #x << ": " << x << " | " << #y << ": " << y << " | " << #z << ": "   \
       << z << endl;
#define trace4(a, b, c, d)                                                     \
  cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": "   \
       << c << " | " << #d << ": " << d << endl;
#define trace5(a, b, c, d, e)                                                  \
  cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": "   \
       << c << " | " << #d << ": " << d << " | " << #e << ": " << e << endl;
#define trace6(a, b, c, d, e, f)                                               \
  cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": "   \
       << c << " | " << #d << ": " << d << " | " << #e << ": " << e << " | "   \
       << #f << ": " << f << endl;
#else
#define trace1(x)
#define trace2(x, y)
#define trace3(x, y, z)
#define trace4(a, b, c, d)
#define trace5(a, b, c, d, e)
#define trace6(a, b, c, d, e, f)

#endif

// Structure of Interval defined by nterviewbit
struct Interval {
  int start;
  int end;
  Interval() : start(0), end(0) {}
  Interval(int s, int e) : start(s), end(e) {}
};

// operator just in case I needed sorting
bool compare(Interval a, Interval b) {
  if (a.start < b.start)
    return true;
  if (a.end < b.end)
    return true;
  return false;
}

// swap function to check if start is greater than end , if so then swap them
void swapp(Interval *t) {
  if (t->start > t->end) {
    int p = t->end;
    t->end = t->start;
    t->start = p;
  }
}

class Solution {
public:
  vector<Interval> merge(vector<Interval> &A) {
    vector<Interval> ans;
    sort(A.begin(), A.end(), compare);
    for (int i = 0; i < (int)A.size(); i++) {
      trace2(A[i].start, A[i].end);
      swapp(&A[i]);
      trace2(A[i].start, A[i].end);
    }
    int j = 0;
    int sz = A.size();
    while (j < sz) {
      while (j + 1 < sz and
             max(A[j].start, A[j + 1].start) <= min(A[j].end, A[j + 1].end)) {
        Interval *x = new Interval(min(A[j].start, A[j + 1].start),
                                   max(A[j].end, A[j + 1].end));
        trace2(x->start, x->end);
        trace2(A[j].start, A[j].end);
        A[j] = *x;
        trace2(A[j].start, A[j].end);
        trace2(A[j + 1].start, A[j + 1].end);
        A[j + 1] = *x;
        trace2(A[j + 1].start, A[j + 1].end);
        j++;
        delete x;
      }
      ans.push_back(A[j]);
      j++;
    }
    // for(int i=0;i<ans.size();i++){
    //     printf("i %d [%d %d]",i,ans[i].start,ans[i].end);
    //     cout<<endl;
    // }
    return ans;
  }
};
// BEGIN CUT HERE

int main() {
  Solution *obj = new Solution();
  // x denotes the number of intervals
  int x;
  cin >> x;
  vector<Interval> v;
  // an interval input consist of 2 integers start and end marked by a and b
  // respectively
  for (int i = 0; i < x; i++) {
    int a, b;
    cin >> a >> b;
    Interval *interval = new Interval(a, b);
    trace2(interval->start, interval->end);
    v.push_back(*interval);

    delete interval;
  }
  vector<Interval> ans = obj->merge(v);
  for (int i = 0; i < (int)ans.size(); i++) {
    printf("i %d [%d %d]", i, ans[i].start, ans[i].end);
    cout << endl;
  }
}
</code>```

答:
A comparator for std::sort must define a strict weak ordering (explained e.g. here).

Your comparator doesn't. Try to compare two intervals (2,3) and (1,4), then the same intervals in the reverse order.

Thus the behaviour is undefined and your sort function may crash, or worse, corrupt the memory arena and cause a crash later.

Changing the comparator to e.g.

```<code> return a.start < b.start || a.start == b.start && a.end < b.end
</code>```

should fix this crash.

Body:
I was trying this problem  and I am not concerned with the logic or algorithm of this program right now. My concern is I am getting the segmentation fault. For that I tried using gdb which showed me a "malloc : memory corruption". This problem has been haunting me as many times I use new operator and get segmentation fault. I am not able to figure out why?. But tracing output on a test case made me think something is wrong with the while loop. Please help me to correct my mistake.

Here is my code link, I was struggling to properly insert code on stackoverflow so used ideone. It also has the test case for which It gives segmentation fault.

I am getting following error message.
* Error in `./mergeoverlapping': malloc(): memory corruption: 0x0000000000a8e130 *

Aborted

(program exited with code: 134)
Press return to continue

#include <bits/stdc++.h>
using namespace std;
// debug statement
#define TRACE
#ifdef TRACE
#define trace1(x) cerr << #x << ": " << x << endl;
#define trace2(x, y)                                                           \
  cerr << #x << ": " << x << " | " << #y << ": " << y << endl;
#define trace3(x, y, z)                                                        \
  cerr << #x << ": " << x << " | " << #y << ": " << y << " | " << #z << ": "   \
       << z << endl;
#define trace4(a, b, c, d)                                                     \
  cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": "   \
       << c << " | " << #d << ": " << d << endl;
#define trace5(a, b, c, d, e)                                                  \
  cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": "   \
       << c << " | " << #d << ": " << d << " | " << #e << ": " << e << endl;
#define trace6(a, b, c, d, e, f)                                               \
  cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": "   \
       << c << " | " << #d << ": " << d << " | " << #e << ": " << e << " | "   \
       << #f << ": " << f << endl;
#else
#define trace1(x)
#define trace2(x, y)
#define trace3(x, y, z)
#define trace4(a, b, c, d)
#define trace5(a, b, c, d, e)
#define trace6(a, b, c, d, e, f)

#endif

// Structure of Interval defined by nterviewbit
struct Interval {
  int start;
  int end;
  Interval() : start(0), end(0) {}
  Interval(int s, int e) : start(s), end(e) {}
};

// operator just in case I needed sorting
bool compare(Interval a, Interval b) {
  if (a.start < b.start)
    return true;
  if (a.end start > t->end) {
    int p = t->end;
    t->end = t->start;
    t->start = p;
  }
}

class Solution {
public:
  vector<Interval> merge(vector<Interval> &A) {
    vector<Interval> ans;
    sort(A.begin(), A.end(), compare);
    for (int i = 0; i < (int)A.size(); i++) {
      trace2(A[i].start, A[i].end);
      swapp(&A[i]);
      trace2(A[i].start, A[i].end);
    }
    int j = 0;
    int sz = A.size();
    while (j < sz) {
      while (j + 1 < sz and
             max(A[j].start, A[j + 1].start) <= min(A[j].end, A[j + 1].end)) {
        Interval *x = new Interval(min(A[j].start, A[j + 1].start),
                                   max(A[j].end, A[j + 1].end));
        trace2(x->start, x->end);
        trace2(A[j].start, A[j].end);
        A[j] = *x;
        trace2(A[j].start, A[j].end);
        trace2(A[j + 1].start, A[j + 1].end);
        A[j + 1] = *x;
        trace2(A[j + 1].start, A[j + 1].end);
        j++;
        delete x;
      }
      ans.push_back(A[j]);
      j++;
    }
    // for(int i=0;i<ans.size();i++){
    //     printf("i %d [%d %d]",i,ans[i].start,ans[i].end);
    //     cout<<endl;
    // }
    return ans;
  }
};
// BEGIN CUT HERE

int main() {
  Solution *obj = new Solution();
  // x denotes the number of intervals
  int x;
  cin >> x;
  vector<Interval> v;
  // an interval input consist of 2 integers start and end marked by a and b
  // respectively
  for (int i = 0; i < x; i++) {
    int a, b;
    cin >> a >> b;
    Interval *interval = new Interval(a, b);
    trace2(interval->start, interval->end);
    v.push_back(*interval);

    delete interval;
  }
  vector<Interval> ans = obj->merge(v);
  for (int i = 0; i < (int)ans.size(); i++) {
    printf("i %d [%d %d]", i, ans[i].start, ans[i].end);
    cout << endl;
  }
}

Body:
A comparator for std::sort must define a strict weak ordering (explained e.g. here).

Your comparator doesn't. Try to compare two intervals (2,3) and (1,4), then the same intervals in the reverse order.

Thus the behaviour is undefined and your sort function may crash, or worse, corrupt the memory arena and cause a crash later.

Changing the comparator to e.g.

 return a.start < b.start || a.start == b.start && a.end < b.end

should fix this crash.


问:
Displaying an image with PHP from a database
I have a problem displaying images for URLs that are saved in a database.

This is my HTML source code:

```<code><div id="posts">
<img id="images" src="php/getImage.php?id=1">
<footer>
<a href="php/getImage.php?id=1" download><p>Download</p></a>
</footer>
</div>
</code>```

And my getImage.php file:

<?php
$id = $_GET['id'];
$db = mysqli_connect("host", "username", "password", "DB name");
$sql = "SELECT image FROM images WHERE imageID=$id";
$result=mysql_query($sql);
mysql_fetch_array($result);
echo "images/$result";
?>
```

答:
You have multiple problems here:

1) STOP using Mysql_ functions and use ONLY mysqli_ functions (or PDO) . Mysql_ PHP funtions are deprecated and no longer supported (and hasn't been for 5+ years!). It is insecure and will only get worse.

2) Your PHP file is simply echo'ing a string, images/someimagename.jpg; this is not what an image file is, you need to output the contents of this filename string.

3) Your current SQL is prone to SQL injection and is currently extremely insecure. Your database can be easily corrupted/abused by nefarious web page visitors.

4) Your mysqli_fetch_array needs to be assigned to a variable for the values in the array to be used.

5) Use single quotes rather than double quotes for your DB authentication so that special characters (such as$) - especially in passwords - are not misinterpreted by PHP.

Solution to the above problems:

```<code><?php
// id is assumed to be an integer value.
// This prevents SQL injection and database compromise by forced
// typecasting of the data to integer.
$id = (int)$_GET['id'];

$db = mysqli_connect('host', 'username', 'password', 'DB name');
$sql = "SELECT image FROM images WHERE imageID=".$id." LIMIT 1";

// only use mysqli_ functions.
$result=mysqli_query($db, $sql);

// assign to a $variable
$output = mysqli_fetch_array($result);

//The [ relative :( ] URL of the resoure requested:
$file = "images/".$output['image'];

// Before the data is output we need to set the correct header so the
// browser knows what sort of file to expect.
$image_mime = image_type_to_mime_type(exif_imagetype($file));
header("Content-type: " . $image_mime);

// Grab and output the raw data in the filepath stored in the URL.
print readfile($file);

// If this is the end of thefile you should not use a closing PHP tag.
// ?>
</code>```

If you do not have the PHP Exif Extension enabled there are various other (possibly more verbose) ways of ouputting the image type using fileinfo or mime_content_type.

PLEASE NOTE:

Your image URL is relative so, as the file getImage.php is in the php folder, the image requested will be in the php/images/<filename> path. If this is NOT where your images are stored, then you need to adjust your image path URL and make it either correct, or use absolute HTML pathing which is HIGHLY recommended.

Body:
I have a problem displaying images for URLs that are saved in a database.

This is my HTML source code:

Download

And my getImage.php file:

<?php
$id = $_GET['id'];
$db = mysqli_connect("host", "username", "password", "DB name");
$sql = "SELECT image FROM images WHERE imageID=$id";
$result=mysql_query($sql);
mysql_fetch_array($result);
echo "images/$result";
?>

Body:
You have multiple problems here:

1) STOP using Mysql_ functions and use ONLY mysqli_ functions (or PDO) . Mysql_ PHP funtions are deprecated and no longer supported (and hasn't been for 5+ years!). It is insecure and will only get worse.

2) Your PHP file is simply echo'ing a string, images/someimagename.jpg; this is not what an image file is, you need to output the contents of this filename string.

3) Your current SQL is prone to SQL injection and is currently extremely insecure. Your database can be easily corrupted/abused by nefarious web page visitors.

4) Your mysqli_fetch_array needs to be assigned to a variable for the values in the array to be used.

5) Use single quotes rather than double quotes for your DB authentication so that special characters (such as$) - especially in passwords - are not misinterpreted by PHP.

Solution to the above problems:

<?php
// id is assumed to be an integer value.
// This prevents SQL injection and database compromise by forced
// typecasting of the data to integer.
$id = (int)$_GET['id'];

$db = mysqli_connect('host', 'username', 'password', 'DB name');
$sql = "SELECT image FROM images WHERE imageID=".$id." LIMIT 1";

// only use mysqli_ functions.
$result=mysqli_query($db, $sql);

// assign to a $variable
$output = mysqli_fetch_array($result);

//The [ relative :( ] URL of the resoure requested:
$file = "images/".$output['image'];

// Before the data is output we need to set the correct header so the
// browser knows what sort of file to expect.
$image_mime = image_type_to_mime_type(exif_imagetype($file));
header("Content-type: " . $image_mime);

// Grab and output the raw data in the filepath stored in the URL.
print readfile($file);

// If this is the end of thefile you should not use a closing PHP tag.
// ?>

If you do not have the PHP Exif Extension enabled there are various other (possibly more verbose) ways of ouputting the image type using fileinfo or mime_content_type.

PLEASE NOTE:

Your image URL is relative so, as the file getImage.php is in the php folder, the image requested will be in the php/images/<filename> path. If this is NOT where your images are stored, then you need to adjust your image path URL and make it either correct, or use absolute HTML pathing which is HIGHLY recommended.