问:
here my requirement is this that when user select option from dropdown than that selected value should not visible in another dropdown

$(document).ready(function() {
  getDetailAmc(investor_id);
  $("#add-amc").on('click', function() {

    count++;
    $("#new-amc-block").append("

Select AMC:<select class='form-control Amcselect' id='Amc_select_" + count + "'></select>

Folio No:<input type='text' placeholder='Enter Folio Number Here..' class='form-control folionotxt' id='folio_no_" + count + "'>

");

    PopulateSelectAmc(AmcArray);
    changesoption();
  });

});

function getDetailAmc(investor_id) {

  $.ajax({
    type: "POST",
    url: "Folio_Mapping1.aspx/getAmc",
    data: JSON.stringify({
      investor_id: investor_id
    }),
    contentType: "application/json;charset=utf-8",
    dataType: "json",
    success: OnSuccess,
    error: OnErrorCall
  });

  function OnSuccess(response) {

    var result = JSON.parse(response.d);
    if (result == "") {
      $("#InvId-error").removeClass("hidden");
      $("#InvId-error").text("Invalid Investor Id");
      $(".Amcselect").empty();
    } else {
      $("#InvId-error").addClass("hidden");
      MapAmcDetail(result);

    }

    function MapAmcDetail(result) {
      AmcArray = [];
      AmcArray = $.map(result, function(el) {
        return {
          "AMC_NAME": el.AMC_NAME

        }
      });

      PopulateSelectAmc(AmcArray);

    }

    function PopulateSelectAmc(AmcArray) {

      var option = '';

      option += '<option value="Select">Select AMC</option>';
      for (var i = 0; i < AmcArray.length; i++) {

        option += '<option value="' + AmcArray[i].AMC_NAME + '"id=a_' + i + '">' + AmcArray[i].AMC_NAME + '</option>';
      }

      $('.Amcselect').append(option);

      function changesoption() {
        var value;
        value = $(".Amcselect option:first").val();
        if (value) {
          $(this).data('previous', value);
          $('select').not(this).find('option[value="' + value + '"]').hide();
        }

        /*  PopulateSelectAmc(AmcArray);*/
        $(".Amcselect").on('change', function() {

          prevValue = $(this).data('previous');
          $('select').not(this).find('option[value="' + prevValue + '"]').show();

          value = $(this).val();
          if (value) {
            $(this).data('previous', value);
            $('select').not(this).find('option[value="' + value + '"]').hide();
          }

        });
      }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<body>
  <form id="form1" runat="server">
    <div class="form-group container margincus">
      <div class="row">
        <div class="col-lg-4">
          <label for="investorId">Investor ID:</label>
          <input type="text" class="form-control" id="Invid" placeholder="Enter InvestorId"><span class="error hidden" id="InvId-error"></span>
        </div>
        <div class="col-lg-4">
          <i class="fa fa-plus-square fa-2x font-icon curs" title="Add More Amc" id="add-amc"></i>
        </div>
      </div>
    </div>
    <div class="container">
      <div class="row">
        <div class="col-sm-4 form-group">
          <label>Select AMC:</label>
          <select class="form-control Amcselect" id="Amc_select_0"></select><span class="error hidden" id="Amcselect_error_0"></span>
        </div>
        <div class="col-sm-4 form-group">
          <label>Enter Folio No:</label>
          <input type="text" placeholder="Example:1234567891,3456789234...." class="form-control folionotxt" id="folio_no_0"><span class="error hidden" id="Foliono_error_0"></span>
        </div>
      </div>
    </div>
    <div id="new-amc-block">

    </div>
    <div class="container">
      <button class="btn btn-success btn-default" id="sendemail" type="button">Send Email</button>
    </div>
  </form>
</body>

</html></code>```

I created plus button to add dropdown as many want and in dropdown options are coming dynamically.here my requirement is this that when user select option from dropdown than that selected value should not visible in another dropdown.I am able to achieve this but problem here I am facing that when user  click plus button and added some dropdown and than select option from dropdown than that selected value not visible in other dropdown which are
Added, but when user  again click plus button and added some dropdown  than all  options are coming into dropdown  so previously selected  option are not hidden from dropdown .

答:
why dont you write a single input (here dropdown change function) something like

```<code>function RemoveOptionsFromOthers(val){
$('select :not('+this+')').find(option['value="val"]').remove();
}
</code>```

then call the function in all the optionchange event

Body:
$(document).ready(function() {
  getDetailAmc(investor_id);
  $("#add-amc").on('click', function() {

    count++;
    $("#new-amc-block").append("

Select AMC:<select class='form-control Amcselect' id='Amc_select_" + count + "'></select>

Folio No:<input type='text' placeholder='Enter Folio Number Here..' class='form-control folionotxt' id='folio_no_" + count + "'>

");

    PopulateSelectAmc(AmcArray);
    changesoption();
  });

});

function getDetailAmc(investor_id) {

  $.ajax({
    type: "POST",
    url: "Folio_Mapping1.aspx/getAmc",
    data: JSON.stringify({
      investor_id: investor_id
    }),
    contentType: "application/json;charset=utf-8",
    dataType: "json",
    success: OnSuccess,
    error: OnErrorCall
  });

  function OnSuccess(response) {

    var result = JSON.parse(response.d);
    if (result == "") {
      $("#InvId-error").removeClass("hidden");
      $("#InvId-error").text("Invalid Investor Id");
      $(".Amcselect").empty();
    } else {
      $("#InvId-error").addClass("hidden");
      MapAmcDetail(result);

    }

    function MapAmcDetail(result) {
      AmcArray = [];
      AmcArray = $.map(result, function(el) {
        return {
          "AMC_NAME": el.AMC_NAME

        }
      });

      PopulateSelectAmc(AmcArray);

    }

    function PopulateSelectAmc(AmcArray) {

      var option = '';

      option += '<option value="Select">Select AMC</option>';
      for (var i = 0; i < AmcArray.length; i++) {

        option += '<option value="' + AmcArray[i].AMC_NAME + '"id=a_' + i + '">' + AmcArray[i].AMC_NAME + '</option>';
      }

      $('.Amcselect').append(option);

      function changesoption() {
        var value;
        value = $(".Amcselect option:first").val();
        if (value) {
          $(this).data('previous', value);
          $('select').not(this).find('option[value="' + value + '"]').hide();
        }

        /*  PopulateSelectAmc(AmcArray);*/
        $(".Amcselect").on('change', function() {

          prevValue = $(this).data('previous');
          $('select').not(this).find('option[value="' + prevValue + '"]').show();

          value = $(this).val();
          if (value) {
            $(this).data('previous', value);
            $('select').not(this).find('option[value="' + value + '"]').hide();
          }

        });
      }

  <form id="form1" runat="server">

          Investor ID:
          <input type="text" class="form-control" id="Invid" placeholder="Enter InvestorId">

          Select AMC:
          <select class="form-control Amcselect" id="Amc_select_0"></select>

          Enter Folio No:
          <input type="text" placeholder="Example:1234567891,3456789234...." class="form-control folionotxt" id="folio_no_0">

      <button class="btn btn-success btn-default" id="sendemail" type="button">Send Email</button>

  </form>

I created plus button to add dropdown as many want and in dropdown options are coming dynamically.here my requirement is this that when user select option from dropdown than that selected value should not visible in another dropdown.I am able to achieve this but problem here I am facing that when user  click plus button and added some dropdown and than select option from dropdown than that selected value not visible in other dropdown which are
Added, but when user  again click plus button and added some dropdown  than all  options are coming into dropdown  so previously selected  option are not hidden from dropdown .

Body:
why dont you write a single input (here dropdown change function) something like

function RemoveOptionsFromOthers(val){
$('select :not('+this+')').find(option['value="val"]').remove();
}

then call the function in all the optionchange event


来源: stackexchange

问:
Are ionic 2 apps heavy with respect to storage space?
I recently started with ionic and developed a very basic app with 3 pages and a sqlite database. I checked the space it took on my phone and saw that it it's almost 8 MB. Are complex ionic apps usually heavy with respect to space?</p>

答: I have long time experience with Ionic 2 mobile applications. But I have not faced such situation like that you mentioned. Usually ionic .apk is very light weight and the space take for the local storage depends on your saves on the local storage. I think you have saved lot of data in your local storage. Because of that app indicates 8MB of space takes.

ContentLicense: CC BY-SA 3.0


问:
Can we read .properties file inside xml?
I have a .properties file that contains the values. I am trying to set one of the value to a field in xml file.
For example session-expiry is set to 300 seconds in property file.
So i need to set the same value in the xml file.

```<code><max-idle-seconds>300</max-idle-seconds>
</code>```

This 300 should be takem from the .properties file.
Can anyone help?

答:
Yes. Add your XML below the code.

```<code><context:property-placeholder location="classpath:your_property_filename.properties"  ignore-unresolvable="true"/>
</code>```

Or you can write:

```<code><bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" lazy-init="false">
    <property name="locations">
        <list>
            <value>classpath:your_property_filename.properties</value>
        </list>
    </property>
</bean>
</code>```

Body:
I have a .properties file that contains the values. I am trying to set one of the value to a field in xml file.
For example session-expiry is set to 300 seconds in property file.
So i need to set the same value in the xml file.

<max-idle-seconds>300</max-idle-seconds>

This 300 should be takem from the .properties file.
Can anyone help?

Body:
Yes. Add your XML below the code.

<context:property-placeholder location="classpath:your_property_filename.properties"  ignore-unresolvable="true"/>

Or you can write:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" lazy-init="false">
    <property name="locations">
        <list>
            <value>classpath:your_property_filename.properties</value>
        </list>
    </property>
</bean>


问:
Getting Coordinates of string using ITextExtractionStrategy and LocationTextExtractionStrategy in Itextsharp
I have a PDF file that i am reading into string using ITextExtractionStrategy.Now from the string i am taking a substring like My name is XYZ and need to get the rectangular coordinates of  substring from the PDF file but not able to do it.On googling i got to know that LocationTextExtractionStrategy but not getting how to use this to get the coordinates.

Here is the code..

```<code>ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);
currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
text.Append(currentText);

string getcoordinate="My name is XYZ";
</code>```

How can i get the rectangular coordinate of this substring using ITEXTSHARP..

Please help.

答:
I know this is a really old question, but below is what I ended up doing. Just posting it here hoping that it will be useful for someone else.

The following code will tell you the starting coordinates of the line(s) that contains a search text. It should not be hard to modify it to give positions of words.
Note. I tested this on itextsharp 5.5.11.0 and won't work on some older versions

As mentioned above pdfs have no concept of words/lines or paragraphs. But I found that the LocationTextExtractionStrategy does a very good job of splitting lines and words. So my solution is based on that.

DISCLAIMER:

This solution is based on the https://github.com/itext/itextsharp/blob/develop/src/core/iTextSharp/text/pdf/parser/LocationTextExtractionStrategy.cs and that file has a comment saying that it's a dev preview. So this might not work in future.

Anyway here's the code.

using System.Collections.Generic;
using iTextSharp.text.pdf.parser;

namespace Logic
{
    public class LocationTextExtractionStrategyWithPosition : LocationTextExtractionStrategy
    {
        private readonly List<TextChunk> locationalResult = new List<TextChunk>();

        private readonly ITextChunkLocationStrategy tclStrat;

        public LocationTextExtractionStrategyWithPosition() : this(new TextChunkLocationStrategyDefaultImp())
        {
        }

        /**
         * Creates a new text extraction renderer, with a custom strategy for
         * creating new TextChunkLocation objects based on the input of the
         * TextRenderInfo.
         * @param strat the custom strategy
         */
        public LocationTextExtractionStrategyWithPosition(ITextChunkLocationStrategy strat)
        {
            tclStrat = strat;
        }

        private bool StartsWithSpace(string str)
        {
            if (str.Length == 0) return false;
            return str[0] == ' ';
        }

        private bool EndsWithSpace(string str)
        {
            if (str.Length == 0) return false;
            return str[str.Length - 1] == ' ';
        }

        /**
         * Filters the provided list with the provided filter
         * @param textChunks a list of all TextChunks that this strategy found during processing
         * @param filter the filter to apply.  If null, filtering will be skipped.
         * @return the filtered list
         * @since 5.3.3
         */

        private List<TextChunk> filterTextChunks(List<TextChunk> textChunks, ITextChunkFilter filter)
        {
            if (filter == null)
            {
                return textChunks;
            }

            var filtered = new List<TextChunk>();

            foreach (var textChunk in textChunks)
            {
                if (filter.Accept(textChunk))
                {
                    filtered.Add(textChunk);
                }
            }

            return filtered;
        }

        public override void RenderText(TextRenderInfo renderInfo)
        {
            LineSegment segment = renderInfo.GetBaseline();
            if (renderInfo.GetRise() != 0)
            { // remove the rise from the baseline - we do this because the text from a super/subscript render operations should probably be considered as part of the baseline of the text the super/sub is relative to
                Matrix riseOffsetTransform = new Matrix(0, -renderInfo.GetRise());
                segment = segment.TransformBy(riseOffsetTransform);
            }
            TextChunk tc = new TextChunk(renderInfo.GetText(), tclStrat.CreateLocation(renderInfo, segment));
            locationalResult.Add(tc);
        }

        public IList<TextLocation> GetLocations()
        {

            var filteredTextChunks = filterTextChunks(locationalResult, null);
            filteredTextChunks.Sort();

            TextChunk lastChunk = null;

            var textLocations = new List<TextLocation>();

            foreach (var chunk in filteredTextChunks)
            {

                if (lastChunk == null)
                {
                    //initial
                    textLocations.Add(new TextLocation
                    {
                        Text = chunk.Text,
                        X = iTextSharp.text.Utilities.PointsToMillimeters(chunk.Location.StartLocation[0]),
                        Y = iTextSharp.text.Utilities.PointsToMillimeters(chunk.Location.StartLocation[1])
                    });

                }
                else
                {
                    if (chunk.SameLine(lastChunk))
                    {
                        var text = "";
                        // we only insert a blank space if the trailing character of the previous string wasn't a space, and the leading character of the current string isn't a space
                        if (IsChunkAtWordBoundary(chunk, lastChunk) && !StartsWithSpace(chunk.Text) && !EndsWithSpace(lastChunk.Text))
                            text += ' ';

                        text += chunk.Text;

                        textLocations[textLocations.Count - 1].Text += text;

                    }
                    else
                    {

                        textLocations.Add(new TextLocation
                        {
                            Text = chunk.Text,
                            X = iTextSharp.text.Utilities.PointsToMillimeters(chunk.Location.StartLocation[0]),
                            Y = iTextSharp.text.Utilities.PointsToMillimeters(chunk.Location.StartLocation[1])
                        });
                    }
                }
                lastChunk = chunk;
            }

            //now find the location(s) with the given texts
            return textLocations;

        }

    }

    public class TextLocation
    {
        public float X { get; set; }
        public float Y { get; set; }

        public string Text { get; set; }
    }
}
```
<p>How to call the method:</p>
<pre class="lang-cs prettyprint-override"><code>using (var reader = new PdfReader(inputPdf))
{
    var parser = new PdfReaderContentParser(reader);
    var strategy = parser.ProcessContent(pageNumber, new LocationTextExtractionStrategyWithPosition());
    var res = strategy.GetLocations();
    reader.Close();
}
var searchResult = res.Where(p => p.Text.Contains(searchText)).OrderBy(p => p.Y).Reverse().ToList();
</code>```

inputPdf is a byte[] that has the pdf data

pageNumber is the page where you want to search in

Body:
I have a PDF file that i am reading into string using ITextExtractionStrategy.Now from the string i am taking a substring like My name is XYZ and need to get the rectangular coordinates of  substring from the PDF file but not able to do it.On googling i got to know that LocationTextExtractionStrategy but not getting how to use this to get the coordinates.

Here is the code..

ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);
currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
text.Append(currentText);

string getcoordinate="My name is XYZ";

How can i get the rectangular coordinate of this substring using ITEXTSHARP..

Please help.

Body:
I know this is a really old question, but below is what I ended up doing. Just posting it here hoping that it will be useful for someone else.

The following code will tell you the starting coordinates of the line(s) that contains a search text. It should not be hard to modify it to give positions of words.
Note. I tested this on itextsharp 5.5.11.0 and won't work on some older versions

As mentioned above pdfs have no concept of words/lines or paragraphs. But I found that the LocationTextExtractionStrategy does a very good job of splitting lines and words. So my solution is based on that.

DISCLAIMER:

This solution is based on the https://github.com/itext/itextsharp/blob/develop/src/core/iTextSharp/text/pdf/parser/LocationTextExtractionStrategy.cs and that file has a comment saying that it's a dev preview. So this might not work in future.

Anyway here's the code.

using System.Collections.Generic;
using iTextSharp.text.pdf.parser;

namespace Logic
{
    public class LocationTextExtractionStrategyWithPosition : LocationTextExtractionStrategy
    {
        private readonly List<TextChunk> locationalResult = new List<TextChunk>();

        private readonly ITextChunkLocationStrategy tclStrat;

        public LocationTextExtractionStrategyWithPosition() : this(new TextChunkLocationStrategyDefaultImp())
        {
        }

        /**
         * Creates a new text extraction renderer, with a custom strategy for
         * creating new TextChunkLocation objects based on the input of the
         * TextRenderInfo.
         * @param strat the custom strategy
         */
        public LocationTextExtractionStrategyWithPosition(ITextChunkLocationStrategy strat)
        {
            tclStrat = strat;
        }

        private bool StartsWithSpace(string str)
        {
            if (str.Length == 0) return false;
            return str[0] == ' ';
        }

        private bool EndsWithSpace(string str)
        {
            if (str.Length == 0) return false;
            return str[str.Length - 1] == ' ';
        }

        /**
         * Filters the provided list with the provided filter
         * @param textChunks a list of all TextChunks that this strategy found during processing
         * @param filter the filter to apply.  If null, filtering will be skipped.
         * @return the filtered list
         * @since 5.3.3
         */

        private List<TextChunk> filterTextChunks(List<TextChunk> textChunks, ITextChunkFilter filter)
        {
            if (filter == null)
            {
                return textChunks;
            }

            var filtered = new List<TextChunk>();

            foreach (var textChunk in textChunks)
            {
                if (filter.Accept(textChunk))
                {
                    filtered.Add(textChunk);
                }
            }

            return filtered;
        }

        public override void RenderText(TextRenderInfo renderInfo)
        {
            LineSegment segment = renderInfo.GetBaseline();
            if (renderInfo.GetRise() != 0)
            { // remove the rise from the baseline - we do this because the text from a super/subscript render operations should probably be considered as part of the baseline of the text the super/sub is relative to
                Matrix riseOffsetTransform = new Matrix(0, -renderInfo.GetRise());
                segment = segment.TransformBy(riseOffsetTransform);
            }
            TextChunk tc = new TextChunk(renderInfo.GetText(), tclStrat.CreateLocation(renderInfo, segment));
            locationalResult.Add(tc);
        }

        public IList<TextLocation> GetLocations()
        {

            var filteredTextChunks = filterTextChunks(locationalResult, null);
            filteredTextChunks.Sort();

            TextChunk lastChunk = null;

            var textLocations = new List<TextLocation>();

            foreach (var chunk in filteredTextChunks)
            {

                if (lastChunk == null)
                {
                    //initial
                    textLocations.Add(new TextLocation
                    {
                        Text = chunk.Text,
                        X = iTextSharp.text.Utilities.PointsToMillimeters(chunk.Location.StartLocation[0]),
                        Y = iTextSharp.text.Utilities.PointsToMillimeters(chunk.Location.StartLocation[1])
                    });

                }
                else
                {
                    if (chunk.SameLine(lastChunk))
                    {
                        var text = "";
                        // we only insert a blank space if the trailing character of the previous string wasn't a space, and the leading character of the current string isn't a space
                        if (IsChunkAtWordBoundary(chunk, lastChunk) && !StartsWithSpace(chunk.Text) && !EndsWithSpace(lastChunk.Text))
                            text += ' ';

                        text += chunk.Text;

                        textLocations[textLocations.Count - 1].Text += text;

                    }
                    else
                    {

                        textLocations.Add(new TextLocation
                        {
                            Text = chunk.Text,
                            X = iTextSharp.text.Utilities.PointsToMillimeters(chunk.Location.StartLocation[0]),
                            Y = iTextSharp.text.Utilities.PointsToMillimeters(chunk.Location.StartLocation[1])
                        });
                    }
                }
                lastChunk = chunk;
            }

            //now find the location(s) with the given texts
            return textLocations;

        }

    }

    public class TextLocation
    {
        public float X { get; set; }
        public float Y { get; set; }

        public string Text { get; set; }
    }
}

How to call the method:

using (var reader = new PdfReader(inputPdf))
{
    var parser = new PdfReaderContentParser(reader);
    var strategy = parser.ProcessContent(pageNumber, new LocationTextExtractionStrategyWithPosition());
    var res = strategy.GetLocations();
    reader.Close();
}
var searchResult = res.Where(p => p.Text.Contains(searchText)).OrderBy(p => p.Y).Reverse().ToList();

inputPdf is a byte[] that has the pdf data

pageNumber is the page where you want to search in

ContentLicense: CC BY-SA 4.0


问:
How to write a package-level static initializer in Kotlin?
A previous question shows how to put a static initializer inside a class using its companion object. I'm trying to find a way to add a static initializer at the package level, but it seems packages have no companion object.

```<code>// compiler error: Modifier 'companion' is not applicable inside 'file'
companion object { init { println("Loaded!") } }
fun main(args: Array<String>) { println("run!") }
</code>```

I've tried other variations that might've made sense (init on its own, static), and I know as a workaround I can use a throwaway val as in

```<code>val static_init = {
    println("ugly workaround")
}()
</code>```

but is there a clean, official way to achieve the same result?

Edit: As @mfulton26's answer mentions, there is no such thing as a package-level function really in the JVM. Behind the scenes, the kotlin compiler is wrapping any free functions, including main in a class. I'm trying to add a static initializer to that class -- the class being generated by kotlin for the free functions declared in the file.

答:
I got around it by using a Backing Property on the top-level, under the Kotlin file. Kotlin Docs: Backing Properties</p>

```<code>private var _table: Map<String, Int>? = null
public val table: Map<String, Int>
    get() {
        if (_table == null) {
            _table = HashMap() // Type parameters are inferred
           // .... some other initialising code here
        }
        return _table ?: throw AssertionError("Set to null by another thread")
    }
</code>```

Body:
A previous question shows how to put a static initializer inside a class using its companion object. I'm trying to find a way to add a static initializer at the package level, but it seems packages have no companion object.

// compiler error: Modifier 'companion' is not applicable inside 'file'
companion object { init { println("Loaded!") } }
fun main(args: Array<String>) { println("run!") }

I've tried other variations that might've made sense (init on its own, static), and I know as a workaround I can use a throwaway val as in

val static_init = {
    println("ugly workaround")
}()

but is there a clean, official way to achieve the same result?

Edit: As @mfulton26's answer mentions, there is no such thing as a package-level function really in the JVM. Behind the scenes, the kotlin compiler is wrapping any free functions, including main in a class. I'm trying to add a static initializer to that class -- the class being generated by kotlin for the free functions declared in the file.

Body:
I got around it by using a Backing Property on the top-level, under the Kotlin file. Kotlin Docs: Backing Properties

private var _table: Map<String, Int>? = null
public val table: Map<String, Int>
    get() {
        if (_table == null) {
            _table = HashMap() // Type parameters are inferred
           // .... some other initialising code here
        }
        return _table ?: throw AssertionError("Set to null by another thread")
    }


问:
Is there anyway to import a publish profile directly into Team Services Build Definition for .NET Core
I have a .NET Core application that I have configured Continuous Integration with through the Azure deployment wizard.

This process created a build definition inside of my team services that I have configured to build and deploy on check in of source code.

The code builds and deploys successfully but I am having trouble getting database changes through migrations to be executed as part of CI. I have downloaded the publish profile from Azure for the web application and imported it into Visual Studio. I could then edit the publish setting to include running migrations on publish as you can see below.

When I run this manually from Visual Studio it publishes successfully and also executes the migration script.

So I am wondering is there a way to import this edited and working publish profile into my Team Services Continuous Integration?

答:
Try to use Visual Studio Build step with arguments of /p:DeployOnBuild=true /p:PublishProfile="[your publish profile]" instead.

Modify publish profile file to add Password and AllowUntrustedCertificate nodes. (refer to: Publish an Azure Web Site from the Command Line)

Add /p:DeployOnBuild=true /p:PublishProfile="[your publish profile]" arguments to Visual Studio Build task.


问:
Unable to center content using margin auto
When the screen size is less than 768px, the 3 boxes are aligned to the left. I'm having a hard time trying to make them appear center.

I managed to center it by setting margin-left to some value however, it isn't responsive afterwards.

Here's the code:

HTML

```<code><meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<body>
      <div class="row bg_color">
            <div class="col-xs-12 col-sm-4 col-md-4 stats_box">
               <h3>2015/16</h3>
               <hr>
               <ul>
                  <li>The Best FIFA Men's Player 2016</li>
                  <li>FIFA Club World Cup</li>
                  <li>France Football Ballon D'Or 2016</li>
                  <li>UEFA Best Player in Europe</li>
                  <li>UEFA Euro 2016 (Portugal)</li>
                  <li>UEFA Champions League (Real Madrid)</li>
               </ul>
            </div>
            <div class="col-xs-12 col-sm-4 col-md-4 stats_box">
               <h3>2014/15</h3>
               <hr>
               <ul>
                  <li>Pichichi Award</li>
                  <li>European Golden Boot 2015</li>
                  <li>FIFA Ballon D'Or 2014</li>
                  <li>Globe Soccer Best Player of the Year</li>
                  <li>Globe Soccer Fan's Favourite Player Award</li>
                  <li>IFFHS Trophy for Best Striker  on the planet</li>
               </ul>
            </div>
            <div class="col-xs-12 col-sm-4 col-md-4 stats_box">
               <h3>2013/14</h3>
               <hr>
               <ul>
                  <li>Club World Cup</li>
                  <li>BBC Overseas Sports  Personality Award</li>
                  <li>World's Top  Goalscorer 2013</li>
                  <li>Pichichi Award</li>
                  <li>Best Player, Best Forward in La Liga</li>
                  <li>UEFA Best Player in Europe</li>
               </ul>
            </div>
         </div>

</body>
</code>```

CSS:

```<code> .bg_color {
    background: #ECFEAA;
}

.stats_box {
    margin: 20px;
    padding: 20px 40px 40px;
    max-width: 400px;
    text-align: left;
    background: #fff;
    border-bottom: 4px solid #ccc;
    border-radius: 6px;

}

@media only screen and (max-width: 768px) {
  .stats_box {
    width: 100%;
    margin-left: 200px;
  }
}
</code>```

Any possible solution for this? And why isn't margin:0 auto not working here?

Link to the code: CodePen

答:
First of all change your mark up just like following and update css part

you are using nesting class with bootstrap classes and the bootstrap classes are using float:left that's why your code is not working.

Working fiddle fiddle

```<code>@media only screen and (max-width: 768px) {
  .stats_box {
    width: 100%;
    margin: 20px auto;
  }
}
</code>```

.bg_color {
  background: #ECFEAA;
}

.stats_box {
  margin: 20px;
  padding: 20px 40px 40px;
  max-width: 400px;
  text-align: left;
  background: #fff;
  border-bottom: 4px solid #ccc;
  border-radius: 6px;
}

@media only screen and (max-width: 768px) {
  .stats_box {
    width: 100%;
    margin: 20px auto;
  }
}

body {
  margin: 0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<body>
  <div class="row bg_color ">
    <div class="col-xs-12 col-sm-4 col-md-4">
      <div class="stats_box"> <!-- Place here the class same as rest -->
        <h3>2015/16</h3>
        <hr>
        <ul>
          <li>The Best FIFA Men's Player 2016</li>
          <li>FIFA Club World Cup</li>
          <li>France Football Ballon D'Or 2016</li>
          <li>UEFA Best Player in Europe</li>
          <li>UEFA Euro 2016 (Portugal)</li>
          <li>UEFA Champions League (Real Madrid)</li>
        </ul>
      </div>
    </div>
    <div class="col-xs-12 col-sm-4 col-md-4">
      <div class="stats_box">
        <h3>2015/16</h3>
        <hr>
        <ul>
          <li>The Best FIFA Men's Player 2016</li>
          <li>FIFA Club World Cup</li>
          <li>France Football Ballon D'Or 2016</li>
          <li>UEFA Best Player in Europe</li>
          <li>UEFA Euro 2016 (Portugal)</li>
          <li>UEFA Champions League (Real Madrid)</li>
        </ul>
      </div>
    </div>
    <div class="col-xs-12 col-sm-4 col-md-4">
      <div class="stats_box">
        <h3>2015/16</h3>
        <hr>
        <ul>
          <li>The Best FIFA Men's Player 2016</li>
          <li>FIFA Club World Cup</li>
          <li>France Football Ballon D'Or 2016</li>
          <li>UEFA Best Player in Europe</li>
          <li>UEFA Euro 2016 (Portugal)</li>
          <li>UEFA Champions League (Real Madrid)</li>
        </ul>
      </div>
    </div>
  </div>

</body></code>```

Body:
When the screen size is less than 768px, the 3 boxes are aligned to the left. I'm having a hard time trying to make them appear center.

I managed to center it by setting margin-left to some value however, it isn't responsive afterwards.

Here's the code:

HTML

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

2015/16

The Best FIFA Men's Player 2016

FIFA Club World Cup

France Football Ballon D'Or 2016

UEFA Best Player in Europe

UEFA Euro 2016 (Portugal)

UEFA Champions League (Real Madrid)

2014/15

Pichichi Award

European Golden Boot 2015

FIFA Ballon D'Or 2014

Globe Soccer Best Player of the Year

Globe Soccer Fan's Favourite Player Award

IFFHS Trophy for Best Striker  on the planet

2013/14

Club World Cup

BBC Overseas Sports  Personality Award

World's Top  Goalscorer 2013

Pichichi Award

Best Player, Best Forward in La Liga

UEFA Best Player in Europe

CSS:

 .bg_color {
    background: #ECFEAA;
}

.stats_box {
    margin: 20px;
    padding: 20px 40px 40px;
    max-width: 400px;
    text-align: left;
    background: #fff;
    border-bottom: 4px solid #ccc;
    border-radius: 6px;

}

@media only screen and (max-width: 768px) {
  .stats_box {
    width: 100%;
    margin-left: 200px;
  }
}

Any possible solution for this? And why isn't margin:0 auto not working here?

Link to the code: CodePen

Body:
First of all change your mark up just like following and update css part

you are using nesting class with bootstrap classes and the bootstrap classes are using float:left that's why your code is not working.

Working fiddle fiddle

@media only screen and (max-width: 768px) {
  .stats_box {
    width: 100%;
    margin: 20px auto;
  }
}

.bg_color {
  background: #ECFEAA;
}

.stats_box {
  margin: 20px;
  padding: 20px 40px 40px;
  max-width: 400px;
  text-align: left;
  background: #fff;
  border-bottom: 4px solid #ccc;
  border-radius: 6px;
}

@media only screen and (max-width: 768px) {
  .stats_box {
    width: 100%;
    margin: 20px auto;
  }
}

body {
  margin: 0 auto;
}

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<body>
  <div class="row bg_color ">
    <div class="col-xs-12 col-sm-4 col-md-4">
      <div class="stats_box"> <!-- Place here the class same as rest -->
        <h3>2015/16</h3>
        <hr>
        <ul>
          <li>The Best FIFA Men's Player 2016</li>
          <li>FIFA Club World Cup</li>
          <li>France Football Ballon D'Or 2016</li>
          <li>UEFA Best Player in Europe</li>
          <li>UEFA Euro 2016 (Portugal)</li>
          <li>UEFA Champions League (Real Madrid)</li>
        </ul>
      </div>
    </div>
    <div class="col-xs-12 col-sm-4 col-md-4">
      <div class="stats_box">
        <h3>2015/16</h3>
        <hr>
        <ul>
          <li>The Best FIFA Men's Player 2016</li>
          <li>FIFA Club World Cup</li>
          <li>France Football Ballon D'Or 2016</li>
          <li>UEFA Best Player in Europe</li>
          <li>UEFA Euro 2016 (Portugal)</li>
          <li>UEFA Champions League (Real Madrid)</li>
        </ul>
      </div>
    </div>
    <div class="col-xs-12 col-sm-4 col-md-4">
      <div class="stats_box">
        <h3>2015/16</h3>
        <hr>
        <ul>
          <li>The Best FIFA Men's Player 2016</li>
          <li>FIFA Club World Cup</li>
          <li>France Football Ballon D'Or 2016</li>
          <li>UEFA Best Player in Europe</li>
          <li>UEFA Euro 2016 (Portugal)</li>
          <li>UEFA Champions League (Real Madrid)</li>
        </ul>
      </div>
    </div>
  </div>

</body>


问:
Shuffle ArrayList of objects
Read carefully before marking duplicate or downvoting.

My Requirement is to shuffle Arraylist of object keeping the list data same just changing the position.
I have an of type Dummydata :

```<code>List<DummyData> dataList = new ArrayList<>();
</code>```

My DummyData class has three String fields.

```<code>So adding some data for clarification:

dataList.add(new DummyData("Item1","Price1","Discount1"));
dataList.add(new DummyData("Item2","Price2","Discount2"));
dataList.add(new DummyData("Item3","Price3","Discount3"));
dataList.add(new DummyData("Item4","Price4","Discount4"));
dataList.add(new DummyData("Item5","Price5","Discount5"));
</code>```

When I use Collections.shuffle(dataList);

the output is :

```<code>Item5 Price3 Discount4
Item2 Price1 Discount2
and some random output like this everytime.
</code>```

My intended output is :

```<code>Item2 Price2 Discount2
Item5 Price5 Discount5
Item1 Price1 Discount1
</code>```

Just the position should change list data should not jumble.
so my question is this possible to achieve using Collections.shuffle or not??

答:
Try this

```<code>Collections.shuffle(dataList);
Log.d(TAG,dataList.toString());
</code>```

Working use your logic

```<code>   Collections.shuffle(dataList);
    ArrayList<DummyData> l1=new ArrayList<>();
    for(DummyData e : dataList){
        l1.add(e);
    }
    Log.d(TAG,l1.toString());
</code>```

Title: Shuffle ArrayList of objects

Body:
Read carefully before marking duplicate or downvoting.

My Requirement is to shuffle Arraylist of object keeping the list data same just changing the position.
I have an of type Dummydata :

List<DummyData> dataList = new ArrayList<>();

My DummyData class has three String fields.

So adding some data for clarification:

dataList.add(new DummyData("Item1","Price1","Discount1"));
dataList.add(new DummyData("Item2","Price2","Discount2"));
dataList.add(new DummyData("Item3","Price3","Discount3"));
dataList.add(new DummyData("Item4","Price4","Discount4"));
dataList.add(new DummyData("Item5","Price5","Discount5"));

When I use Collections.shuffle(dataList);

the output is :

Item5 Price3 Discount4
Item2 Price1 Discount2
and some random output like this everytime.

My intended output is :

Item2 Price2 Discount2
Item5 Price5 Discount5
Item1 Price1 Discount1

Just the position should change list data should not jumble.
so my question is this possible to achieve using Collections.shuffle or not??

Body:
Try this

Collections.shuffle(dataList);
Log.d(TAG,dataList.toString());

Working use your logic

   Collections.shuffle(dataList);
    ArrayList<DummyData> l1=new ArrayList<>();
    for(DummyData e : dataList){
        l1.add(e);
    }
    Log.d(TAG,l1.toString());


问:
I want to retrieve all data from table between two dates

The above screenshot shows table data where ClNum - 97 has three rows of data with different dates. I want to get all dates data for CLNum-97 from

```<code>EntryDate >= '1-6-2017' to EntryDate <= '30-6-2017'
</code>```

and order by EntryDate ASC but retrieve only the last date data.

Please help me out here I want all data of that employee between this two dates.

答:
You have to use date in the format of yyyy-mm-dd. Try below query.
May be it solve your problem.</p>

```<code>Select * from TimeSheet where EntryDate >= '2017-06-01' and EntryDate <= '2017-06-30'
</code>```

Body:
The above screenshot shows table data where ClNum - 97 has three rows of data with different dates. I want to get all dates data for CLNum-97 from

EntryDate >= '1-6-2017' to EntryDate <= '30-6-2017'

and order by EntryDate ASC but retrieve only the last date data.

Please help me out here I want all data of that employee between this two dates.

Body:
You have to use date in the format of yyyy-mm-dd. Try below query.
May be it solve your problem.

Select * from TimeSheet where EntryDate >= '2017-06-01' and EntryDate <= '2017-06-30'


问:
HTTP Status [404] ? [Not Found] (The origin server did not find a current representatio)
I have created one servlet project using (jsp,servlet,apache tomcat 9, eclipse neon,oracle 11g). I have created index.jsp (to take login details and redirect to LoginServlet for username and password validations in database table. In index.jsp I even mentioned a "register.jsp" link to register if first time user). When I run project index.jsp page opens.

When I provide user id and password details (manually entered username and password details in database), it's successfully redirecting me LoginServlet and then so on servlets.

But when I click on the link for "register", I am getting above mentioned error (HTTP Status [404] ? [Not Found] Type Status Report Message /TodayServlet/register.jsp Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. Apache Tomcat/9.0.0.M20)

My problem is from index.jsp, I am unable to open "register.jsp" ("register.jsp provided through anchor tag in index.jsp).

Please find my attachments for directory structure and main jsp and servlets and web.xml code.

index.jsp (main code):

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<center>
<form action="LoginServlet" method="post">
enter name:<input type="text" name="name"><br>
enter pass:<input type="password" name="pass"><br>

<a href="register.jsp">New User Register here...!!!</a><br>
<input type="submit" value="login"><br>
</form>
</center>
</body>
</html>
</code>```

register.jsp (main code):

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<center>
<form action="RegisterServlet" method="post">
enter name:<input type="text" name= "name1"> <br>
enter pass:<input type="text" name= "pass1"><br>
enter email:<input type="text" name="email1"><br>
<input type="submit" value="register"><br>
</form>
</center>
</body>
</html>
</code>```

RegisterServlet.java (main code):

```<code>package com.pack;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RegisterServlet extends HttpServlet {

    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        res.setContentType("text/html");
        PrintWriter out=res.getWriter();
        String uname1=req.getParameter("name1");
        String upass1=req.getParameter("pass1");
        String uemail1=req.getParameter("email1");
        req.setAttribute("username", uname1);
        try{
        Connection conn=DbConnection.getConnection();
        PreparedStatement ps=conn.prepareStatement("insert into register_table values(?,?,?)");
        ps.setString(1, uname1);
        ps.setString(2, upass1);
        ps.setString(3, uemail1);
        int i=ps.executeUpdate();
        if(i>0){
            req.getRequestDispatcher("WelcomeServlet").forward(req, res);
        }
        else{
            out.print("try registering again ");
            req.getRequestDispatcher("register.jsp").include(req, res);
        }
        }
            catch(Exception e){
            e.printStackTrace();
        }
    }

}
</code>```

I am facing no problem with other servlets (LoginServlet, WelcomeServlet...)

LoginServlet.java (whole code):

```<code>package com.pack;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {

    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    RequestDispatcher rd= null;
        res.setContentType("text/html");
    PrintWriter out=res.getWriter();
    String upassword=req.getParameter("pass");
    out.println(upassword);

    String uname2=req.getParameter("name");
    out.println(uname2);
    try{
        Connection con=DbConnection.getConnection();
        out.println("conection established");
        PreparedStatement ps=con.prepareStatement("select * from register_table where username=? and password=?");
        ps.setString(1, uname2);
        ps.setString(2, upassword);
        ResultSet rs= ps.executeQuery();

        if(rs.next()){
            out.println("username is "+rs.getString(1)+" and pwd is "+rs.getString(2));
            req.setAttribute("uid", uname2);
            req.getRequestDispatcher("MainServlet").forward(req, res);
        }else{
            out.println("user name or password incorrect.Check and login again or register");
            req.getRequestDispatcher("index.jsp").include(req, res);
        }
    }catch(Exception e){
        e.printStackTrace();
    }

    }

}
</code>```

web.xml  (code):

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>TodayServlet</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>LoginServlet</display-name>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.pack.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>RegisterServlet</display-name>
    <servlet-name>RegisterServlet</servlet-name>
    <servlet-class>com.pack.RegisterServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>RegisterServlet</servlet-name>
    <url-pattern>/RegisterServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>WelcomeServlet</display-name>
    <servlet-name>WelcomeServlet</servlet-name>
    <servlet-class>com.pack.WelcomeServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>WelcomeServlet</servlet-name>
    <url-pattern>/WelcomeServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>MainServlet</display-name>
    <servlet-name>MainServlet</servlet-name>
    <servlet-class>com.pack.MainServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>MainServlet</servlet-name>
    <url-pattern>/MainServlet</url-pattern>
  </servlet-mapping>

</web-app>
</code>```

Directory structure:

TodayServlet( project name)>src>com.pack>servlets

web-inf> (web.xml and jsp files)

答:
Though the resources which need to be protected from Http access are placed under WEB-INF.
Normally jsps serves the purpose of presentation to the user, that is why they are placed outside WEB-INF.
But due to some reasons, if you insist of keeping jsp file under WEB-INF folder than create one servlet,
and invoke that servlet from your registration link.

In the servlet, you need to use requestdispatcher to redirect to your register.jsp

Keep your Servlet code like this :(I assume that your register.jsp is availabe directly under WEB-INF folder)

```<code>@WebServlet("/ControlFlowServlet")
public class ControlFlowServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        RequestDispatcher dispatcher = getServletContext()
                .getRequestDispatcher("/WEB-INF/register.jsp");
        dispatcher.forward(request, response);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}
</code>```

Add this mapping in your web.xml:

```<code> <servlet-mapping>
    <servlet-name>ControlFlowServlet</servlet-name>
    <url-pattern>/register</url-pattern>
  </servlet-mapping>
</code>```

And in your index.jsp keep like this:

```<code><a href="${pageContext.request.contextPath}/register">New User Register here...!!!</a><br>
</code>```

For more information kindly read this explanation carefully.
If you need any clarification, kindly let me know.

Body:
I have created one servlet project using (jsp,servlet,apache tomcat 9, eclipse neon,oracle 11g). I have created index.jsp (to take login details and redirect to LoginServlet for username and password validations in database table. In index.jsp I even mentioned a "register.jsp" link to register if first time user). When I run project index.jsp page opens.

When I provide user id and password details (manually entered username and password details in database), it's successfully redirecting me LoginServlet and then so on servlets.

But when I click on the link for "register", I am getting above mentioned error (HTTP Status [404] ? [Not Found] Type Status Report Message /TodayServlet/register.jsp Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. Apache Tomcat/9.0.0.M20)

My problem is from index.jsp, I am unable to open "register.jsp" ("register.jsp provided through anchor tag in index.jsp).

Please find my attachments for directory structure and main jsp and servlets and web.xml code.

index.jsp (main code):

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

<form action="LoginServlet" method="post">
enter name:<input type="text" name="name">

enter pass:<input type="password" name="pass">

New User Register here...!!!

<input type="submit" value="login">

</form>

register.jsp (main code):

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

<form action="RegisterServlet" method="post">
enter name:<input type="text" name= "name1">

enter pass:<input type="text" name= "pass1">

enter email:<input type="text" name="email1">

<input type="submit" value="register">

</form>

RegisterServlet.java (main code):

package com.pack;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RegisterServlet extends HttpServlet {

    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        res.setContentType("text/html");
        PrintWriter out=res.getWriter();
        String uname1=req.getParameter("name1");
        String upass1=req.getParameter("pass1");
        String uemail1=req.getParameter("email1");
        req.setAttribute("username", uname1);
        try{
        Connection conn=DbConnection.getConnection();
        PreparedStatement ps=conn.prepareStatement("insert into register_table values(?,?,?)");
        ps.setString(1, uname1);
        ps.setString(2, upass1);
        ps.setString(3, uemail1);
        int i=ps.executeUpdate();
        if(i>0){
            req.getRequestDispatcher("WelcomeServlet").forward(req, res);
        }
        else{
            out.print("try registering again ");
            req.getRequestDispatcher("register.jsp").include(req, res);
        }
        }
            catch(Exception e){
            e.printStackTrace();
        }
    }

}

I am facing no problem with other servlets (LoginServlet, WelcomeServlet...)

LoginServlet.java (whole code):

package com.pack;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {

    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    RequestDispatcher rd= null;
        res.setContentType("text/html");
    PrintWriter out=res.getWriter();
    String upassword=req.getParameter("pass");
    out.println(upassword);

    String uname2=req.getParameter("name");
    out.println(uname2);
    try{
        Connection con=DbConnection.getConnection();
        out.println("conection established");
        PreparedStatement ps=con.prepareStatement("select * from register_table where username=? and password=?");
        ps.setString(1, uname2);
        ps.setString(2, upassword);
        ResultSet rs= ps.executeQuery();

        if(rs.next()){
            out.println("username is "+rs.getString(1)+" and pwd is "+rs.getString(2));
            req.setAttribute("uid", uname2);
            req.getRequestDispatcher("MainServlet").forward(req, res);
        }else{
            out.println("user name or password incorrect.Check and login again or register");
            req.getRequestDispatcher("index.jsp").include(req, res);
        }
    }catch(Exception e){
        e.printStackTrace();
    }

    }

}

web.xml  (code):

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>TodayServlet</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>LoginServlet</display-name>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.pack.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>RegisterServlet</display-name>
    <servlet-name>RegisterServlet</servlet-name>
    <servlet-class>com.pack.RegisterServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>RegisterServlet</servlet-name>
    <url-pattern>/RegisterServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>WelcomeServlet</display-name>
    <servlet-name>WelcomeServlet</servlet-name>
    <servlet-class>com.pack.WelcomeServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>WelcomeServlet</servlet-name>
    <url-pattern>/WelcomeServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>MainServlet</display-name>
    <servlet-name>MainServlet</servlet-name>
    <servlet-class>com.pack.MainServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>MainServlet</servlet-name>
    <url-pattern>/MainServlet</url-pattern>
  </servlet-mapping>

</web-app>

Directory structure:

TodayServlet( project name)>src>com.pack>servlets

web-inf> (web.xml and jsp files)

Body:
Though the resources which need to be protected from Http access are placed under WEB-INF.
Normally jsps serves the purpose of presentation to the user, that is why they are placed outside WEB-INF.
But due to some reasons, if you insist of keeping jsp file under WEB-INF folder than create one servlet,
and invoke that servlet from your registration link.

In the servlet, you need to use requestdispatcher to redirect to your register.jsp

Keep your Servlet code like this :(I assume that your register.jsp is availabe directly under WEB-INF folder)

@WebServlet("/ControlFlowServlet")
public class ControlFlowServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        RequestDispatcher dispatcher = getServletContext()
                .getRequestDispatcher("/WEB-INF/register.jsp");
        dispatcher.forward(request, response);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

Add this mapping in your web.xml:

 <servlet-mapping>
    <servlet-name>ControlFlowServlet</servlet-name>
    <url-pattern>/register</url-pattern>
  </servlet-mapping>

And in your index.jsp keep like this:

<a href="${pageContext.request.contextPath}/register">New User Register here...!!!</a><br>

For more information kindly read this explanation carefully.
If you need any clarification, kindly let me know.


问:
Square Subsequence
A string is called a square string if it can be obtained by concatenating two copies of the same string. For example, "abab", "aa" are square strings, while "aaa", "abba" are not. Given a string, how many subsequences of the string are square strings? A subsequence of a string can be obtained by deleting zero or more characters from it, and maintaining the relative order of the remaining characters.The subsequence need not be unique.

eg string 'aaa' will have 3 square subsequences

答:
```<code>import java.io.*;
import java.util.*;

public class Solution {
    /*
        Sample Input:
        3
        aaa
        abab
        baaba

        Sample Output:
        3
        3
        6
    */
    public static void main(String[] args) {
        //Creating an object of SquareString class
        SquareString squareStringObject=new SquareString();
        Scanner in = new Scanner(System.in);
        //Number of Test Cases
        int T = in.nextInt();
        in.nextLine();
        String[] inputString=new String[T];
        for(int i=0;i<T;i++){
            // Taking input and storing in String Array
            inputString[i]=in.nextLine();
        }
        for(int i=0;i<T;i++){
            //Calculating and printing the number of Square Strings
            squareStringObject.numberOfSquareStrings(inputString[i]);
        }
    }
}
class SquareString{
    //The counter maintained for keeping a count of Square Strings
    private int squareStringCounter;
    //Default Constructor initialising the counter as 0
    public SquareString(){
        squareStringCounter=0;
    }
    //Function calculates and prints the number of square strings
    public void numberOfSquareStrings(String inputString){
        squareStringCounter=0;
        //Initialising the string part1 as a single character iterated over the length
        for(int iterStr1=0;iterStr1<inputString.length()-1;iterStr1++){
            String str1=""+inputString.charAt(iterStr1);
            String str2=inputString.substring(iterStr1+1);
            //Calling a recursive method to generate substring
            generateSubstringAndCountSquareStrings(str1,str2);
        }
        System.out.println(squareStringCounter);
    }
    //Recursive method to generate sub strings
    private void generateSubstringAndCountSquareStrings(String str1,String str2){
        for(int iterStr2=0;iterStr2<str2.length();iterStr2++){
            String newStr1=str1+str2.charAt(iterStr2);
            if(isSquareString(newStr1)){
                squareStringCounter++;
            }
            String newStr2=str2.substring(iterStr2+1);
            generateSubstringAndCountSquareStrings(newStr1,newStr2);
        }
    }
    private boolean isSquareString(String str){
        if(str.length()%2!=0)
            return false;
        String strPart1=str.substring(0,str.length()/2);
        String strPart2=str.substring(str.length()/2);
        return strPart1.equals(strPart2);
    }
}
</code>```

Title: Square Subsequence


问:
PHP - get object parent
I have a function that is called like this:

```<code>foo($object->ID);
</code>```

and in the function I need to somehow select $object if $object->ID is passed as a variable.

```<code>function foo($id = NULL){
  if($id != NULL) ... // here I want to get $object
  else ...
}
</code>```

How can I do this?

答:
If I understand what you're asking correctly, why not just pass the object itself by ref?

```<code>function foo(&$obj)
{
    if($obj != NULL && $obj->ID != NULL)
    {
       // ...process your stuff
    }
}
</code>```

My PHP's pretty rusty, but I'm fairly sure that's how you pass by ref...

ContentLicense: CC BY-SA 2.5

Title: PHP - get object parent

Body:
I have a function that is called like this:

foo($object->ID);

and in the function I need to somehow select $object if $object->ID is passed as a variable.

function foo($id = NULL){
  if($id != NULL) ... // here I want to get $object
  else ...
}

How can I do this?

Body:
If I understand what you're asking correctly, why not just pass the object itself by ref?

function foo(&$obj)
{
    if($obj != NULL && $obj->ID != NULL)
    {
       // ...process your stuff
    }
}

My PHP's pretty rusty, but I'm fairly sure that's how you pass by ref...


答:
margin: 0 auto; does not work because you have float: left; on the .stats_box. So you can handle this a couple of ways.

1) Remove float when 768px <, DEMO

```<code>@media only screen and (max-width: 768px) {
  .stats_box {
    float: none;
    margin: 15px auto;
  }
}
</code>```

2) do not work "directly" under the col-xs-12, have a container inside and have that have the max-width and all other styling, set margin: 0 auto; on that. This would be my suggested solution. DEMO

```<code><div class="col-xs-12 col-sm-4 col-md-4">
    <div class="stats_box">
      <h3>2015/16</h3>
      <hr>
      <ul>
        <li>The Best FIFA Men's Player 2016</li>
        <li>FIFA Club World Cup</li>
        <li>France Football Ballon D'Or 2016</li>
        <li>UEFA Best Player in Europe</li>
        <li>UEFA Euro 2016 (Portugal)</li>
        <li>UEFA Champions League (Real Madrid)</li>
      </ul>
    </div>
  </div>

@media only screen and (max-width: 768px) {
  .stats_box {
    margin: 15px auto;
  }
}
</code>```

3) Use flexbox when 768px <, DEMO

```<code>@media only screen and (max-width: 768px) {
      .row {
        display: flex;
        justify-content: center;
        flex-wrap: wrap;
      }
    }
</code>```

4) Use inline (I would not suggest this solution so no example)

Title: Unable to center content using margin auto

Body:
margin: 0 auto; does not work because you have float: left; on the .stats_box. So you can handle this a couple of ways.

1) Remove float when 768px <, DEMO

@media only screen and (max-width: 768px) {
  .stats_box {
    float: none;
    margin: 15px auto;
  }
}

2) do not work "directly" under the col-xs-12, have a container inside and have that have the max-width and all other styling, set margin: 0 auto; on that. This would be my suggested solution. DEMO

<div class="col-xs-12 col-sm-4 col-md-4">
    <div class="stats_box">
      <h3>2015/16</h3>
      <hr>
      <ul>
        <li>The Best FIFA Men's Player 2016</li>
        <li>FIFA Club World Cup</li>
        <li>France Football Ballon D'Or 2016</li>
        <li>UEFA Best Player in Europe</li>
        <li>UEFA Euro 2016 (Portugal)</li>
        <li>UEFA Champions League (Real Madrid)</li>
      </ul>
    </div>
  </div>

@media only screen and (max-width: 768px) {
  .stats_box {
    margin: 15px auto;
  }
}

3) Use flexbox when 768px <, DEMO

@media only screen and (max-width: 768px) {
      .row {
        display: flex;
        justify-content: center;
        flex-wrap: wrap;
      }
    }

4) Use inline (I would not suggest this solution so no example)


问:
calling super class init when child class is created using type()
I am trying to create a class dynamically using the python type() method.

So, say i have a base class 'A'

```<code>>>> class A:
    def __init__(self):
        print("I am in init of A..")
</code>```

Now i create a child class 'C' by using type method

```<code>>>> C = type('C',(A,),{})
</code>```

When i create an object

```<code>>>> c = C()
I am in init of A..
</code>```

The init of base class is also called correctly..

now i want to do something in my init method and i write a custom init method..

```<code>>>> def BsInit(self):
    print ("I am in init of B..")
</code>```

and i create a class 'B' and create an instance..

```<code>>>> B = type('B',(A,),{'__init__':BsInit})
>>> b = B()
I am in init of B..
</code>```

The init of class A is not called at all..

So tried to modify BsInit method like this:

```<code>>>> def BsInit(self):
    super().__init__();
    print ("I am in init of B..")
</code>```

And i get the below error when i create an instance...

```<code>>>> B = type('B',(A,),{'__init__':BsInit})
>>> b = B()
Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>
    b = B()
  File "<pyshell#19>", line 2, in BsInit
    super().__init__();print ("I am in init of B..")
RuntimeError: super(): __class__ cell not found
</code>```

All the examples i find with custom init using type() are really simple, like just initialising a variable.. but if i want to call base class Init too how to do it??

答: You need to call it like so: super(B, self).__init__().

Body:
I am trying to create a class dynamically using the python type() method.

So, say i have a base class 'A'

>>> class A:
    def __init__(self):
        print("I am in init of A..")

Now i create a child class 'C' by using type method

>>> C = type('C',(A,),{})

When i create an object

>>> c = C()
I am in init of A..

The init of base class is also called correctly..

now i want to do something in my init method and i write a custom init method..

>>> def BsInit(self):
    print ("I am in init of B..")

and i create a class 'B' and create an instance..

>>> B = type('B',(A,),{'__init__':BsInit})
>>> b = B()
I am in init of B..

The init of class A is not called at all..

So tried to modify BsInit method like this:

>>> def BsInit(self):
    super().__init__();
    print ("I am in init of B..")

And i get the below error when i create an instance...

>>> B = type('B',(A,),{'__init__':BsInit})
>>> b = B()
Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>
    b = B()
  File "<pyshell#19>", line 2, in BsInit
    super().__init__();print ("I am in init of B..")
RuntimeError: super(): __class__ cell not found

All the examples i find with custom init using type() are really simple, like just initialising a variable.. but if i want to call base class Init too how to do it??


答:
You need to pass cls in init method instead of self. Below is the solution of your problem:</p>

```<code>def init(cls):
    super(type(cls), cls).__init__()

B = type('B',(A,),{'__init__':init})
b = B()
"I am in init of A.."
</code>```

Title: calling super class init when child class is created using type()

Body:
You need to pass cls in init method instead of self. Below is the solution of your problem:

def init(cls):
    super(type(cls), cls).__init__()

B = type('B',(A,),{'__init__':init})
b = B()
"I am in init of A.."


问:
How to create the confusion matrix with stargazer and caret
I'm trying to create a one table in sweave r, but it does not come out as I want. This is the code I have.</p>

```<code><<results='asis'>>=
## 2 class example
library(caret)
lvs <- c("normal", "abnormal")
truth <- factor(rep(lvs, times = c(86, 258)),
                levels = rev(lvs))

pred <- factor(c(rep(lvs, times = c(54, 32)),
                 rep(lvs, times = c(27, 231))),
                 levels = rev(lvs))

xtab <- table(pred, truth)
Con.Mat <- confusionMatrix(xtab)
Con.Mat$table
Con.Mat$overall
Con.Mat$byClass

stargazer::stargazer(Con.Mat$table,head=FALSE,title = "Table")
stargazer::stargazer(Con.Mat$overall,head=FALSE,title = "overall")
stargazer::stargazer(Con.Mat$byClass,head=FALSE,title = "byClass")
@
</code>```

答:
The output of R with the confusionMatrix () function is as follows

```<code>> confusionMatrix(xtab)
Confusion Matrix and Statistics

          truth
pred       abnormal normal
  abnormal      231     32
  normal         27     54

               Accuracy : 0.8285
                 95% CI : (0.7844, 0.8668)
    No Information Rate : 0.75
    P-Value [Acc > NIR] : 0.0003097

                  Kappa : 0.5336
 Mcnemar's Test P-Value : 0.6025370

            Sensitivity : 0.8953
            Specificity : 0.6279
         Pos Pred Value : 0.8783
         Neg Pred Value : 0.6667
             Prevalence : 0.7500
         Detection Rate : 0.6715
   Detection Prevalence : 0.7645
      Balanced Accuracy : 0.7616

       'Positive' Class : abnormal
</code>```

While using stargazer
enter image description here

Body:
I'm trying to create a one table in sweave r, but it does not come out as I want. This is the code I have.

<<results='asis'>>=
## 2 class example
library(caret)
lvs <- c("normal", "abnormal")
truth <- factor(rep(lvs, times = c(86, 258)),
                levels = rev(lvs))

pred <- factor(c(rep(lvs, times = c(54, 32)),
                 rep(lvs, times = c(27, 231))),
                 levels = rev(lvs))

xtab <- table(pred, truth)
Con.Mat <- confusionMatrix(xtab)
Con.Mat$table
Con.Mat$overall
Con.Mat$byClass

stargazer::stargazer(Con.Mat$table,head=FALSE,title = "Table")
stargazer::stargazer(Con.Mat$overall,head=FALSE,title = "overall")
stargazer::stargazer(Con.Mat$byClass,head=FALSE,title = "byClass")
@

Body:
The output of R with the confusionMatrix () function is as follows

> confusionMatrix(xtab)
Confusion Matrix and Statistics

          truth
pred       abnormal normal
  abnormal      231     32
  normal         27     54

               Accuracy : 0.8285
                 95% CI : (0.7844, 0.8668)
    No Information Rate : 0.75
    P-Value [Acc > NIR] : 0.0003097

                  Kappa : 0.5336
 Mcnemar's Test P-Value : 0.6025370

            Sensitivity : 0.8953
            Specificity : 0.6279
         Pos Pred Value : 0.8783
         Neg Pred Value : 0.6667
             Prevalence : 0.7500
         Detection Rate : 0.6715
   Detection Prevalence : 0.7645
      Balanced Accuracy : 0.7616

       'Positive' Class : abnormal

While using stargazer
enter image description here


问:
Connection pooling options with JDBC: DBCP vs C3P0
What is the best connection pooling library available for Java/JDBC?

I'm considering the 2 main candidates (free / open-source):

Apache DBCP - http://commons.apache.org/dbcp/

C3P0 - http://sourceforge.net/projects/c3p0

I've read a lot about them in blogs and other forums but could not reach a decision.

Are there any relevant alternatives to these two?

答:
I was having trouble with DBCP when the connections times out so I trialled c3p0.  I was going to release this to production but then started performance testing.  I found that c3p0 performed terribly.  I couldn't configure it to perform well at all.  I found it twice as slow as DBCP.

I then tried the Tomcat connection pooling.

This was twice as fast as c3p0 and fixed other issues I was having with DBCP.  I spent a lot of time investigating and testing the 3 pools.  My advice if you are deploying to Tomcat is to use the new Tomcat JDBC pool.

OwnerDisplayName: Dema


问:
How to create boxplot with large amount of continuous x-variables and continuous y-variables with R (not ggplot)
How to create boxplot with large amount of continuous x-variables and continuous y-variableswith R
don't use ggplot.
Just like the following figure, the x-axis and y-axis are all continuous numerical variable.
example boxplot</p>

答:
Boxplot between two variables

```<code> boxplot(xval~yval)
</code>```

I would advise a scatterplot though

Now suppose I want to reduce the number of boxplots, I would convert the x axis into some mind of bins using cut

cut divides the range of x into intervals and codes the values in x according to which interval they fall

newyval=cut(yval,20) for 20 bins

then

```<code>boxplot(xval~newyval)
</code>```

Body:
Boxplot between two variables

 boxplot(xval~yval)

I would advise a scatterplot though

Now suppose I want to reduce the number of boxplots, I would convert the x axis into some mind of bins using cut

cut divides the range of x into intervals and codes the values in x according to which interval they fall

newyval=cut(yval,20) for 20 bins

then

boxplot(xval~newyval)


问:
get textarea value in post in php
I have a textarea in my HTML. How can I post it to my PHP?

```<code><textarea>
<div id="keditor-content-area-1496927072839" class="keditor-content-area ui-droppable ui-sortable"><section class="keditor-container keditor-initialized-container showed-keditor-toolbar" id="keditor-container-1496927074545">   <section class="keditor-container-inner"><div class="row">        <div class="col-sm-12 keditor-container-content ui-droppable ui-sortable" data-type="container-content" id="keditor-container-content-1496927074546">        <section class="keditor-component keditor-initialized-component" data-type="component-text" id="keditor-component-1496927076874">   <section class="keditor-component-content cke_editable cke_editable_inline cke_contents_ltr cke_show_borders" id="keditor-component-content-1496927076875" contenteditable="true" tabindex="0" spellcheck="false" role="textbox" aria-label="false" aria-describedby="cke_46"><div class="page-header"><h1 style="margin-bottom: 30px; font-size: 50px;"><b class="text-uppercase">Cras justo odio</b> <small>Donec id elit non mi</small></h1><p class="lead"><em>Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.</em></p></div></section><div class="keditor-toolbar keditor-toolbar-component">   <a href="#" class="btn-component-reposition"><i class="fa fa-arrows"></i></a>   <a href="#" class="btn-component-duplicate"><i class="fa fa-files-o"></i></a>   <a href="#" class="btn-component-delete"><i class="fa fa-times"></i></a></div></section></div>    </div></section><div class="keditor-toolbar keditor-toolbar-container">   <a href="#" class="btn-container-reposition"><i class="fa fa-sort"></i></a>   <a href="#" class="btn-container-duplicate"><i class="fa fa-files-o"></i></a>   <a href="#" class="btn-container-delete"><i class="fa fa-times"></i></a></div></section></div>
</textarea>
</code>```

but it always take
Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.
in post i want all div tag and all html code. please help me out.

答:
You need something like this:</p>

```<code>if(isset($_POST['textarea_value'])){
    echo $_POST['textarea_value'];
}

<form method="post" action="">
    <textarea name="textarea_value"></textarea>
    <input type="submit" value="Send" />
</form>
</code>```

Title: get textarea value in post in php

Body:
I have a textarea in my HTML. How can I post it to my PHP?

<textarea>

Cras justo odio Donec id elit non mi

Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.

</textarea>

but it always take
Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.
in post i want all div tag and all html code. please help me out.

Body:
You need something like this:

if(isset($_POST['textarea_value'])){
    echo $_POST['textarea_value'];
}

<form method="post" action="">
    <textarea name="textarea_value"></textarea>
    <input type="submit" value="Send" />
</form>


问:
NSString extension method doesn't call String extension method
I have an extension on String that defines test.  I also want to be able to get test's functionality from NSString.  In the real code String.test is more complex.  So rather than re-implementing it for NSString I cast str to String and call test on it.  My understanding here is that now str is of type String and String.test will be invoked, returning String Test.

However, it seems that str.test() winds up calling NSString.test and I wind up with unending recursion until the stack overflows.

```<code>import Foundation

extension NSString {

    func test() -> NSString {
        let str = self as String
        return str.test() as NSString
    }
}

extension String {

    func test() -> String {
        return "String test"
    }
}

let s: NSString = "test"
s.test()
</code>```

答:
I didn't actually realize it did this, but apparently Swift automatically exposes extension methods you define on NSString to String. So you can actually delete your String version and just use the NSString one. Alternatively, if you want to avoid bridging strings into Obj-C just to call your method, you can pull out the implementation into a private global function (rather than an extension method) and call that from both implementations, like so:

```<code>import Foundation

private func stringTest(_ str: String) -> String {
    return "String test"
}

extension NSString {
    func test() -> NSString {
        return stringTest(self as String) as NSString
    }
}

extension String {
    func test() -> String {
        return stringTest(self)
    }
}
</code>```

Body:
I have an extension on String that defines test.  I also want to be able to get test's functionality from NSString.  In the real code String.test is more complex.  So rather than re-implementing it for NSString I cast str to String and call test on it.  My understanding here is that now str is of type String and String.test will be invoked, returning String Test.

However, it seems that str.test() winds up calling NSString.test and I wind up with unending recursion until the stack overflows.

import Foundation

extension NSString {

    func test() -> NSString {
        let str = self as String
        return str.test() as NSString
    }
}

extension String {

    func test() -> String {
        return "String test"
    }
}

let s: NSString = "test"
s.test()

Body:
I didn't actually realize it did this, but apparently Swift automatically exposes extension methods you define on NSString to String. So you can actually delete your String version and just use the NSString one. Alternatively, if you want to avoid bridging strings into Obj-C just to call your method, you can pull out the implementation into a private global function (rather than an extension method) and call that from both implementations, like so:

import Foundation

private func stringTest(_ str: String) -> String {
    return "String test"
}

extension NSString {
    func test() -> NSString {
        return stringTest(self as String) as NSString
    }
}

extension String {
    func test() -> String {
        return stringTest(self)
    }
}


问:
Kivy how to access widget in function, no KV just python code
Sorry for my very basic problem but I have been searching around of an answer for an hour to no avail.

this is my basic code:

```<code>class LoginScreen(Screen):

def __init__(self,**kwargs):
    super(LoginScreen,self).__init__(**kwargs)

    l = BoxLayout(orientation='vertical')
    sound_btn = Button(text="Play Sound", font_size = 300)
    word_bx = TextInput(multiline=False,hint_text='type here...',font_size=300)
    submit_btn = Button(text = 'Submit', font_size=300)
    submit_btn.bind(on_press = self.submitAction)
    l.add_widget(sound_btn)
    l.add_widget(word_bx)
    l.add_widget(submit_btn)
    self.add_widget(l)

def submitAction(self,*args):
    if self.word_bx.text == KivyApp.word:
        KivyApp.point+=1
    self.word_bx.text=""
    KivyApp.i +=1
    print(KivyApp.point)
</code>```

As you can see, in the submitAction function I want to reference the word_bx widget, but this throws an error stating that Class LoginPage has no attribute word_bx. I then tried to place 'ids' infront of self but that throws another error. What am I doing wrong? sorry for my incompetence..

答:
These lines

```<code>word_bx = TextInput(multiline=False,hint_text='type here...',font_size=300)
...
l.add_widget(word_bx)
</code>```

define word_bx as a temporary variable. It's not available after __init__() exits. If you want it to be persistent so that you can access it from other methods, you need to make it a member of the class.

```<code>self.word_bx = TextInput(multiline=False,hint_text='type here...',font_size=300)
...
l.add_widget(self.word_bx)
</code>```

Then the line

```<code>self.word_bx.text=""
</code>```

in submitAction() will refer to something that actually exists.

Body:
Sorry for my very basic problem but I have been searching around of an answer for an hour to no avail.

this is my basic code:

class LoginScreen(Screen):

def __init__(self,**kwargs):
    super(LoginScreen,self).__init__(**kwargs)

    l = BoxLayout(orientation='vertical')
    sound_btn = Button(text="Play Sound", font_size = 300)
    word_bx = TextInput(multiline=False,hint_text='type here...',font_size=300)
    submit_btn = Button(text = 'Submit', font_size=300)
    submit_btn.bind(on_press = self.submitAction)
    l.add_widget(sound_btn)
    l.add_widget(word_bx)
    l.add_widget(submit_btn)
    self.add_widget(l)

def submitAction(self,*args):
    if self.word_bx.text == KivyApp.word:
        KivyApp.point+=1
    self.word_bx.text=""
    KivyApp.i +=1
    print(KivyApp.point)

As you can see, in the submitAction function I want to reference the word_bx widget, but this throws an error stating that Class LoginPage has no attribute word_bx. I then tried to place 'ids' infront of self but that throws another error. What am I doing wrong? sorry for my incompetence..

Body:
These lines

word_bx = TextInput(multiline=False,hint_text='type here...',font_size=300)
...
l.add_widget(word_bx)

define word_bx as a temporary variable. It's not available after __init__() exits. If you want it to be persistent so that you can access it from other methods, you need to make it a member of the class.

self.word_bx = TextInput(multiline=False,hint_text='type here...',font_size=300)
...
l.add_widget(self.word_bx)

Then the line

self.word_bx.text=""

in submitAction() will refer to something that actually exists.


问:
OpenCV 3.2 CUDA support python
I've just installed OpenCV 3.2 compiling with CUDA support following instruction in http://www.pyimagesearch.com/2016/07/11/compiling-opencv-with-cuda-support/
I just wonder how to check whether my OpenCV is using CUDA and GPU support when running (I use python2.7)</p>

答:
As you can see in the link you gave, you can always check whether you have installed CUDA correctly by typing this on python console.

```<code>print(cv2.getBuildInformation())
</code>```

If you have CUDA support, you will be seen that Use CUDA: YES (version) in the printed text.

Then you can use opencv cuda commands in cv2.cuda module.

But as said in that tutorial CUDA support is not there at present in python. (As these tutorials are on OpenCV python you will get confused whether this will add CUDA support for python. But it will not..)

Furthermore, in a GPU-enabled CUDA environment, there are a number of compile-time optimizations we can make to OpenCV, allowing it to take advantage of the GPU for faster computation (but mainly for C++ applications, not so much for Python, at least at the present time).

But as described in this answer, you can get OpenCL support on python. As in this document,

Open Computing Language (OpenCL) is an open standard for writing code that runs across heterogeneous platforms including CPUs, GPUs, DSPs and etc.

Edit 1:

Another thing that you can do is, you can write python wrappers for each GPU methods in OpenCV C++ and call those methods via python. I will not recommend that because this will always copy images and other data between GPU memory and RAM resulting bad performance. Sometimes this will take more time than CPU alone.

Another thing that you can do is writing the whole function you need to do using GPU in C++ and write a python wrapper for that function. This is much more better than the previous method but you will need to know C++.

There can be even better ways of doing this..

Title: OpenCV 3.2 CUDA support python

Body:
As you can see in the link you gave, you can always check whether you have installed CUDA correctly by typing this on python console.

print(cv2.getBuildInformation())

If you have CUDA support, you will be seen that Use CUDA: YES (version) in the printed text.

Then you can use opencv cuda commands in cv2.cuda module.

But as said in that tutorial CUDA support is not there at present in python. (As these tutorials are on OpenCV python you will get confused whether this will add CUDA support for python. But it will not..)

Furthermore, in a GPU-enabled CUDA environment, there are a number of compile-time optimizations we can make to OpenCV, allowing it to take advantage of the GPU for faster computation (but mainly for C++ applications, not so much for Python, at least at the present time).

But as described in this answer, you can get OpenCL support on python. As in this document,

Open Computing Language (OpenCL) is an open standard for writing code that runs across heterogeneous platforms including CPUs, GPUs, DSPs and etc.

Edit 1:

Another thing that you can do is, you can write python wrappers for each GPU methods in OpenCV C++ and call those methods via python. I will not recommend that because this will always copy images and other data between GPU memory and RAM resulting bad performance. Sometimes this will take more time than CPU alone.

Another thing that you can do is writing the whole function you need to do using GPU in C++ and write a python wrapper for that function. This is much more better than the previous method but you will need to know C++.

There can be even better ways of doing this..