问:
jQuery strange hoisting/initializing behaviour
```<code>$(function () {
        //hard coded for initial debugging usage, must add table to reference
        var userPermissionLevelRequired = 31;
        var currentUserDescription = $('.user-menu .hidden-xs').html(); //to get user description
        var userList = null;
        var table = null;
        var userName = $.grep(userDetail, function (item) {
            return item.Description === currentUserDescription;
        });

        getUserMembers();

        /*$.ajax({

            'url': '/Home/GetUserMembers',
            'type': 'GET',
            dataType: "json",
            'success': function (data) {
                userList = data;
                populateDropDown(data);
                debugger;
            },
            'error': function (request, error) {
                alert("Request: " + JSON.stringify(request));
            }
        });*/

        function setPermission() {
            //do something...
        }
        function getUserMembers() {
            $.ajax({

                'url': '/Home/GetUserMembers',
                'type': 'GET',
                'dataType': 'json',
                'async':'false',
                'success': function (data) {
                    userList = data;
                    populateDropDown(data);
                    debugger;
                    //alert("data.length " + data.length);
                    setPermission();
                },
                'error': function (request, error) {
                    alert("Request: " + JSON.stringify(request));
                }
            });
        }
</code>```

I wanted to add further code after the ajax call which is commented out.  But the code would run further before returning from the ajax call.  The only way I can get setPermission to run after the ajax call was to put the call in the ajax success function.  Why did I have to do this????

答:
It is actually the $.ajax function is asynchronous by default not the javascript by itself. Using async attribute, you can actually change the behaviour to be synchronous.

However, you have to mention the false without the quotes, like below:

```<code>$.ajax({

    'url': '/Home/GetUserMembers',
    'type': 'GET',
    'dataType': 'json',
    'async': false,
    'success': function (data) {
        userList = data;
        populateDropDown(data);
        debugger;
        //alert("data.length " + data.length);
        setPermission();
    },
    'error': function (request, error) {
        alert("Request: " + JSON.stringify(request));
    }
});
</code>```

in that case, the $.ajax would behave as synchronous call and you can have any statements following that and you need not call setPersmission() inside the success block.

Body:
$(function () {
        //hard coded for initial debugging usage, must add table to reference
        var userPermissionLevelRequired = 31;
        var currentUserDescription = $('.user-menu .hidden-xs').html(); //to get user description
        var userList = null;
        var table = null;
        var userName = $.grep(userDetail, function (item) {
            return item.Description === currentUserDescription;
        });

        getUserMembers();

        /*$.ajax({

            'url': '/Home/GetUserMembers',
            'type': 'GET',
            dataType: "json",
            'success': function (data) {
                userList = data;
                populateDropDown(data);
                debugger;
            },
            'error': function (request, error) {
                alert("Request: " + JSON.stringify(request));
            }
        });*/

        function setPermission() {
            //do something...
        }
        function getUserMembers() {
            $.ajax({

                'url': '/Home/GetUserMembers',
                'type': 'GET',
                'dataType': 'json',
                'async':'false',
                'success': function (data) {
                    userList = data;
                    populateDropDown(data);
                    debugger;
                    //alert("data.length " + data.length);
                    setPermission();
                },
                'error': function (request, error) {
                    alert("Request: " + JSON.stringify(request));
                }
            });
        }

I wanted to add further code after the ajax call which is commented out.  But the code would run further before returning from the ajax call.  The only way I can get setPermission to run after the ajax call was to put the call in the ajax success function.  Why did I have to do this????

Body:
It is actually the $.ajax function is asynchronous by default not the javascript by itself. Using async attribute, you can actually change the behaviour to be synchronous.

However, you have to mention the false without the quotes, like below:

$.ajax({

    'url': '/Home/GetUserMembers',
    'type': 'GET',
    'dataType': 'json',
    'async': false,
    'success': function (data) {
        userList = data;
        populateDropDown(data);
        debugger;
        //alert("data.length " + data.length);
        setPermission();
    },
    'error': function (request, error) {
        alert("Request: " + JSON.stringify(request));
    }
});

in that case, the $.ajax would behave as synchronous call and you can have any statements following that and you need not call setPersmission() inside the success block.


来源: stackexchange

问:
Add missing rows to SQL query
I have a data set in which I need each issue to have 3 rows. 1 for each status that is possible. Below is an example of what I currently have.

```<code>Issue  Status  Time
-------------------
1      SLM      30
1      SNB      43
1      EOB      22
2      SLM      12
2      EOB      87
</code>```

I need something like this, where is an issue doesn't have a status then a row is added and 0 is set for the time.

```<code> Issue   Status    Time
 ----------------------
    1      SLM      30
    1      SNB      43
    1      EOB      22
    2      SLM      12
    2      EOB      87
    2      SNB      0
</code>```

How can I do this?

答:
Cross join id's with statuses and left join the table on to that.</p>

```<code>select i.issue,s.status,coalesce(t.time,0) as time
from (select distinct status from tbl) s --replace this with status table if you have one
cross join (select distinct issue from tbl) i
left join tbl t on t.issue=i.issue and t.status=s.status
</code>```

ContentLicense: CC BY-SA 3.0

Title: Add missing rows to SQL query

Body:
I have a data set in which I need each issue to have 3 rows. 1 for each status that is possible. Below is an example of what I currently have.

Issue  Status  Time
-------------------
1      SLM      30
1      SNB      43
1      EOB      22
2      SLM      12
2      EOB      87

I need something like this, where is an issue doesn't have a status then a row is added and 0 is set for the time.

 Issue   Status    Time
 ----------------------
    1      SLM      30
    1      SNB      43
    1      EOB      22
    2      SLM      12
    2      EOB      87
    2      SNB      0

How can I do this?

Body:
Cross join id's with statuses and left join the table on to that.

select i.issue,s.status,coalesce(t.time,0) as time
from (select distinct status from tbl) s --replace this with status table if you have one
cross join (select distinct issue from tbl) i
left join tbl t on t.issue=i.issue and t.status=s.status


问:
Get selected data and fill textboxes
I am trying to make easy-to-use form for the users who are using our internal application. Basicly I have a select element. What I want is when I choose anything I want to fill specified text boxes.

Codes are below. That works fine but fill only 1 box.Pls do not forget normally I am getting data from the mySQL db.

html file:

```<code><script src="choose.js"></script>
<select onchange="ChooseGuest(this.value)">
<option value="1">guest 1</option>
<option value="2">guest 2</option>
<option value="3">guest 3</option>
</select>
<input type="text" id="guestdetails"/>
<input type="text" id="guestdetails2"/>
</code>```

php data file:

```<code>$AskForIt = $_GET["q"];
If ($AskForIt == "1") {
echo "guest 1 data";
} Elseif ($AskForIt == "2") {
echo "guest 2 data";
} Elseif ($AskForIt == "3") {
echo "guest 3 data";
}
</code>```

js file:

```<code>var xmlHttp

function ChooseGuest(str)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
  {
  alert ("upgrade your browser");
  return;
  }
var url="guests.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}

function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("guestdetails").value=xmlHttp.responseText;
}
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
return xmlHttp;
}
</code>```

答:
Here is a way you can do this with just jQuery.

Example: https://jsfiddle.net/Twisty/u2gqwfL4/

JavaScript

```<code>var myData = [
  "guest 1 data",
  "guest 2 data",
  "guest 3 data"
];
$(function() {
  function ChooseGuest(v, str) {
    // Example AJAX Post call in jQuery
    // Replace '/echo/json/' with 'guests.php'
    // or use $.get() in the same way
    $.post("/echo/json/", {
      json: JSON.stringify(myData),
      q: str
    }, function(results) {
      console.log(results, v);
      $("#guestdetails" + v).val(results[v - 1]);
    });
  }
  $("#guestSelect option").click(function() {
    var selVal = parseInt($(this).val());
    var selText = $(this).html();
    ChooseGuest(selVal, selText);
  });
});
</code>```

Your code will be a bit different due to the nature of jsfiddle and the way exampled are made. I would suggest:

```<code>  function ChooseGuest(v, str) {
    $.get("guests.php", {
      q: str,
      sid: Math.random()
    }, function(results) {
      console.log(results, v);
      $("#guestdetails" + v).val(results);
    });
  }
</code>```

Title: Get selected data and fill textboxes

Body:
I am trying to make easy-to-use form for the users who are using our internal application. Basicly I have a select element. What I want is when I choose anything I want to fill specified text boxes.

Codes are below. That works fine but fill only 1 box.Pls do not forget normally I am getting data from the mySQL db.

html file:

<select onchange="ChooseGuest(this.value)">
<option value="1">guest 1</option>
<option value="2">guest 2</option>
<option value="3">guest 3</option>
</select>
<input type="text" id="guestdetails"/>
<input type="text" id="guestdetails2"/>

php data file:

$AskForIt = $_GET["q"];
If ($AskForIt == "1") {
echo "guest 1 data";
} Elseif ($AskForIt == "2") {
echo "guest 2 data";
} Elseif ($AskForIt == "3") {
echo "guest 3 data";
}

js file:

var xmlHttp

function ChooseGuest(str)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
  {
  alert ("upgrade your browser");
  return;
  }
var url="guests.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}

function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("guestdetails").value=xmlHttp.responseText;
}
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
return xmlHttp;
}

Body:
Here is a way you can do this with just jQuery.

Example: https://jsfiddle.net/Twisty/u2gqwfL4/

JavaScript

var myData = [
  "guest 1 data",
  "guest 2 data",
  "guest 3 data"
];
$(function() {
  function ChooseGuest(v, str) {
    // Example AJAX Post call in jQuery
    // Replace '/echo/json/' with 'guests.php'
    // or use $.get() in the same way
    $.post("/echo/json/", {
      json: JSON.stringify(myData),
      q: str
    }, function(results) {
      console.log(results, v);
      $("#guestdetails" + v).val(results[v - 1]);
    });
  }
  $("#guestSelect option").click(function() {
    var selVal = parseInt($(this).val());
    var selText = $(this).html();
    ChooseGuest(selVal, selText);
  });
});

Your code will be a bit different due to the nature of jsfiddle and the way exampled are made. I would suggest:

  function ChooseGuest(v, str) {
    $.get("guests.php", {
      q: str,
      sid: Math.random()
    }, function(results) {
      console.log(results, v);
      $("#guestdetails" + v).val(results);
    });
  }


问:
how can i make edge system so that i can implement Dijkstra's or A* Algorithm?
i want to apply Dijkstra's algorithm on list of features provided with geoJson file i have up to 100 features look at example .

what i have done so far :

extracted all points from features (variable called points)

<s>2. i have built a adjacency list like this using index's from points
so 0-1-10 ,will be point of index 0 at points and the same for 1 and the third is the distance from each other.
 3. i have built adjacency array but i don't see any use of it
the example shown in the image is not the full features i am seeking only the starting point then i can working on the rest of the map.</s>

all black points are (lat , lang)

how can i make edge system so that i can implement Dijkstra's or A* Algorithm

<s>my question is how can i continue to go from A to B ? </s>
any suggestions are welcome.

edit 1 : added code

edit 2 : updated question

 var start = [34.000750, 71.485753];
            var end = [34.000937, 71.485180];

            var points=[];
            var nodes=[];
            var features=[];
            var adjacent=[];

            var map = L.map('map').setView(start, 17);;

        map.attributionControl.addAttribution('qgis2web');
        var bounds_group = new L.featureGroup([]);
        var basemap0 = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors,CC-BY-SA',
            maxZoom: 22
        });
        basemap0.addTo(map);
        L.geoJSON(data).addTo(map);
        //OpenStreetMap_BlackAndWhite.addTo(map)
          //basemap0.addTo(map);
            function getid(){
             var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
             var d = possible.charAt(Math.floor(Math.random() * possible.length));
             while(nodes.indexOf(d) >-1){
               d = possible.charAt(Math.floor(Math.random() * possible.length));
             }
          return d;
            }
            L.geoJSON(data, {
                onEachFeature: function(feature, layer) {
                    //console.log(feature);
                    points.push.apply(points,feature.geometry.coordinates);
                    features.push(feature.geometry.coordinates);
                   // return L.Polyline(layer, geojsonMarkerOptions);
                }
            });

            function init(){
             var marks= [];
             for (var i = 0; i < features.length; i++) {
                 var s = features[i];

                 //var m = L.marker([s[1],s[0]]);
                 //marks.push(m);
                 for (var j = 0; j < s.length; j++) {
                     var k = s[j];

                     var m = L.marker([k[1],k[0]]);
                     m.on('click',function(e){
                         console.log(this.getLatLng());
                     })
                     marks.push(m);
                 }

             }
             var heuristik
             for (var i = 0; i < marks.length-1; i++) {
                 var lt = marks[i].getLatLng().distanceTo(marks[i+1].getLatLng());
                 var a =i;
                 var b =i+1;
                 if(lt != 0 ){
                 console.log(a,b,lt,);

                 adjacent.push([a,b,lt]);
                 }
                 //Array.prototype.push.apply(adjacent,{a,b,lt});

             }
             //console.log(adjacent)
            }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,body {
  width: 100%;
  height: 100%;
  overflow: hidden;
 }
 #map{
  width: 100%;
  height: 100%;
 } </code>```

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css" />

 ```

答: after while searching for solution, the only possible solution was using Per Liedman existing NodeJs package https://github.com/perliedman/geojson-path-finder .</p>

Body:
i want to apply Dijkstra's algorithm on list of features provided with geoJson file i have up to 100 features look at example .

what i have done so far :

extracted all points from features (variable called points)

<s>2. i have built a adjacency list like this using index's from points
so 0-1-10 ,will be point of index 0 at points and the same for 1 and the third is the distance from each other.
 3. i have built adjacency array but i don't see any use of it
the example shown in the image is not the full features i am seeking only the starting point then i can working on the rest of the map.</s>

all black points are (lat , lang)

how can i make edge system so that i can implement Dijkstra's or A* Algorithm

<s>my question is how can i continue to go from A to B ? </s>
any suggestions are welcome.

edit 1 : added code

edit 2 : updated question

 var start = [34.000750, 71.485753];
            var end = [34.000937, 71.485180];

            var points=[];
            var nodes=[];
            var features=[];
            var adjacent=[];

            var map = L.map('map').setView(start, 17);;

        map.attributionControl.addAttribution('qgis2web');
        var bounds_group = new L.featureGroup([]);
        var basemap0 = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors,CC-BY-SA',
            maxZoom: 22
        });
        basemap0.addTo(map);
        L.geoJSON(data).addTo(map);
        //OpenStreetMap_BlackAndWhite.addTo(map)
          //basemap0.addTo(map);
            function getid(){
             var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
             var d = possible.charAt(Math.floor(Math.random() * possible.length));
             while(nodes.indexOf(d) >-1){
               d = possible.charAt(Math.floor(Math.random() * possible.length));
             }
          return d;
            }
            L.geoJSON(data, {
                onEachFeature: function(feature, layer) {
                    //console.log(feature);
                    points.push.apply(points,feature.geometry.coordinates);
                    features.push(feature.geometry.coordinates);
                   // return L.Polyline(layer, geojsonMarkerOptions);
                }
            });

            function init(){
             var marks= [];
             for (var i = 0; i < features.length; i++) {
                 var s = features[i];

                 //var m = L.marker([s[1],s[0]]);
                 //marks.push(m);
                 for (var j = 0; j < s.length; j++) {
                     var k = s[j];

                     var m = L.marker([k[1],k[0]]);
                     m.on('click',function(e){
                         console.log(this.getLatLng());
                     })
                     marks.push(m);
                 }

             }
             var heuristik
             for (var i = 0; i < marks.length-1; i++) {
                 var lt = marks[i].getLatLng().distanceTo(marks[i+1].getLatLng());
                 var a =i;
                 var b =i+1;
                 if(lt != 0 ){
                 console.log(a,b,lt,);

                 adjacent.push([a,b,lt]);
                 }
                 //Array.prototype.push.apply(adjacent,{a,b,lt});

             }
             //console.log(adjacent)
            }

html,body {
  width: 100%;
  height: 100%;
  overflow: hidden;
 }
 #map{
  width: 100%;
  height: 100%;
 }

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css" />

ContentLicense: CC BY-SA 4.0


问:
Change Text to Bold or Add Images using Google Script
This is the Code I have so far and it works great! I just want to know how to change the text to bold and add images if possible.For where it says grows, glows, apropos. I would like that to be bolded for example.</p>

```<code>       function sendEmails() {
  var allData,counter,emailAddress,fourRowsOfData,i,lastRow,
      message,messageStart,messageEnd,numRows,
      row,sheet,startRow,studentName,subject;

  //USER INPUT
  startRow = 2;  // First row of data to process
  numRows = 4;   // Number of rows to process
  subject = "Camp Pursuit: Report Card ";
  messageStart = "Dear Parents,"+'\n' +'\n' +
  "Every week at Camp Pursuit, we ask the teachers to make observations about how the kiddos did." +'\n' +
  "We know that one week isn't enough to truly know a child, so we call this our " +"Glows, Grows, & Apropos." +'\n' +
    "Meaning..." + '\n' +'\n' +
    "Glows: Positive things the teacher noticed" +'\n' +
    "Grows: Areas for continued growth" +'\n' +
    "Apropos: Ways to continue your son/daughter's enrichment" +'\n' +
    "We hope you appreciate seeing what the teachers saw last week, and perhaps you can use some of"+'\n' +
    "the recommendations for further enrichment this summer.  Feel free to let us know your thoughts on the camp through our anonymous online survey."+'\n' +
     "Your feedback helps us improve the experience for all kiddos! "+'\n' +
"Survey Link: https://docs.google.com/forms/d/1g4LvA9a8sdKECr1yvp5uOoPnvKACFm3HvbTBfvQGRyo/viewform?usp=send_form" +'\n' +
"We look forward to seeing your child at our programs throughout the year!" +'\n' +
"Sincerely, "+'\n' +
"The Camp Pursuit Team"
+'\n';
  //END USER INPUT

  sheet = SpreadsheetApp.getActiveSheet();
  lastRow = sheet.getLastRow();

  allData = sheet.getRange(startRow, 1, lastRow-startRow, 10);// Get All data first

  counter = 0;

  while (counter < lastRow-startRow) {
    Logger.log('counter: ' + counter)

    fourRowsOfData = sheet.getRange(startRow + counter, 1, numRows, 6).getValues();
    emailAddress = fourRowsOfData[0][0];  // First column of first row
    Logger.log('emailAddress: ' + emailAddress)

    studentName = fourRowsOfData[0][1];

    messageEnd = "";//Reset on every outer loop

    for (i = 0; i < numRows; i++) {//loop numRows times - once for each row
        row = fourRowsOfData[i];

        messageEnd = messageEnd + '\n' +
            "Class: " + row[2] + '\n' +'\n' +
              "Glows: " + row[3]+ '\n' +
              "Grows: " + row[4] +'\n' +
                "Apropos: " + row[5] +'\n';
    }

    message = messageStart + "\n" + studentName + "\n" + messageEnd;

    MailApp.sendEmail(emailAddress, subject, message);//Send the email outside of inner loop
    counter+=numRows;//Increment counter by number of rows to process
  }
}
</code>```

答:
Use standard html tags in your message string, then pass an empty string "" or 'null' as body parameter in sendEmail() method. Finally, assign your message string to 'htmlBody' property of 'options' parameter. Use 'br' tags for line breaks. Example

```<code>function sendEmail() {

var body = "<b>Hello </b> world. <i><Hello /i> world. <br /> New line";

MailApp.sendEmail("anton.dementyev@gmail.com", "test", "", {htmlBody: body});

}
</code>```

See 'Advanced parameters' section here https://developers.google.com/apps-script/reference/mail/mail-app#sendEmail(String,String,String,Object)

Body:
This is the Code I have so far and it works great! I just want to know how to change the text to bold and add images if possible.For where it says grows, glows, apropos. I would like that to be bolded for example.

       function sendEmails() {
  var allData,counter,emailAddress,fourRowsOfData,i,lastRow,
      message,messageStart,messageEnd,numRows,
      row,sheet,startRow,studentName,subject;

  //USER INPUT
  startRow = 2;  // First row of data to process
  numRows = 4;   // Number of rows to process
  subject = "Camp Pursuit: Report Card ";
  messageStart = "Dear Parents,"+'\n' +'\n' +
  "Every week at Camp Pursuit, we ask the teachers to make observations about how the kiddos did." +'\n' +
  "We know that one week isn't enough to truly know a child, so we call this our " +"Glows, Grows, & Apropos." +'\n' +
    "Meaning..." + '\n' +'\n' +
    "Glows: Positive things the teacher noticed" +'\n' +
    "Grows: Areas for continued growth" +'\n' +
    "Apropos: Ways to continue your son/daughter's enrichment" +'\n' +
    "We hope you appreciate seeing what the teachers saw last week, and perhaps you can use some of"+'\n' +
    "the recommendations for further enrichment this summer.  Feel free to let us know your thoughts on the camp through our anonymous online survey."+'\n' +
     "Your feedback helps us improve the experience for all kiddos! "+'\n' +
"Survey Link: https://docs.google.com/forms/d/1g4LvA9a8sdKECr1yvp5uOoPnvKACFm3HvbTBfvQGRyo/viewform?usp=send_form" +'\n' +
"We look forward to seeing your child at our programs throughout the year!" +'\n' +
"Sincerely, "+'\n' +
"The Camp Pursuit Team"
+'\n';
  //END USER INPUT

  sheet = SpreadsheetApp.getActiveSheet();
  lastRow = sheet.getLastRow();

  allData = sheet.getRange(startRow, 1, lastRow-startRow, 10);// Get All data first

  counter = 0;

  while (counter < lastRow-startRow) {
    Logger.log('counter: ' + counter)

    fourRowsOfData = sheet.getRange(startRow + counter, 1, numRows, 6).getValues();
    emailAddress = fourRowsOfData[0][0];  // First column of first row
    Logger.log('emailAddress: ' + emailAddress)

    studentName = fourRowsOfData[0][1];

    messageEnd = "";//Reset on every outer loop

    for (i = 0; i < numRows; i++) {//loop numRows times - once for each row
        row = fourRowsOfData[i];

        messageEnd = messageEnd + '\n' +
            "Class: " + row[2] + '\n' +'\n' +
              "Glows: " + row[3]+ '\n' +
              "Grows: " + row[4] +'\n' +
                "Apropos: " + row[5] +'\n';
    }

    message = messageStart + "\n" + studentName + "\n" + messageEnd;

    MailApp.sendEmail(emailAddress, subject, message);//Send the email outside of inner loop
    counter+=numRows;//Increment counter by number of rows to process
  }
}

Body:
Use standard html tags in your message string, then pass an empty string "" or 'null' as body parameter in sendEmail() method. Finally, assign your message string to 'htmlBody' property of 'options' parameter. Use 'br' tags for line breaks. Example

function sendEmail() {

var body = "<b>Hello </b> world. <i><Hello /i> world. <br /> New line";

MailApp.sendEmail("anton.dementyev@gmail.com", "test", "", {htmlBody: body});

}

See 'Advanced parameters' section here https://developers.google.com/apps-script/reference/mail/mail-app#sendEmail(String,String,String,Object)


问:
DrRacket: put two objects into big-bang
How can i put two objects with its own coordinates

```<code>(define padle1 (rectangle 10 30 "solid" "red"))
(define padle2 (rectangle 10 30 "solid" "red"))
(define (place-dot-at ... ) ...)
</code>```

into bin-bang function

```<code>(big-bang ...
[to-draw place-dot-at])
</code>```

Can i use list of padles

```<code>(define new-list (list padle1 padle2))
</code>```

答:
big-bang stores only one piece of information, usually called the "world state." All the functions that work with big-bang, like your drawing function, tick handler, and so on, must accept that world state as a single parameter.

It's up to you to decide what to store in your world state. If you want to store two locations (one for each paddle), a list or struct is the way to go. For instance, here is how you might define a struct called world that can hold two positions at once.

```<code>; Create a type called `world` that holds two locations.
(define-struct world [paddle1 paddle2])

; Create a variable to store the initial state of the world.
(define initial-world (make-world (make-posn 0 100) (make-posn 300 100)))
</code>```

When you write your drawing function, it must accept the entire world state at once:

```<code>(define (draw-game world)
   (place-image
      paddle1
      (posn-x (world-paddle1 world))
      (posn-y (world-paddle1 world))
      (place-image
         paddle2
         (posn-x (world-paddle2 world))
         (posn-y (world-paddle2 world))
         BACKGROUND)))
</code>```

In your big-bang, treat the world state like any other kind of data:

```<code>(big-bang
  initial-world
  [to-draw draw-game])
</code>```

Title: DrRacket: put two objects into big-bang

Body:
How can i put two objects with its own coordinates

(define padle1 (rectangle 10 30 "solid" "red"))
(define padle2 (rectangle 10 30 "solid" "red"))
(define (place-dot-at ... ) ...)

into bin-bang function

(big-bang ...
[to-draw place-dot-at])

Can i use list of padles

(define new-list (list padle1 padle2))

Body:
big-bang stores only one piece of information, usually called the "world state." All the functions that work with big-bang, like your drawing function, tick handler, and so on, must accept that world state as a single parameter.

It's up to you to decide what to store in your world state. If you want to store two locations (one for each paddle), a list or struct is the way to go. For instance, here is how you might define a struct called world that can hold two positions at once.

; Create a type called `world` that holds two locations.
(define-struct world [paddle1 paddle2])

; Create a variable to store the initial state of the world.
(define initial-world (make-world (make-posn 0 100) (make-posn 300 100)))

When you write your drawing function, it must accept the entire world state at once:

(define (draw-game world)
   (place-image
      paddle1
      (posn-x (world-paddle1 world))
      (posn-y (world-paddle1 world))
      (place-image
         paddle2
         (posn-x (world-paddle2 world))
         (posn-y (world-paddle2 world))
         BACKGROUND)))

In your big-bang, treat the world state like any other kind of data:

(big-bang
  initial-world
  [to-draw draw-game])


问:
html & css - using different image between each nav menu item as separator
I've yet to see a known-good way of using a different image between different nav menu elements, though I know there is a way to use one image as the consistent separator.

I have seven nav elements:

```<code>#menu-item-26{
}
//blue square here
#menu-item-25{
}
//yellow square here
#menu-item-24{
}
//red square here
#menu-item-23{
}
//pink square here
#menu-item-22{
}
//green square here
#menu-item-21{
}
//purple square here
#menu-item-20{
}
</code>```

And I've created 6 images in photoshop, essentially just 10px by 10px squares, each a different color. I want to use a different one between each set but I don't know if it would need to be used as a background image with each item and padding or if maybe there's another responsive-friendly way.

答:
You have a lot of options available to you. You can use an element to place the image, I would start with  unless you have a good reason not to. Though you can use it as a background image too. Simply use background-position to place it on the element and provided a little extra padding for the background image to reside in.

Here's a couple options.

Using an Element

body {
  margin: 0;
}

ul,
li {
  margin: 0;
  padding: 0;
  list-style: none;
}

li {
  display: inline-block;
}

li img {
  padding: 0.25rem;
  vertical-align: middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li><img src="http://placehold.it/10x10/fc0">One</li>
  <li><img src="http://placehold.it/10x10/">Two</li>
  <li><img src="http://placehold.it/10x10/fc0">Three</li>
  <li><img src="http://placehold.it/10x10/">Four</li>
  <li><img src="http://placehold.it/10x10/fc0">Five</li>
</ul></code>```

Using as Background Image

body {
  margin: 0;
}

ul,
li {
  margin: 0;
  padding: 0;
  list-style: none;
}

li {
  display: inline-block;
}

li {
  padding: 0.25rem 0.25rem 0.25rem 1rem;
  background-position: left center;
  background-repeat: no-repeat;
}

li:nth-child(odd) {
  background-image: url( 'http://placehold.it/10x10/fc0' );
}
li:nth-child(even) {
  background-image: url( 'http://placehold.it/10x10' );
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
  <li>Five</li>
</ul></code>```

--- Edit ---

After seeing an answer to a comment above. Since your images are actually a solid color you can use elements with a background color to reduce network requests and simplify maintenance and flexibility of application.

Using Elements Instead of Images

body {
  margin: 0;
}

ul,
li {
  margin: 0;
  padding: 0;
  list-style: none;
}

li,
i {
  display: inline-block;
}

li i {
  width: 0.5rem;
  height: 0.5rem;
  margin-right: 0.5rem;
  vertical-align: middle;
}

li:nth-child(odd) i {
  background-color: gold;
}
li:nth-child(even) i {
  background-color: lightgray;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li><i></i>One</li>
  <li><i></i>Two</li>
  <li><i></i>Three</li>
  <li><i></i>Four</li>
  <li><i></i>Five</li>
</ul></code>```

You could also use a pseudo element instead of an actual element like above.

Using Pseudo Elements Instead of Images

body {
  margin: 0;
}

ul,
li {
  margin: 0;
  padding: 0;
  list-style: none;
}

li {
  display: inline-block;
  padding: 0 0.5rem;
}

li:before {
  content: '';
  display: inline-block;
  position: relative;
  left: -0.5rem;
  width: 0.5rem;
  height: 0.5rem;
  vertical-align: middle;
}

li:nth-child(odd):before {
  background-color: gold;
}
li:nth-child(even):before {
  background-color: lightgray;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
  <li>Five</li>
</ul></code>```

Body:
I've yet to see a known-good way of using a different image between different nav menu elements, though I know there is a way to use one image as the consistent separator.

I have seven nav elements:

#menu-item-26{
}
//blue square here
#menu-item-25{
}
//yellow square here
#menu-item-24{
}
//red square here
#menu-item-23{
}
//pink square here
#menu-item-22{
}
//green square here
#menu-item-21{
}
//purple square here
#menu-item-20{
}

And I've created 6 images in photoshop, essentially just 10px by 10px squares, each a different color. I want to use a different one between each set but I don't know if it would need to be used as a background image with each item and padding or if maybe there's another responsive-friendly way.

Body:
You have a lot of options available to you. You can use an element to place the image, I would start with <img> unless you have a good reason not to. Though you can use it as a background image too. Simply use background-position to place it on the element and provided a little extra padding for the background image to reside in.

Here's a couple options.

Using an Element <img>

body {
  margin: 0;
}

ul,
li {
  margin: 0;
  padding: 0;
  list-style: none;
}

li {
  display: inline-block;
}

li img {
  padding: 0.25rem;
  vertical-align: middle;
}

<ul>
  <li><img src="http://placehold.it/10x10/fc0"><a href="#">One</a></li>
  <li><img src="http://placehold.it/10x10/"><a href="#">Two</a></li>
  <li><img src="http://placehold.it/10x10/fc0"><a href="#">Three</a></li>
  <li><img src="http://placehold.it/10x10/"><a href="#">Four</a></li>
  <li><img src="http://placehold.it/10x10/fc0"><a href="#">Five</a></li>
</ul>

Using as Background Image

body {
  margin: 0;
}

ul,
li {
  margin: 0;
  padding: 0;
  list-style: none;
}

li {
  display: inline-block;
}

li {
  padding: 0.25rem 0.25rem 0.25rem 1rem;
  background-position: left center;
  background-repeat: no-repeat;
}

li:nth-child(odd) {
  background-image: url( 'http://placehold.it/10x10/fc0' );
}
li:nth-child(even) {
  background-image: url( 'http://placehold.it/10x10' );
}

<ul>
  <li><a href="#">One</a></li>
  <li><a href="#">Two</a></li>
  <li><a href="#">Three</a></li>
  <li><a href="#">Four</a></li>
  <li><a href="#">Five</a></li>
</ul>

--- Edit ---

After seeing an answer to a comment above. Since your images are actually a solid color you can use elements with a background color to reduce network requests and simplify maintenance and flexibility of application.

Using Elements Instead of Images

body {
  margin: 0;
}

ul,
li {
  margin: 0;
  padding: 0;
  list-style: none;
}

li,
i {
  display: inline-block;
}

li i {
  width: 0.5rem;
  height: 0.5rem;
  margin-right: 0.5rem;
  vertical-align: middle;
}

li:nth-child(odd) i {
  background-color: gold;
}
li:nth-child(even) i {
  background-color: lightgray;
}

<ul>
  <li><i></i><a href="#">One</a></li>
  <li><i></i><a href="#">Two</a></li>
  <li><i></i><a href="#">Three</a></li>
  <li><i></i><a href="#">Four</a></li>
  <li><i></i><a href="#">Five</a></li>
</ul>

You could also use a pseudo element instead of an actual element like above.

Using Pseudo Elements Instead of Images

body {
  margin: 0;
}

ul,
li {
  margin: 0;
  padding: 0;
  list-style: none;
}

li {
  display: inline-block;
  padding: 0 0.5rem;
}

li:before {
  content: '';
  display: inline-block;
  position: relative;
  left: -0.5rem;
  width: 0.5rem;
  height: 0.5rem;
  vertical-align: middle;
}

li:nth-child(odd):before {
  background-color: gold;
}
li:nth-child(even):before {
  background-color: lightgray;
}

<ul>
  <li><a href="#">One</a></li>
  <li><a href="#">Two</a></li>
  <li><a href="#">Three</a></li>
  <li><a href="#">Four</a></li>
  <li><a href="#">Five</a></li>
</ul>


问:
dns_get_record(): A temporary server error occurred.
I'm querying a whole bunch of addresses, some are online and some are not. I can't seem to get around this error however, even catching the exception fails :(

```<code> dns_get_record(): A temporary server error occurred.

        try {
            $result = dns_get_record('_minecraft._tcp.' . $addr, DNS_SRV);
        }
        catch (Exception $e) {
            return [$addr,$port];
        }
</code>```

If this error occurs, I want to continue the script, skipping the record, however currently the script just halts.

Any help appreciated!!

答:
I can't catch this exception too. And how I understood it's a bug of php:
https://bugs.php.net/bug.php?id=73149

But I found another solution. You can use @ when you call this function. This symbol kill all errors when you call this one. And it will looks like that:

```<code>$dns = @dns_get_record($domain, DNS_A);
if(!$dns){
    return false;
}
</code>```

Body:
I'm querying a whole bunch of addresses, some are online and some are not. I can't seem to get around this error however, even catching the exception fails :(

 dns_get_record(): A temporary server error occurred.

        try {
            $result = dns_get_record('_minecraft._tcp.' . $addr, DNS_SRV);
        }
        catch (Exception $e) {
            return [$addr,$port];
        }

If this error occurs, I want to continue the script, skipping the record, however currently the script just halts.

Any help appreciated!!

Body:
I can't catch this exception too. And how I understood it's a bug of php:
https://bugs.php.net/bug.php?id=73149

But I found another solution. You can use @ when you call this function. This symbol kill all errors when you call this one. And it will looks like that:

$dns = @dns_get_record($domain, DNS_A);
if(!$dns){
    return false;
}


问:
UISlider in Android?
is there some kind of widget for Android which does same job what UISlider for iPhone or jQuery slider for js ?

cheers,
/Marcin

答:
Have a look at the SeekBar. It took me a while to find that under a different name, too.

http://developer.android.com/reference/android/widget/SeekBar.html

ContentLicense: CC BY-SA 2.5

Title: UISlider in Android?


问:
Generate random sequence in Oracle
I am trying to generate random numbers into 2 columns where the first column is from_number and second column in to_number.

My query looks as following

```<code>select to_char(5001 + (level-1)),
       to_char(5005 + (level-1))
  from dual
connect by level <= 100;
</code>```

My output is for the above query is:

```<code>5001    5005
5002    5006
5003    5007
5004    5008
5005    5009
</code>```

and so on...

But my output should be like following:

```<code>5001    5005
5006    5010
5011    5015
5016    5020
</code>```

and so on...

The second-row 'from_number' should be the first-row 'to_number'+1

How can achieve this?

Thanks in advance.

答:
Note that what you are using here is not a random sequence. It is a fixed sequence. To know how to generate random number read this

Now coming back to your question, you can do it by playing a little with level. Note I reduced the <=100 to <=20 as we are using a multiplier of 5 so the maximum value you will get is 5005 + 20*5 - 5 = 6000. Change it back to <=100 if you want total of 100 rows.

```<code>select
 to_char(5001 + (level*5) - 5 ),
 to_char(5005 + (level*5) - 5)
from dual
connect by level <= 20;
</code>```

Title: Generate random sequence in Oracle

Body:
I am trying to generate random numbers into 2 columns where the first column is from_number and second column in to_number.

My query looks as following

select to_char(5001 + (level-1)),
       to_char(5005 + (level-1))
  from dual
connect by level <= 100;

My output is for the above query is:

5001    5005
5002    5006
5003    5007
5004    5008
5005    5009

and so on...

But my output should be like following:

5001    5005
5006    5010
5011    5015
5016    5020

and so on...

The second-row 'from_number' should be the first-row 'to_number'+1

How can achieve this?

Thanks in advance.

Body:
Note that what you are using here is not a random sequence. It is a fixed sequence. To know how to generate random number read this

Now coming back to your question, you can do it by playing a little with level. Note I reduced the <=100 to <=20 as we are using a multiplier of 5 so the maximum value you will get is 5005 + 20*5 - 5 = 6000. Change it back to <=100 if you want total of 100 rows.

select
 to_char(5001 + (level*5) - 5 ),
 to_char(5005 + (level*5) - 5)
from dual
connect by level <= 20;


问:
SQL to merge rows in Oracle
I want to merge some rows.

First, my table and data exist as below

```<code>GRP     CRRO_NO  TYPE_CD  TYPE_ID
PERSON  1111     FATHER   Tom
PERSON  1111     MOTHER   Jennifer
PERSON  1111     JOB_     Teacher
PERSON  1111     FRIEND   Jimmy
PERSON  1111     FRIEND   Kim
PERSON  1111     FRIEND   Michael
</code>```

And I want to get the result like

```<code>GRP     CRRO_NO   FATHER    MOTHER     JOB_      FRIEND
PERSON  1111      Tom       Jennifer   Teacher   Jimmy
PERSON  1111      Tom       Jennifer   Teacher   Kim
PERSON  1111      Tom       Jennifer   Teacher   Michael
</code>```

With this situation, how to write SQL?

I've been trying like

```<code>SELECT  T1.GRP_CD GRP, T1.CRRO_NO CRRO
      , MAX(T1.MOTHER) MOTHER, MAX(T1.FATHER) FATHER, MAX(T1.JOB_) JOB, T1.FRIEND FRIEND
  FROM (
        SELECT  DISTINCT
                GRP_CD
               ,CRRO_NO
               ,CASE WHEN TYPE_CD  = 'FATHER'  THEN TYPE_ID   ELSE '' END FATHER
               ,CASE WHEN TYPE_CD  = 'MOTHER'  THEN TYPE_ID   ELSE '' END MOTHER
               ,CASE WHEN TYPE_CD  = 'JOB_'    THEN TYPE_ID    ELSE '' END JOB_
               ,CASE WHEN TYPE_CD  = 'FRIEND'  THEN TYPE_ID   ELSE '' END FRIEND
         FROM    TMP
        WHERE   1=1   AND     TRIM(CRRO_NO) = '1111'
       ) T1
  WHERE T1.CRRO_NO = '1111'
        GROUP BY T1.GRP_CD, T1.CRRO_NO, T1.FRIEND
;
</code>```

Then, the result of sql above is

```<code>GRP      CRRO_NO  MOTHER     FATHER    JOB       FRIEND
PERSON   1111     Jennifer   Tom       Teacher   (null)
PERSON   1111     (null)     (null)    (null)    Jimmy
PERSON   1111     (null)     (null)    (null)    Kim
PERSON   1111     (null)     (null)    (null)    Michael
</code>```

Now I know why the result of my query is wrong(not the one I want), but still I can't find the way.

Actually, there are strict rules to classify which one would be duplicated (Mother, Father, Job) and which would not (friend)

For some reasons, I can't modify the structure of my table.
(I've changed contents of this question from my business terms and simplified the situation to explain)

Please give any advice to try again

答:
Just to give another way of doing this.</p>

```<code>with MFJQuery as (
select * from (
            select
                   A.GRP,
                   A.CRRO_NO,
                   A.TYPE_CD,
                   A.TYPE_ID
            from test_data A
            where A.TYPE_CD <> 'FRIEND')
pivot
(
    max(TYPE_ID)
    for TYPE_CD in ('MOTHER' as "MOTHER",
                    'FATHER' as "FATHER",
                    'JOB_' as "JOB")
))
select A.GRP, A.CRRO_NO, B.MOTHER, B.FATHER, B.JOB, A.TYPE_ID as FRIEND
from test_data A inner join
        MFJQuery B on A.GRP = B.GRP
        and A.CRRO_NO = B.CRRO_NO
where
    A.TYPE_CD = 'FRIEND'
</code>```

Title: SQL to merge rows in Oracle

Body:
I want to merge some rows.

First, my table and data exist as below

GRP     CRRO_NO  TYPE_CD  TYPE_ID
PERSON  1111     FATHER   Tom
PERSON  1111     MOTHER   Jennifer
PERSON  1111     JOB_     Teacher
PERSON  1111     FRIEND   Jimmy
PERSON  1111     FRIEND   Kim
PERSON  1111     FRIEND   Michael

And I want to get the result like

GRP     CRRO_NO   FATHER    MOTHER     JOB_      FRIEND
PERSON  1111      Tom       Jennifer   Teacher   Jimmy
PERSON  1111      Tom       Jennifer   Teacher   Kim
PERSON  1111      Tom       Jennifer   Teacher   Michael

With this situation, how to write SQL?

I've been trying like

SELECT  T1.GRP_CD GRP, T1.CRRO_NO CRRO
      , MAX(T1.MOTHER) MOTHER, MAX(T1.FATHER) FATHER, MAX(T1.JOB_) JOB, T1.FRIEND FRIEND
  FROM (
        SELECT  DISTINCT
                GRP_CD
               ,CRRO_NO
               ,CASE WHEN TYPE_CD  = 'FATHER'  THEN TYPE_ID   ELSE '' END FATHER
               ,CASE WHEN TYPE_CD  = 'MOTHER'  THEN TYPE_ID   ELSE '' END MOTHER
               ,CASE WHEN TYPE_CD  = 'JOB_'    THEN TYPE_ID    ELSE '' END JOB_
               ,CASE WHEN TYPE_CD  = 'FRIEND'  THEN TYPE_ID   ELSE '' END FRIEND
         FROM    TMP
        WHERE   1=1   AND     TRIM(CRRO_NO) = '1111'
       ) T1
  WHERE T1.CRRO_NO = '1111'
        GROUP BY T1.GRP_CD, T1.CRRO_NO, T1.FRIEND
;

Then, the result of sql above is

GRP      CRRO_NO  MOTHER     FATHER    JOB       FRIEND
PERSON   1111     Jennifer   Tom       Teacher   (null)
PERSON   1111     (null)     (null)    (null)    Jimmy
PERSON   1111     (null)     (null)    (null)    Kim
PERSON   1111     (null)     (null)    (null)    Michael

Now I know why the result of my query is wrong(not the one I want), but still I can't find the way.

Actually, there are strict rules to classify which one would be duplicated (Mother, Father, Job) and which would not (friend)

For some reasons, I can't modify the structure of my table.
(I've changed contents of this question from my business terms and simplified the situation to explain)

Please give any advice to try again

Body:
Just to give another way of doing this.

with MFJQuery as (
select * from (
            select
                   A.GRP,
                   A.CRRO_NO,
                   A.TYPE_CD,
                   A.TYPE_ID
            from test_data A
            where A.TYPE_CD <> 'FRIEND')
pivot
(
    max(TYPE_ID)
    for TYPE_CD in ('MOTHER' as "MOTHER",
                    'FATHER' as "FATHER",
                    'JOB_' as "JOB")
))
select A.GRP, A.CRRO_NO, B.MOTHER, B.FATHER, B.JOB, A.TYPE_ID as FRIEND
from test_data A inner join
        MFJQuery B on A.GRP = B.GRP
        and A.CRRO_NO = B.CRRO_NO
where
    A.TYPE_CD = 'FRIEND'


答:
Something like this... which could be done with cross apply as well.

```<code>declare @table table (CurrTime datetime2)
insert into @table
values
('2017-05-05 12:59:52.000'),
('2017-05-05 12:59:29.000'),
('2017-05-05 12:59:22.000'),
('2017-05-05 12:58:53.000'),
('2017-05-05 12:58:49.000')

;with cte as(
select distinct
    t.CurrTime
    ,DATEDIFF(SECOND,t.CurrTime,t2.CurrTime) d
from
    @table t
inner join
    @table t2 on
    t2.CurrTime <> t.CurrTime)

select *
from cte
where d <= 5 and d >= -5
</code>```

For cross apply, just remove the self reference by d <> 0

```<code>;with cte as(
select distinct
    t.CurrTime
    ,DATEDIFF(SECOND,t.CurrTime,t2.CurrTime) d
from
    @table t
    cross apply @table t2)

select * from cte
where d <= 5 and d >= -5 and d <> 0
</code>```

Title: How to select rows with timestamp close to adjacent rows?

Body:
I have a SQL table with timestamps as one field. How can I select "adjacent" rows, i.e., rows that have timestamps within a certain delta (e.g. 5 seconds)?

Edit:

Sample Table:

CurrTime                Weight Length
----------------------- ------ -------------
2017-05-05 12:59:52.000 392    18.18
2017-05-05 12:59:29.000 396    18.18
2017-05-05 12:59:22.000 511    18.5
2017-05-05 12:58:53.000 512    18.5
2017-05-05 12:58:49.000 537    18.5

So the query should return:

CurrTime                Weight Length
----------------------- ------ -------------
2017-05-05 12:58:53.000 512    18.5
2017-05-05 12:58:49.000 537    18.5

Body:
Something like this... which could be done with cross apply as well.

declare @table table (CurrTime datetime2)
insert into @table
values
('2017-05-05 12:59:52.000'),
('2017-05-05 12:59:29.000'),
('2017-05-05 12:59:22.000'),
('2017-05-05 12:58:53.000'),
('2017-05-05 12:58:49.000')

;with cte as(
select distinct
    t.CurrTime
    ,DATEDIFF(SECOND,t.CurrTime,t2.CurrTime) d
from
    @table t
inner join
    @table t2 on
    t2.CurrTime <> t.CurrTime)

select *
from cte
where d <= 5 and d >= -5

For cross apply, just remove the self reference by d <> 0

;with cte as(
select distinct
    t.CurrTime
    ,DATEDIFF(SECOND,t.CurrTime,t2.CurrTime) d
from
    @table t
    cross apply @table t2)

select * from cte
where d <= 5 and d >= -5 and d <> 0


问:
Silent Install Weblogic in a Vagrant VM
When executing the command java -jar /opt/TAR/fmw_12.2.1.0_wls.jar -silent -responseFile /opt/TAR/wls.rsp -invPtrLoc /opt/TAR/oraInst.locto download Weblogic, I get the following errors:

```<code>[ERROR] Data Insufficient to start Install.
[ERROR] Select one and only one Install Type. Any one of the variables SOFTWARE ONLY TYPE,BASIC TYPE or ADVANCED
[ERROR] Rule_VDiskSpace_Error. Aborting Install
</code>```

I have passed all the checks including enough swap space and temp space. I have also tried to increase more swap space by doing the following

```<code>$ dd if=/dev/zero of=/myswap count=3000 bs=MiB
$ chmod 600 /myswap
$ mkswap /myswap
$ swapon /myswap
</code>```

My wls.rsp file looks like this

```<code>[ENGINE]
Response File Version=1.0.0.0.0
[GENERIC]
ORACLE_HOME/opt/weblogic/wls12.2.1.2.0
INSTALL_TYPE=WebLogic Server
MYORACLESUPPORT_USERNAME=
MYORACLESUPPORT_PASSWORD=<SECURE VALUE>
DECLINE_SECURITY_UPDATES=true
SECURITY_UPDATES_VIA_MYORACLESUPPORT=false
PROXY_HOST=
PROXY_PORT=
PROXY_USER=
PROXY_PWD=<SECURE VALUE>
COLLECTOR_SUPPORTHUB_URL=
</code>```

and oraInst.loc looks like this

```<code>inventory_loc=/opt/weblogic/oraInventory
inst_group=weblogic
</code>```

What can fix those three errors?

答:
Your response file has some issues - see fixed

```<code>[ENGINE]
Response File Version=1.0.0.0.0
[GENERIC]
DECLINE_AUTO_UPDATES=true
ORACLE_HOME=/opt/weblogic/wls12.2.1.2.0
INSTALL_TYPE=WebLogic Server
MYORACLESUPPORT_USERNAME=
MYORACLESUPPORT_PASSWORD=
DECLINE_SECURITY_UPDATES=true
SECURITY_UPDATES_VIA_MYORACLESUPPORT=false
PROXY_HOST=
PROXY_PORT=
PROXY_USER=
PROXY_PWD=
COLLECTOR_SUPPORTHUB_URL=
</code>```

You need to add a value for DECLINE_AUTO_UPDATES if you set to false, you need to add other parameters

the <SECURE VALUE> is just a template - if you dont set username you dont need password, just leave blank

Title: Silent Install Weblogic in a Vagrant VM

Body:
When executing the command java -jar /opt/TAR/fmw_12.2.1.0_wls.jar -silent -responseFile /opt/TAR/wls.rsp -invPtrLoc /opt/TAR/oraInst.locto download Weblogic, I get the following errors:

[ERROR] Data Insufficient to start Install.
[ERROR] Select one and only one Install Type. Any one of the variables SOFTWARE ONLY TYPE,BASIC TYPE or ADVANCED
[ERROR] Rule_VDiskSpace_Error. Aborting Install

I have passed all the checks including enough swap space and temp space. I have also tried to increase more swap space by doing the following

$ dd if=/dev/zero of=/myswap count=3000 bs=MiB
$ chmod 600 /myswap
$ mkswap /myswap
$ swapon /myswap

My wls.rsp file looks like this

[ENGINE]
Response File Version=1.0.0.0.0
[GENERIC]
ORACLE_HOME/opt/weblogic/wls12.2.1.2.0
INSTALL_TYPE=WebLogic Server
MYORACLESUPPORT_USERNAME=
MYORACLESUPPORT_PASSWORD=<SECURE VALUE>
DECLINE_SECURITY_UPDATES=true
SECURITY_UPDATES_VIA_MYORACLESUPPORT=false
PROXY_HOST=
PROXY_PORT=
PROXY_USER=
PROXY_PWD=<SECURE VALUE>
COLLECTOR_SUPPORTHUB_URL=

and oraInst.loc looks like this

inventory_loc=/opt/weblogic/oraInventory
inst_group=weblogic

What can fix those three errors?

Body:
Your response file has some issues - see fixed

[ENGINE]
Response File Version=1.0.0.0.0
[GENERIC]
DECLINE_AUTO_UPDATES=true
ORACLE_HOME=/opt/weblogic/wls12.2.1.2.0
INSTALL_TYPE=WebLogic Server
MYORACLESUPPORT_USERNAME=
MYORACLESUPPORT_PASSWORD=
DECLINE_SECURITY_UPDATES=true
SECURITY_UPDATES_VIA_MYORACLESUPPORT=false
PROXY_HOST=
PROXY_PORT=
PROXY_USER=
PROXY_PWD=
COLLECTOR_SUPPORTHUB_URL=

You need to add a value for DECLINE_AUTO_UPDATES if you set to false, you need to add other parameters

the <SECURE VALUE> is just a template - if you dont set username you dont need password, just leave blank


问:
MySQL Workbench: No objects selected
I have installed MySQL Workbench in my machine. But now I'm unable to select a table on left hand side. Here's what I have currently:

How can I get to the tables in my database?

答: pull the scroll bar downward. i had the same issue but all i needed to do was to extend the navigation menu.

Title: MySQL Workbench: No objects selected


问:
How to apply images on spark numericstepper using stylesheet
I want to customize the images on increment and decrement buttons in spark numericstepper and I trying the following in my css file. But it doesnot work for spark numericstepper.</p>

```<code>s|NumericStepper
{
 downArrowDisabledSkin: Embed(source="assets/componentImages/downArrowDisabledSkin.png");
 downArrowDownSkin: Embed(source="assets/componentImages/downArrowDownSkin.png");
 downArrowOverSkin: Embed(source="assets/componentImages/downArrowOverSkin.png");
 downArrowUpSkin: Embed(source="assets/componentImages/downArrowUpSkin.png");
 upArrowDisabledSkin: Embed(source="assets/componentImages/upArrowDisabledSkin.png");
 upArrowDownSkin: Embed(source="assets/componentImages/upArrowDownSkin.png");
 upArrowOverSkin: Embed(source="assets/componentImages/upArrowOverSkin.png");
 upArrowUpSkin: Embed(source="assets/componentImages/upArrowUpSkin.png");
}
</code>```

答:
This is how you skin a halo (mx) NumericStepper but it won't work for the spark NumericStepper.

You have to create a new spark skin and use BitmapImage in it.

Before that, I suggest you read more about the new spark architecture

Body:
I want to customize the images on increment and decrement buttons in spark numericstepper and I trying the following in my css file. But it doesnot work for spark numericstepper.

s|NumericStepper
{
 downArrowDisabledSkin: Embed(source="assets/componentImages/downArrowDisabledSkin.png");
 downArrowDownSkin: Embed(source="assets/componentImages/downArrowDownSkin.png");
 downArrowOverSkin: Embed(source="assets/componentImages/downArrowOverSkin.png");
 downArrowUpSkin: Embed(source="assets/componentImages/downArrowUpSkin.png");
 upArrowDisabledSkin: Embed(source="assets/componentImages/upArrowDisabledSkin.png");
 upArrowDownSkin: Embed(source="assets/componentImages/upArrowDownSkin.png");
 upArrowOverSkin: Embed(source="assets/componentImages/upArrowOverSkin.png");
 upArrowUpSkin: Embed(source="assets/componentImages/upArrowUpSkin.png");
}


问:
UIButton label detect tap on specific text
I have the following UIButton to render a checkbox and label;

To create this, I used a UIButton control with an NSMutableAttributedString to give "Terms & Conditions" a different style to the rest of the text.

Just like with a checkbox on a web page, I want the user to be able to tap either the grey text or the image itself to toggle the checkbox on or off.

But if the user clicks "Terms & Conditions" I want that to perform an action (e.g. load a terms URL).

This is really easy to do in Android as you can use checkbox.setMovementMethod(LinkMovementMethod.getInstance());, but in iOS I'm really struggling to find a way to basically create a checkbox with a label that contains a link.

Has anyone ever done this before and how did you approach?

答:
I ended up doing the following;

Created a UIButton (empty text label) for my actual checkbox and a UITextView for my adjacent checkbox label text.

I then used NSMutableAttributedString like so;

```<code>class MyViewController: UIViewController, UITextViewDelegate {

    override func viewDidLoad() {
        let attributedTermsTitle = NSMutableAttributedString()
        attributedTermsTitle.append(NSAttributedString(string: "I have read and accept the ", attributes: [NSFontAttributeName:UIFont(name: "My-Font", size: 14)!]))
        attributedTermsTitle.append(NSAttributedString(string: "Terms & Conditions", attributes: [NSFontAttributeName:UIFont(name: "My-Font", size: 14)!, NSLinkAttributeName: "terms"]))

        termsText.linkTextAttributes = [NSForegroundColorAttributeName: UIColor.blue]
        termsText.attributedText = attributedTermsTitle

        termsText.delegate = self
        termsText.isSelectable = true
        termsText.isUserInteractionEnabled = true
        termsText.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(MyViewController.toggleCheckbox)))
    }

    func toggleCheckbox(sender: UITapGestureRecognizer) {
        termsButton.isChecked = !termsButton.isChecked
    }

    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {

        let link = URL.absoluteString
        if(link == "terms") {
             // link to the Terms web page / screen
        }

        return false
    }

}
</code>```

and for the UIButton, gave the class;

```<code>class CheckBox: UIButton {
    let checkedImage = UIImage(named: "checkbox_on")! as UIImage
    let uncheckedImage = UIImage(named: "checkbox_off")! as UIImage

    var isChecked: Bool = false {
        didSet{
            if isChecked == true {
                self.setImage(checkedImage, for: UIControlState.normal)
            } else {
                self.setImage(uncheckedImage, for: UIControlState.normal)
            }
        }
    }

    override func awakeFromNib() {
        self.addTarget(self, action:#selector(buttonClicked(sender:)), for: UIControlEvents.touchUpInside)
        self.isChecked = false
    }

    func buttonClicked(sender: UIButton) {
        if sender == self {
            isChecked = !isChecked
        }
    }
}
</code>```

End result is that both the UIButton and the non-linked text of the UITextView will toggle the checkbox on and off.  The "Terms & Conditions" text will link to the website or segue somewhere else.

Hopefully this helps someone else out.

Body:
I ended up doing the following;

Created a UIButton (empty text label) for my actual checkbox and a UITextView for my adjacent checkbox label text.

I then used NSMutableAttributedString like so;

class MyViewController: UIViewController, UITextViewDelegate {

    override func viewDidLoad() {
        let attributedTermsTitle = NSMutableAttributedString()
        attributedTermsTitle.append(NSAttributedString(string: "I have read and accept the ", attributes: [NSFontAttributeName:UIFont(name: "My-Font", size: 14)!]))
        attributedTermsTitle.append(NSAttributedString(string: "Terms & Conditions", attributes: [NSFontAttributeName:UIFont(name: "My-Font", size: 14)!, NSLinkAttributeName: "terms"]))

        termsText.linkTextAttributes = [NSForegroundColorAttributeName: UIColor.blue]
        termsText.attributedText = attributedTermsTitle

        termsText.delegate = self
        termsText.isSelectable = true
        termsText.isUserInteractionEnabled = true
        termsText.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(MyViewController.toggleCheckbox)))
    }

    func toggleCheckbox(sender: UITapGestureRecognizer) {
        termsButton.isChecked = !termsButton.isChecked
    }

    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {

        let link = URL.absoluteString
        if(link == "terms") {
             // link to the Terms web page / screen
        }

        return false
    }

}

and for the UIButton, gave the class;

class CheckBox: UIButton {
    let checkedImage = UIImage(named: "checkbox_on")! as UIImage
    let uncheckedImage = UIImage(named: "checkbox_off")! as UIImage

    var isChecked: Bool = false {
        didSet{
            if isChecked == true {
                self.setImage(checkedImage, for: UIControlState.normal)
            } else {
                self.setImage(uncheckedImage, for: UIControlState.normal)
            }
        }
    }

    override func awakeFromNib() {
        self.addTarget(self, action:#selector(buttonClicked(sender:)), for: UIControlEvents.touchUpInside)
        self.isChecked = false
    }

    func buttonClicked(sender: UIButton) {
        if sender == self {
            isChecked = !isChecked
        }
    }
}

End result is that both the UIButton and the non-linked text of the UITextView will toggle the checkbox on and off.  The "Terms & Conditions" text will link to the website or segue somewhere else.

Hopefully this helps someone else out.


问:
Python plotting issue
I wrote the following code:

```<code>full_list = [0, 10**3, 10**6, 10**9, 10**12, 10**15]

list1 = []
list2 = []
list3 = []

for hash_power in full_list:
    x1 = Calc1()
    list1.append(x1)

    x2 = Calc2()
    list2.append(x2)

    x3 = Calc3()
    list3.append(x3)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(full_list,list1,'r-->',full_list,list2,'g--o',full_list,list3,'b--o')
plt.show()
</code>```

When the figure is generated, the distribution on the x-axis only produces the first and last point, ignoring all the points from the full_list in the middle.

I know the range is really big but is there a way to display it?

答:
If you have large numeric values populating your axes - you might want to consider rescaling your figure axes such that they are logarithmic instead of linear. Steps on how to do that is found in this stackoverflow thread.

Or even more simply, customizing the scale on your figure axes in non-logarithmic increments, which is found in this thread.

Title: Python plotting issue

Body:
I wrote the following code:

full_list = [0, 10**3, 10**6, 10**9, 10**12, 10**15]

list1 = []
list2 = []
list3 = []

for hash_power in full_list:
    x1 = Calc1()
    list1.append(x1)

    x2 = Calc2()
    list2.append(x2)

    x3 = Calc3()
    list3.append(x3)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(full_list,list1,'r-->',full_list,list2,'g--o',full_list,list3,'b--o')
plt.show()

When the figure is generated, the distribution on the x-axis only produces the first and last point, ignoring all the points from the full_list in the middle.

I know the range is really big but is there a way to display it?


问:
Using Twython to send a tweet, twitter api error
I'm trying to make python send a tweet for me using Twython but for some reason everything I'm trying isn't working.

I've followed the Twython README but still unable to acheive what I want.

Below is my latest attempted code:

```<code>from twython import Twython, TwythonError

APP_KEY = "KEYHERE"
APP_SECRET = "SECRETHERE"

twitter = Twython(APP_KEY, APP_SECRET)
auth = twitter.get_authentication_tokens()

OAUTH_TOKEN = auth['oauth_token']
OAUTH_TOKEN_SECRET = auth['oauth_token_secret']

twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

try:
    twitter.update_status(status='See how easy this was?')
except TwythonError as e:
    print e
</code>```

On running the above code I get the following traceback error:

```<code>Twitter API returned a 401 (Unauthorized), Invalid or expired token
</code>```

Does anyone know what I'm doing wrong and more importantly how do I fix this?

I dont have enough points for a bounty, but I would really appreciate the help!

Thanks in advance

edit

```<code>Traceback (most recent call last):
  File "C:\testtweet.py", line 20, in <module>
    final_step = twitter.get_authorized_tokens(oauth_verifier)
  File "C:\Python27\lib\site-packages\twython\api.py", line 313, in get_authorized_tokens
    raise TwythonError('Unable to decode authorized tokens.')
TwythonError: Unable to decode authorized tokens.
</code>```

The above is the traceback recieved from the code supplied by @justhalf

Thanks SMNALLY

答: I am adding to the following discussion that a connection to another server might also prevent the connection on the stream api. For example, I had a Rserve() open and kept getting the 401 error but when I killall Rserve in my command prompt , the authorization was granted...</p>

Body:
I'm trying to make python send a tweet for me using Twython but for some reason everything I'm trying isn't working.

I've followed the Twython README but still unable to acheive what I want.

Below is my latest attempted code:

from twython import Twython, TwythonError

APP_KEY = "KEYHERE"
APP_SECRET = "SECRETHERE"

twitter = Twython(APP_KEY, APP_SECRET)
auth = twitter.get_authentication_tokens()

OAUTH_TOKEN = auth['oauth_token']
OAUTH_TOKEN_SECRET = auth['oauth_token_secret']

twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

try:
    twitter.update_status(status='See how easy this was?')
except TwythonError as e:
    print e

On running the above code I get the following traceback error:

Twitter API returned a 401 (Unauthorized), Invalid or expired token

Does anyone know what I'm doing wrong and more importantly how do I fix this?

I dont have enough points for a bounty, but I would really appreciate the help!

Thanks in advance

edit

Traceback (most recent call last):
  File "C:\testtweet.py", line 20, in <module>
    final_step = twitter.get_authorized_tokens(oauth_verifier)
  File "C:\Python27\lib\site-packages\twython\api.py", line 313, in get_authorized_tokens
    raise TwythonError('Unable to decode authorized tokens.')
TwythonError: Unable to decode authorized tokens.

The above is the traceback recieved from the code supplied by @justhalf

Thanks SMNALLY


问:
Access Main thread data from the Background thread
I´m using a backgroundworker to handle processing of data while the user is still free to for instance click another button that aborts the process.
However, the code in backgroundworker requires several pieces of data, for instance it needs to know whether a radio button is checked.

Is there a way to access data in another thread from the background thread? Or should I create global variables that hold this information?

```<code>Public Class Test
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Button1.Content = "Working..."
        BackgroundWorker1.RunWorkerAsync()
    End Sub

    Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        If RadioButton1.IsChecked Then
           MsgBox("It works")
        End If
    End Sub
End Class
</code>```

答:
You can pass the RadioButton checked state to the RunWorkerAsync method like this:

```<code>Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    BackgroundWorker1.RunWorkerAsync(RadioButton1.Checked)
End Sub

Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
    Dim checked As Boolean = CBool(e.Argument)
    If checked Then
        MessageBox.Show("It works")
    End If
End Sub
</code>```

Let me know if you need to be checking the RadioButton continuously from inside a loop, as that would be different.

Body:
I´m using a backgroundworker to handle processing of data while the user is still free to for instance click another button that aborts the process.
However, the code in backgroundworker requires several pieces of data, for instance it needs to know whether a radio button is checked.

Is there a way to access data in another thread from the background thread? Or should I create global variables that hold this information?

Public Class Test
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Button1.Content = "Working..."
        BackgroundWorker1.RunWorkerAsync()
    End Sub

    Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        If RadioButton1.IsChecked Then
           MsgBox("It works")
        End If
    End Sub
End Class

Body:
You can pass the RadioButton checked state to the RunWorkerAsync method like this:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    BackgroundWorker1.RunWorkerAsync(RadioButton1.Checked)
End Sub

Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
    Dim checked As Boolean = CBool(e.Argument)
    If checked Then
        MessageBox.Show("It works")
    End If
End Sub

Let me know if you need to be checking the RadioButton continuously from inside a loop, as that would be different.


问:
Django: To use User model or Profile model for related models
General question here (more specifically for Django/Python), when creating a model such as a Company for example, and several users (employees) are going to be related to such model, how should the different models be related?

I.e. a user profile will be related to a user object via a OneToOneField. But should the Company object be related by a ForeignKey to the User object or the UserProfile object, and why is this the appropriate way?

So

```<code>class UserProfile(models.Model): # For the Company Employees
    user = models.OneToOneField(UserModel, related_name='employeeprofilemodel', on_delete=models.CASCADE, blank=True,
    null=True)
    ...
    company_rel = models.ForeignKey(CompanyModel, related_name='companyrel', null=True)
</code>```

or

```<code>class User(AbstractBaseUser): # For all Users
    ...
    company_rel = models.ForeignKey(CompanyModel, related_name='companyrel', null=True)
</code>```

答:
This is more of an opinion based question, rather than technicality. I'd recommend the former way, which is creating a One-to-one relationship with the AUTH_USER_MODEL. Then, you could store the employee related data in the User Profile table which can be related to the Company table through a ForeignKey relationship. The advantage of this kind of database schema is that,  you can alter the User table(which is AUTH_USER_MODEL ) in future (if needed, of course) without affecting the employee details which maybe sensitive in nature. The User table lives independent of the Company table in the database and could be used for the Authorisation. Also less data is carried during db queries and implicitly a small level of optimisation can be achieved. I assume this is more appropriate way than extending from the auth.User model.

The latter way could compromise the above said sensitive data whenever a database refactoring ever required. Also, the queries would be much more heavy, when the User models have more data than necessary regarding the users. Extra care for optimisation may be required when handling the db queries with user tables.

Body:
General question here (more specifically for Django/Python), when creating a model such as a Company for example, and several users (employees) are going to be related to such model, how should the different models be related?

I.e. a user profile will be related to a user object via a OneToOneField. But should the Company object be related by a ForeignKey to the User object or the UserProfile object, and why is this the appropriate way?

So

class UserProfile(models.Model): # For the Company Employees
    user = models.OneToOneField(UserModel, related_name='employeeprofilemodel', on_delete=models.CASCADE, blank=True,
    null=True)
    ...
    company_rel = models.ForeignKey(CompanyModel, related_name='companyrel', null=True)

or

class User(AbstractBaseUser): # For all Users
    ...
    company_rel = models.ForeignKey(CompanyModel, related_name='companyrel', null=True)


问:
Force HTTPS using .htaccess
How can I force HTTPS on my website? I tried the solution from this answer, but for some reason I get redirected to the parent directory when I visit the index page by clicking on a link (it worked fine before adding those lines of code in .htaccess). Also, when I try to visit my website using HTTP, it lets me do it. What am I missing?</p>

答:
With Apache, you have several alternatives - including .htaccess.

Look here:

https://wiki.apache.org/httpd/RedirectSSL

Per the documentation, your best bet is to use a Redirect directive inside the non-secureVirtualHost:

```<code>NameVirtualHost *:80
<VirtualHost *:80>
   ServerName mysite.example.com
   DocumentRoot /usr/local/apache2/htdocs
   Redirect permanent /secure https://mysite.example.com/secure
</VirtualHost>

<VirtualHost _default_:443>
   ServerName mysite.example.com
   DocumentRoot /usr/local/apache2/htdocs
   SSLEngine On
# etc...
</VirtualHost>
</code>```

Here is an .htaccess example, from the same link:

```<code> Redirect permanent /login https://mysite.example.com/login
</code>```

Finally, look here for additional troubleshooting tips (for example, forgetting 'NameVirtualHost *:443' to enable Named virtual hosting for port 443):

Why might Apache ignore a virtual host with a ServerName matching the requested URL?

Title: Force HTTPS using .htaccess

Body:
With Apache, you have several alternatives - including .htaccess.

Look here:

https://wiki.apache.org/httpd/RedirectSSL

Per the documentation, your best bet is to use a Redirect directive inside the non-secureVirtualHost:

NameVirtualHost *:80
<VirtualHost *:80>
   ServerName mysite.example.com
   DocumentRoot /usr/local/apache2/htdocs
   Redirect permanent /secure https://mysite.example.com/secure
</VirtualHost>

<VirtualHost _default_:443>
   ServerName mysite.example.com
   DocumentRoot /usr/local/apache2/htdocs
   SSLEngine On
# etc...
</VirtualHost>

Here is an .htaccess example, from the same link:

 Redirect permanent /login https://mysite.example.com/login

Finally, look here for additional troubleshooting tips (for example, forgetting 'NameVirtualHost *:443' to enable Named virtual hosting for port 443):

Why might Apache ignore a virtual host with a ServerName matching the requested URL?


问:
Accessing a method of a bound service from an IntentReceiver on Android
I'm having a service class that I bind from my main activity with a ServiceConnection to call a method within the service as soon as it is bound. I need to explicitly call the method to pass over the context of my main activity.

If I call this service class from within an IntentReceiver, I need to use peekService to bind to the service. But how can I spawn it's method then? :-s

Best regards / Thanks alot!

S.

答:
peekService returns you IBinder implementation. you need only to call getService() from it and you will get your service object.

Put your code inside your service:

```<code>public class LocalBinder extends Binder {
    public NotificationService getService() {
        return NotificationService.this;
    }
}

@Override
public IBinder onBind(Intent intent) {
    return new LocalBinder();
}
</code>```

Body:
peekService returns you IBinder implementation. you need only to call getService() from it and you will get your service object.

Put your code inside your service:

public class LocalBinder extends Binder {
    public NotificationService getService() {
        return NotificationService.this;
    }
}

@Override
public IBinder onBind(Intent intent) {
    return new LocalBinder();
}


问:
Node.JS async.parallel doesn't wait until all the tasks have completed
I am using aync.parallel to run two functions in parallel. The functions request RSS feeds. Then the RSS feeds are parsed and added to my web page.

But for some reason async.parallel runs the callback method without waiting until the two functions have completed

The documentation says:

Once the tasks have completed, the results are passed to the final
  callback as an array.

My code.

```<code>require('async').parallel([ function(callback) {
        fetchRss(res, bbcOpts); // Needs time to request and parse
        callback();
    }, function(callback) {
        // Very fast.
        callback();
    } ], function done(err, results) {
        if (err) {
            throw err;
        }
        res.end("Done!");
    });
</code>```

In fact I only have "Done!" on my web page. Why?

Why do I need to call res.end()?

The Node.JS documentation says:

The method, response.end(), MUST be called on each response.

If I don't call it, my web page will be being "downloaded" (I mean a progress bar in the address line of my browser).

答:
You can use async.reflect or async.reflectAll to do make sure all functions are completed
http://caolan.github.io/async/docs.html#reflect

Body:
I am using aync.parallel to run two functions in parallel. The functions request RSS feeds. Then the RSS feeds are parsed and added to my web page.

But for some reason async.parallel runs the callback method without waiting until the two functions have completed

The documentation says:

Once the tasks have completed, the results are passed to the final
  callback as an array.

My code.

require('async').parallel([ function(callback) {
        fetchRss(res, bbcOpts); // Needs time to request and parse
        callback();
    }, function(callback) {
        // Very fast.
        callback();
    } ], function done(err, results) {
        if (err) {
            throw err;
        }
        res.end("Done!");
    });

In fact I only have "Done!" on my web page. Why?

Why do I need to call res.end()?

The Node.JS documentation says:

The method, response.end(), MUST be called on each response.

If I don't call it, my web page will be being "downloaded" (I mean a progress bar in the address line of my browser).


问:
Android MediaStore from Air App
I am writing an Air app that needs to access the Android Media Store.

So far tried:
Direct access to the SQLite database. Seems Android does not give permissions for this.
Next attempted calling a native Android app from my Air app. Burrito does not seem to support NativeProcess for Android.

Any ideas or workarounds?
Or do we drop AS3 and code native for Android?

Thanks, Ronnie

答:
The only solution today is to combine a native apk with an AIR for Android apk.  More details here:

http://elromdesign.com/blog/2010/10/29/hacking-native-android-with-air-app-to-allow-air-access-unavailable-apis/

Title: Android MediaStore from Air App


问:
R - Apply dist function to groups
I am trying to apply the dist() function row wise in R but the result I get is as if it isn't grouping at all, it is simply applying dist() to all of my dataframe.

```<code>df2 %>% dplyr::group_by(X1) %>% dist()
</code>```

Where df2 is my dataframe and I am just applying to the head for now, for simplicity. Essentially, each group contains coordinates (A,B) and I am trying to get the distance between each point.

Here is my dataframe:

```<code>   X1  A              B
1   1  12             0.0
2   1  18             0.0
3   1  18             1.0
4   1  13             0.0
5   1  18             4.0
6   1  18             0.0
7   1  18             5.0
8   1  18             0.0
9   1  18             0.0
10  2  73            -2.0
11  2  73            -0.5
12  2  74            -0.5
13  2  73             0.0
14  2  71            -1.0
15  2  75             0.0
</code>```

My desired output is the lower triangular matrix of each group, here is an example:

答:
Here's an example of creating distance matrices of the iris data set by species

```<code>results = list()

for(spec in unique(iris$Species)){
  temp = iris[iris$Species==spec, 1:4]
  results[[length(results)+1]] = dist(temp)
}
names(results) = unique(iris$Species)
</code>```

You'll have to figure out what to do with it afterwords.

Title: R - Apply dist function to groups

Body:
I am trying to apply the dist() function row wise in R but the result I get is as if it isn't grouping at all, it is simply applying dist() to all of my dataframe.

df2 %>% dplyr::group_by(X1) %>% dist()

Where df2 is my dataframe and I am just applying to the head for now, for simplicity. Essentially, each group contains coordinates (A,B) and I am trying to get the distance between each point.

Here is my dataframe:

   X1  A              B
1   1  12             0.0
2   1  18             0.0
3   1  18             1.0
4   1  13             0.0
5   1  18             4.0
6   1  18             0.0
7   1  18             5.0
8   1  18             0.0
9   1  18             0.0
10  2  73            -2.0
11  2  73            -0.5
12  2  74            -0.5
13  2  73             0.0
14  2  71            -1.0
15  2  75             0.0

My desired output is the lower triangular matrix of each group, here is an example:

Body:
Here's an example of creating distance matrices of the iris data set by species

results = list()

for(spec in unique(iris$Species)){
  temp = iris[iris$Species==spec, 1:4]
  results[[length(results)+1]] = dist(temp)
}
names(results) = unique(iris$Species)

You'll have to figure out what to do with it afterwords.


问:
drawString on large JPanel turns messy on Linux but not on Windows
I've experienced a problem on the Graphics drawString method. Briefly, I observe unexpected behaviour of drawString on Linux where the string goes messy if the panel size is large.

As an example. I have modified the ScrollDemo2 class from Oracle to draw strings on the drawingPane:

```<code>import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class ScrollDemo2 extends JPanel
                          {
    private Dimension area;
    private JPanel drawingPane;

    public ScrollDemo2() {
        super(new BorderLayout());

        area = new Dimension(100000,1000);

        drawingPane = new DrawingPane();
        drawingPane.setBackground(Color.white);
        drawingPane.setPreferredSize(area);
        drawingPane.revalidate();
        drawingPane.repaint();

        JScrollPane scroller = new JScrollPane(drawingPane);
        scroller.setPreferredSize(new Dimension(500,500));

        add(scroller, BorderLayout.CENTER);
    }

    public class DrawingPane extends JPanel {
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            // drawString gives correct results in Windows but gives messy strings in Linux; drawLine gives correct lines in both Windows and Linux
            for (int i = 0; i < 100000; i += 100)
                g.drawString("Mark " + i, i, 20);
            for (int i = 0; i < 100000; i += 100)
                g.drawLine(i, i % 1000 / 10 + 25, i, i % 1000 / 10 + 35);

        }

    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("ScrollDemo2");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JComponent newContentPane = new ScrollDemo2();
        newContentPane.setOpaque(true);
        frame.setContentPane(newContentPane);

        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
</code>```

Program runs on Windows 7

The program displays correct strings on Windows 7.

Program runs on Linux 14.04

The program displays messy strings on Linux.

A drawLine method is added in addition to the drawString method, and the drawLine method works properly in both Windows and Linux.

Why is it? How should I rewrite the code to solve the problem on Linux?

答:
As noted in comments, if drawing a static (stable unchanging background image) use a BufferedImage. For example:

```<code>import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class ScrollDemo2B extends JPanel
                          {
    private static final int IMG_W = 100000;
    private static final int IMG_H = 1000;
    // private Dimension area;
    private JPanel drawingPane;
    private BufferedImage img = new BufferedImage(IMG_W, IMG_H, BufferedImage.TYPE_INT_ARGB);

    public ScrollDemo2B() {
        super(new BorderLayout());

        Graphics2D g2 = img.createGraphics();
        g2.setColor(Color.BLACK);
        for (int i = 0; i < 100000; i += 100) {
            g2.drawString("Mark " + i, i, 20);
        }
        for (int i = 0; i < 100000; i += 100) {
            g2.drawLine(i, i % 1000 / 10 + 25, i, i % 1000 / 10 + 35);
        }
        g2.dispose();

        drawingPane = new DrawingPane();
        drawingPane.setBackground(Color.white);
        drawingPane.revalidate();
        drawingPane.repaint();

        JScrollPane scroller = new JScrollPane(drawingPane);
        scroller.setPreferredSize(new Dimension(500,500));

        add(scroller, BorderLayout.CENTER);
    }

    public class DrawingPane extends JPanel {
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (img != null) {
                g.drawImage(img, 0, 0, this);
            }
        }

        @Override
        public Dimension getPreferredSize() {
            if (isPreferredSizeSet() || img == null) {
                return super.getPreferredSize();
            }
            int w = img.getWidth();
            int h = img.getHeight();
            return new Dimension(w, h);
        }

    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("ScrollDemo2");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JComponent newContentPane = new ScrollDemo2B();
        newContentPane.setOpaque(true);
        frame.setContentPane(newContentPane);

        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
</code>```

Then if you have mobile sprites or dynamic images, you would draw them within the paintComponent method.

Body:
I've experienced a problem on the Graphics drawString method. Briefly, I observe unexpected behaviour of drawString on Linux where the string goes messy if the panel size is large.

As an example. I have modified the ScrollDemo2 class from Oracle to draw strings on the drawingPane:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class ScrollDemo2 extends JPanel
                          {
    private Dimension area;
    private JPanel drawingPane;

    public ScrollDemo2() {
        super(new BorderLayout());

        area = new Dimension(100000,1000);

        drawingPane = new DrawingPane();
        drawingPane.setBackground(Color.white);
        drawingPane.setPreferredSize(area);
        drawingPane.revalidate();
        drawingPane.repaint();

        JScrollPane scroller = new JScrollPane(drawingPane);
        scroller.setPreferredSize(new Dimension(500,500));

        add(scroller, BorderLayout.CENTER);
    }

    public class DrawingPane extends JPanel {
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            // drawString gives correct results in Windows but gives messy strings in Linux; drawLine gives correct lines in both Windows and Linux
            for (int i = 0; i < 100000; i += 100)
                g.drawString("Mark " + i, i, 20);
            for (int i = 0; i < 100000; i += 100)
                g.drawLine(i, i % 1000 / 10 + 25, i, i % 1000 / 10 + 35);

        }

    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("ScrollDemo2");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JComponent newContentPane = new ScrollDemo2();
        newContentPane.setOpaque(true);
        frame.setContentPane(newContentPane);

        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

Program runs on Windows 7

The program displays correct strings on Windows 7.

Program runs on Linux 14.04

The program displays messy strings on Linux.

A drawLine method is added in addition to the drawString method, and the drawLine method works properly in both Windows and Linux.

Why is it? How should I rewrite the code to solve the problem on Linux?

Body:
As noted in comments, if drawing a static (stable unchanging background image) use a BufferedImage. For example:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class ScrollDemo2B extends JPanel
                          {
    private static final int IMG_W = 100000;
    private static final int IMG_H = 1000;
    // private Dimension area;
    private JPanel drawingPane;
    private BufferedImage img = new BufferedImage(IMG_W, IMG_H, BufferedImage.TYPE_INT_ARGB);

    public ScrollDemo2B() {
        super(new BorderLayout());

        Graphics2D g2 = img.createGraphics();
        g2.setColor(Color.BLACK);
        for (int i = 0; i < 100000; i += 100) {
            g2.drawString("Mark " + i, i, 20);
        }
        for (int i = 0; i < 100000; i += 100) {
            g2.drawLine(i, i % 1000 / 10 + 25, i, i % 1000 / 10 + 35);
        }
        g2.dispose();

        drawingPane = new DrawingPane();
        drawingPane.setBackground(Color.white);
        drawingPane.revalidate();
        drawingPane.repaint();

        JScrollPane scroller = new JScrollPane(drawingPane);
        scroller.setPreferredSize(new Dimension(500,500));

        add(scroller, BorderLayout.CENTER);
    }

    public class DrawingPane extends JPanel {
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (img != null) {
                g.drawImage(img, 0, 0, this);
            }
        }

        @Override
        public Dimension getPreferredSize() {
            if (isPreferredSizeSet() || img == null) {
                return super.getPreferredSize();
            }
            int w = img.getWidth();
            int h = img.getHeight();
            return new Dimension(w, h);
        }

    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("ScrollDemo2");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JComponent newContentPane = new ScrollDemo2B();
        newContentPane.setOpaque(true);
        frame.setContentPane(newContentPane);

        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

Then if you have mobile sprites or dynamic images, you would draw them within the paintComponent method.


问:
Is there a way to know if a specific prop was updated without using state in React?
I'm using React, Redux, and some antd components

I'm using this modal to alert users of errors, but if you look at it, its not exactly a component, its a function, so right now I'm using componentDidUpdate like this:

```<code>componentDidUpdate () {
  if (this.props.states.ErrorReducer.displayError) {
    error(() => {
      this.props.dispatch(ErrorActionCreators.acceptError())
    }, this.props.states.ErrorReducer.errorMessage )
  }
}
</code>```

Problem is, if I make multiple changes to state at once, for example make multiple calls to the API and they alter the state at different times, this modal open multiple times.

I could use state to do something like

```<code>if (this.state.displayError !== this.props.displayError {
  updateState();
  error();
}
</code>```

But I'm avoiding using React state.

Is there anyway I can check if one specific prop was changed on the Component?

答:
You can use the lifecycle method, componentWillReceiveProps. This gets called every time props are updated. Here's a link for help componentWillreceiveProps and a code snippet:

```<code>componentWillReceiveProps(nextProps){
  if(this.props !== nextProps){
    // your code and conditions go here
  }
}
</code>```

You can actually compare the old props (this.props) with the new or updated props (nextProps).

Body:
I'm using React, Redux, and some antd components

I'm using this modal to alert users of errors, but if you look at it, its not exactly a component, its a function, so right now I'm using componentDidUpdate like this:

componentDidUpdate () {
  if (this.props.states.ErrorReducer.displayError) {
    error(() => {
      this.props.dispatch(ErrorActionCreators.acceptError())
    }, this.props.states.ErrorReducer.errorMessage )
  }
}

Problem is, if I make multiple changes to state at once, for example make multiple calls to the API and they alter the state at different times, this modal open multiple times.

I could use state to do something like

if (this.state.displayError !== this.props.displayError {
  updateState();
  error();
}

But I'm avoiding using React state.

Is there anyway I can check if one specific prop was changed on the Component?

Body:
You can use the lifecycle method, componentWillReceiveProps. This gets called every time props are updated. Here's a link for help componentWillreceiveProps and a code snippet:

componentWillReceiveProps(nextProps){
  if(this.props !== nextProps){
    // your code and conditions go here
  }
}

You can actually compare the old props (this.props) with the new or updated props (nextProps).


问:
Add missing rows to SQL query
I have a data set in which I need each issue to have 3 rows. 1 for each status that is possible. Below is an example of what I currently have.

```<code>Issue  Status  Time
-------------------
1      SLM      30
1      SNB      43
1      EOB      22
2      SLM      12
2      EOB      87
</code>```

I need something like this, where is an issue doesn't have a status then a row is added and 0 is set for the time.

```<code> Issue   Status    Time
 ----------------------
    1      SLM      30
    1      SNB      43
    1      EOB      22
    2      SLM      12
    2      EOB      87
    2      SNB      0
</code>```

How can I do this?

答:
You can easily add another row by using this sql command.

```<code>INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
</code>```

for instance if your tables name is

Title: Add missing rows to SQL query

Body:
I have a data set in which I need each issue to have 3 rows. 1 for each status that is possible. Below is an example of what I currently have.

Issue  Status  Time
-------------------
1      SLM      30
1      SNB      43
1      EOB      22
2      SLM      12
2      EOB      87

I need something like this, where is an issue doesn't have a status then a row is added and 0 is set for the time.

 Issue   Status    Time
 ----------------------
    1      SLM      30
    1      SNB      43
    1      EOB      22
    2      SLM      12
    2      EOB      87
    2      SNB      0

How can I do this?

Body:
You can easily add another row by using this sql command.

INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

for instance if your tables name is


答:
As far as I understand, you have an input datetime, and you want to find the rows within @delta value. You could use the below if that's the case:

```<code>DECLARE @datetime   DATETIME    = GETDATE() -- use your valid input date here.
DECLARE @delta      INT         = 5 -- delta in seconds

SELECT *
FROM    YourTable
WHERE   CurrTime BETWEEN DATEADD(SECOND, -1 * @delta, @datetime) AND DATEADD(SECOND, @delta, @datetime)
</code>```

Body:
I have a SQL table with timestamps as one field. How can I select "adjacent" rows, i.e., rows that have timestamps within a certain delta (e.g. 5 seconds)?

Edit:

Sample Table:

CurrTime                Weight Length
----------------------- ------ -------------
2017-05-05 12:59:52.000 392    18.18
2017-05-05 12:59:29.000 396    18.18
2017-05-05 12:59:22.000 511    18.5
2017-05-05 12:58:53.000 512    18.5
2017-05-05 12:58:49.000 537    18.5

So the query should return:

CurrTime                Weight Length
----------------------- ------ -------------
2017-05-05 12:58:53.000 512    18.5
2017-05-05 12:58:49.000 537    18.5

Body:
As far as I understand, you have an input datetime, and you want to find the rows within @delta value. You could use the below if that's the case:

DECLARE @datetime   DATETIME    = GETDATE() -- use your valid input date here.
DECLARE @delta      INT         = 5 -- delta in seconds

SELECT *
FROM    YourTable
WHERE   CurrTime BETWEEN DATEADD(SECOND, -1 * @delta, @datetime) AND DATEADD(SECOND, @delta, @datetime)