问:
Unexpected token in module export
I'm getting the following error with a file that's part of a React app:

```<code>./src/utils/api.js
Syntax error: Unexpected token (118:1)

  116 |         }
  117 |     }
> 118 | }
      |  ^
</code>```

Here's the full code for the file in question:

```<code>import GtfsRealtimeBindings from 'mta-gtfs-realtime-bindings';
import rp from 'request-promise';

function getFeedData (sub) {
    var feedId;
    switch (sub) {
        case '1': case '2': case '3': case '4': case '5': case '6': case 'S':
                feedId = 1;
                break;
            case 'A': case 'C': case 'E':
                feedId = 26;
                break;
            case 'N': case 'Q': case 'R': case 'W':
                feedId = 16;
                break;
            case 'B': case 'D': case 'F': case 'M':
                feedId = 21;
                break;
            case 'L':
                feedId = 2;
                break;
            case 'G':
                feedId = 31;
                break;
    }
    rp({
        method: 'GET',
        url: 'http://datamine.mta.info/mta_esi.php?key=5db5e052519d17320f490738f2afe0d5&feed_id=' + feedId,
        encoding: null
    }).then((buf) => {
        const feed = GtfsRealtimeBindings.transit_realtime.FeedMessage.decode(buf);
        return { feed: feed };
    });

function reverseStop (sub, stop) {
    var stopIdN
    var stopIdS
    var stopData = require('./stops');
    var invalidEntries = 0;
    function filterByName (item) {
        if (item.stop_name == stop && item.stop_id.charAt(0) == sub) {
            return true;
        }
        invalidEntries++;
        return false;
    }
    var stopObjs = stopData.filter(filterByName);
    for (var i = 0; i < stopObjs.length; i++) {
        if (stopObjs[i].stop_id.charAt(stopObjs[i].stop_id.length - 1) == 'N') {
            stopIdN = stopObjs[i].stop_id;
        } else if (stopObjs[i].stop_id.charAt(stopObjs[i].stop_id.length - 1) == 'S') {
            stopIdS = stopObjs[i].stop_id;
        }
    }
    return {
        stopIdN: stopIdN,
        stopIdS: stopIdS
    };
}

module.exports = {
    isDelayN: function (sub, stop) {
        var arrivals = [];
        var delays = [];
        reverseStop(sub, stop);
        getFeedData(sub);
        (function () {
                var invalidEntries = 0;
                var feedObjs = getFeedData.feed.filter(function (feedObj) {
                    if (feedObj.entity.trip_update.stop_time_update.stop_id == reverseStop.stopIdN) {
                        return feedObj.entity.trip_update.stop_time_update;
                    }
                });
                for (var i = 0; i < feedObjs.length; i++) {
                    arrivals.push(feedObjs.arrival.time.low);
                    delays.push(feedObjs.arrival.delay);
                }
            })();
        var nextArrival = Math.min(...arrivals);
        var delayIndex = arrivals.findIndexOf(nextArrival);
        var delay = delays.delayIndex;
        if (delay === null || Math.ceil(delay / 60) <= 5) {
            var noDelay = Math.ceil((nextArrival - getFeedData.feed.header.timestamp.low) / 60);
            return { noDelay: noDelay };
        } else {
            var yesDelay = Math.ceil(delay / 60);
            return { yesDelay: yesDelay };
        }
    },
    isDelayS: function (sub, stop) {
        var arrivals = [];
        var delays = [];
        reverseStop(stop);
        getFeedData(sub)
            .then(function (feed) {
                var invalidEntries = 0;
                var feedObjs = feed.filter(function (feedObj) {
                    if (feedObj.entity.trip_update.stop_time_update.stop_id == reverseStop.stopIdS) {
                        return feedObj.entity.trip_update.stop_time_update;
                    }
                });
                for (var i = 0; i < feedObjs; i++) {
                    arrivals.push(feedObjs.arrival.time.low);
                    delays.push(feedObjs.arrival.delay);
                }
            });
        var nextArrival = Math.min(...arrivals);
        var delayInex = arrivals.findIndexOf(nextArrival);
        var delay = delays.delayIndex;
        if (delay === null || Math.ceil(delay / 60) <= 5) {
            var noDelay = Math.ceil((nextArrival - getFeedData.feed.header.timestamp.low) / 60);
            return { noDelay: noDelay };
        } else {
            var yesDelay = Math.ceil(delay / 60);
            return { yesDelay: yesDelay };
        }
    }
}
</code>```

The thing is I'm pretty sure it's not that final bracket that's actually causing the error, but I'm not sure how to diagnose what is doing it. My guess is that there's something I'm not understanding properly about exporting modules? I realize a question about syntax errors isn't the best thing to post here, so thank you for bearing with me. If anyone has tips for how I can better diagnose problems like this on my own (Google wasn't helpful), I'd greatly appreciate those as well.

答: I was missing a closing bracket in an earlier function. Let this be a lesson to me to use a linter.</p>

Title: Unexpected token in module export

Body:
I'm getting the following error with a file that's part of a React app:

./src/utils/api.js
Syntax error: Unexpected token (118:1)

  116 |         }
  117 |     }
> 118 | }
      |  ^

Here's the full code for the file in question:

import GtfsRealtimeBindings from 'mta-gtfs-realtime-bindings';
import rp from 'request-promise';

function getFeedData (sub) {
    var feedId;
    switch (sub) {
        case '1': case '2': case '3': case '4': case '5': case '6': case 'S':
                feedId = 1;
                break;
            case 'A': case 'C': case 'E':
                feedId = 26;
                break;
            case 'N': case 'Q': case 'R': case 'W':
                feedId = 16;
                break;
            case 'B': case 'D': case 'F': case 'M':
                feedId = 21;
                break;
            case 'L':
                feedId = 2;
                break;
            case 'G':
                feedId = 31;
                break;
    }
    rp({
        method: 'GET',
        url: 'http://datamine.mta.info/mta_esi.php?key=5db5e052519d17320f490738f2afe0d5&feed_id=' + feedId,
        encoding: null
    }).then((buf) => {
        const feed = GtfsRealtimeBindings.transit_realtime.FeedMessage.decode(buf);
        return { feed: feed };
    });

function reverseStop (sub, stop) {
    var stopIdN
    var stopIdS
    var stopData = require('./stops');
    var invalidEntries = 0;
    function filterByName (item) {
        if (item.stop_name == stop && item.stop_id.charAt(0) == sub) {
            return true;
        }
        invalidEntries++;
        return false;
    }
    var stopObjs = stopData.filter(filterByName);
    for (var i = 0; i < stopObjs.length; i++) {
        if (stopObjs[i].stop_id.charAt(stopObjs[i].stop_id.length - 1) == 'N') {
            stopIdN = stopObjs[i].stop_id;
        } else if (stopObjs[i].stop_id.charAt(stopObjs[i].stop_id.length - 1) == 'S') {
            stopIdS = stopObjs[i].stop_id;
        }
    }
    return {
        stopIdN: stopIdN,
        stopIdS: stopIdS
    };
}

module.exports = {
    isDelayN: function (sub, stop) {
        var arrivals = [];
        var delays = [];
        reverseStop(sub, stop);
        getFeedData(sub);
        (function () {
                var invalidEntries = 0;
                var feedObjs = getFeedData.feed.filter(function (feedObj) {
                    if (feedObj.entity.trip_update.stop_time_update.stop_id == reverseStop.stopIdN) {
                        return feedObj.entity.trip_update.stop_time_update;
                    }
                });
                for (var i = 0; i < feedObjs.length; i++) {
                    arrivals.push(feedObjs.arrival.time.low);
                    delays.push(feedObjs.arrival.delay);
                }
            })();
        var nextArrival = Math.min(...arrivals);
        var delayIndex = arrivals.findIndexOf(nextArrival);
        var delay = delays.delayIndex;
        if (delay === null || Math.ceil(delay / 60) <= 5) {
            var noDelay = Math.ceil((nextArrival - getFeedData.feed.header.timestamp.low) / 60);
            return { noDelay: noDelay };
        } else {
            var yesDelay = Math.ceil(delay / 60);
            return { yesDelay: yesDelay };
        }
    },
    isDelayS: function (sub, stop) {
        var arrivals = [];
        var delays = [];
        reverseStop(stop);
        getFeedData(sub)
            .then(function (feed) {
                var invalidEntries = 0;
                var feedObjs = feed.filter(function (feedObj) {
                    if (feedObj.entity.trip_update.stop_time_update.stop_id == reverseStop.stopIdS) {
                        return feedObj.entity.trip_update.stop_time_update;
                    }
                });
                for (var i = 0; i < feedObjs; i++) {
                    arrivals.push(feedObjs.arrival.time.low);
                    delays.push(feedObjs.arrival.delay);
                }
            });
        var nextArrival = Math.min(...arrivals);
        var delayInex = arrivals.findIndexOf(nextArrival);
        var delay = delays.delayIndex;
        if (delay === null || Math.ceil(delay / 60) <= 5) {
            var noDelay = Math.ceil((nextArrival - getFeedData.feed.header.timestamp.low) / 60);
            return { noDelay: noDelay };
        } else {
            var yesDelay = Math.ceil(delay / 60);
            return { yesDelay: yesDelay };
        }
    }
}

The thing is I'm pretty sure it's not that final bracket that's actually causing the error, but I'm not sure how to diagnose what is doing it. My guess is that there's something I'm not understanding properly about exporting modules? I realize a question about syntax errors isn't the best thing to post here, so thank you for bearing with me. If anyone has tips for how I can better diagnose problems like this on my own (Google wasn't helpful), I'd greatly appreciate those as well.


来源: stackexchange

问:
Get parent element id using javascript (Chrome OS)
Ok I'm going to be extremely specific this time.

```<code>curAcc = 0;
newItemInfo = null;
newItemId = null;
removeButtonId = null;

function addAccount(method, account) {
  curAcc = curAcc + 1;
  if (method == "new") {
    newItemId = "a" + curAcc;
    removeButtonId = "ra" + curAcc + "btn";

    newItemInfo = {
      Website: websiteIn.value,
      Username: usernameIn.value,
      Password: passwordIn.value,
      Id: newItemId,
      RemoveButton: {Id: removeButtonId}
    };
  } else if (method == "load") {}
  console.log(newItemInfo);

  newItem = document.createElement("li");
  newItem.innerHTML =
    "<li><label><b>Website:</b></label> <input type='text' value='" +
      newItemInfo.Website + "' id='a" + curAcc + "ws'></li>" +
    "<li><label><b>Username:</b></label> <input type='text' value='" +
      newItemInfo.Username + "' id='a" + curAcc + "un'></li>" +
    "<li><label><b>Password:</b></label> <input type='text' value='" +
      newItemInfo.Password + "' id='a" + curAcc + "pw'></li>" +
    "<li><button id='" + newItemInfo.RemoveButton.Id + "'>Remove</button>
      </li>" +
    "<br/><br/>";
   newItem.setAttribute("id", newItemId);
   accountList.appendChild(newItem);

   removeButton = document.getElementById(removeButtonId);
   removeButton.addEventListener("click", function(event) {
   console.log("Button ID:" + this.id);
 });
</code>```

}

The remove button along with the list items are created using .innerHTML.
I tried using accountList.removeChild(document.getElementById(newItemId));
It worked but it only got rid of the most recently created list item and doesn't get rid of anything else after the first use. Can anyone tell me how to get the remove button to remove newItem from the list using addEventListener?

答:
Javascript is losing scope once you create an element in a function and the function ends.

You can pass on this scope by binding it to the even listenet. Pass the this identifier by binding it to the function with .bind(this). Then you can call the element by using the target selector.

By using the event.target selector you have the button. The parent of that (parentNode) is the listitem itself. The parent of that is the actual list. I'm guessing you want to remove the li item from the list. And not just the button from the li item.

I wrote the code a bit more expansive to make it more obvious.

var list = document.getElementById("list"); // The list element

addButton = document.getElementById("btnAdd"); // The add button
addButton.addEventListener("click", function() {
  var newButton = document.createElement("button"); // Create a new button
  var btnText = document.createTextNode("Remove"); // Create the button's text
  newButton.appendChild(btnText); // Add the text to the button

  newButton.addEventListener("click", function(event) { // Create click listener for button
    var elButton = event.target; // The button that you clicked
    var elLi = elButton.parentNode; // The
 element that button was in
    list.removeChild(elLi); // Remove the
 element from the list
  }.bind(this)); // Bind the this so the "event" parameter will be the clicked button

  var newItem = document.createElement("li"); // Create a new
 element
  newItem.appendChild(newButton); // Add the button to that element
  list.appendChild(newItem); // Add the
 element to the list
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="list">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>
<button id="btnAdd">Add</button></code>```

Edit: Since you want several listitems to be removed when the button is clicked you can very simply extrapolate by adding another layer of lis. As such:

var list = document.getElementById("list"); // The list element

addButton = document.getElementById("btnAdd"); // The add button
addButton.addEventListener("click", function() {
  var newButton = document.createElement("button"); // Create a new button
  var btnText = document.createTextNode("Remove"); // Create the button's text
  newButton.appendChild(btnText); // Add the text to the button

  newButton.addEventListener("click", function(event) { // Create click listener for button
    var elButton = event.target; // The button that you clicked
    var elLi = elButton.parentNode; // The
 element that button was in
    var parentLi = elLi.parentNode; // The
 element all the other
s are in
    list.removeChild(parentLi); // Remove the
 element from the list
  }.bind(this)); // Bind the this so the "event" parameter will be the clicked button

  var newItemBtn = document.createElement("li"); // Create a new
 element
  newItemBtn.appendChild(newButton); // Add the button to that element

  // Create other child
s
  var newItem1 = document.createElement("li");
  newItem1.appendChild(document.createTextNode("Item 1"));
  var newItem2 = document.createElement("li");
  newItem2.appendChild(document.createTextNode("Item 2"));
  var newItem3 = document.createElement("li");
  newItem3.appendChild(document.createTextNode("Item 3"));

  var parentLi = document.createElement("li"); // Create a new
 parent element to wrap the other
 elements in
  parentLi.appendChild(newItem1); // Add the child
 to that element
  parentLi.appendChild(newItem2); // Add the child
 to that element
  parentLi.appendChild(newItem3); // Add the child
 to that element
  parentLi.appendChild(newItemBtn); // Add the child
 to that element
  list.appendChild(parentLi); // Add the
 element to the list
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="list">
  <li>Some listitem</li>
</ul>
<button id="btnAdd">Add</button></code>```

ContentLicense: CC BY-SA 3.0

Body:
Ok I'm going to be extremely specific this time.

curAcc = 0;
newItemInfo = null;
newItemId = null;
removeButtonId = null;

function addAccount(method, account) {
  curAcc = curAcc + 1;
  if (method == "new") {
    newItemId = "a" + curAcc;
    removeButtonId = "ra" + curAcc + "btn";

    newItemInfo = {
      Website: websiteIn.value,
      Username: usernameIn.value,
      Password: passwordIn.value,
      Id: newItemId,
      RemoveButton: {Id: removeButtonId}
    };
  } else if (method == "load") {}
  console.log(newItemInfo);

  newItem = document.createElement("li");
  newItem.innerHTML =
    "
Website: <input type='text' value='" +
      newItemInfo.Website + "' id='a" + curAcc + "ws'>
" +
    "
Username: <input type='text' value='" +
      newItemInfo.Username + "' id='a" + curAcc + "un'>
" +
    "
Password: <input type='text' value='" +
      newItemInfo.Password + "' id='a" + curAcc + "pw'>
" +
    "
<button id='" + newItemInfo.RemoveButton.Id + "'>Remove</button>

" +
    "

";
   newItem.setAttribute("id", newItemId);
   accountList.appendChild(newItem);

   removeButton = document.getElementById(removeButtonId);
   removeButton.addEventListener("click", function(event) {
   console.log("Button ID:" + this.id);
 });

}

The remove button along with the list items are created using .innerHTML.
I tried using accountList.removeChild(document.getElementById(newItemId));
It worked but it only got rid of the most recently created list item and doesn't get rid of anything else after the first use. Can anyone tell me how to get the remove button to remove newItem from the list using addEventListener?

Body:
Javascript is losing scope once you create an element in a function and the function ends.

You can pass on this scope by binding it to the even listenet. Pass the this identifier by binding it to the function with .bind(this). Then you can call the element by using the target selector.

By using the event.target selector you have the button. The parent of that (parentNode) is the listitem itself. The parent of that is the actual list. I'm guessing you want to remove the li item from the list. And not just the button from the li item.

I wrote the code a bit more expansive to make it more obvious.

var list = document.getElementById("list"); // The list element

addButton = document.getElementById("btnAdd"); // The add button
addButton.addEventListener("click", function() {
  var newButton = document.createElement("button"); // Create a new button
  var btnText = document.createTextNode("Remove"); // Create the button's text
  newButton.appendChild(btnText); // Add the text to the button

  newButton.addEventListener("click", function(event) { // Create click listener for button
    var elButton = event.target; // The button that you clicked
    var elLi = elButton.parentNode; // The <li> element that button was in
    list.removeChild(elLi); // Remove the <li> element from the list
  }.bind(this)); // Bind the this so the "event" parameter will be the clicked button

  var newItem = document.createElement("li"); // Create a new <li> element
  newItem.appendChild(newButton); // Add the button to that element
  list.appendChild(newItem); // Add the <li> element to the list
});

<ul id="list">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>
<button id="btnAdd">Add</button>

Edit: Since you want several listitems to be removed when the button is clicked you can very simply extrapolate by adding another layer of lis. As such:

var list = document.getElementById("list"); // The list element

addButton = document.getElementById("btnAdd"); // The add button
addButton.addEventListener("click", function() {
  var newButton = document.createElement("button"); // Create a new button
  var btnText = document.createTextNode("Remove"); // Create the button's text
  newButton.appendChild(btnText); // Add the text to the button

  newButton.addEventListener("click", function(event) { // Create click listener for button
    var elButton = event.target; // The button that you clicked
    var elLi = elButton.parentNode; // The <li> element that button was in
    var parentLi = elLi.parentNode; // The <li> element all the other <li>s are in
    list.removeChild(parentLi); // Remove the <li> element from the list
  }.bind(this)); // Bind the this so the "event" parameter will be the clicked button

  var newItemBtn = document.createElement("li"); // Create a new <li> element
  newItemBtn.appendChild(newButton); // Add the button to that element

  // Create other child <li>s
  var newItem1 = document.createElement("li");
  newItem1.appendChild(document.createTextNode("Item 1"));
  var newItem2 = document.createElement("li");
  newItem2.appendChild(document.createTextNode("Item 2"));
  var newItem3 = document.createElement("li");
  newItem3.appendChild(document.createTextNode("Item 3"));

  var parentLi = document.createElement("li"); // Create a new <li> parent element to wrap the other <li> elements in
  parentLi.appendChild(newItem1); // Add the child <li> to that element
  parentLi.appendChild(newItem2); // Add the child <li> to that element
  parentLi.appendChild(newItem3); // Add the child <li> to that element
  parentLi.appendChild(newItemBtn); // Add the child <li> to that element
  list.appendChild(parentLi); // Add the <li> element to the list
});

<ul id="list">
  <li>Some listitem</li>
</ul>
<button id="btnAdd">Add</button>


问:
Scope associated element with join table
I'm trying to scope the main group of my user. This group is noted with a cat: which is 2.

So I thought of doing this with a scope like

```<code>class User < ApplicationRecord
  has_many :users_group, dependent: :destroy
  has_many :groups, through: :users_group

  scope :my_group, -> { self.joins(:groups).where('groups.cat = 2').limit(1) }
end
</code>```

But the command below is not working :

current_user.my_group

Can you lead me on the good way to achieve it ?

答:
As Mario says, a scope works on a collection, not an instance.

If you want to keep the method in the User model you can use the following:

user.rb

```<code>def my_group
  groups.find_by_cat(2)
end
</code>```

Using find_by will return a single group, rather than using where / limit. If the group isn't found, it will return nil.

I'd suggest using a scope to return a single instance is a bit of an anti-pattern, and it would be better achieved using this method, or dropping the following method into Group and calling current_user.groups.my_group - although the name my_group sounds a bit out of place like that. For completeness, here it is regardless:

group.rb

```<code>def my_group
  find_by_cat(2)
end
</code>```

Body:
I'm trying to scope the main group of my user. This group is noted with a cat: which is 2.

So I thought of doing this with a scope like

class User < ApplicationRecord
  has_many :users_group, dependent: :destroy
  has_many :groups, through: :users_group

  scope :my_group, -> { self.joins(:groups).where('groups.cat = 2').limit(1) }
end

But the command below is not working :

current_user.my_group

Can you lead me on the good way to achieve it ?

Body:
As Mario says, a scope works on a collection, not an instance.

If you want to keep the method in the User model you can use the following:

user.rb

def my_group
  groups.find_by_cat(2)
end

Using find_by will return a single group, rather than using where / limit. If the group isn't found, it will return nil.

I'd suggest using a scope to return a single instance is a bit of an anti-pattern, and it would be better achieved using this method, or dropping the following method into Group and calling current_user.groups.my_group - although the name my_group sounds a bit out of place like that. For completeness, here it is regardless:

group.rb

def my_group
  find_by_cat(2)
end


问:
Break <option> items in loop
I am trying to loop 100 values from an API into a dropdown list. When the function runs the page loads all 100 values but inserts them into the list on 1 line, rather than on 100 separate lines. I have tried adding a break tag to the loop but that didn't work.
How do you separate each item onto its own line?

// GET STATION NAMES AND PUT THEM INTO DROPDOWN LIST
function addressList() {
    // var xhr = new XMLHttpRequest();
    // xhr.open('GET', 'https://api.jcdecaux.com/vls/v1/stations?contract=Dublin&apiKey=xxxxxxxxxx');
    // xhr.onreadystatechange = function() {
    //      if (xhr.readyState == 4 && xhr.status == 200) {
    //          var items = JSON.parse(xhr.responseText);
                var items = [{"address":"Smithfield North"},{"address":"Parnell Square North"},{"address":"Pearse Street"},{"address":"Excise Walk"},{"address":"Fitzwilliam Square West"},{"address":"St. James Hospital (Central)"},{"address":"Hanover Quay"},{"address":"Oliver Bond Street"},{"address":"Collins Barracks Museum"},{"address":"Brookfield Road"},{"address":"Clonmel Street"},{"address":"Mount Street Lower"},{"address":"Christchurch Place"},{"address":"Grantham Street"},{"address":"York Street East"},{"address":"Portobello Road"},{"address":"Parnell Street"},{"address":"Frederick Street South"},{"address":"Fownes Street Upper"},{"address":"Clarendon Row"},{"address":"Custom House"},{"address":"Benson Street"},{"address":"Fenian Street"},{"address":"South Dock Road"},{"address":"The Point"},{"address":"Lime Street"},{"address":"Kilmainham Gaol"},{"address":"Guild Street"},{"address":"Herbert Place"},{"address":"Western Way"},{"address":"Newman House"},{"address":"King Street North"},{"address":"Herbert Street"},{"address":"Earlsfort Terrace"},{"address":"Golden Lane"},{"address":"Deverell Place"},{"address":"John Street West"},{"address":"City Quay"},{"address":"Exchequer Street"},{"address":"Hatch Street"},{"address":"Charlemont Street"},{"address":"Hardwicke Place"},{"address":"Wolfe Tone Street"},{"address":"Francis Street"},{"address":"Greek Street"},{"address":"High Street"},{"address":"North Circular Road"},{"address":"Talbot Street"},{"address":"Sir Patrick's Dun"},{"address":"New Central Bank"},{"address":"Georges Quay"},{"address":"Mount Brown"},{"address":"Royal Hospital"},{"address":"Heuston Station (Central)"},{"address":"Townsend Street"},{"address":"Portobello Harbour"},{"address":"Custom House Quay"},{"address":"Molesworth Street"},{"address":"Kilmainham Lane"},{"address":"Market Street South"},{"address":"Kevin Street"},{"address":"Eccles Street East"},{"address":"Grand Canal Dock"},{"address":"Merrion Square East"},{"address":"York Street West"},{"address":"St. Stephen's Green South"},{"address":"Denmark Street Great"},{"address":"Heuston Station (Car Park)"},{"address":"St. Stephen's Green East"},{"address":"Eccles Street"},{"address":"Mater Hospital"},{"address":"Blessington Street"},{"address":"Merrion Square West"},{"address":"Convention Centre"},{"address":"Hardwicke Street"},{"address":"Smithfield"},{"address":"Dame Street"},{"address":"Sandwith Street"},{"address":"Princes Street / O'Connell Street"},{"address":"Grattan Street"},{"address":"St James Hospital (Luas)"},{"address":"Bolton Street"},{"address":"Strand Street Great"},{"address":"Barrow Street"},{"address":"Mountjoy Square West"},{"address":"Wilton Terrace"},{"address":"Leinster Street South"},{"address":"James Street"},{"address":"Parkgate Street"},{"address":"Heuston Bridge (South)"},{"address":"Cathal Brugha Street"},{"address":"Rothe Abbey"},{"address":"Upper Sherrard Street"},{"address":"Fitzwilliam Square East"},{"address":"Harcourt Terrace"},{"address":"Jervis Street"},{"address":"Ormond Quay Upper"},{"address":"Emmet Road"},{"address":"Heuston Bridge (North)"},{"address":"Blackhall Place"}];
                var output = '<select>'
                for (var i in items) {
                    output += '<option>' + items[i].address + '</option>
'
                }
                output += '</select>'
                document.getElementById("replaceOption").innerHTML = output
    //      }
    // }
    // xhr.send();
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <script src="stations.js"></script>
    <title></title>
</head>
<body onload="addressList()">
    <div>
        <div id="addressDropdown">
            <form>
                <select>
                    <option id="addressList" value="select station" selected="selected">Select Station..</option>
                    <option id="replaceOption">0</option>
                </select>
                <br>
                <input type="submit" value="Go" id="sumbit" href="#">
            </form>
        </div>
    </div>
</body>
</html></code>```

答:
The problem is that you're inserting an extra <select> into the existing select. Here's what your output HTML looks like:

```<code><form>
  <select>
    <option id="addressList" ...</option>
    <option id="replaceOption">
      <select>
        <option>Smithfield North</option>
        ...
</code>```

What you want to do instead is to append the options to the select box directly, rather than replacing the existing one. Note that the select box has an ID now instead of the option box. Here's the code that you need:

//GET STATION NAMES AND PUT THEM INTO DROPDOWN LIST
function addressList() {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://api.jcdecaux.com/vls/v1/stations?contract=Dublin&apiKey=xxxxxxxxxx');
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var items = JSON.parse(xhr.responseText);

            // get the select box by id
            var addressList = document.getElementById("addressList")

            // loop through all of the items and add an option to the list
            for (var i in items) {
                var option = document.createElement("option");
                option.text = items[i].address;
                option.value = i
                addressList.add(option)
            }

        }
    }
    xhr.send();
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
    <head>
        <script src="stations.js"></script>
        <title></title>
    </head>
    <body onload="addressList()">
        <div>
            <div id="addressDropdown">
                <form>
                    <select id="addressList">
                        <option value="select station" selected="selected">Select Station..</option>
                    </select>
                    <br>
                    <input type="submit" value="Go" id="sumbit" href="#">
                </form>
            </div>
        </div>
    </body>
</html></code>```

Title: Break <option> items in loop

Body:
I am trying to loop 100 values from an API into a dropdown list. When the function runs the page loads all 100 values but inserts them into the list on 1 line, rather than on 100 separate lines. I have tried adding a break tag to the loop but that didn't work.
How do you separate each item onto its own line?

// GET STATION NAMES AND PUT THEM INTO DROPDOWN LIST
function addressList() {
    // var xhr = new XMLHttpRequest();
    // xhr.open('GET', 'https://api.jcdecaux.com/vls/v1/stations?contract=Dublin&apiKey=xxxxxxxxxx');
    // xhr.onreadystatechange = function() {
    //      if (xhr.readyState == 4 && xhr.status == 200) {
    //          var items = JSON.parse(xhr.responseText);
                var items = [{"address":"Smithfield North"},{"address":"Parnell Square North"},{"address":"Pearse Street"},{"address":"Excise Walk"},{"address":"Fitzwilliam Square West"},{"address":"St. James Hospital (Central)"},{"address":"Hanover Quay"},{"address":"Oliver Bond Street"},{"address":"Collins Barracks Museum"},{"address":"Brookfield Road"},{"address":"Clonmel Street"},{"address":"Mount Street Lower"},{"address":"Christchurch Place"},{"address":"Grantham Street"},{"address":"York Street East"},{"address":"Portobello Road"},{"address":"Parnell Street"},{"address":"Frederick Street South"},{"address":"Fownes Street Upper"},{"address":"Clarendon Row"},{"address":"Custom House"},{"address":"Benson Street"},{"address":"Fenian Street"},{"address":"South Dock Road"},{"address":"The Point"},{"address":"Lime Street"},{"address":"Kilmainham Gaol"},{"address":"Guild Street"},{"address":"Herbert Place"},{"address":"Western Way"},{"address":"Newman House"},{"address":"King Street North"},{"address":"Herbert Street"},{"address":"Earlsfort Terrace"},{"address":"Golden Lane"},{"address":"Deverell Place"},{"address":"John Street West"},{"address":"City Quay"},{"address":"Exchequer Street"},{"address":"Hatch Street"},{"address":"Charlemont Street"},{"address":"Hardwicke Place"},{"address":"Wolfe Tone Street"},{"address":"Francis Street"},{"address":"Greek Street"},{"address":"High Street"},{"address":"North Circular Road"},{"address":"Talbot Street"},{"address":"Sir Patrick's Dun"},{"address":"New Central Bank"},{"address":"Georges Quay"},{"address":"Mount Brown"},{"address":"Royal Hospital"},{"address":"Heuston Station (Central)"},{"address":"Townsend Street"},{"address":"Portobello Harbour"},{"address":"Custom House Quay"},{"address":"Molesworth Street"},{"address":"Kilmainham Lane"},{"address":"Market Street South"},{"address":"Kevin Street"},{"address":"Eccles Street East"},{"address":"Grand Canal Dock"},{"address":"Merrion Square East"},{"address":"York Street West"},{"address":"St. Stephen's Green South"},{"address":"Denmark Street Great"},{"address":"Heuston Station (Car Park)"},{"address":"St. Stephen's Green East"},{"address":"Eccles Street"},{"address":"Mater Hospital"},{"address":"Blessington Street"},{"address":"Merrion Square West"},{"address":"Convention Centre"},{"address":"Hardwicke Street"},{"address":"Smithfield"},{"address":"Dame Street"},{"address":"Sandwith Street"},{"address":"Princes Street / O'Connell Street"},{"address":"Grattan Street"},{"address":"St James Hospital (Luas)"},{"address":"Bolton Street"},{"address":"Strand Street Great"},{"address":"Barrow Street"},{"address":"Mountjoy Square West"},{"address":"Wilton Terrace"},{"address":"Leinster Street South"},{"address":"James Street"},{"address":"Parkgate Street"},{"address":"Heuston Bridge (South)"},{"address":"Cathal Brugha Street"},{"address":"Rothe Abbey"},{"address":"Upper Sherrard Street"},{"address":"Fitzwilliam Square East"},{"address":"Harcourt Terrace"},{"address":"Jervis Street"},{"address":"Ormond Quay Upper"},{"address":"Emmet Road"},{"address":"Heuston Bridge (North)"},{"address":"Blackhall Place"}];
                var output = '<select>'
                for (var i in items) {
                    output += '<option>' + items[i].address + '</option>
'
                }
                output += '</select>'
                document.getElementById("replaceOption").innerHTML = output
    //      }
    // }
    // xhr.send();
};

<!DOCTYPE html>

    <title></title>

            <form>
                <select>
                    <option id="addressList" value="select station" selected="selected">Select Station..</option>
                    <option id="replaceOption">0</option>
                </select>

                <input type="submit" value="Go" id="sumbit" href="#">
            </form>

Body:
The problem is that you're inserting an extra <select> into the existing select. Here's what your output HTML looks like:

<form>
  <select>
    <option id="addressList" ...</option>
    <option id="replaceOption">
      <select>
        <option>Smithfield North</option>
        ...

What you want to do instead is to append the options to the select box directly, rather than replacing the existing one. Note that the select box has an ID now instead of the option box. Here's the code that you need:

//GET STATION NAMES AND PUT THEM INTO DROPDOWN LIST
function addressList() {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://api.jcdecaux.com/vls/v1/stations?contract=Dublin&apiKey=xxxxxxxxxx');
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var items = JSON.parse(xhr.responseText);

            // get the select box by id
            var addressList = document.getElementById("addressList")

            // loop through all of the items and add an option to the list
            for (var i in items) {
                var option = document.createElement("option");
                option.text = items[i].address;
                option.value = i
                addressList.add(option)
            }

        }
    }
    xhr.send();
};

<!DOCTYPE html>
<html>
    <head>
        <script src="stations.js"></script>
        <title></title>
    </head>
    <body onload="addressList()">
        <div>
            <div id="addressDropdown">
                <form>
                    <select id="addressList">
                        <option value="select station" selected="selected">Select Station..</option>
                    </select>
                    <br>
                    <input type="submit" value="Go" id="sumbit" href="#">
                </form>
            </div>
        </div>
    </body>
</html>


问:
Kafka Connect - JDBC Connector - Oracle Database
Hello I am trying to create a jdbc kafka connect using io.confluent.connect.jdbc.JdbcSourceConnector  and getting following error:

```<code>java.util.concurrent.ExecutionException: org.apache.kafka.connect.runtime.rest.errors.BadRequestException: Connector configuration is invalid and contains the following 2 error(s):
Invalid value java.sql.SQLException: ORA-00604: error occurred at recursive SQL level 1
ORA-01882: timezone region not found
</code>```

These are the parameters.

```<code>JDBC_URL= jdbc:oracle:thin:USERNAME/PASSWORD@URL:PORT:DBNAME
MODE=bulk
QUERY=select * tablename
TOPIC=topicname
POLL_INTERVAL_MS=86400000
</code>```

答: The error was because I was using ojdbc7.Using ojdbc6 did the trick for me! But I am still not sure why ojdbc7 did give this error. But its working now!</p>

Body:
Hello I am trying to create a jdbc kafka connect using io.confluent.connect.jdbc.JdbcSourceConnector  and getting following error:

java.util.concurrent.ExecutionException: org.apache.kafka.connect.runtime.rest.errors.BadRequestException: Connector configuration is invalid and contains the following 2 error(s):
Invalid value java.sql.SQLException: ORA-00604: error occurred at recursive SQL level 1
ORA-01882: timezone region not found

These are the parameters.

JDBC_URL= jdbc:oracle:thin:USERNAME/PASSWORD@URL:PORT:DBNAME
MODE=bulk
QUERY=select * tablename
TOPIC=topicname
POLL_INTERVAL_MS=86400000


问:
What may be the difficulties, if any, with the web applications developed in Java EE?
I have a few questions to understand better Java's usage in context of web applications:-

Is Java EE web development suitable for small start-up (with less human resource) looking to develop an web application ?

What kind of difficulties may arise in Java EE web development, deployment & maintenance ?

What kind of things should be kept in mind/ considerations to be made when moving from PHP background to Java ?

Why Java web applications are not so popular today?  ( or in case I perceived it wrongly, please list any major deployments beside linkedIn and ebay)

and Finally, What are some of the most important things to learn before starting web development in Java EE ?

Thank you

答:
Is Java EE web development suitable for small start-up (with less human resource) looking to develop an web application ?

Yes, I worked in a startup where I was the only full time programmer.

What kind of difficulties may arise in Java EE web development, deployment & maintenance ?

The same as in any other web development shop. Of course, the problems have their Java flavor. For instance, one bug we discovered was caused by different  minor version of JDK used on the live system than on our test system.

What kind of things should be kept in mind/ considerations to be made when moving from PHP background to Java ? Do not code the PHP way. Java's strength is OOP and its many libraries/ open source frameworks. Use that.

Why Java web applications are not so popular today? ( or in case I perceived it wrongly, please list any major deployments beside linkedIn and ebay)

I don't know why you think that, but Java is used everywhere. It is one of the few languages that Google officially uses. They use PHP as well, but it has a "lower" status.

and Finally, What are some of the most important things to learn before starting web development in Java EE ? Use Java's strong points which I mentioned above.

Updated after comment

I cannot make the choice for you. If you are in doubt and in a big hurry you should not go with Java. This is common sense. However, it is an opportunity for your team to learn and grow. Maybe there is a PHP/other client for Cassandra. I knew a former PHP programmer in a startup, who switched to Java. Not saying anything bad about PHP programmers in general, but he did all kinds of strange things, such as not leveraging the power of Java web frameworks and writing lots of procedural code mixed with HTML and SQL. Obviously there are lots of Java programmers who would do the same thing. The point is that your team will probably learn new ways to do things and benefit from it in the future.

ContentLicense: CC BY-SA 2.5


问:
Fetching descendant nodes always return null XML C#
I have an XML file that looks like this

```<code><modules>
<level4>
<module>
  <name>Programming Principles I</name>
  <credit>20</credit>
  <assessments>

    <assessment>
      <assessment_name>Course Work 1</assessment_name>
      <weight>50</weight>
      <passing>55</passing>
      <obtain>55</obtain>
    </assessment>
    <assessment>
      <assessment_name>Course Work 2</assessment_name>
      <weight>50</weight>
      <passing>55</passing>
      <obtain>55</obtain>
    </assessment>

  </assessments>
</module>
</level4>
</modules>
</code>```

Whilst, getting into assessment childs of parent assessments it returns null..

using this code

```<code>XDocument xml = XDocument.Load("module.xml");
var result = xml.Descendants("module")
                         .FirstOrDefault(x => (string)x.Element("name") == "Programming Principles I");
var assessments = result.Element("assessments");
var assessment = assessments.Descendants("assessment");
foreach(var a in assessment)
{
    a.Remove();
}
</code>```

At this assessment variable I am getting null value exception. The LINQ query works fine but the next two lines I am uncertain. I am actually, removing all the nodes present inside assessments node.

答:
The problem is that you cannot remove an item (the item that part of the construct that is being iterated on) in a foreach loop.

Your code:

```<code>foreach(var a in assessment)
{
    a.Remove();
}
</code>```

is the culprit.  You may remove an item in a for loop as follows:

```<code>var la = assessment.ToList();
for (int i = la.Count; i > 0; --i)
    la[i - 1].Remove();
</code>```

Body:
I have an XML file that looks like this

<modules>
<level4>
<module>
  <name>Programming Principles I</name>
  <credit>20</credit>
  <assessments>

    <assessment>
      <assessment_name>Course Work 1</assessment_name>
      <weight>50</weight>
      <passing>55</passing>
      <obtain>55</obtain>
    </assessment>
    <assessment>
      <assessment_name>Course Work 2</assessment_name>
      <weight>50</weight>
      <passing>55</passing>
      <obtain>55</obtain>
    </assessment>

  </assessments>
</module>
</level4>
</modules>

Whilst, getting into assessment childs of parent assessments it returns null..

using this code

XDocument xml = XDocument.Load("module.xml");
var result = xml.Descendants("module")
                         .FirstOrDefault(x => (string)x.Element("name") == "Programming Principles I");
var assessments = result.Element("assessments");
var assessment = assessments.Descendants("assessment");
foreach(var a in assessment)
{
    a.Remove();
}

At this assessment variable I am getting null value exception. The LINQ query works fine but the next two lines I am uncertain. I am actually, removing all the nodes present inside assessments node.

Body:
The problem is that you cannot remove an item (the item that part of the construct that is being iterated on) in a foreach loop.

Your code:

foreach(var a in assessment)
{
    a.Remove();
}

is the culprit.  You may remove an item in a for loop as follows:

var la = assessment.ToList();
for (int i = la.Count; i > 0; --i)
    la[i - 1].Remove();


问:
iPhone X - Set the color of the area around home indicator
I'm pretty much new to Xcode when trying to align a sheet to the safe area of iPhone X, it leaves a transparent area below the sheet.

Is there a way to set the fill of that area w/o expanding the sheet or align outside of the safe area?

答:
Here is my tiny extension.
If anybody can suggest an improvement to not access added view by "magic number" tag - welcome!

```<code>extension UIViewController {

private static let insetBackgroundViewTag = 98721 //Cool number

func paintSafeAreaBottomInset(withColor color: UIColor) {
    guard #available(iOS 11.0, *) else {
        return
    }
    if let insetView = view.viewWithTag(UIViewController.insetBackgroundViewTag) {
        insetView.backgroundColor = color
        return
    }

    let insetView = UIView(frame: .zero)
    insetView.tag = UIViewController.insetBackgroundViewTag
    insetView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(insetView)
    view.sendSubview(toBack: insetView)

    insetView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    insetView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
    insetView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    insetView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true

    insetView.backgroundColor = color
}
</code>```

}

Body:
Here is my tiny extension.
If anybody can suggest an improvement to not access added view by "magic number" tag - welcome!

extension UIViewController {

private static let insetBackgroundViewTag = 98721 //Cool number

func paintSafeAreaBottomInset(withColor color: UIColor) {
    guard #available(iOS 11.0, *) else {
        return
    }
    if let insetView = view.viewWithTag(UIViewController.insetBackgroundViewTag) {
        insetView.backgroundColor = color
        return
    }

    let insetView = UIView(frame: .zero)
    insetView.tag = UIViewController.insetBackgroundViewTag
    insetView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(insetView)
    view.sendSubview(toBack: insetView)

    insetView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    insetView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
    insetView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    insetView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true

    insetView.backgroundColor = color
}

}


问:
C++ Avoiding library linking
I currently have a c++ setup like the following

```<code>class FlowController
{
   public:
    //...
   private:
       cntrl::OneWayValve _intake;
}
</code>```

As you can see i'm using a cntrl::OneWayValve instance within my class. The Valve class resides in another library which i link with at compile time. The cntrl::OneWayValve has a cntrl::Value within its implementation like so.

```<code>class OneWayValve
{
   public:
    //...
   private:
       cntrl::Valve _valve;
}
</code>```

And as before the cntrl::Valve resides in a different library for reasons you'll have to ask the previous developer about.

Now when i compile my FlowController class i'm required to link with the OneWayValve library and the cntrl::Valve library as well.

My question:
Is it possible to only link with the cntrl::OneWayValve library at compile time?

Forward declaration?

Static libraries (really don't want to do this tho)?

Another alternative?

Basically i don't want to know that its using a cntrl::Valve internally, its none of my business.

Note: apologies the OS is Unix.

Cheers,
Ben

答:
You can do it by defining all methods of OneWayValve and Valve in their headers as inline. Then you don't need to link to the library.

But if it was designed that way, then what problems are linking to this library causing? Nothing wrong with dynamically linking a library.

Title: C++ Avoiding library linking

Body:
I currently have a c++ setup like the following

class FlowController
{
   public:
    //...
   private:
       cntrl::OneWayValve _intake;
}

As you can see i'm using a cntrl::OneWayValve instance within my class. The Valve class resides in another library which i link with at compile time. The cntrl::OneWayValve has a cntrl::Value within its implementation like so.

class OneWayValve
{
   public:
    //...
   private:
       cntrl::Valve _valve;
}

And as before the cntrl::Valve resides in a different library for reasons you'll have to ask the previous developer about.

Now when i compile my FlowController class i'm required to link with the OneWayValve library and the cntrl::Valve library as well.

My question:
Is it possible to only link with the cntrl::OneWayValve library at compile time?

Forward declaration?

Static libraries (really don't want to do this tho)?

Another alternative?

Basically i don't want to know that its using a cntrl::Valve internally, its none of my business.

Note: apologies the OS is Unix.

Cheers,
Ben


问:
Regexp to add a string after found a regexp in a file
At the beginning i was looking for an Emacs command, I found query-replace-regexp but I didn't find how to solve my problem with this command.
I m looking for replace a string by another one in a file.

I want to replace this:

container random1-string {

by this:

container random1-string {

string:string-string 0;

or this:

container 1-string {

by this:

container 1-string {

string:string-string 0;

or this:

container string-24 {

by this:

container string-24 {

string:string-string 0;

random1-string is a random string.
I'm looking for a recursive command. I have to change 400 nodes.
I can use every linux command.

答:
If your random-string does not have a specific pattern it will difficult to use a regex to replace it efficiently.

What you could do, is list up the variable name that you want to change in a file (strings_list.in)

```<code>random1-string
random2-string
random3-string
</code>```

and then loop on the file and change your source file in the following way:

```<code>for v in `cat strings_list.in`;
do
    sed -i "s/container\s+$v\{/container $v\{\nstring:string-string 0;/g" file_to_edit;
done;
</code>```

Take a backup of your file before any operation.

If your random string is actually a variable, then you can use the following regex in your sed command to process the file, with a back reference to it:

```<code>sed -i "s/container\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\{/container \1 \{\nstring:string-string 0;/g" file_to_edit;
</code>```

Body:
If your random-string does not have a specific pattern it will difficult to use a regex to replace it efficiently.

What you could do, is list up the variable name that you want to change in a file (strings_list.in)

random1-string
random2-string
random3-string

and then loop on the file and change your source file in the following way:

for v in `cat strings_list.in`;
do
    sed -i "s/container\s+$v\{/container $v\{\nstring:string-string 0;/g" file_to_edit;
done;

Take a backup of your file before any operation.

If your random string is actually a variable, then you can use the following regex in your sed command to process the file, with a back reference to it:

sed -i "s/container\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\{/container \1 \{\nstring:string-string 0;/g" file_to_edit;


问:
karate - Parsing runtime integer value coming from response of SOAP 1 to request of SOAP 2
Question is as follows:-

I have a two SOAP request , I am getting response from SOAP 1 in the form of integer at runtime. I want to parse that value to another soap request in three places to process the soap.

So far I have tried following things

I have taken the response of the first soap and took the value I wanted into one variable and printed it to make sure variable is receiving correct value.

In second soap request, I have re-defined the variable and set parameter of 2nd soap request = to the variable of 1st soap.

I am getting following error message

'no var found with name: response'

and if I directly put #(variable) name in parameter of the soap then I get following error message
'variable name can not be parsed as Int32'

Also I tried to parse the string into integer using groovy in feature fie but that didn't worked out.

Can someone please help me out with correct resolution to get the parse the runtime integer value of one soap into multiple places in soap 2?

Appreciate your help.

答:
Here are the 2 patterns you can use:

Using embedded expressions:

```<code>* def myInt = 5
* def payload = <foo>#(myInt)</foo>
</code>```

Using set

```<code>* def myInt = 5
* def payload = <foo></foo>
* set payload/foo = myInt
</code>```

Don't forget to refer to the documentation. Also refer to this set of tests for more ideas: xml.feature

Body:
Here are the 2 patterns you can use:

Using embedded expressions:

* def myInt = 5
* def payload = <foo>#(myInt)</foo>

Using set

* def myInt = 5
* def payload = <foo></foo>
* set payload/foo = myInt

Don't forget to refer to the documentation. Also refer to this set of tests for more ideas: xml.feature


问:
Showing converting error for varchar to numeric
I am getting this error

Msg 8114, Level 16, State 5, Line 13

  Error converting data type varchar to numeric.

This is my code:

```<code>SELECT DISTINCT
                      DI.DealName AS 'Deal Name',
    DI.OfferingType AS 'Offering Type',
    DI.Date AS 'Date',
    DI.ClassName AS 'Class',
    ISNULL(Bench,'-') AS 'BM',
    ISNULL(Guidance,'-') AS 'Guid',
    DI.Industry AS 'Industry',
    CAST( (ISNULL(DI.AverageLife,0)) AS VARCHAR(20)) AS 'WAL',CAST(  ISNULL(DI.ClassSize,0) AS VARCHAR(20)) AS 'Balance',CAST(   REPLACE(ISNULL(DI.Coupon,0),'%','') AS VARCHAR(20)) AS 'Coupon',
       CAST(  CASE WHEN CAST(REPLACE(ISNULL(DI.PX2,0),'%','') AS DECIMAL(18,5)) = 0.00 THEN (CASE WHEN ISNULL(CAST(DI.Yield * 100 AS DECIMAL(18,3)),0) = 0 THEN (CASE WHEN (ISNULL(DI.Coupon,0)+'cpn' = 'cpn' OR ISNULL(DI.Coupon,0)+'cpn' = '0cpn') THEN '-' ELSE (ISNULL(DI.Coupon,0)+'cpn')END)ELSE CAST(ISNULL(CAST(DI.Yield * 100 AS DECIMAL(18,3)),0) AS VARCHAR(15))+'%yld' END) ELSE (ISNULL(DI.PX,0)) END AS VARCHAR(20)) AS 'Spread',  CAST(  ISNULL(CAST(DI.Yield * 100 AS DECIMAL(18,3)),0) AS VARCHAR(20)) AS 'Yield', CAST(  CASE WHEN LTRIM(RTRIM(DI.Dollar_Px)) = '' THEN 0.00 ELSE CAST(ISNULL(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(LTRIM(RTRIM(Dollar_Px)),CHAR(10),''),CHAR(13),''),'-',''),'/',''),' ',''),'%cpn',''),0) AS DECIMAL(18,5)) END AS VARCHAR(20)) AS 'Dollar_Px',  ISNULL(Notes,'') AS Notes,
           CAST((FRM.Rating + '/' + KBRARM.Rating) AS VARCHAR(15)) AS 'Rating'  FROM DI_DealIssuancePost DI
         INNER JOIN DI_CompanyRatingMapping MRM ON MRM.CompanyRatingMappingID = DI.Mdy                   INNER JOIN DI_CompanyRatingMapping SPRM ON SPRM.CompanyRatingMappingID = DI.S_P
         INNER JOIN DI_CompanyRatingMapping FRM ON FRM.CompanyRatingMappingID = DI.Fitch
         INNER JOIN DI_CompanyRatingMapping DBRSRM ON DBRSRM.CompanyRatingMappingID = DI.DBRS                 INNER JOIN DI_CompanyRatingMapping KBRARM ON KBRARM.CompanyRatingMappingID = DI.KBRA

         INNER JOIN DI_WeeklySectors DIWeekly ON DI.Industry = DIWeekly.Sector

        WHERE DI.IsDeleted = 0
          AND MRM.IsDeleted = 0
          AND SPRM.IsDeleted = 0
          AND FRM.IsDeleted = 0
          AND DBRSRM.IsDeleted = 0
          AND KBRARM.IsDeleted = 0
          AND DI.Date IS NOT NULL
          AND (CONVERT(DATETIME,DI.Date ,101) >= CONVERT(DATETIME,@StartDate,101))
          AND (CONVERT(DATETIME,DI.Date ,101) <= CONVERT(DATETIME,@EndDate,101)) AND DI.CurrencyID IN (SELECT * FROM CsvToTable(@Currency)) ORDER BY DI.Date desc
</code>```

Msg 8114, Level 16, State 5, Line 13
Error converting data type varchar to numeric.

And i Can find that here is an error

```<code> CAST(  CASE WHEN CAST(REPLACE(ISNULL(DI.PX2,0),'%','') AS DECIMAL(18,5)) = 0.00 THEN (CASE WHEN ISNULL(CAST(DI.Yield * 100 AS DECIMAL(18,3)),0) = 0 THEN (CASE WHEN (ISNULL(DI.Coupon,0)+'cpn' = 'cpn' OR ISNULL(DI.Coupon,0)+'cpn' = '0cpn') THEN '-' ELSE (ISNULL(DI.Coupon,0)+'cpn')END)ELSE CAST(ISNULL(CAST(DI.Yield * 100 AS DECIMAL(18,3)),0) AS VARCHAR(15))+'%yld' END) ELSE (ISNULL(DI.PX,0)) END AS VARCHAR(20)) AS 'Spread',  CAST(  ISNULL(CAST(DI.Yield * 100 AS DECIMAL(18,3)),0) AS VARCHAR(20)) AS 'Yield', CAST(  CASE WHEN LTRIM(RTRIM(DI.Dollar_Px)) = '' THEN 0.00 ELSE CAST(ISNULL(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(LTRIM(RTRIM(Dollar_Px)),CHAR(10),''),CHAR(13),''),'-',''),'/',''),' ',''),'%cpn',''),0) AS DECIMAL(18,5)) END AS VARCHAR(20)) AS 'Dollar_Px',  ISNULL(Notes,'') AS Notes,
</code>```

some one help to solve this error

答:
Check below one by one:

```<code>SELECT ISNUMERIC(ISNULL(DI.PX2,0)) FROM DI WHERE ISNUMERIC(ISNULL(DI.PX2,0)) = 0

SELECT ISNUMERIC(ISNULL(DI.Yield,0)) FROM DI WHERE ISNUMERIC(ISNULL(DI.Yield,0)) = 0

SELECT ISNUMERIC(ISNULL(Dollar_Px,0)) FROM TABLE WHERE ISNUMERIC(ISNULL(Dollar_Px,0)) = 0
</code>```

There must exist any varchar string that cannot be converted to decimal

Body:
I am getting this error

Msg 8114, Level 16, State 5, Line 13

  Error converting data type varchar to numeric.

This is my code:

SELECT DISTINCT
                      DI.DealName AS 'Deal Name',
    DI.OfferingType AS 'Offering Type',
    DI.Date AS 'Date',
    DI.ClassName AS 'Class',
    ISNULL(Bench,'-') AS 'BM',
    ISNULL(Guidance,'-') AS 'Guid',
    DI.Industry AS 'Industry',
    CAST( (ISNULL(DI.AverageLife,0)) AS VARCHAR(20)) AS 'WAL',CAST(  ISNULL(DI.ClassSize,0) AS VARCHAR(20)) AS 'Balance',CAST(   REPLACE(ISNULL(DI.Coupon,0),'%','') AS VARCHAR(20)) AS 'Coupon',
       CAST(  CASE WHEN CAST(REPLACE(ISNULL(DI.PX2,0),'%','') AS DECIMAL(18,5)) = 0.00 THEN (CASE WHEN ISNULL(CAST(DI.Yield * 100 AS DECIMAL(18,3)),0) = 0 THEN (CASE WHEN (ISNULL(DI.Coupon,0)+'cpn' = 'cpn' OR ISNULL(DI.Coupon,0)+'cpn' = '0cpn') THEN '-' ELSE (ISNULL(DI.Coupon,0)+'cpn')END)ELSE CAST(ISNULL(CAST(DI.Yield * 100 AS DECIMAL(18,3)),0) AS VARCHAR(15))+'%yld' END) ELSE (ISNULL(DI.PX,0)) END AS VARCHAR(20)) AS 'Spread',  CAST(  ISNULL(CAST(DI.Yield * 100 AS DECIMAL(18,3)),0) AS VARCHAR(20)) AS 'Yield', CAST(  CASE WHEN LTRIM(RTRIM(DI.Dollar_Px)) = '' THEN 0.00 ELSE CAST(ISNULL(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(LTRIM(RTRIM(Dollar_Px)),CHAR(10),''),CHAR(13),''),'-',''),'/',''),' ',''),'%cpn',''),0) AS DECIMAL(18,5)) END AS VARCHAR(20)) AS 'Dollar_Px',  ISNULL(Notes,'') AS Notes,
           CAST((FRM.Rating + '/' + KBRARM.Rating) AS VARCHAR(15)) AS 'Rating'  FROM DI_DealIssuancePost DI
         INNER JOIN DI_CompanyRatingMapping MRM ON MRM.CompanyRatingMappingID = DI.Mdy                   INNER JOIN DI_CompanyRatingMapping SPRM ON SPRM.CompanyRatingMappingID = DI.S_P
         INNER JOIN DI_CompanyRatingMapping FRM ON FRM.CompanyRatingMappingID = DI.Fitch
         INNER JOIN DI_CompanyRatingMapping DBRSRM ON DBRSRM.CompanyRatingMappingID = DI.DBRS                 INNER JOIN DI_CompanyRatingMapping KBRARM ON KBRARM.CompanyRatingMappingID = DI.KBRA

         INNER JOIN DI_WeeklySectors DIWeekly ON DI.Industry = DIWeekly.Sector

        WHERE DI.IsDeleted = 0
          AND MRM.IsDeleted = 0
          AND SPRM.IsDeleted = 0
          AND FRM.IsDeleted = 0
          AND DBRSRM.IsDeleted = 0
          AND KBRARM.IsDeleted = 0
          AND DI.Date IS NOT NULL
          AND (CONVERT(DATETIME,DI.Date ,101) >= CONVERT(DATETIME,@StartDate,101))
          AND (CONVERT(DATETIME,DI.Date ,101) <= CONVERT(DATETIME,@EndDate,101)) AND DI.CurrencyID IN (SELECT * FROM CsvToTable(@Currency)) ORDER BY DI.Date desc

Msg 8114, Level 16, State 5, Line 13
Error converting data type varchar to numeric.

And i Can find that here is an error

 CAST(  CASE WHEN CAST(REPLACE(ISNULL(DI.PX2,0),'%','') AS DECIMAL(18,5)) = 0.00 THEN (CASE WHEN ISNULL(CAST(DI.Yield * 100 AS DECIMAL(18,3)),0) = 0 THEN (CASE WHEN (ISNULL(DI.Coupon,0)+'cpn' = 'cpn' OR ISNULL(DI.Coupon,0)+'cpn' = '0cpn') THEN '-' ELSE (ISNULL(DI.Coupon,0)+'cpn')END)ELSE CAST(ISNULL(CAST(DI.Yield * 100 AS DECIMAL(18,3)),0) AS VARCHAR(15))+'%yld' END) ELSE (ISNULL(DI.PX,0)) END AS VARCHAR(20)) AS 'Spread',  CAST(  ISNULL(CAST(DI.Yield * 100 AS DECIMAL(18,3)),0) AS VARCHAR(20)) AS 'Yield', CAST(  CASE WHEN LTRIM(RTRIM(DI.Dollar_Px)) = '' THEN 0.00 ELSE CAST(ISNULL(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(LTRIM(RTRIM(Dollar_Px)),CHAR(10),''),CHAR(13),''),'-',''),'/',''),' ',''),'%cpn',''),0) AS DECIMAL(18,5)) END AS VARCHAR(20)) AS 'Dollar_Px',  ISNULL(Notes,'') AS Notes,

some one help to solve this error

Body:
Check below one by one:

SELECT ISNUMERIC(ISNULL(DI.PX2,0)) FROM DI WHERE ISNUMERIC(ISNULL(DI.PX2,0)) = 0

SELECT ISNUMERIC(ISNULL(DI.Yield,0)) FROM DI WHERE ISNUMERIC(ISNULL(DI.Yield,0)) = 0

SELECT ISNUMERIC(ISNULL(Dollar_Px,0)) FROM TABLE WHERE ISNUMERIC(ISNULL(Dollar_Px,0)) = 0

There must exist any varchar string that cannot be converted to decimal


问:
When printing an image, what determines how large it will appear on a page?
Using Python's Imaging Library I want to create a PNG file.

I would like it if when printing this image, without any scaling, it would always print at a known and consistent 'size' on the printed page.

Is the resolution encoded in the image?

If so, how do I specify it?

And even if it is, does this have any relevance when it goes to the printer?

答: Much is going to depend on the software you're using to print. If you're placing the image in a Word document, it will scale according to the DPI, up to the width of your page. If you're putting it on a web page, the DPI will not matter at all.</p>

OwnerDisplayName: carrier

OwnerDisplayName: Mark Ransom


问:
android Gps Application
i did the GPS application which gets the current location.It is working in android emulator by using DDMS perspective(by passing mock location).But it is not working in android phone and phone is Samsung gt-i5801.please help me.
And one more thing i want to ask you guys.
(Why i need Gps) bcoz
in my appln i want to display the nearest cinema theatres by using latitude and longitude.
Is there any other way to do that.
Please tell me.</p>

答:
First of all, tell us what errors are you getting when you run it on the device. Logcat messages!?

Secondly, there must be any webservice which gives you the nearby cinema theatres, so you might be required to give it your current location in latitude and longitude.

For getting your current location, GPS is necessary.

On the other note, you can also use NETWORK_PROVIDER to get your current location.

Title: android Gps Application


问:
Navigation bar not showing over TableView
I can't explain why this code is not working. For some reason the navigation bar is translucent and the contents of the tableView are scrolling over it.

here is the code of the Button

```<code> let outlineViewController = OutlineTableviewController()
        outlineViewController.pdfOutlineRoot = pdfoutline
        outlineViewController.delegate = self

        let nav = UINavigationController(rootViewController: outlineViewController)
        self.present(nav, animated: true, completion:nil)
</code>```

here is the code of the tableView

```<code>super.viewDidLoad()

    let newBackButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.plain, target: self, action: #selector(dismissView))

    self.navigationItem.rightBarButtonItem = newBackButton

    navigationController?.navigationBar.backgroundColor = UIColor(red:0.00, green:0.51, blue:0.78, alpha:1.0)

   self.tableView.dataSource = self
   self.tableView.delegate = self

   tableView?.register(UINib(nibName: "OutlineTableViewCell", bundle: nil),
                        forCellReuseIdentifier: "OutlineTableViewCell")
}
</code>```

and here is the result:
the background color is not showing and the table goes under the navigationbar.

What am I missing?

答:
Thank you trungduc for your reply.

after spending hours trying to figure out what the problem was, I finally was able to fix this issue by changing the color in the root view.

```<code>        let nav = UINavigationController(rootViewController: oulineViewController)
        nav.navigationBar.backgroundColor = UIColor(red:0.00, green:0.51, blue:0.78, alpha:1.0)
        self.present(nav, animated: true, completion:nil)
</code>```

Body:
I can't explain why this code is not working. For some reason the navigation bar is translucent and the contents of the tableView are scrolling over it.

here is the code of the Button

 let outlineViewController = OutlineTableviewController()
        outlineViewController.pdfOutlineRoot = pdfoutline
        outlineViewController.delegate = self

        let nav = UINavigationController(rootViewController: outlineViewController)
        self.present(nav, animated: true, completion:nil)

here is the code of the tableView

super.viewDidLoad()

    let newBackButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.plain, target: self, action: #selector(dismissView))

    self.navigationItem.rightBarButtonItem = newBackButton

    navigationController?.navigationBar.backgroundColor = UIColor(red:0.00, green:0.51, blue:0.78, alpha:1.0)

   self.tableView.dataSource = self
   self.tableView.delegate = self

   tableView?.register(UINib(nibName: "OutlineTableViewCell", bundle: nil),
                        forCellReuseIdentifier: "OutlineTableViewCell")
}

and here is the result:
the background color is not showing and the table goes under the navigationbar.

What am I missing?

Body:
Thank you trungduc for your reply.

after spending hours trying to figure out what the problem was, I finally was able to fix this issue by changing the color in the root view.

        let nav = UINavigationController(rootViewController: oulineViewController)
        nav.navigationBar.backgroundColor = UIColor(red:0.00, green:0.51, blue:0.78, alpha:1.0)
        self.present(nav, animated: true, completion:nil)


问:
Composite Template: can't prefill first tabs
Using the below code, everything works except I am only able to fill the Tabs from whatever document I attach second. Tabs from the first don't even show up on the "Form Data" list. I'm sure this is something minor that I am overlooking, but I can not see a differance between what I have and what I have seen elsewhere on this forum, and I can not find another post with this problem. Any help would be appreciated.</p>

```<code>{
"emailSubject": "DocuSign API - Composite Test",
"status": "sent",
"compositeTemplates": [
    {
        "serverTemplates": [
            {
                "sequence": "1",
                "templateId": "TEMPLATEID"
            }
        ],
        "inlineTemplates":[
            {
                "sequence":"1",
                "recipients": {
                    "inPersonSigner": [
                        {
                            "hostEmail": "HOTEMAIL",
                            "hostName": "HOSTNAME",
                            "inPersonSigningType": "inPersonSigner",
                            "recipientId": "1",
                            "roleName": "Primary",
                            "signerName": "John Doe",
                            "signerEmail": "Test@Test.com",
                            "clientUserId": "1001"
                        }
                    ]
                },
                "tabs": {
                    "textTabs": [
                        {
                            "tabLabel": "Address",
                            "value": "221 Cherry St"
                        }
                    ]
                }
            }
        ]
    },
{
        "serverTemplates":[
            {
                "sequence": "2",
                "templateId": "TEMPLATEID"
            }
        ],
         "inlineTemplates":[
            {
                "sequence":"2",
                "recipients": {
                    "inPersonSigners": [
                        {
                            "hostEmail": "HOSTEMAIL",
                            "hostName": "HOSTNAME",
                            "inPersonSigningType": "inPersonSigner",
                            "recipientId": "1",
                            "roleName": "Primary",
                            "signerName": "John Doe",
                            "signerEmail": "test@test.com",
                            "clientUserId": "1001"
                        }
                    ]
                },
                "tabs": {
                    "textTabs": [
                        {
                            "tabLabel": "ApplicantPhone",
                            "value": "123-456-7890"
                        }
                    ]
                }
            }
        ]
    }
]
}
</code>```

答:
A couple of comments about the JSON you've posted:

the property name for the inPersonSigners should be plural (in your JSON, it's singular InPersonSigner in the first composite template object)

tabs should be a property of each inPersonSigner object (in your JSON, it's a property of the inlineTemplate object)

With this feedback in mind, here's how your inPersonSigners section should be structured:

```<code>"inPersonSigners": [
    {
        "hostEmail": "HOSTEMAIL",
        "hostName": "HOSTNAME",
        "inPersonSigningType": "inPersonSigner",
        "recipientId": "1",
        "roleName": "Primary",
        "signerName": "John Doe",
        "signerEmail": "Test@Test.com",
        "clientUserId": "1001",
        "tabs": {
            "textTabs": [
                {
                    "tabLabel": "...",
                    "value": "..."
                }
            ]
        }
    }
]
</code>```

And, here's your entire JSON request, modified to reflect the changes I've described above:

```<code>{
    "emailSubject": "DocuSign API - Composite Test",
    "status": "sent",
    "compositeTemplates": [
        {
            "serverTemplates": [
                {
                    "sequence": "1",
                    "templateId": "TEMPLATEID"
                }
            ],
            "inlineTemplates":[
                {
                    "sequence":"2",
                    "recipients": {
                        "inPersonSigners": [
                            {
                                "hostEmail": "HOSTMAIL",
                                "hostName": "HOSTNAME",
                                "inPersonSigningType": "inPersonSigner",
                                "recipientId": "1",
                                "roleName": "Primary",
                                "signerName": "John Doe",
                                "signerEmail": "Test@Test.com",
                                "clientUserId": "1001",
                                "tabs": {
                                    "textTabs": [
                                        {
                                            "tabLabel": "Address",
                                            "value": "221 Cherry St"
                                        }
                                    ]
                                }
                            }
                        ]
                    }
                }
            ]
        },
        {
            "serverTemplates":[
                {
                    "sequence": "1",
                    "templateId": "TEMPLATEID"
                }
            ],
             "inlineTemplates":[
                {
                    "sequence":"2",
                    "recipients": {
                        "inPersonSigners": [
                            {
                                "hostEmail": "HOSTEMAIL",
                                "hostName": "HOSTNAME",
                                "inPersonSigningType": "inPersonSigner",
                                "recipientId": "1",
                                "roleName": "Primary",
                                "signerName": "John Doe",
                                "signerEmail": "test@test.com",
                                "clientUserId": "1001",
                                "tabs": {
                                    "textTabs": [
                                        {
                                            "tabLabel": "ApplicantPhone",
                                            "value": "123-456-7890"
                                        }
                                    ]
                                }
                            }
                        ]
                    }
                }
            ]
        }
    ]
}
</code>```

Body:
Using the below code, everything works except I am only able to fill the Tabs from whatever document I attach second. Tabs from the first don't even show up on the "Form Data" list. I'm sure this is something minor that I am overlooking, but I can not see a differance between what I have and what I have seen elsewhere on this forum, and I can not find another post with this problem. Any help would be appreciated.

{
"emailSubject": "DocuSign API - Composite Test",
"status": "sent",
"compositeTemplates": [
    {
        "serverTemplates": [
            {
                "sequence": "1",
                "templateId": "TEMPLATEID"
            }
        ],
        "inlineTemplates":[
            {
                "sequence":"1",
                "recipients": {
                    "inPersonSigner": [
                        {
                            "hostEmail": "HOTEMAIL",
                            "hostName": "HOSTNAME",
                            "inPersonSigningType": "inPersonSigner",
                            "recipientId": "1",
                            "roleName": "Primary",
                            "signerName": "John Doe",
                            "signerEmail": "Test@Test.com",
                            "clientUserId": "1001"
                        }
                    ]
                },
                "tabs": {
                    "textTabs": [
                        {
                            "tabLabel": "Address",
                            "value": "221 Cherry St"
                        }
                    ]
                }
            }
        ]
    },
{
        "serverTemplates":[
            {
                "sequence": "2",
                "templateId": "TEMPLATEID"
            }
        ],
         "inlineTemplates":[
            {
                "sequence":"2",
                "recipients": {
                    "inPersonSigners": [
                        {
                            "hostEmail": "HOSTEMAIL",
                            "hostName": "HOSTNAME",
                            "inPersonSigningType": "inPersonSigner",
                            "recipientId": "1",
                            "roleName": "Primary",
                            "signerName": "John Doe",
                            "signerEmail": "test@test.com",
                            "clientUserId": "1001"
                        }
                    ]
                },
                "tabs": {
                    "textTabs": [
                        {
                            "tabLabel": "ApplicantPhone",
                            "value": "123-456-7890"
                        }
                    ]
                }
            }
        ]
    }
]
}

Body:
A couple of comments about the JSON you've posted:

the property name for the inPersonSigners should be plural (in your JSON, it's singular InPersonSigner in the first composite template object)

tabs should be a property of each inPersonSigner object (in your JSON, it's a property of the inlineTemplate object)

With this feedback in mind, here's how your inPersonSigners section should be structured:

"inPersonSigners": [
    {
        "hostEmail": "HOSTEMAIL",
        "hostName": "HOSTNAME",
        "inPersonSigningType": "inPersonSigner",
        "recipientId": "1",
        "roleName": "Primary",
        "signerName": "John Doe",
        "signerEmail": "Test@Test.com",
        "clientUserId": "1001",
        "tabs": {
            "textTabs": [
                {
                    "tabLabel": "...",
                    "value": "..."
                }
            ]
        }
    }
]

And, here's your entire JSON request, modified to reflect the changes I've described above:

{
    "emailSubject": "DocuSign API - Composite Test",
    "status": "sent",
    "compositeTemplates": [
        {
            "serverTemplates": [
                {
                    "sequence": "1",
                    "templateId": "TEMPLATEID"
                }
            ],
            "inlineTemplates":[
                {
                    "sequence":"2",
                    "recipients": {
                        "inPersonSigners": [
                            {
                                "hostEmail": "HOSTMAIL",
                                "hostName": "HOSTNAME",
                                "inPersonSigningType": "inPersonSigner",
                                "recipientId": "1",
                                "roleName": "Primary",
                                "signerName": "John Doe",
                                "signerEmail": "Test@Test.com",
                                "clientUserId": "1001",
                                "tabs": {
                                    "textTabs": [
                                        {
                                            "tabLabel": "Address",
                                            "value": "221 Cherry St"
                                        }
                                    ]
                                }
                            }
                        ]
                    }
                }
            ]
        },
        {
            "serverTemplates":[
                {
                    "sequence": "1",
                    "templateId": "TEMPLATEID"
                }
            ],
             "inlineTemplates":[
                {
                    "sequence":"2",
                    "recipients": {
                        "inPersonSigners": [
                            {
                                "hostEmail": "HOSTEMAIL",
                                "hostName": "HOSTNAME",
                                "inPersonSigningType": "inPersonSigner",
                                "recipientId": "1",
                                "roleName": "Primary",
                                "signerName": "John Doe",
                                "signerEmail": "test@test.com",
                                "clientUserId": "1001",
                                "tabs": {
                                    "textTabs": [
                                        {
                                            "tabLabel": "ApplicantPhone",
                                            "value": "123-456-7890"
                                        }
                                    ]
                                }
                            }
                        ]
                    }
                }
            ]
        }
    ]
}


问:
Simulink how to reproduce code generation bugs
I am interested in reproducing a Simulink bug reported in their official site. The bug is marked as a code generation bug. From my limited understanding, Simulink generates code when run in accelerator or rapid accelerator modes. Alternatively, I can generated code using Code > C/C++ Code > Build Model menu option but I do not now how to "run" this code in my Desktop computer.

To reproduce this bug (and possibly all other bugs categorized as code generation bugs), will it be sufficient to run simulation in these modes (accelerator or rapid accelerator mode) where Simulink generates code? Once the code is generated (in a directory called "slprj"), will these code suffer from the bugs reported?

Or, should there be any other approaches for generating code to reproduce this bug? I have never used the code generation feature of Simulink and only know that I can generate code for a model using "Code" menu (Code > C/C++ Code > Build Model). For this particular bug, I was able to use the above menu options and generated code (not in "slprj" directory, in a different directory which has _ert_rtw prefix). Should I inspect code in this directory? Also, I would like to know how to run this code to reproduce the bug.

Thank you for any advices!

答:
This bug seems to be a missing initialization in the generated code which you can verify by investigating the generated code. Try to reproduce in the model attached to this bug report. However, in order to check the correctness between the model simulation result and the generated code, I would recommend using SIL based testing which is described here:

https://in.mathworks.com/help/ecoder/examples/software-and-processor-in-the-loop-sil-and-pil-simulation.html


问:
jQuery Accordion problem
HI all.

I have this very simple code for simple accordion.

```<code>$('div.header').click(function() {
            $('div.content').slideUp('normal');
            $(this).next().slideDown('normal');
        }); $("div.content").hide();
</code>```

HTML

```<code><div class="header">Header</div>
<div class="content">Content... </div>
</code>```

So whenever header is being click content expands.

the problem is that when I click on the same header content slides up and going back down.

I'm not sure how to sort this out.

Any help much appreciated.

Thank you in advance

Dom

答:
use slideToggle()

```<code>$('div.header').click(function() {
        $(this).next().slideToggle('normal');
    }); $("div.content").hide();
</code>```

http://api.jquery.com/slideToggle/

Title: jQuery Accordion problem

Body:
HI all.

I have this very simple code for simple accordion.

$('div.header').click(function() {
            $('div.content').slideUp('normal');
            $(this).next().slideDown('normal');
        }); $("div.content").hide();

HTML

Header

Content...

So whenever header is being click content expands.

the problem is that when I click on the same header content slides up and going back down.

I'm not sure how to sort this out.

Any help much appreciated.

Thank you in advance

Dom

Body:
use slideToggle()

$('div.header').click(function() {
        $(this).next().slideToggle('normal');
    }); $("div.content").hide();

http://api.jquery.com/slideToggle/


问:
Why do we put @nonobjc attribute before fetchRequest() declaration?
I'm declaring usual managedobject class like this

```<code> public extension Camper {
 @nonobjc class func fetchRequest() -> NSFetchRequest<Camper> {
  return NSFetchRequest<Camper>(entityName: "Camper")
}

@NSManaged var fullName: String?
@NSManaged var phoneNumber: String?
@NSManaged var reservations: Reservation?

}
</code>```

and I'm really confused about intention of @nonobjc attribute in that concrete situation.

答:
Normally you would use @nonobjc annotations to resolve circular dependency issues that this would generate.
So for example, you define something in swift, that uses something that is defined in objc, which uses this "something" from swift again.
This would not work because you need to import the bridging header from objc into swift, and vice versa. The compiler cannot resolve this, if you would not supply this @nonobjc annotation.

Refer to Apple's documentation about how to use @objc and @nonobjc: https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithObjective-CAPIs.html

Body:
I'm declaring usual managedobject class like this

 public extension Camper {
 @nonobjc class func fetchRequest() -> NSFetchRequest<Camper> {
  return NSFetchRequest<Camper>(entityName: "Camper")
}

@NSManaged var fullName: String?
@NSManaged var phoneNumber: String?
@NSManaged var reservations: Reservation?

}

and I'm really confused about intention of @nonobjc attribute in that concrete situation.


问:
Angular 4 get local JSON File
I have searched 3 Hours and cant solved the problem. So i hope one of you know how i can fix it. I develope

First the code:

import { Injectable } from '@angular/core';
import { OnInit } from '@angular/core/src/metadata/lifecycle_hooks';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class UserService {
  isLoggedIn: boolean;
  user: string[];
  constructor(private http: HttpClient) {
  }

  getData(): void {
    this.http.get('./src/assets/dummy-response/authentication/login.dummy.json').subscribe(data => {
      // Read the user infos  from the JSON response
      this.user = data['user'];
      console.log(data);
    });
    this.http.get('').subscribe(data => {
      // Read the login_success from the JSON response
      this.isLoggedIn = data['login_success'];
      console.log(data);
    },
  err => {
    console.log('ALARM');
  });
  }
}
console.log('HALLOOOO');```

The error code:

enter image description here

directories structure:

enter image description here

So my question is, how can i access this file in assets/dummy-response/authentication/login.dummy.json?
I use the router from Angular and i think, thats the problem, that they dont let me pass.

答:
when angular is compiled, the path for your json will be

```<code>http://localhost:4200/assets/dummy-response/authentication/login.dummy.json
</code>```

not http://localhost:4200/src/assets/dummy-response/authentication/login.dummy.json

so your get request needs to be as following:

```<code>this.http.get('assets/dummy-response/authentication/login.dummy.json').subscribe(data => {
  // Read the user infos  from the JSON response
  this.user = data['user'];
  console.log(data);
});
</code>```

Title: Angular 4 get local JSON File

Body:
I have searched 3 Hours and cant solved the problem. So i hope one of you know how i can fix it. I develope

First the code:

import { Injectable } from '@angular/core';
import { OnInit } from '@angular/core/src/metadata/lifecycle_hooks';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class UserService {
  isLoggedIn: boolean;
  user: string[];
  constructor(private http: HttpClient) {
  }

  getData(): void {
    this.http.get('./src/assets/dummy-response/authentication/login.dummy.json').subscribe(data => {
      // Read the user infos  from the JSON response
      this.user = data['user'];
      console.log(data);
    });
    this.http.get('').subscribe(data => {
      // Read the login_success from the JSON response
      this.isLoggedIn = data['login_success'];
      console.log(data);
    },
  err => {
    console.log('ALARM');
  });
  }
}
console.log('HALLOOOO');

The error code:

enter image description here

directories structure:

enter image description here

So my question is, how can i access this file in assets/dummy-response/authentication/login.dummy.json?
I use the router from Angular and i think, thats the problem, that they dont let me pass.

Body:
when angular is compiled, the path for your json will be

http://localhost:4200/assets/dummy-response/authentication/login.dummy.json

not http://localhost:4200/src/assets/dummy-response/authentication/login.dummy.json

so your get request needs to be as following:

this.http.get('assets/dummy-response/authentication/login.dummy.json').subscribe(data => {
  // Read the user infos  from the JSON response
  this.user = data['user'];
  console.log(data);
});


问:
Is it possible to escape a space in a word list sigil?
I'm trying to create an atom list with all the provinces of Argentina. Since some of the are composed of multiple words, I need to escape the whitespace.

```<code>~w[
  Buenos\sAires
  Capital\sfederal Catamarca Chaco Chubut Corrientes Córdoba
  Entre\sRíos Formosa Jujuy La\sPampa La\sRioja Mendoza Misiones Neuquén
  Río\sNegro Salta San\sJuan San\ Luis Santa\sCruz Santa\sFe
  Santiago\sdel\sEstero Tierra\sdel\sFuego Tucumán
]a
</code>```

I've tried using sigil_w and sigil_W, with the classic escaping sequences \ and \s, but it does not work.

(26 provinces - 1) * (2 quotes (") + 1 comma (,) + 1 space for readability(" ")) - 25 spaces I would use with the sigil form = 75 characters I could save

I know I can achieve this using a custom sigil:

```<code>defmodule MySigil do
  def sigil_X(string, [])  do
   string
   |> String.split(~r/\s/)
   |> Enum.map(&String.replace(&1, "\\s", " "))
  end
end

import MySigil
~X[Buenos\sAires La\sPlata]
["Buenos Aires", "La Plata"]
</code>```

... but is there less "homemade" approach?

答:
While it’s not possible without hacks, there is a kludge around. Copy-paste the code below into your iex and execute it:

```<code>~w|a b c|
#⇒ ["a b", "c"]
</code>```

[NB unfortunately, SO has the original symbol converted to normal space, hence copy-paste won’t work out of the box]
I can hear your “wut?” :)

This is achieved with a non-breakable space. If you are fine with this, just use nbsp and you are all set.

Body:
I'm trying to create an atom list with all the provinces of Argentina. Since some of the are composed of multiple words, I need to escape the whitespace.

~w[
  Buenos\sAires
  Capital\sfederal Catamarca Chaco Chubut Corrientes Córdoba
  Entre\sRíos Formosa Jujuy La\sPampa La\sRioja Mendoza Misiones Neuquén
  Río\sNegro Salta San\sJuan San\ Luis Santa\sCruz Santa\sFe
  Santiago\sdel\sEstero Tierra\sdel\sFuego Tucumán
]a

I've tried using sigil_w and sigil_W, with the classic escaping sequences \ and \s, but it does not work.

(26 provinces - 1) * (2 quotes (") + 1 comma (,) + 1 space for readability(" ")) - 25 spaces I would use with the sigil form = 75 characters I could save

I know I can achieve this using a custom sigil:

defmodule MySigil do
  def sigil_X(string, [])  do
   string
   |> String.split(~r/\s/)
   |> Enum.map(&String.replace(&1, "\\s", " "))
  end
end

import MySigil
~X[Buenos\sAires La\sPlata]
["Buenos Aires", "La Plata"]

... but is there less "homemade" approach?

Body:
While it’s not possible without hacks, there is a kludge around. Copy-paste the code below into your iex and execute it:

~w|a b c|
#⇒ ["a b", "c"]

[NB unfortunately, SO has the original symbol converted to normal space, hence copy-paste won’t work out of the box]
I can hear your “wut?” :)

This is achieved with a non-breakable space. If you are fine with this, just use nbsp and you are all set.


问:
Qt: How to adjust QGraphicsItem to dynamicaly change size
I've this problem for several days. I have created QGraphicsItem and I want to stretch/adjust it's size to size of my QGraphicsView. I was using paint() method, but got with it problems with updating. Now I've used boundingRect() but it uses fixed size. When I set too big size it expand my scene and scrollbars are appearing. Is there way to adjust size of item to size of View?

EDIT: I want only adjust height of my object.

Here's some code:

Header of my Item:

```<code>#ifndef POINTER_H
#define POINTER_H
#include <QObject>
#include <QColor>
#include <QRect>
#include <QGraphicsLineItem>
#include <QPainter>
#include <QGraphicsSceneMouseEvent>

class Pointer : public QGraphicsLineItem
{
public:
    Pointer();
    void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget);
    QRectF boundingRect() const;
    int position;
    void changePosition(int x);

};

#endif // TRACKPOINTER_H
</code>```

Implementation of my Item:

```<code>#include "pointer.h"

Pointer::Pointer()
{
    //this->setFlag(QGraphicsLineItem::ItemIsMovable);
    //setFlag(QGraphicsLineItem::ItemIsFocusable);
    //setFocus();

}

void Pointer::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{

    QPen pen(Qt::red);
    painter->setPen(pen);
    painter->setBrush(QColor(77,77,77));
    painter->drawLine(0,0,0,2000);

}

QRectF Pointer::boundingRect() const
{
    return QRectF(0,0,2,600);
}

void Pointer::changePosition(int x)
{
    //position = x;
    setPos(x,0);
    update();
}
</code>```

And my Window:

```<code>Window::Window(Timers *timer, TrackPointer *tp)
{
Timeline = new QGraphicsScene(this);
TimelineView = new QGraphicsView(Timeline);
TimelineView->setAlignment(Qt::AlignTop|Qt::AlignLeft);

QVBoxLayout *timeLineLayout = new QVBoxLayout;
timeLineLayout->addWidget(TimelineView);

Pointer *pointer = new Pointer;
Timeline->addItem(pointer);
}
</code>```

I have also problems with my scene: When my object moves somewhere away - it expand scene. Later when I bring my object back to it's starting position scene still is expanded and I have scrollbars to scroll my view around the scene. Is there way to decrease scene size using my object?

答:
The promised example looks something like this:

MainWindow.h

```<code>#include <QMainWindow>

class QGraphicsView;
class QGraphicsRectItem;

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    explicit MainWindow(QWidget *parent = nullptr);

    bool eventFilter(QObject *watched, QEvent *event) override;

private:
    QGraphicsView *m_view;
    QGraphicsRectItem *m_item;
};
</code>```

MainWindow.cpp

```<code>#include "MainWindow.h"
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsRectItem>
#include <QEvent>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    m_view(new QGraphicsView(this)),
    m_item(new QGraphicsRectItem(0, 0, 1, 1))
{
    m_view->setScene(new QGraphicsScene());
    m_view->setFrameStyle(QFrame::NoFrame);
    m_view->setAlignment(Qt::AlignLeft | Qt::AlignTop);
    m_view->setSceneRect(0, 0, 1, 1);
    m_view->installEventFilter(this);
    m_view->scene()->addItem(m_item);

    setCentralWidget(m_view);
    resize(600, 400);
}

bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
    if ((watched == m_view) && (event->type() == QEvent::Resize))
        m_item->setRect(m_view->viewport()->rect().adjusted(5, 5, -5, -5));

    return QMainWindow::eventFilter(watched, event);
}
</code>```

Body:
I've this problem for several days. I have created QGraphicsItem and I want to stretch/adjust it's size to size of my QGraphicsView. I was using paint() method, but got with it problems with updating. Now I've used boundingRect() but it uses fixed size. When I set too big size it expand my scene and scrollbars are appearing. Is there way to adjust size of item to size of View?

EDIT: I want only adjust height of my object.

Here's some code:

Header of my Item:

#ifndef POINTER_H
#define POINTER_H
#include <QObject>
#include <QColor>
#include <QRect>
#include <QGraphicsLineItem>
#include <QPainter>
#include <QGraphicsSceneMouseEvent>

class Pointer : public QGraphicsLineItem
{
public:
    Pointer();
    void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget);
    QRectF boundingRect() const;
    int position;
    void changePosition(int x);

};

#endif // TRACKPOINTER_H

Implementation of my Item:

#include "pointer.h"

Pointer::Pointer()
{
    //this->setFlag(QGraphicsLineItem::ItemIsMovable);
    //setFlag(QGraphicsLineItem::ItemIsFocusable);
    //setFocus();

}

void Pointer::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{

    QPen pen(Qt::red);
    painter->setPen(pen);
    painter->setBrush(QColor(77,77,77));
    painter->drawLine(0,0,0,2000);

}

QRectF Pointer::boundingRect() const
{
    return QRectF(0,0,2,600);
}

void Pointer::changePosition(int x)
{
    //position = x;
    setPos(x,0);
    update();
}

And my Window:

Window::Window(Timers *timer, TrackPointer *tp)
{
Timeline = new QGraphicsScene(this);
TimelineView = new QGraphicsView(Timeline);
TimelineView->setAlignment(Qt::AlignTop|Qt::AlignLeft);

QVBoxLayout *timeLineLayout = new QVBoxLayout;
timeLineLayout->addWidget(TimelineView);

Pointer *pointer = new Pointer;
Timeline->addItem(pointer);
}

I have also problems with my scene: When my object moves somewhere away - it expand scene. Later when I bring my object back to it's starting position scene still is expanded and I have scrollbars to scroll my view around the scene. Is there way to decrease scene size using my object?

Body:
The promised example looks something like this:

MainWindow.h

#include <QMainWindow>

class QGraphicsView;
class QGraphicsRectItem;

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    explicit MainWindow(QWidget *parent = nullptr);

    bool eventFilter(QObject *watched, QEvent *event) override;

private:
    QGraphicsView *m_view;
    QGraphicsRectItem *m_item;
};

MainWindow.cpp

#include "MainWindow.h"
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsRectItem>
#include <QEvent>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    m_view(new QGraphicsView(this)),
    m_item(new QGraphicsRectItem(0, 0, 1, 1))
{
    m_view->setScene(new QGraphicsScene());
    m_view->setFrameStyle(QFrame::NoFrame);
    m_view->setAlignment(Qt::AlignLeft | Qt::AlignTop);
    m_view->setSceneRect(0, 0, 1, 1);
    m_view->installEventFilter(this);
    m_view->scene()->addItem(m_item);

    setCentralWidget(m_view);
    resize(600, 400);
}

bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
    if ((watched == m_view) && (event->type() == QEvent::Resize))
        m_item->setRect(m_view->viewport()->rect().adjusted(5, 5, -5, -5));

    return QMainWindow::eventFilter(watched, event);
}