问:
Get HTML with current input values
I need to get the HTML of the whole page, with the current values of all inputs in their value="...".

I've tried this:

```<code>document.getElementById("htmlId").innerHTML;
</code>```

and this:

```<code>$('html').html();
</code>```

but the both return the HTML page but without the input values.

I know that this looks like this other question, but it is not the same. I really need get the HTML with the value attributes.

答:
An input has a value attribute that determines the initial value of the input. It also has a value property that holds the current value of the input.

It appears that you want to export the HTML markup of the page, where the value attributes of all inputs are set to the value of the value property.

You can do so as follows:

```<code>// first, set `value` attribute to value of property for all inputs
$('input').attr('value', function() {
  return $(this).val();
});
// export HTML with correct `value` attributes
$('html').html();
</code>```

And here is a little demo of that in action.

$('#export').on('click', () => {
  $('input').attr('value', function() {
    return $(this).val();
  });
  console.log($('html').html());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Some paragraph.</p>
<input type="text" value="initial value" />
<h1>Header</h1>
<p>Another paragraph</p>
<button id="export">Export page</button></code>```

Title: Get HTML with current input values

Body:
I need to get the HTML of the whole page, with the current values of all inputs in their value="...".

I've tried this:

document.getElementById("htmlId").innerHTML;

and this:

$('html').html();

but the both return the HTML page but without the input values.

I know that this looks like this other question, but it is not the same. I really need get the HTML with the value attributes.

Body:
An input has a value attribute that determines the initial value of the input. It also has a value property that holds the current value of the input.

It appears that you want to export the HTML markup of the page, where the value attributes of all inputs are set to the value of the value property.

You can do so as follows:

// first, set `value` attribute to value of property for all inputs
$('input').attr('value', function() {
  return $(this).val();
});
// export HTML with correct `value` attributes
$('html').html();

And here is a little demo of that in action.

$('#export').on('click', () => {
  $('input').attr('value', function() {
    return $(this).val();
  });
  console.log($('html').html());
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Some paragraph.</p>
<input type="text" value="initial value" />
<h1>Header</h1>
<p>Another paragraph</p>
<button id="export">Export page</button>


来源: stackexchange

问:
jquery json decimal rounding
im pulling data from quandl and doing some calculations. the issue is the result goes upto 15 decimal points. is there any way that could be done to limit this to two?</p>

```<code><script>
var apikey = "myapikey";
var url = "https://www.quandl.com/api/v1/datasets/"
var database = "BSE/BOM532667";
var parameters = ".json?auth_token=";
var fullUrl = url + database + parameters + apikey;
jQuery.getJSON(fullUrl, function (data1) {
$('#value1').html((data1.data[0][4]-data1.data[29][4])*100/data1.data[0][4]);
</script>

1-Month return (%): <span id="value1"></span><br>
</code>```

答:
Try this.

```<code>// ((data1.data[0][4]-data1.data[29][4])*100/data1.data[0][4]).toFixed(2)
$('#value1').html(((data1.data[0][4]-data1.data[29][4])*100/data1.data[0][4]).toFixed(2));
</code>```

This will reduce your decimal points to 2 from any number of points.

ContentLicense: CC BY-SA 3.0

Title: jquery json decimal rounding

Body:
im pulling data from quandl and doing some calculations. the issue is the result goes upto 15 decimal points. is there any way that could be done to limit this to two?

1-Month return (%):

Body:
Try this.

// ((data1.data[0][4]-data1.data[29][4])*100/data1.data[0][4]).toFixed(2)
$('#value1').html(((data1.data[0][4]-data1.data[29][4])*100/data1.data[0][4]).toFixed(2));

This will reduce your decimal points to 2 from any number of points.


问:
Count Values associated with key in Sql Server
I have three tables

Table Category

```<code>CategoryID         Category
1                   Climate
2                   Area
</code>```

Table CategoryDetail

```<code>DetailID    CategoryID      Desc
1            1              Hot
2            1              Cold
3            2              Area1
</code>```

Table CategoryDetailValues

```<code>PK  AnotherFK  CategoryDetailID
1    1           1
2    1           1
3    1           2
4    2           1
</code>```

Here AnotherFK is foreign key referring to another table. In record 1 and 2 duplicate exists that's ok but AnotherFK 1 has reference of CategoryDetailID 1 and 2 which has categoryID of 1 which is not ok

So from above tables
this result is valid from above three table

```<code>PK   AnotherFK    CategoryID  DetailID     Desc
1    1             1            1          Hot
2    1             1            1          Hot
</code>```

But below result is not valid

```<code>PK   AnotherFK    CategoryID  DetailID     Desc
2    1             1           1           Hot
3    1             1           2           Cold
</code>```

I can not put same AnotherFK in two different DetailID which has same CategoryID. I could have eliminated this by introducing CategoryID in CategoryDetailValues table and creating unique constraint but I am not allowed to do so.

Now my aim is to find all those record in CategoryDetailValues table which has different DetailID that are associated with same CategoryID. So that I can delete them.

Trying to achieve this in SQL Server 2012.

答:
I think you could use something like this:

Script to create sample tables:

```<code>CREATE TABLE mytable(
   PK               INTEGER  NOT NULL PRIMARY KEY
  ,AnotherFK        INTEGER  NOT NULL
  ,CategoryDetailID INTEGER  NOT NULL
);
INSERT INTO mytable(PK,AnotherFK,CategoryDetailID) VALUES (1,1,1);
INSERT INTO mytable(PK,AnotherFK,CategoryDetailID) VALUES (2,1,1);
INSERT INTO mytable(PK,AnotherFK,CategoryDetailID) VALUES (3,1,2);
INSERT INTO mytable(PK,AnotherFK,CategoryDetailID) VALUES (4,2,1);
INSERT INTO mytable(PK,AnotherFK,CategoryDetailID) VALUES (5,1,3);
INSERT INTO mytable(PK,AnotherFK,CategoryDetailID) VALUES (6,1,3);
INSERT INTO mytable(PK,AnotherFK,CategoryDetailID) VALUES (7,1,3);

CREATE TABLE mytable2(
   DetailID   INTEGER  NOT NULL
  ,CategoryID INTEGER  NOT NULL
  ,Descr       VARCHAR(5) NOT NULL
);
</code>```

Query to show "suspect" record (I think you have to decide what records delete...):

```<code>SELECT *  FROM (
SELECT * ,COUNT(*) OVER (PARTITION BY CategoryID, ANotherFK) AS X
, COUNT(*) OVER (PARTITION BY CategoryID, DetailID, ANotherFK) AS X1
FROM mytable A
INNER JOIN mytable2 B ON A.CategoryDetailID= B.DetailID
)C
WHERE X-X1 >0
</code>```

Output:

```<code>+--+----+-----------+------------------+----------+------------+-------+---+----+
|  | PK | AnotherFK | CategoryDetailID | DetailID | CategoryID | Descr | X | X1 |
+--+----+-----------+------------------+----------+------------+-------+---+----+
|  |  1 |         1 |                1 |        1 |          1 | Hot   | 3 |  2 |
|  |  2 |         1 |                1 |        1 |          1 | Hot   | 3 |  2 |
|  |  3 |         1 |                2 |        2 |          1 | Cold  | 3 |  1 |
+--+----+-----------+------------------+----------+------------+-------+---+----+
</code>```

Body:
I have three tables

Table Category

CategoryID         Category
1                   Climate
2                   Area

Table CategoryDetail

DetailID    CategoryID      Desc
1            1              Hot
2            1              Cold
3            2              Area1

Table CategoryDetailValues

PK  AnotherFK  CategoryDetailID
1    1           1
2    1           1
3    1           2
4    2           1

Here AnotherFK is foreign key referring to another table. In record 1 and 2 duplicate exists that's ok but AnotherFK 1 has reference of CategoryDetailID 1 and 2 which has categoryID of 1 which is not ok

So from above tables
this result is valid from above three table

PK   AnotherFK    CategoryID  DetailID     Desc
1    1             1            1          Hot
2    1             1            1          Hot

But below result is not valid

PK   AnotherFK    CategoryID  DetailID     Desc
2    1             1           1           Hot
3    1             1           2           Cold

I can not put same AnotherFK in two different DetailID which has same CategoryID. I could have eliminated this by introducing CategoryID in CategoryDetailValues table and creating unique constraint but I am not allowed to do so.

Now my aim is to find all those record in CategoryDetailValues table which has different DetailID that are associated with same CategoryID. So that I can delete them.

Trying to achieve this in SQL Server 2012.

Body:
I think you could use something like this:

Script to create sample tables:

CREATE TABLE mytable(
   PK               INTEGER  NOT NULL PRIMARY KEY
  ,AnotherFK        INTEGER  NOT NULL
  ,CategoryDetailID INTEGER  NOT NULL
);
INSERT INTO mytable(PK,AnotherFK,CategoryDetailID) VALUES (1,1,1);
INSERT INTO mytable(PK,AnotherFK,CategoryDetailID) VALUES (2,1,1);
INSERT INTO mytable(PK,AnotherFK,CategoryDetailID) VALUES (3,1,2);
INSERT INTO mytable(PK,AnotherFK,CategoryDetailID) VALUES (4,2,1);
INSERT INTO mytable(PK,AnotherFK,CategoryDetailID) VALUES (5,1,3);
INSERT INTO mytable(PK,AnotherFK,CategoryDetailID) VALUES (6,1,3);
INSERT INTO mytable(PK,AnotherFK,CategoryDetailID) VALUES (7,1,3);

CREATE TABLE mytable2(
   DetailID   INTEGER  NOT NULL
  ,CategoryID INTEGER  NOT NULL
  ,Descr       VARCHAR(5) NOT NULL
);

Query to show "suspect" record (I think you have to decide what records delete...):

SELECT *  FROM (
SELECT * ,COUNT(*) OVER (PARTITION BY CategoryID, ANotherFK) AS X
, COUNT(*) OVER (PARTITION BY CategoryID, DetailID, ANotherFK) AS X1
FROM mytable A
INNER JOIN mytable2 B ON A.CategoryDetailID= B.DetailID
)C
WHERE X-X1 >0

Output:

+--+----+-----------+------------------+----------+------------+-------+---+----+
|  | PK | AnotherFK | CategoryDetailID | DetailID | CategoryID | Descr | X | X1 |
+--+----+-----------+------------------+----------+------------+-------+---+----+
|  |  1 |         1 |                1 |        1 |          1 | Hot   | 3 |  2 |
|  |  2 |         1 |                1 |        1 |          1 | Hot   | 3 |  2 |
|  |  3 |         1 |                2 |        2 |          1 | Cold  | 3 |  1 |
+--+----+-----------+------------------+----------+------------+-------+---+----+


问:
CSS - Line height property, how it works (simple)
So in this simple example I have as final result:

This is a very simple question but I simply can't get my head around it.

To achieve the vertical centering of the numbers I used:

```<code>line-height:100px;
</code>```

Which works great and have been doing it trial and error basis.

My question is specifically why the line-height:50px; just gets if half of the way.

If the small div has a height of 100px and I an positioning relative to it, shouldn't the half of it center it to the half.

This specially puzzles me since, when I center a div:

I would use: margin:50px 0 0 50px; to get this:

I realize this question might be an overkill since the answer might be (probably will be very simple), so sorry! but I guess it is better the "why doesn't this work" questions ;)

Thanks in advance!!

答: When you give an element a line-height of 100% (in your example, this equates to 100px), the text is placed in the middle vertically of a line that's 100px tall.</p>

ContentLicense: CC BY-SA 2.5

Body:
So in this simple example I have as final result:

This is a very simple question but I simply can't get my head around it.

To achieve the vertical centering of the numbers I used:

line-height:100px;

Which works great and have been doing it trial and error basis.

My question is specifically why the line-height:50px; just gets if half of the way.

If the small div has a height of 100px and I an positioning relative to it, shouldn't the half of it center it to the half.

This specially puzzles me since, when I center a div:

I would use: margin:50px 0 0 50px; to get this:

I realize this question might be an overkill since the answer might be (probably will be very simple), so sorry! but I guess it is better the "why doesn't this work" questions ;)

Thanks in advance!!


答:
Assuming "html" itself is an id of an element, you can try cloneNode.

```<code>var clonedElem = document.getElementById("html").cloneNode(true);
</code>```

This clonedElem is a DOM object which contains both html as well as values ( and all other attributes). You can now use this DOM for all your purposes.

For Eg. If you wish to insert it into another element, you can do like

```<code>document.getElementById('newElement').appendChild(clonedElem)
</code>```

This will put the entire node with its values

Title: Get HTML with current input values

Body:
Assuming "html" itself is an id of an element, you can try cloneNode.

var clonedElem = document.getElementById("html").cloneNode(true);

This clonedElem is a DOM object which contains both html as well as values ( and all other attributes). You can now use this DOM for all your purposes.

For Eg. If you wish to insert it into another element, you can do like

document.getElementById('newElement').appendChild(clonedElem)

This will put the entire node with its values


答:
Use document.cloneNode to clone the whole document with retaining the state of the html.

cloneNode has a boolean parameter that denotes the following

true - Clone the node, its attributes, and its descendants

false - Default. Clone only the node and its attributes

For more details check this document

function cloneMe() {
  var newelement = document.cloneNode(true);
  console.log(newelement.getElementsByTagName("input")[0].value)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" value="Change My Value" style="width:100%" />
<input type="submit" onclick="cloneMe()" value="Clone Now" /></code>```

Title: Get HTML with current input values

Body:
Use document.cloneNode to clone the whole document with retaining the state of the html.

cloneNode has a boolean parameter that denotes the following

true - Clone the node, its attributes, and its descendants

false - Default. Clone only the node and its attributes

For more details check this document

function cloneMe() {
  var newelement = document.cloneNode(true);
  console.log(newelement.getElementsByTagName("input")[0].value)
}

<input type="text" value="Change My Value" style="width:100%" />
<input type="submit" onclick="cloneMe()" value="Clone Now" />


问:
Text to speech error, conflicting with the speech to text button
I am trying to use iOS speech to text api and text to speech api together. Basically a user will speak and what they say will be transcribed in a textview. Then the user will press a  button which will provide text to speech from the transcribed text in the textview. My error is that when the user presses the speech-to-text button,  the text to speech button stops working. However if I don't press the speech to text button at all and input some text in the textview via keyboard then text to speech button works. I am guess it is has issue with the speech to text button.  I am not getting any errors on my code and i am confused as to what is going on.

import UIKit
import Speech
import AVFoundation

class SpeechRecognitionViewController: UIViewController, SFSpeechRecognizerDelegate, UIPickerViewDataSource, UIPickerViewDelegate {

    private var speechRecognizer: SFSpeechRecognizer!
    private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest!
    private var recognitionTask: SFSpeechRecognitionTask!
    private let audioEngine = AVAudioEngine()
    private var locales: [Locale]!
    private let defaultLocale = Locale(identifier: "en-US")

    @IBOutlet weak var recordBtn: UIButton!

    @IBOutlet weak var speaker: UIButton!
    @IBOutlet weak var textView: UITextField!
    //@IBOutlet weak var textView: UITextView!
    //@IBOutlet private weak var recordBtn : UIButton!
    //@IBOutlet private weak var picker: UIPickerView!
    @IBOutlet weak var picker: UIPickerView!

    override func viewDidLoad() {
        super.viewDidLoad()

        recordBtn.isEnabled = false

        locales = SFSpeechRecognizer.supportedLocales().map({$0})

        let index = NSArray(array: locales).index(of: defaultLocale)
        picker.selectRow(index, inComponent: 0, animated: false)

        prepareRecognizer(locale: defaultLocale)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        SFSpeechRecognizer.requestAuthorization { authStatus in
            /*
             The callback may not be called on the main thread. Add an
             operation to the main queue to update the record button's state.
             */
            OperationQueue.main.addOperation {
                switch authStatus {
                case .authorized:
                    self.recordBtn.isEnabled = true

                case .denied:
                    self.recordBtn.isEnabled = false
                    self.recordBtn.setTitle("User denied access to speech recognition", for: .disabled)

                case .restricted:
                    self.recordBtn.isEnabled = false
                    self.recordBtn.setTitle("Speech recognition restricted on this device", for: .disabled)

                case .notDetermined:
                    self.recordBtn.isEnabled = false
                    self.recordBtn.setTitle("Speech recognition not yet authorized", for: .disabled)
                }
            }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    private func prepareRecognizer(locale: Locale) {
        speechRecognizer = SFSpeechRecognizer(locale: locale)!
        speechRecognizer.delegate = self
    }

    private func startRecording() throws {

        // Cancel the previous task if it's running.
        if let recognitionTask = recognitionTask {
            recognitionTask.cancel()
            self.recognitionTask = nil
        }

        let audioSession = AVAudioSession.sharedInstance()
        try audioSession.setCategory(AVAudioSessionCategoryRecord)
        try audioSession.setMode(AVAudioSessionModeMeasurement)
        try audioSession.setActive(true, with: .notifyOthersOnDeactivation)

        recognitionRequest = SFSpeechAudioBufferRecognitionRequest()

        guard let inputNode = audioEngine.inputNode else { fatalError("Audio engine has no input node") }
        guard let recognitionRequest = recognitionRequest else { fatalError("Unable to created a SFSpeechAudioBufferRecognitionRequest object") }

        // Configure request so that results are returned before audio recording is finished
        recognitionRequest.shouldReportPartialResults = true

        // A recognition task represents a speech recognition session.
        // We keep a reference to the task so that it can be cancelled.
        recognitionTask = speechRecognizer.recognitionTask(with: recognitionRequest) { result, error in
            var isFinal = false

            if let result = result {
                self.textView.text = result.bestTranscription.formattedString
                isFinal = result.isFinal
            }

            if error != nil || isFinal {
                self.audioEngine.stop()
                inputNode.removeTap(onBus: 0)

                self.recognitionRequest = nil
                self.recognitionTask = nil

                self.recordBtn.isEnabled = true
                self.recordBtn.setTitle("Start Recording", for: [])
            }
        }

        let recordingFormat = inputNode.outputFormat(forBus: 0)
        inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer: AVAudioPCMBuffer, when: AVAudioTime) in
            self.recognitionRequest?.append(buffer)
        }

        audioEngine.prepare()

        try audioEngine.start()

        textView.text = "(listening...)"
    }

    // =========================================================================
    // MARK: - UIPickerViewDataSource

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return locales.count
    }

    // =========================================================================
    // MARK: - UIPickerViewDelegate

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return locales[row].identifier
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        let locale = locales[row]
        prepareRecognizer(locale: locale)
    }

    // =========================================================================
    // MARK: - SFSpeechRecognizerDelegate

    public func speechRecognizer(_ speechRecognizer: SFSpeechRecognizer, availabilityDidChange available: Bool) {
        if available {
            recordBtn.isEnabled = true
            recordBtn.setTitle("Start Recording", for: [])
        } else {
            recordBtn.isEnabled = false
            recordBtn.setTitle("Recognition not available", for: .disabled)
        }
    }

    // =========================================================================
    // MARK: - Actions

    @IBAction func recordbuttontapped(_ sender: Any) {

        if audioEngine.isRunning {
            audioEngine.stop()
            recognitionRequest?.endAudio()
            recordBtn.isEnabled = false
            recordBtn.setTitle("Stopping", for: .disabled)
        } else {
            try! startRecording()
            recordBtn.setTitle("Stop recording", for: [])
        }
    }

    @IBAction func speaktome(_ sender: Any) {

        let something = textView.text!
        let utterance = AVSpeechUtterance(string: something)
        utterance.voice = AVSpeechSynthesisVoice(language: "en-US" )

        let synthesizer = AVSpeechSynthesizer()

        synthesizer.speak(utterance)
    }
}
```

答:
Change the try audioSession.setCategory(AVAudioSessionCategoryRecord)
 to try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
 it should work as intended. During speech to text you are changing the audio session to record mode and it is not getting changed to play mode during TTS. The other alternative is to set the audio session to AVAudioSessionCategoryPlayback during the TTS.


问:
jQuery UI Datepicker is not working in Angular JS UI Bootstrap modal
I am not able to open jQuery UI Date Picker in UI Bootstrap Model. Normal HTML date picker is opening up but jQuery Date Picker is not opening up. Here is the code:-

Test.html

```<code><!DOCTYPE html>
<html ng-app="appHome">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <link href="https://code.jquery.com/ui/1.10.4/themes/redmond/jquery-ui.css" rel="stylesheet">
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
    <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js"></script>
    <script src="../Scripts/AngularControllers/Test.js"></script>
    <script src="../Scripts/AngularControllers/Test1.js"></script>
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div ng-controller="ModalDemoCtrl">
        <button type="button"  ng-click="open()">Open me!</button>
    </div>
</body>
</html>
</code>```

Test.js

```<code>var myApp = angular.module('appHome', ['ui.bootstrap']);

myApp.controller('ModalDemoCtrl', ['$scope', '$uibModal', function ($scope, $uibModal) {
    $scope.open = function (size, parentSelector) {
        var modalInstance = $uibModal.open({
            templateUrl: 'Test1.html',
            controller: 'ModalDemoCtrl1',
            size :'lg'
        });
    };
}])
</code>```

Test1.html

```<code><div>
        <h1>Modal Body</h1>
        <input type="date" />
        Date of Birth<input type="text" class="datepicker-ui" id="dateDOB" ng-model="dob">
    </div>
</code>```

Test1. js

```<code> var myApp = angular.module('appHome');
 myApp.controller('ModalDemoCtrl1', ['$scope',  function ($scope) {

        $(".datepicker-ui").datepicker({

            dateFormat: "dd/mm/yy",
            changeMonth: true,
            changeYear: true,
            yearRange: "-100:+0",
            stepMonths: 1,
            onSelect: function (date) {
                  if (this.id == "dateDOB") {
                       $scope.dob = date;
                       $scope.$apply();
            }

        }
       });
    }])
</code>```

Please find below the screenshot of HTML Pages after rendered in browser:-

Test.html

After clicking on "Open Me" button

Here you can see the normal HTML Date control is working but jQuery UI Datepicker is not.

Please help me in making jQuery UI datepicker work in Modal.

答:
angular.module('HomeApp', ['ui.bootstrap']);
var ModalDemoCtrl = function($scope, $modal, $log) {

  $scope.open = function() {

    var modalInstance = $modal.open({
      templateUrl: 'myModalContent.html',
      controller: ModalInstanceCtrl
    });

    modalInstance.result.then(function(selected) {
      $scope.selected = selected;
    }, function() {
      $log.info('Modal dismissed at: ' + new Date());
    });
  };
};

var ModalInstanceCtrl = function($scope, $modalInstance, $timeout) {

  $scope.dt = new Date();

  $scope.open = function() {

    $timeout(function() {
      $scope.opened = true;
    });
  };

  $scope.ok = function() {
    $modalInstance.close($scope.dt);
  };

  $scope.cancel = function() {
    $modalInstance.dismiss('cancel');
  };
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html ng-app="HomeApp">

<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  <script src="https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.7.0.js"></script>
  <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
</head>

<body>

  <div ng-controller="ModalDemoCtrl">
    <script type="text/ng-template" id="myModalContent.html">

      <div class="modal-header">
        <h3>I'm a modal!</h3>
      </div>
      <div class="modal-body" style="height:600px;">
        ```Selected date is: {{dt | date:'fullDate' }}```
        <div class="form-horizontal">
          <div class="input-group">
            <input type="text" class="form-control" datepicker-popup="dd.mm.yyyy" ng-model="dt" is-open="$parent.opened" ng-required="true" close-text="Close" />

            <span class="input-group-btn">
              <button style="height:34px;" class="btn calendar btn-default" ng-click="open()">

              </span>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-primary" ng-click="ok()">OK</button>
        <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
      </div>
    </script>

    <button class="btn" ng-click="open()">Open me!</button>
    <div ng-show="selected">Selection from a modal: {{ selected }}</div>
  </div>
</body>

</html></code>```

Body:
I am not able to open jQuery UI Date Picker in UI Bootstrap Model. Normal HTML date picker is opening up but jQuery Date Picker is not opening up. Here is the code:-

Test.html

<!DOCTYPE html>

    <link href="https://code.jquery.com/ui/1.10.4/themes/redmond/jquery-ui.css" rel="stylesheet">

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

        <button type="button"  ng-click="open()">Open me!</button>

Test.js

var myApp = angular.module('appHome', ['ui.bootstrap']);

myApp.controller('ModalDemoCtrl', ['$scope', '$uibModal', function ($scope, $uibModal) {
    $scope.open = function (size, parentSelector) {
        var modalInstance = $uibModal.open({
            templateUrl: 'Test1.html',
            controller: 'ModalDemoCtrl1',
            size :'lg'
        });
    };
}])

Test1.html

Modal Body

        <input type="date" />
        Date of Birth<input type="text" class="datepicker-ui" id="dateDOB" ng-model="dob">

Test1. js

 var myApp = angular.module('appHome');
 myApp.controller('ModalDemoCtrl1', ['$scope',  function ($scope) {

        $(".datepicker-ui").datepicker({

            dateFormat: "dd/mm/yy",
            changeMonth: true,
            changeYear: true,
            yearRange: "-100:+0",
            stepMonths: 1,
            onSelect: function (date) {
                  if (this.id == "dateDOB") {
                       $scope.dob = date;
                       $scope.$apply();
            }

        }
       });
    }])

Please find below the screenshot of HTML Pages after rendered in browser:-

Test.html

After clicking on "Open Me" button

Here you can see the normal HTML Date control is working but jQuery UI Datepicker is not.

Please help me in making jQuery UI datepicker work in Modal.

Body:
angular.module('HomeApp', ['ui.bootstrap']);
var ModalDemoCtrl = function($scope, $modal, $log) {

  $scope.open = function() {

    var modalInstance = $modal.open({
      templateUrl: 'myModalContent.html',
      controller: ModalInstanceCtrl
    });

    modalInstance.result.then(function(selected) {
      $scope.selected = selected;
    }, function() {
      $log.info('Modal dismissed at: ' + new Date());
    });
  };
};

var ModalInstanceCtrl = function($scope, $modalInstance, $timeout) {

  $scope.dt = new Date();

  $scope.open = function() {

    $timeout(function() {
      $scope.opened = true;
    });
  };

  $scope.ok = function() {
    $modalInstance.close($scope.dt);
  };

  $scope.cancel = function() {
    $modalInstance.dismiss('cancel');
  };
};

<!doctype html>
<html ng-app="HomeApp">

<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  <script src="https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.7.0.js"></script>
  <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
</head>

<body>

  <div ng-controller="ModalDemoCtrl">
    <script type="text/ng-template" id="myModalContent.html">

      <div class="modal-header">
        <h3>I'm a modal!</h3>
      </div>
      <div class="modal-body" style="height:600px;">
        <pre>Selected date is: <em>{{dt | date:'fullDate' }}</em></pre>
        <div class="form-horizontal">
          <div class="input-group">
            <input type="text" class="form-control" datepicker-popup="dd.mm.yyyy" ng-model="dt" is-open="$parent.opened" ng-required="true" close-text="Close" />

            <span class="input-group-btn">
              <button style="height:34px;" class="btn calendar btn-default" ng-click="open()">

              </span>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-primary" ng-click="ok()">OK</button>
        <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
      </div>
    </script>

    <button class="btn" ng-click="open()">Open me!</button>
    <div ng-show="selected">Selection from a modal: {{ selected }}</div>
  </div>
</body>

</html>


问:
Ellipsize - start not working in TextView
I have a textView as follows:

```<code><TextView
    android:id="@+id/pointsTextView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/pointTextView"
    android:ellipsize="start"
    android:lines="2"
    android:paddingEnd="5dp"
    android:paddingStart="5dp"
    android:text="this is a very very very very very very very very very very very very very very very very very very very very very long sentence." />
</code>```

Here ellipsize="end" is working perfectly, but ellipsize="start" is not wroking when no of lines is not 1.

How can I make this work in such TextView with 2 or more no of lines?

答:
Try this one</p>

```<code>  <TextView
        android:id="@+id/pointsTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ellipsize="start"
        android:paddingEnd="5dp"
        android:paddingStart="5dp"
        android:maxLines="1"
        android:text="Hello this is a very very very very very very very very very very very very very very very very very very very very very long sentence. "
        />
</code>```

Body:
I have a textView as follows:

<TextView
    android:id="@+id/pointsTextView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/pointTextView"
    android:ellipsize="start"
    android:lines="2"
    android:paddingEnd="5dp"
    android:paddingStart="5dp"
    android:text="this is a very very very very very very very very very very very very very very very very very very very very very long sentence." />

Here ellipsize="end" is working perfectly, but ellipsize="start" is not wroking when no of lines is not 1.

How can I make this work in such TextView with 2 or more no of lines?

Body:
Try this one

  <TextView
        android:id="@+id/pointsTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ellipsize="start"
        android:paddingEnd="5dp"
        android:paddingStart="5dp"
        android:maxLines="1"
        android:text="Hello this is a very very very very very very very very very very very very very very very very very very very very very long sentence. "
        />


问:
Advantages of IQueryable<T> over IList<T>
In C# DAL, What advantages will i derive if i return IQueryable than IList, Iam not using Entity Framework / N Hibernate, just plain old ADO.Net.. </p>

答: You can keep querying against IQueryable.  IQueryable is not for your final return type but good for private helpers which build on original queries - reusable, composable pieces of queries that have an expected return type of the underlying type in your IQueryable<>.</p>

ContentLicense: CC BY-SA 4.0


问:
don't want whitespace to occur when text is too long and i got to enter
Is there any way when your text is too long - and you break it up with new lines - to not have whitespace happen? What I need is three values to be joint without whitespace in between.

```<code><div style='font-size:100%; color:blue'>
    {{ $record->m_pk_address_line1 }}
    {{ $record->m_pk_address_line2 }}
    {{ $record->m_pk_address_line3 }}
</div>
</code>```

Without entering new line, it'll be too long even if they can be joined together.

```<code><div style='font-size:100%; color:blue'>{{ $record->m_pk_address_line1 }}{{ $record->m_pk_address_line2 }}{{ $record->m_pk_address_line3 }}</div>
</code>```

Is there no standard way of going about this without resorting to tricks? What do people do when their code is too long and they need to break it up into new lines but they don't want the whitespace that comes with it?

答:
Concatenate all three items:

```<code><div style='font-size:100%; color:blue'>
    {{ $record->m_pk_address_line1.$record->m_pk_address_line2.$record->m_pk_address_line3 }}
</div>
</code>```

Body:
Is there any way when your text is too long - and you break it up with new lines - to not have whitespace happen? What I need is three values to be joint without whitespace in between.

    {{ $record->m_pk_address_line1 }}
    {{ $record->m_pk_address_line2 }}
    {{ $record->m_pk_address_line3 }}

Without entering new line, it'll be too long even if they can be joined together.

{{ $record->m_pk_address_line1 }}{{ $record->m_pk_address_line2 }}{{ $record->m_pk_address_line3 }}

Is there no standard way of going about this without resorting to tricks? What do people do when their code is too long and they need to break it up into new lines but they don't want the whitespace that comes with it?

Body:
Concatenate all three items:

<div style='font-size:100%; color:blue'>
    {{ $record->m_pk_address_line1.$record->m_pk_address_line2.$record->m_pk_address_line3 }}
</div>


问:
How can Detect UTF 16 decoding
I have to read a file and identify its decoding type, I used mb_detect_encoding() to detect utf-16 but am getting wrong result.. how can i detectutf-16 encoding type in php.

Php file is utf-16 and my header was windows-1256 ( because of Arabic)

```<code>header('Content-Type: text/html; charset=windows-1256');

$delimiter = '\t';
$f= file("$fileName");

 foreach($f as $dailystatmet)
{
    $transactionData = str_replace("'", '', $dailystatmet);
    preg_match_all("/('?\d+,\d+\.\d+)?([a-zA-Z]|[0-9]|)[^".$delimiter."]+/",$transactionData,$matches);

        array_push($matchesz, $matches[0]);

}

$searchKeywords = array ("apple", "orange", 'mango');

$rowCount = count($matchesz);

for ($row = 1; $row <= $rowCount; $row++) {
    $myRow = $row;
    $cell = $matchesz[$row];

    foreach ($searchKeywords as $val) {

        if (partialArraySearch($cell[$c_description], $val)) {

          }
       }}

function partialArraySearch($cell, $searchword)
{

    if (strpos(strtoupper($cell), strtoupper($searchword)) !== false) {

        return true;
    }

    return false;
}
</code>```

Above code is for search with in the uploaded file.. if the file was in utf-8 then match was getting but when same file with utf-16 or utf-32 am not getting the result..

so how can i get the encoding type of uploaded file ..

答:
My solution is to detect UTF-16 and convert the code in Latin 15 is

```<code>  preg_match_all('/\x00/',$content,$count);
  if(count($count[0])/strlen($content)>0.4) {
     $content = iconv('UTF-16', 'ISO-8859-15', $content);
  }
</code>```

In other words i check the frequency of the hexadecimal character 00. If it is higher than 0.4 probably the text contains characters in the base set encoded in UTF-16. This means two bytes for character but usually the second byte is 00.

Title: How can Detect UTF 16 decoding

Body:
I have to read a file and identify its decoding type, I used mb_detect_encoding() to detect utf-16 but am getting wrong result.. how can i detectutf-16 encoding type in php.

Php file is utf-16 and my header was windows-1256 ( because of Arabic)

header('Content-Type: text/html; charset=windows-1256');

$delimiter = '\t';
$f= file("$fileName");

 foreach($f as $dailystatmet)
{
    $transactionData = str_replace("'", '', $dailystatmet);
    preg_match_all("/('?\d+,\d+\.\d+)?([a-zA-Z]|[0-9]|)[^".$delimiter."]+/",$transactionData,$matches);

        array_push($matchesz, $matches[0]);

}

$searchKeywords = array ("apple", "orange", 'mango');

$rowCount = count($matchesz);

for ($row = 1; $row <= $rowCount; $row++) {
    $myRow = $row;
    $cell = $matchesz[$row];

    foreach ($searchKeywords as $val) {

        if (partialArraySearch($cell[$c_description], $val)) {

          }
       }}

function partialArraySearch($cell, $searchword)
{

    if (strpos(strtoupper($cell), strtoupper($searchword)) !== false) {

        return true;
    }

    return false;
}

Above code is for search with in the uploaded file.. if the file was in utf-8 then match was getting but when same file with utf-16 or utf-32 am not getting the result..

so how can i get the encoding type of uploaded file ..

Body:
My solution is to detect UTF-16 and convert the code in Latin 15 is

  preg_match_all('/\x00/',$content,$count);
  if(count($count[0])/strlen($content)>0.4) {
     $content = iconv('UTF-16', 'ISO-8859-15', $content);
  }

In other words i check the frequency of the hexadecimal character 00. If it is higher than 0.4 probably the text contains characters in the base set encoded in UTF-16. This means two bytes for character but usually the second byte is 00.


问:
What Does The Spring Boot "debug" Config Property Set?
If I configure my Spring Boot web app with the following property in my application.yaml config file:

```<code>debug: true
</code>```

I've noticed that my logging config gets ignored and everything is set to a DEBUG level. Makes sense.

Does debug=true affect anything else though? Or is this simply a logging thing?

答:
From the documentation at https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html

you can also specify debug=true in your application.properties.

When the debug mode is enabled, a selection of core loggers (embedded
  container, Hibernate and Spring Boot) are configured to output more
  information.

Body:
If I configure my Spring Boot web app with the following property in my application.yaml config file:

debug: true

I've noticed that my logging config gets ignored and everything is set to a DEBUG level. Makes sense.

Does debug=true affect anything else though? Or is this simply a logging thing?


问:
Get dataframe of random time between two input times pandas python
i am trying to create a pandas dataframe which has two columns,

```<code>id  time
1   2017/06/07 11:30:22
2   2017/06/07 12:03:32
...  ...
800 2017/07/07 02:10:28
</code>```

i.e  total no. of id's should be 800 and ,

it should fill the time column by random dates(in the same format),between past 30 hours.

i tried:

```<code>import pandas as pd
N = 800
df = pd.DataFrame({ 'id' : range(1, N + 1 ,1)})
</code>```

this will give me sequential 800 values for id column, i am confused how to have time column and fill it with random time for past 30 hours( from current time)

Body:
i am trying to create a pandas dataframe which has two columns,

id  time
1   2017/06/07 11:30:22
2   2017/06/07 12:03:32
...  ...
800 2017/07/07 02:10:28

i.e  total no. of id's should be 800 and ,

it should fill the time column by random dates(in the same format),between past 30 hours.

i tried:

import pandas as pd
N = 800
df = pd.DataFrame({ 'id' : range(1, N + 1 ,1)})

this will give me sequential 800 values for id column, i am confused how to have time column and fill it with random time for past 30 hours( from current time)

Body:
You can create DatetimeIndex by date_range and then use numpy.random.choice:

last30 = pd.datetime.now().replace(microsecond=0) - pd.Timedelta('30H')
print (last30)
2017-06-08 03:28:58

dates = pd.date_range(last30, periods = 30 * 60 * 60, freq='S')
print (dates)
DatetimeIndex(['2017-06-08 03:28:58', '2017-06-08 03:28:59',
               '2017-06-08 03:29:00', '2017-06-08 03:29:01',
               '2017-06-08 03:29:02', '2017-06-08 03:29:03',
               '2017-06-08 03:29:04', '2017-06-08 03:29:05',
               '2017-06-08 03:29:06', '2017-06-08 03:29:07',
               ...
               '2017-06-09 09:28:48', '2017-06-09 09:28:49',
               '2017-06-09 09:28:50', '2017-06-09 09:28:51',
               '2017-06-09 09:28:52', '2017-06-09 09:28:53',
               '2017-06-09 09:28:54', '2017-06-09 09:28:55',
               '2017-06-09 09:28:56', '2017-06-09 09:28:57'],
              dtype='datetime64[ns]', length=108000, freq='S')

N = 30
df = pd.DataFrame({ 'id' : range(1, N + 1, 1),
                   'time': np.random.choice(dates, size=N)})
print (df)
    id                time
0    1 2017-06-09 03:08:09
1    2 2017-06-08 21:30:41
2    3 2017-06-08 06:45:23
3    4 2017-06-08 05:30:37
4    5 2017-06-09 05:59:04
5    6 2017-06-08 16:08:51
6    7 2017-06-08 13:34:37
7    8 2017-06-09 02:51:59
8    9 2017-06-08 23:34:46
9   10 2017-06-08 18:01:22
10  11 2017-06-09 06:40:02
11  12 2017-06-08 07:58:49
12  13 2017-06-08 17:34:46
13  14 2017-06-08 20:07:05
14  15 2017-06-08 18:04:57
15  16 2017-06-08 07:28:35
16  17 2017-06-08 05:36:14
17  18 2017-06-08 08:05:19
18  19 2017-06-08 11:59:51
19  20 2017-06-08 11:53:28
20  21 2017-06-08 05:48:51
21  22 2017-06-08 11:06:42
22  23 2017-06-08 14:42:22
23  24 2017-06-08 03:31:41
24  25 2017-06-08 07:21:26
25  26 2017-06-08 22:08:06
26  27 2017-06-09 03:46:35
27  28 2017-06-08 16:24:45
28  29 2017-06-08 22:29:15
29  30 2017-06-09 03:22:23


问:
How to add a chat messenger feature in an Android application?
I am developing an Android Application. I wanted to include chat feature in it. I tried to search Scringo but it has shut down since February 2015. Kindly suggest some alternative solution for the problem. 1:1 chat constraint is not needed. </p>

答:
Developing your own chat platform takes time and efforts.
There are many companies who provides chat as a service :

Applozic

List item

Sendbird

Layer

Quickblox

read more in this article.


答:
Use numObj.toFixed([digits]) for round.

toFixed() returns a string representation of numObj that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If numObj is greater than 1e+21, this method simply calls Number.prototype.toString() and returns a string in exponential notation.

Examples

```<code>var numObj = 12345.6789;

numObj.toFixed();       // Returns '12346': note rounding, no fractional part
numObj.toFixed(1);      // Returns '12345.7': note rounding
numObj.toFixed(6);      // Returns '12345.678900': note added zeros
(1.23e+20).toFixed(2);  // Returns '123000000000000000000.00'
(1.23e-10).toFixed(2);  // Returns '0.00'
2.34.toFixed(1);        // Returns '2.3'
2.35.toFixed(1);        // Returns '2.4'. Note that it rounds up in this case.
-2.34.toFixed(1);       // Returns -2.3 (due to operator precedence, negative number literals don't return a string...)
(-2.34).toFixed(1);     // Returns '-2.3' (...unless you use parentheses)
</code>```

Title: jquery json decimal rounding

Body:
im pulling data from quandl and doing some calculations. the issue is the result goes upto 15 decimal points. is there any way that could be done to limit this to two?

1-Month return (%):

Body:
Use numObj.toFixed([digits]) for round.

toFixed() returns a string representation of numObj that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If numObj is greater than 1e+21, this method simply calls Number.prototype.toString() and returns a string in exponential notation.

Examples

var numObj = 12345.6789;

numObj.toFixed();       // Returns '12346': note rounding, no fractional part
numObj.toFixed(1);      // Returns '12345.7': note rounding
numObj.toFixed(6);      // Returns '12345.678900': note added zeros
(1.23e+20).toFixed(2);  // Returns '123000000000000000000.00'
(1.23e-10).toFixed(2);  // Returns '0.00'
2.34.toFixed(1);        // Returns '2.3'
2.35.toFixed(1);        // Returns '2.4'. Note that it rounds up in this case.
-2.34.toFixed(1);       // Returns -2.3 (due to operator precedence, negative number literals don't return a string...)
(-2.34).toFixed(1);     // Returns '-2.3' (...unless you use parentheses)


答:
```<code>DECLARE @StartDT DATETIME = '2017-01-01'
   DECLARE @EndDT DATETIME = '2017-01-05'
   DECLARE @Id INT = 1

SELECT RANK() OVER (
        ORDER BY (SELECT 1)) AS SeqNo
        ,CAST (Start_Date AS DATE) AS Start_Date
FROM (
    SELECT @StartDT + Row_Number() OVER (ORDER BY Rno) - 1 AS Start_Date
    FROM (
        SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 0)) - 1 AS Rno
            FROM master..spt_values
        ) Dt
    ) Dt2
WHERE Dt2.Start_Date <= @EndDT
</code>```

OutPut

```<code>   SeqNo    Start_Date
   --------------------
    1       2017-01-01
    1       2017-01-02
    1       2017-01-03
    1       2017-01-04
    1       2017-01-05
</code>```

Title: sql server print all dates between two date columns

Body:
i have a table containing 3 columns. ID,Start_Date,End_Date.i want to print all the days between Start_Date and End_Date along with ID.
For Example i have table

+----+------------+------------+
| ID | Start_Date | End_Date   |
+----+------------+------------+
| 1  | 2017-01-01 | 2017-01-05 |
+----+------------+------------+

and i want result like

+----+------------+
| ID | Date       |
+----+------------+
| 1  | 2017-01-01 |
| 1  | 2017-01-02 |
| 1  | 2017-01-03 |
| 1  | 2017-01-04 |
| 1  | 2017-04-05 |
+----+------------+

Body:
DECLARE @StartDT DATETIME = '2017-01-01'
   DECLARE @EndDT DATETIME = '2017-01-05'
   DECLARE @Id INT = 1

SELECT RANK() OVER (
        ORDER BY (SELECT 1)) AS SeqNo
        ,CAST (Start_Date AS DATE) AS Start_Date
FROM (
    SELECT @StartDT + Row_Number() OVER (ORDER BY Rno) - 1 AS Start_Date
    FROM (
        SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 0)) - 1 AS Rno
            FROM master..spt_values
        ) Dt
    ) Dt2
WHERE Dt2.Start_Date <= @EndDT

OutPut

   SeqNo    Start_Date
   --------------------
    1       2017-01-01
    1       2017-01-02
    1       2017-01-03
    1       2017-01-04
    1       2017-01-05


问:
Data Breakpoints by Variable Name
Is there a simple way to define a breakpoint, in Visual C++ 2005, that will pause the program whenever a certain value changes? I found Data Breakpoints, but those require a memory address, and provide no simple way to tie that to a variable.</p>

答:
"In the Address box, type a memory address or expression that evaluates to a memory address. For example, &avar to break when the contents of variable avar change."

http://msdn.microsoft.com/en-us/library/350dyxd0.aspx

OwnerDisplayName: Andrei

Title: Data Breakpoints by Variable Name

OwnerDisplayName: edg


问:
getting warning Invalid argument for foreach in codeigniter
In foreach loop i am getting warning Invalid argument supplied for foreach() below is my loop code and modal code please let me know where i done wrong

Controller

```<code>$concond = array("con_id"=>1,"con_status"=>1);
$this->data['contact']=$this->Frontend_model->get_contact($concond);
$this->load->view('frontend/clienthome',$this->data);
</code>```

foreach Loop

```<code>if($contact)
{
  foreach($contact as $foot)
  {
     $footadr1 = $foot->con_addr_line_1;
     $footadr2 = $foot->con_addr_line_2;
     $footcity = $foot->con_city;
     $footstate = $foot->con_state;
     $footcountry = $foot->con_country;
     $footpin = $foot->con_pincode;
     $footp1 = $foot->con_phone_1;
     $footp2 = $foot->con_phone_2;
     $footp3 = $foot->con_phone_3;
     $footp4 = $foot->con_phone_4;
     $footemail = $foot->con_email_id;
  }
}
</code>```

modal

```<code>function get_contact($concond)
{
  $this->db->select('*');
  $this->db->from('is_addres_contact');
  $this->db->where($concond);
  $query = $this->db->get();
  return $query->result();
}
</code>```

答:
Seems like I got your problem!

You should try to do it like this:

```<code>$data['contact'] = $this->Frontend_model->get_contact($concond);
$this->load->view('frontend/clienthome', $data);
</code>```

Body:
In foreach loop i am getting warning Invalid argument supplied for foreach() below is my loop code and modal code please let me know where i done wrong

Controller

$concond = array("con_id"=>1,"con_status"=>1);
$this->data['contact']=$this->Frontend_model->get_contact($concond);
$this->load->view('frontend/clienthome',$this->data);

foreach Loop

if($contact)
{
  foreach($contact as $foot)
  {
     $footadr1 = $foot->con_addr_line_1;
     $footadr2 = $foot->con_addr_line_2;
     $footcity = $foot->con_city;
     $footstate = $foot->con_state;
     $footcountry = $foot->con_country;
     $footpin = $foot->con_pincode;
     $footp1 = $foot->con_phone_1;
     $footp2 = $foot->con_phone_2;
     $footp3 = $foot->con_phone_3;
     $footp4 = $foot->con_phone_4;
     $footemail = $foot->con_email_id;
  }
}

modal

function get_contact($concond)
{
  $this->db->select('*');
  $this->db->from('is_addres_contact');
  $this->db->where($concond);
  $query = $this->db->get();
  return $query->result();
}

Body:
Seems like I got your problem!

You should try to do it like this:

$data['contact'] = $this->Frontend_model->get_contact($concond);
$this->load->view('frontend/clienthome', $data);


问:
Change Button Content and Text Based On Previous Click
I want to change the button content depending on the previous content click. For example, if its Add then it should change to Save, and if it is Save then it should change back to Add.

I know how to change the content of a button. but how can one read the content to make a change?

答:
I agree with Surfens answer that the question here is not a perfect example for a ToggleButton because "Save" and "Add" a really different operations which should each have the own "ICommand" set on the respective button.

But here is some style that will change the content depending on the IsChecked value of the ToggleButton.

The content will be "ValueForUnToggledState" if the button is not checked and change to "ValueForToggledState" when checked.

```<code><ToggleButton>
    <ToggleButton.Style>
        <Style TargetType="{x:Type ToggleButton}">
            <Setter Property="Content" Value="ValueForUnToggledState" />
            <Style.Triggers>
                <Trigger Property="IsChecked" Value="True">
                    <Setter Property="Content" Value="ValueForToggledState" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </ToggleButton.Style>
</ToggleButton>
</code>```

This is more WPF like than some of the other answers.

Body:
I agree with Surfens answer that the question here is not a perfect example for a ToggleButton because "Save" and "Add" a really different operations which should each have the own "ICommand" set on the respective button.

But here is some style that will change the content depending on the IsChecked value of the ToggleButton.

The content will be "ValueForUnToggledState" if the button is not checked and change to "ValueForToggledState" when checked.

<ToggleButton>
    <ToggleButton.Style>
        <Style TargetType="{x:Type ToggleButton}">
            <Setter Property="Content" Value="ValueForUnToggledState" />
            <Style.Triggers>
                <Trigger Property="IsChecked" Value="True">
                    <Setter Property="Content" Value="ValueForToggledState" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </ToggleButton.Style>
</ToggleButton>

This is more WPF like than some of the other answers.


问:
Running MSBuild fails to read SDKToolsPath
Howdy, I'm having a bit of an issue runnning a NAnt script that used to properly build my .Net 2.0 based website, when compiling with VS2008 and it's associated tools.  I've recently upgraded all the project/solution files to VS2010, and now my build fails with the following error:

[exec]
  C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Microsoft.Common.targets(2249,9):
  error MSB3086: Task could not find
  "sgen.exe" using the S dkToolsPath ""
  or the registry key
  "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft
  SDKs\Windows\v7.0A". Make sure the
  SdkToolsPath is set and the tool
  exists in the correct processor
  specific location under the
  SdkToolsPath and that the Microsoft
  Windows SDK is installed

Now, I DO have prior versions (.Net 3.5) of the Windows SDK installed on the build server, and the full .Net 4.0 framework is installed, but I've not run across a .Net 4.0 specific version of the Windows SDK.

After a bit of experimentation and research, I finally just setup a new environmental variable "SDKToolsPath" and pointed it to the copy of sgen.exe in my windows 6.0 sdk folder.  This generated the same error, but it got me to notice that even though the SDKToolsPath environmental variable IS set (confirmed that I can "echo" it at the command line and it has the expected value), the error message seems to indicated that it's not being read (note the empty quotes).

Most of the information I've found is .Net 3.5 (or earlier) specific.  Not much 4.0 related out there yet.  Searching for error code MSB3086 generated nothing useful either.  Any idea what this might be?

Scott

答:
I manually pass the variables to MSBuild on build server.</p>

```<code>msbuild.exe MyProject.csproj "/p:TargetFrameworkSDKToolsDirectory=C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools" "/p:AspnetMergePath=C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools"
</code>```

Body:
I manually pass the variables to MSBuild on build server.

msbuild.exe MyProject.csproj "/p:TargetFrameworkSDKToolsDirectory=C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools" "/p:AspnetMergePath=C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools"


问:
How call multi js function in one wasm function? with text format
```<code>  var importObject = {
        funcs: {
            echo: arg => document.write(arg),
            log: console.log
        }
    };
</code>```

I want to call both 'echo' and 'log' in one wasm function.

How can i code with text format?

答:
```<code>(module
  (import "funcs" "echo" (func $echo (result i32)))
  (import "funcs" "log" (func $log (result i32)))
  (table 0 anyfunc)
  (memory $0 1)
  (export "memory" (memory $0))
  (export "main" (func $main))
  (func $main (result i32)
    (drop
      (call $echo)
    )
    (drop
      (call $log)
    )
    (i32.const 1)
  )
)
</code>```

The mainly is

(drop (call $echo))
(drop (call $echo))

Body:
  var importObject = {
        funcs: {
            echo: arg => document.write(arg),
            log: console.log
        }
    };

I want to call both 'echo' and 'log' in one wasm function.

How can i code with text format?

Body:
(module
  (import "funcs" "echo" (func $echo (result i32)))
  (import "funcs" "log" (func $log (result i32)))
  (table 0 anyfunc)
  (memory $0 1)
  (export "memory" (memory $0))
  (export "main" (func $main))
  (func $main (result i32)
    (drop
      (call $echo)
    )
    (drop
      (call $log)
    )
    (i32.const 1)
  )
)

The mainly is

(drop (call $echo))
(drop (call $echo))


问:
Email class PHP stopped working
I had this working and I don't know what I did that made it stop.  Here is my Email class:

```<code><?php

    //  File Details: Base mail class

class Email {

    private $to = 'scott@...';
    public $email = NULL;
    public $phone = NULL;
    public $subject = NULL;
    public $body = NULL;
    //private $magic_quotes_active;
//  private $real_escape_string_exists;

    //function __construct() {
        //$this->magic_quotes_active = get_magic_quotes_gpc();
        //$this->real_escape_string_exists = function_exists("mysql_real_escape_string");
    //}

    public function send() {
        $this->addHeader('From: moreinfo@ulsinc.com' . "\r\n" .
                         'Reply-To: moreinfo@ulsinc.com' . "\r\n" .
                         'X-Mailer: PHP/' . phpversion() . "\r\n");
        $this->addHeader("MIME-Version: 1.0\r\n");
        $this->addHeader("Content-Type: text/html; charset=ISO-8859-1\r\n");
        $success = mail($this->to, $this->subject, $this->body, $this->headers);
        if ($success) {
            return true;
        } else {
            return false;
        }
    }

    private function addHeader($header) {
        $this->headers .= $header;
    }

    public function setName($first, $last) {
        $this->first = $first;
        $this->last = $last;
    }

    public function setSubject($subject) {
        $this->subject = $subject;
    }

    public function setPhone($phone) {
        $this->phone = $phone;
    }

    public function setEmail($email) {
        $this->email = $email;
    }

    public function setBody($body) {
        //$this->body = $this->escape_value($body);
        $this->body = $body;
    }

    //public function escape_value($value) {
//      if ($this->real_escape_string_exists) { // PHP 4.3.0 or higher
//          // undo any magic quote effects so mysql_real_escape_string can do the work
//          if ($this->magic_quotes_active) {
//              $value = stripslashes($value);
//          }
//          $value = mysql_real_escape_string($value);
//
//      } else { // before PHP v.4.3.0
//          //if magic quotes aren't already on then add slashes manually
//          if (!$magic_quotes_active) {
//              $value = addslashes($value);
//          }
//      }
//
//      return $test;
//  }

}

$mail = new Email();
$mail->setSubject($_POST['subject']);
$mail->setBody($_POST['body']);
$mail->setName($_POST['first'], $_POST['last']);
$mail->setEmail($_POST['email']);
$mail->setPhone($_POST['phone']);
$mail->send();

?>
</code>```

And here I'm calling it:

```<code>$mail = new Email();
        $mail->setName($_POST['first'], $_POST['last']);
        $mail->setSubject($_POST['subject']);
        $mail->setBody($_POST['body']);
        $mail->setEmail($_POST['email']);
        $mail->setPhone($_POST['phone']);
        $mail->send();
</code>```

I have the class required once at the top of the script and I don't get any PHP errors when I run it.  When I echo $mail->send(); it comes back as true.  So could someone please help me understand what is happening here (or why anything isn't happening anymore, to be more exact).  The email never comes.

Thanks for everyone's help today, btw.

答:
Like all issues with the core mail() (which your class is based on) function, there are MANY variables that go into what could be causing the email not to deliver.  Your host may have limits to how many messages you can queue up, especially when php is mailing it out (which depending on how your server is configured, means it could be dispatching it as user:nobody)

This function is very commonly abused and many shared hosts will impose limitations on its use.

Best suggestion that you run into regularly on SO is to use a mature, complete mailing class solution like PHPMailer.  This will allow you to set headers and perform many preparation steps that ensure better deliverability.

The syntax for PHPMailer is very similar to the roll-your-own you've made here, so you should have no trouble adapting it.  It also allows you to send attachments and HTML formatted email in a much easier system.

Title: Email class PHP stopped working

Body:
I had this working and I don't know what I did that made it stop.  Here is my Email class:

<?php

    //  File Details: Base mail class

class Email {

    private $to = 'scott@...';
    public $email = NULL;
    public $phone = NULL;
    public $subject = NULL;
    public $body = NULL;
    //private $magic_quotes_active;
//  private $real_escape_string_exists;

    //function __construct() {
        //$this->magic_quotes_active = get_magic_quotes_gpc();
        //$this->real_escape_string_exists = function_exists("mysql_real_escape_string");
    //}

    public function send() {
        $this->addHeader('From: moreinfo@ulsinc.com' . "\r\n" .
                         'Reply-To: moreinfo@ulsinc.com' . "\r\n" .
                         'X-Mailer: PHP/' . phpversion() . "\r\n");
        $this->addHeader("MIME-Version: 1.0\r\n");
        $this->addHeader("Content-Type: text/html; charset=ISO-8859-1\r\n");
        $success = mail($this->to, $this->subject, $this->body, $this->headers);
        if ($success) {
            return true;
        } else {
            return false;
        }
    }

    private function addHeader($header) {
        $this->headers .= $header;
    }

    public function setName($first, $last) {
        $this->first = $first;
        $this->last = $last;
    }

    public function setSubject($subject) {
        $this->subject = $subject;
    }

    public function setPhone($phone) {
        $this->phone = $phone;
    }

    public function setEmail($email) {
        $this->email = $email;
    }

    public function setBody($body) {
        //$this->body = $this->escape_value($body);
        $this->body = $body;
    }

    //public function escape_value($value) {
//      if ($this->real_escape_string_exists) { // PHP 4.3.0 or higher
//          // undo any magic quote effects so mysql_real_escape_string can do the work
//          if ($this->magic_quotes_active) {
//              $value = stripslashes($value);
//          }
//          $value = mysql_real_escape_string($value);
//
//      } else { // before PHP v.4.3.0
//          //if magic quotes aren't already on then add slashes manually
//          if (!$magic_quotes_active) {
//              $value = addslashes($value);
//          }
//      }
//
//      return $test;
//  }

}

$mail = new Email();
$mail->setSubject($_POST['subject']);
$mail->setBody($_POST['body']);
$mail->setName($_POST['first'], $_POST['last']);
$mail->setEmail($_POST['email']);
$mail->setPhone($_POST['phone']);
$mail->send();

?>

And here I'm calling it:

$mail = new Email();
        $mail->setName($_POST['first'], $_POST['last']);
        $mail->setSubject($_POST['subject']);
        $mail->setBody($_POST['body']);
        $mail->setEmail($_POST['email']);
        $mail->setPhone($_POST['phone']);
        $mail->send();

I have the class required once at the top of the script and I don't get any PHP errors when I run it.  When I echo $mail->send(); it comes back as true.  So could someone please help me understand what is happening here (or why anything isn't happening anymore, to be more exact).  The email never comes.

Thanks for everyone's help today, btw.


问:
Hide 1 line of text with CSS
I have two lines of code in a PHP file

```<code><div align="center">The quick brown fox</div>
<div align="center">jumps over the lazy dog.</div>
</code>```

How can I hide only the first line of text displayed with CSS?

答:
```<code><div align="center" hidden="yes">The quick brown fox</div>
<div align="center">jumps over the lazy dog.</div>
</code>```

only add hidden="yes"

use CSS  display="none";

Title: Hide 1 line of text with CSS

Body:
I have two lines of code in a PHP file

The quick brown fox

jumps over the lazy dog.

How can I hide only the first line of text displayed with CSS?

Body:
<div align="center" hidden="yes">The quick brown fox</div>
<div align="center">jumps over the lazy dog.</div>

only add hidden="yes"

use CSS  display="none";


问:
Package Manager Console Tools doesn't support .Net Core Project
I am following the tutorial link

for learning the .Net Core. Everything I have installed properly.
But when I am Running the migration it giving error.

Project.json Code is:

```<code>{
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.0",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.1.2",
    "Microsoft.EntityFrameworkCore.Tools": "2.0.0-preview1-final",
    "Microsoft.AspNetCore.Mvc": "1.0.0"
  },

  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "web.config"
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}
</code>```

Please let me know where I am wrong Thanks for your help in advance.

答:
Don't mix up versions. Don't use EF Core tools 2.0.0 with EF Core 1.1

Use Microsoft.EntityFrameworkCore.Tools 1.0.0-preview2-final, iirc it is the LAST version which supports the project.json structure and hence Visual 2015

It's best to upgrade to Visual Studio 2017 and csproj if you want to continue to develop ASP.NET Core applications, since project.json-type projects won't be supported/updated anymore. All new versions of the dotnet/PowerShell tools will only support VS2017 with csproj.

Additionally

Starting with csproj (Version 1.0.0-preview3-final) If you want dotnet ef support, you also need to install Microsoft.EntityFrameworkCore.Tools.DotNet for dotnet ef commands. Otherwise only powershell commands will be available.

Body:
I am following the tutorial link

for learning the .Net Core. Everything I have installed properly.
But when I am Running the migration it giving error.

Project.json Code is:

{
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.0",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.1.2",
    "Microsoft.EntityFrameworkCore.Tools": "2.0.0-preview1-final",
    "Microsoft.AspNetCore.Mvc": "1.0.0"
  },

  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "web.config"
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

Please let me know where I am wrong Thanks for your help in advance.


问:
javascript regex search from end of string to begining
Is it possible to use regex to search from end of string to beginning?

for example i have a string: "a2bba2b"

I know i need the last occurrence of /a2/ and it seems highly inefficient to make machine go trough whole string which can be quite long. I know the needle will  be somewhere near the end of string(haystack), so i would like to reverse the order simply tell the script to search from end to beginning to save some resources.
Regex seems like a way to go match more complicated string.And it is way easier to write complex regex than your own search function.

So is there a way maybe a flag or something to reverse searching order to match regex from end to start of input string. Does any of the modern languages support something like that? if not why?

答:
No, JavaScript RegExp does not allow searching from the end of the string. The usual workaround is using a greedy dot matching pattern to make the engine grab the whole string and then backtrack to find the last occurrence (as /.*a\d/), but it will become a pain if a large string does not really contain this pattern.

If the purpose is to extract the last match, you may get all matches and grab the last one (s.match(/a\d/g).pop() (well, there must be a null check, of course)).

There are regex engines that actually let you parse the string from right to left.

.NET regex uses RegexOptions.RightToLeft modifier for this (see the regex demo)

In Python PyPi regex, you may also pass a regex.R (or inline (?r) version) to force a reverse matching: regex.compile(r'a\d', regex.R).sub(r"**\g<0>**", "a2bba2b", count=1) ==> a2bb**a2**b) (see RexTester demo).


问:
AdBlock plus hids elements with ids or class with the word "ad"
I have two divs in my site one with id ad_holder and another with id ad_buttons"

When testing the site on Mozilla with ad block plus installed I noticed that both divs were hidden. On further inspection I noticed it that Adblock was the culprit probably because of the ID names.
I also noticed that Adblock created (or maybe has a ready made) CSS file, that sets the display to hidden.

I know I can fix this by simply changing the IDs or trying to override the Adblock CSS but still need to know if there is yet another alternative way of fixing this, like a small piece of code that tells Adblock it's not a real ad.

The contents of the divs are not real ads, it just holds .jpegs about the client's business.

答:
List could be found here. Just double check because different on version and software, but i think it cover most of parts.
https://easylist.to/</p>


答:
Can you add some info about if, for instance, did you recently recompiled something in your environment?

If this is so, I remember that the email extension, which comes included in PHP 5.x, requires for the unxi email binary to be accesible during the install process.

About the errors, that could be explained by your php.ini configuration. That doesn't mean that there are no warnings.

Hope I was of some help.

Cheers.

A.

Title: Email class PHP stopped working


问:
How do I calculate totals based on Dropdown ranges in Google sheets?
This is my table:

```<code>Item | Person | Price
Shoes | John | $25
Clothes | John | $25
Pants | John | $50
Bags | Sarah | $50
Watch | Sarah | $150
Aftershave | John | $15
</code>```

The Person table I have managed to make it a dropdown following a tutorial.

I know want another column called totals that will work out the total based on the user:

```<code>Total Sarah:
Total John:
</code>```

It should dynamically find ALL Sarah for example and update the total. I have tried using sumif but how can I do a sumif if all rows in a selected column match the total

This is my sample sheet:

https://docs.google.com/spreadsheets/d/13MwyK-Suvvg9LfvzFcW-ojL9ilvb5OKCFjQwXgI4h70/edit?usp=sharing

I also tried

=query(sum(B:B,"count * where B ='John'" ,-1)) and

=sum(query(B:B, "select B where B='John'")+query(C:C, "select B,C where B='John'"))

答:
For Google Sheets only:

={QUERY({A:C},"select Col2, sum(Col3) where Col2 <> '' group by Col2");"Total",SUM(C:C)}

How it works

use array {} to convert range A:C to array {A:C}. This is made in order to use Col1, Col2... notation in query. I prefer this because range letters A, B, C may change ant this will cause crash of formula.

use query to get the sum.

```<code># Syntax
QUERY(data, query, [headers])

# data = The range of cells to perform the query on.
</code>```

You can refer here or here
4. use arrays {array; value,calue} to combine the formula. Here's the link to documentation.

Commas: Separate columns to help you write a row of data in an array. For example, ={"Total",SUM(C:C)} would place the Total in the first cell and the Sum of C column in the cell to the right in a new column.

Semicolons: Separate rows to help you write a column of data in an array. For example, ={QUERY; TOTAL} would place all the queries in the row and then total in the cell below in a new row

Body:
This is my table:

Item | Person | Price
Shoes | John | $25
Clothes | John | $25
Pants | John | $50
Bags | Sarah | $50
Watch | Sarah | $150
Aftershave | John | $15

The Person table I have managed to make it a dropdown following a tutorial.

I know want another column called totals that will work out the total based on the user:

Total Sarah:
Total John:

It should dynamically find ALL Sarah for example and update the total. I have tried using sumif but how can I do a sumif if all rows in a selected column match the total

This is my sample sheet:

https://docs.google.com/spreadsheets/d/13MwyK-Suvvg9LfvzFcW-ojL9ilvb5OKCFjQwXgI4h70/edit?usp=sharing

I also tried

=query(sum(B:B,"count * where B ='John'" ,-1)) and

=sum(query(B:B, "select B where B='John'")+query(C:C, "select B,C where B='John'"))

Body:
For Google Sheets only:

={QUERY({A:C},"select Col2, sum(Col3) where Col2 <> '' group by Col2");"Total",SUM(C:C)}

How it works

use array {} to convert range A:C to array {A:C}. This is made in order to use Col1, Col2... notation in query. I prefer this because range letters A, B, C may change ant this will cause crash of formula.

use query to get the sum.

# Syntax
QUERY(data, query, [headers])

# data = The range of cells to perform the query on.

You can refer here or here
4. use arrays {array; value,calue} to combine the formula. Here's the link to documentation.

Commas: Separate columns to help you write a row of data in an array. For example, ={"Total",SUM(C:C)} would place the Total in the first cell and the Sum of C column in the cell to the right in a new column.

Semicolons: Separate rows to help you write a column of data in an array. For example, ={QUERY; TOTAL} would place all the queries in the row and then total in the cell below in a new row


问:
How can I fill element with jquery?
I'm creating a modal (bootstrap modal) as string when you click button with jquery and I have two option class in my modal is

Call Today and Call Tomorrow it's okey so far.

and my modal has been creating when you clicked the button so that's why I added two attribute to my button is data-open-hours and data-closed-hours and I want to explain what I want with an example:

for example:

my data-open-hours is : 09:00
my data-closed-hours : 22:00

then fill my .when-call select from 09:00 to 22:00 with Call Now option

so if you choose Call Tomorrow then fill my select from 09:00 to 22:00 without Call Now string.

My working example:

function agencyModal(modalTitle, modalWidth, modalHeight, openHours, closedHours) {
  console.log("Open: " + openHours + " Closed hours: " + closedHours);
  var html =
    '

<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>';
  html = html + '
' + modalTitle + "

";
  html = html + '
';
  html = html + '

<select class="when-call form-control"><option class="call-today">Call Today</option><option class="call-tomorrow">Call Tomorrow</option></select>

<select class="form-control"><option class="call-now">Call Now</option></select>

';
  html = html + '

';
  // check length and append if it is not added before
  !$(".agencyModal").length && $(document.body).append(html);
  $(".agencyModal").modal();
}

$(document).on("click", ".open-agency", function() {
  var openHours = $(this).data("open-hours");
  var closedHours = $(this).data("closed-hours");
  agencyModal("Test Title ", "70%", "500px", openHours, closedHours);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.open-agency {
  border: 3px solid #ccc;
  display: inline-block;
  padding: 12px;
  font-size: 14px;
  margin: 100px;
  cursor: pointer;
  box-shadow: 0px 0px 10px #ccc;
}

.open-agency:hover {
  background: #050505;
  color: #fff;
  border-color: #000;
}</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

See Agency

```

CodePen Demo

答:
I see a few problems with this code, like the fact that your select has no name, your options have no value, and most classes seem like they should be ids instead... I would suggest reviewing these parts.

Working with what you have at the moment, anyway, and supposing you want to add an option for every hour from opening to closure, you should:
- fill the second select with the correct options, parsing your open/close times;
- add a listener on change for the first select to add/remove the "Call now" option

This should work, even if it's quite rough

function agencyModal(modalTitle, modalWidth, modalHeight, openHours, closedHours) {
  console.log("Open: " + openHours + " Closed hours: " + closedHours);
  var html =
    '

<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>';
  html = html + '
' + modalTitle + "

";
  html = html + '
';
  html = html + '

<select class="when-call form-control"><option class="call-today">Call Today</option><option class="call-tomorrow">Call Tomorrow</option></select>

';
  html = html + '<select class="hour-call form-control">'+getOptions(openHours, closedHours, true)+'</select>

';
  html = html + '

';
  // check length and append if it is not added before
  !$(".agencyModal").length && $(document.body).append(html);
  $(".agencyModal").modal();
}

$(document).on("click", ".open-agency", function() {
  var openHours = $(this).data("open-hours");
  var closedHours = $(this).data("closed-hours");
  agencyModal("Test Title ", "70%", "500px", openHours, closedHours);
});

function callNow() {
  return '<option class="call-now">Call Now</option>';
}

function getOptions(open, close, now) {
  var options = now ? callNow() : '';
  console.log(open,close,now);
  // get open/close time as hours only
  var start = open.split(':')[0];
  var end = close.split(':')[0];
  // using +start will convert to a base 10 number - avoiding the problem that numbers with a leading zero are octal numbers
  // loop and add an option for each
  for (var h = +start; h <= +end; h++) {
    options += '<option>Call at '+h+':00</option>'
  }
  return options;
}

$(document).on("change", ".when-call", function(event) {
  // not the most efficient way, but you can always remove 'Call now', then add it back only if needed
  $(".hour-call .call-now").remove();
  if($('.call-today').is(':selected'))
    $('.hour-call').prepend(callNow());
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.open-agency {
  border: 3px solid #ccc;
  display: inline-block;
  padding: 12px;
  font-size: 14px;
  margin: 100px;
  cursor: pointer;
  box-shadow: 0px 0px 10px #ccc;
}

.open-agency:hover {
  background: #050505;
  color: #fff;
  border-color: #000;
}</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

See Agency

```

Title: How can I fill element with jquery?

Body:
I'm creating a modal (bootstrap modal) as string when you click button with jquery and I have two option class in my modal is

Call Today and Call Tomorrow it's okey so far.

and my modal has been creating when you clicked the button so that's why I added two attribute to my button is data-open-hours and data-closed-hours and I want to explain what I want with an example:

for example:

my data-open-hours is : 09:00
my data-closed-hours : 22:00

then fill my .when-call select from 09:00 to 22:00 with Call Now option

so if you choose Call Tomorrow then fill my select from 09:00 to 22:00 without Call Now string.

My working example:

function agencyModal(modalTitle, modalWidth, modalHeight, openHours, closedHours) {
  console.log("Open: " + openHours + " Closed hours: " + closedHours);
  var html =
    '

<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>';
  html = html + '
' + modalTitle + "

";
  html = html + '
';
  html = html + '

<select class="when-call form-control"><option class="call-today">Call Today</option><option class="call-tomorrow">Call Tomorrow</option></select>

<select class="form-control"><option class="call-now">Call Now</option></select>

';
  html = html + '

';
  // check length and append if it is not added before
  !$(".agencyModal").length && $(document.body).append(html);
  $(".agencyModal").modal();
}

$(document).on("click", ".open-agency", function() {
  var openHours = $(this).data("open-hours");
  var closedHours = $(this).data("closed-hours");
  agencyModal("Test Title ", "70%", "500px", openHours, closedHours);
});

.open-agency {
  border: 3px solid #ccc;
  display: inline-block;
  padding: 12px;
  font-size: 14px;
  margin: 100px;
  cursor: pointer;
  box-shadow: 0px 0px 10px #ccc;
}

.open-agency:hover {
  background: #050505;
  color: #fff;
  border-color: #000;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

See Agency

CodePen Demo

Body:
I see a few problems with this code, like the fact that your select has no name, your options have no value, and most classes seem like they should be ids instead... I would suggest reviewing these parts.

Working with what you have at the moment, anyway, and supposing you want to add an option for every hour from opening to closure, you should:
- fill the second select with the correct options, parsing your open/close times;
- add a listener on change for the first select to add/remove the "Call now" option

This should work, even if it's quite rough

function agencyModal(modalTitle, modalWidth, modalHeight, openHours, closedHours) {
  console.log("Open: " + openHours + " Closed hours: " + closedHours);
  var html =
    '<div class="modal fade agencyModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"><div class="modal-dialog" role="document" style="width:' + modalWidth + ';height:' + modalHeight + '"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>';
  html = html + '<h4 class="modal-title" id="myModalLabel">' + modalTitle + "</h4></div>";
  html = html + '<div class="modal-body">';
  html = html + '<div class="row"><div class="col-lg-6"><select class="when-call form-control"><option class="call-today">Call Today</option><option class="call-tomorrow">Call Tomorrow</option></select></div><div class="col-lg-6">';
  html = html + '<select class="hour-call form-control">'+getOptions(openHours, closedHours, true)+'</select></div></div>';
  html = html + '</div></div></div></div>';
  // check length and append if it is not added before
  !$(".agencyModal").length && $(document.body).append(html);
  $(".agencyModal").modal();
}

$(document).on("click", ".open-agency", function() {
  var openHours = $(this).data("open-hours");
  var closedHours = $(this).data("closed-hours");
  agencyModal("Test Title ", "70%", "500px", openHours, closedHours);
});

function callNow() {
  return '<option class="call-now">Call Now</option>';
}

function getOptions(open, close, now) {
  var options = now ? callNow() : '';
  console.log(open,close,now);
  // get open/close time as hours only
  var start = open.split(':')[0];
  var end = close.split(':')[0];
  // using +start will convert to a base 10 number - avoiding the problem that numbers with a leading zero are octal numbers
  // loop and add an option for each
  for (var h = +start; h <= +end; h++) {
    options += '<option>Call at '+h+':00</option>'
  }
  return options;
}

$(document).on("change", ".when-call", function(event) {
  // not the most efficient way, but you can always remove 'Call now', then add it back only if needed
  $(".hour-call .call-now").remove();
  if($('.call-today').is(':selected'))
    $('.hour-call').prepend(callNow());
});

.open-agency {
  border: 3px solid #ccc;
  display: inline-block;
  padding: 12px;
  font-size: 14px;
  margin: 100px;
  cursor: pointer;
  box-shadow: 0px 0px 10px #ccc;
}

.open-agency:hover {
  background: #050505;
  color: #fff;
  border-color: #000;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<p class="open-agency" data-toggle="modal" data-target=".agencyModal" data-open-hours="09:00" data-closed-hours="22:00">See Agency</p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>


问:
Count Values associated with key in Sql Server
I have three tables

Table Category

```<code>CategoryID         Category
1                   Climate
2                   Area
</code>```

Table CategoryDetail

```<code>DetailID    CategoryID      Desc
1            1              Hot
2            1              Cold
3            2              Area1
</code>```

Table CategoryDetailValues

```<code>PK  AnotherFK  CategoryDetailID
1    1           1
2    1           1
3    1           2
4    2           1
</code>```

Here AnotherFK is foreign key referring to another table. In record 1 and 2 duplicate exists that's ok but AnotherFK 1 has reference of CategoryDetailID 1 and 2 which has categoryID of 1 which is not ok

So from above tables
this result is valid from above three table

```<code>PK   AnotherFK    CategoryID  DetailID     Desc
1    1             1            1          Hot
2    1             1            1          Hot
</code>```

But below result is not valid

```<code>PK   AnotherFK    CategoryID  DetailID     Desc
2    1             1           1           Hot
3    1             1           2           Cold
</code>```

I can not put same AnotherFK in two different DetailID which has same CategoryID. I could have eliminated this by introducing CategoryID in CategoryDetailValues table and creating unique constraint but I am not allowed to do so.

Now my aim is to find all those record in CategoryDetailValues table which has different DetailID that are associated with same CategoryID. So that I can delete them.

Trying to achieve this in SQL Server 2012.

答:
This query will look in Categorydetail for records with duplicate DetailID. Than join the tables to provide you the details. It's still up to you to decide which records should be deleted.</p>

```<code>select *
from(
    Select CategoryID
    from CategoryDetail
    group by CategoryID
    having count(DetailID)>1)aggr
join CategoryDetail c on aggr.CategoryID = c.CategoryID
join CategoryDetailValues v on c.CategoryDetailID = v.CategoryDetailID
</code>```

Body:
I have three tables

Table Category

CategoryID         Category
1                   Climate
2                   Area

Table CategoryDetail

DetailID    CategoryID      Desc
1            1              Hot
2            1              Cold
3            2              Area1

Table CategoryDetailValues

PK  AnotherFK  CategoryDetailID
1    1           1
2    1           1
3    1           2
4    2           1

Here AnotherFK is foreign key referring to another table. In record 1 and 2 duplicate exists that's ok but AnotherFK 1 has reference of CategoryDetailID 1 and 2 which has categoryID of 1 which is not ok

So from above tables
this result is valid from above three table

PK   AnotherFK    CategoryID  DetailID     Desc
1    1             1            1          Hot
2    1             1            1          Hot

But below result is not valid

PK   AnotherFK    CategoryID  DetailID     Desc
2    1             1           1           Hot
3    1             1           2           Cold

I can not put same AnotherFK in two different DetailID which has same CategoryID. I could have eliminated this by introducing CategoryID in CategoryDetailValues table and creating unique constraint but I am not allowed to do so.

Now my aim is to find all those record in CategoryDetailValues table which has different DetailID that are associated with same CategoryID. So that I can delete them.

Trying to achieve this in SQL Server 2012.

Body:
This query will look in Categorydetail for records with duplicate DetailID. Than join the tables to provide you the details. It's still up to you to decide which records should be deleted.

select *
from(
    Select CategoryID
    from CategoryDetail
    group by CategoryID
    having count(DetailID)>1)aggr
join CategoryDetail c on aggr.CategoryID = c.CategoryID
join CategoryDetailValues v on c.CategoryDetailID = v.CategoryDetailID


问:
Azure Stream Analytics Get Previous Output Row for Join to Input
I have the following scenario:

Mobile app produces events that are sent to Event Hub which is input stream source to a Stream Analytics query.  From there they are passed through a sequential flow of queries that splits the stream into 2 streams based on criteria, evaluates other conditions and decides whether or not to let the event keep flowing through the pipeline (if it doesn't it is simply discarded).  You could classify what we are doing is noise reduction/event filtering.  Basically if A just happened don't let A happen again unless B & C happened or X time passes.  At the end of the query gauntlet the streams are merged again and the "selected" events are propagated as "chosen" outputs.

My problem is that I need the ability to compare the current event to the previous "chosen" event (not just the previous input event) so in essence I need to join my input stream to my output stream.  I have tried various ways to do this and so far none have worked, I know that other CEP engines support this concept.  My queries are mostly all defined as temporary results sets inside of a WITH statement (that's where my initial input stream is pulled into the first query and each following query depends on the one above it) but I see no way to either join my input to my output or to join my input to another temporary result set that is further down in the chain. It appears that join only supports inputs?

For the moment I am attempting to work around this limitation with something I really don't want to do in production, but I actually have an output defined going to an Azure Queue then an Azure Function triggered by events on that queue that wakes up and posts it to a different Event hub that is mapped as a recirc feed input back into my queries which I can join to.  Still wiring all of that up so not 100% sure it will work but thinking there has to be a better option for this relatively common pattern?

答:
AFAIK, the stream analytics job supports two distinct data input types: data stream inputs and reference data inputs. Per my understanding, you could leverage Reference data to perform a lookup or to correlate with your data stream. For more details, you could refer to the following tutorials:

Data input types: Data stream and reference data

Configuring reference data

Tips on refreshing your reference data

Reference Data JOIN (Azure Stream Analytics)