问:
Why does ngrx/store example app use multiple stores? (how to design store)
I am trying to make a rather big, scalable application and I was told it is best practice to have one single store storing the current global state (including both transient/deleted-on-reload and session-persistent data) of the whole application, even if it is separated into multiple modules.

Now I was wondering why the example app of the ngrx/store which you can find on the ngrx/store-website uses multiple stores; each reducer has an own piece of code like this:

```<code>export interface State {
  ids: string[];
  entities: { [id: string]: Book };
  selectedBookId: string | null;
};

export const initialState: State = {
  ids: [],
  entities: {},
  selectedBookId: null,
};
</code>```

So why does the official guide not use a single store as recommended by most people? Or is it considered as a single store as long as all reducers belong to one module? If not, how do I implement one single, central store? My idea would be to use a Store generic and put their variations into a table. The other option would be to have one single JS-object whose properties you update with reducer-actions. Either way you have to have some structure in the table or Object. Are there any best practices for this? Do you know a better example-app?

答:
The example app is using a single store. State in this case is the interface for a reducer. You can have many reducers in one store.

It's considered best practise to use a single store. A single store should be sufficient for almost all small and medium sized apps.

There is a very good example of the Angular Tour of Heroes application recreated with NGRX Store. You can find it here:
http://bodiddlie.github.io/ng-2-toh-with-ngrx-suite/

Body:
I am trying to make a rather big, scalable application and I was told it is best practice to have one single store storing the current global state (including both transient/deleted-on-reload and session-persistent data) of the whole application, even if it is separated into multiple modules.

Now I was wondering why the example app of the ngrx/store which you can find on the ngrx/store-website uses multiple stores; each reducer has an own piece of code like this:

export interface State {
  ids: string[];
  entities: { [id: string]: Book };
  selectedBookId: string | null;
};

export const initialState: State = {
  ids: [],
  entities: {},
  selectedBookId: null,
};

So why does the official guide not use a single store as recommended by most people? Or is it considered as a single store as long as all reducers belong to one module? If not, how do I implement one single, central store? My idea would be to use a Store generic and put their variations into a table. The other option would be to have one single JS-object whose properties you update with reducer-actions. Either way you have to have some structure in the table or Object. Are there any best practices for this? Do you know a better example-app?


来源: stackexchange

问:
How can I make div not disappear when buttons are clicked
So I have a page that fades in when a button is pressed, and the page has 3 font-awesome icons on it. And when you click anywhere on the page it fades it fades the page out. When you click the font-awesome icons on the page it takes you to another page. But the problem is that the page fades out when you click the buttons. I want it to only fade out when you click anywhere except on the font-awesome icons.

$(function() {

  $('#fadeContent').click(function(){
    var bodyContent = $('#bodyContent')
    bodyContent.fadeIn(400);
    bodyContent.click(function() {
      $(this).fadeOut(400);
    })
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color: black;
  font-family: "Source Sans Pro", sans-serif;
  color: #ccc;
  z-index: -100;
  background-color:black;
}

#bodyContent{
  display:none;
  position:absolute;
  text-align: center;
  color: white;
  width:100%;
  height:100%;
  background:#454545;
  z-index: 100;
}

.fa-times{
    position: absolute;
    top: 0px;
    right: 0px;
    font-size: 3em;
    margin-right: 2%;
    margin-top: 1.5%;
}

.fa-twitter,
.fa-github,
.fa-steam {
    display: inline-block;
    position: relative;
    color: white;
    border-radius: 100px;
    font-size: 3.5em;
    padding: .5em;
    border: 5px solid white;
    margin-top: 20%;
    margin-left: 1.5%;
    margin-right: 1.5%;
}

.fa-times:hover {
    color: #f06262;
    cursor: pointer;
}

.fa-twitter:hover,
.fa-github:hover,
.fa-steam:hover {
    background-color: #1dd2e2;
    cursor: pointer;
}

.home {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 20%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

.about {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 37%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

.projects {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 54%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

.contact {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 71%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

.home:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

.about:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

.projects:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

.contact:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

@keyframes fadein {
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}
@-webkit-keyframes fadein { /* Safari and Chrome */
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Home</title>

    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro|Play" rel="stylesheet">

    <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css'>
    <link rel='stylesheet prefetch' href='http://rawgit.com/fralec/elegantShareJS/master/css/elegant.css'>

    <link rel="stylesheet" type="text/css" href="css/style.css">

    <button class="home">Home</button>
    <button class="about">About</button>
    <button class="projects">Projects</button>
    <button id="fadeContent" class="contact">Contact</button>

```

答:
You should  register click event on each icon and cancel further event handling by calling stopPropagation method.

Exsample:

```<code>$(".fa").click(function(e) {
  e.stopPropagation();
})
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So I have a page that fades in when a button is pressed, and the page has 3 font-awesome icons on it. And when you click anywhere on the page it fades it fades the page out. When you click the font-awesome icons on the page it takes you to another page. But the problem is that the page fades out when you click the buttons. I want it to only fade out when you click anywhere except on the font-awesome icons.

$(function() {

  $('#fadeContent').click(function(){
    var bodyContent = $('#bodyContent')
    bodyContent.fadeIn(400);
    bodyContent.click(function() {
      $(this).fadeOut(400);
    })
  });

});

body {
  background-color: black;
  font-family: "Source Sans Pro", sans-serif;
  color: #ccc;
  z-index: -100;
  background-color:black;
}

#bodyContent{
  display:none;
  position:absolute;
  text-align: center;
  color: white;
  width:100%;
  height:100%;
  background:#454545;
  z-index: 100;
}

.fa-times{
    position: absolute;
    top: 0px;
    right: 0px;
    font-size: 3em;
    margin-right: 2%;
    margin-top: 1.5%;
}

.fa-twitter,
.fa-github,
.fa-steam {
    display: inline-block;
    position: relative;
    color: white;
    border-radius: 100px;
    font-size: 3.5em;
    padding: .5em;
    border: 5px solid white;
    margin-top: 20%;
    margin-left: 1.5%;
    margin-right: 1.5%;
}

.fa-times:hover {
    color: #f06262;
    cursor: pointer;
}

.fa-twitter:hover,
.fa-github:hover,
.fa-steam:hover {
    background-color: #1dd2e2;
    cursor: pointer;
}

.home {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 20%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

.about {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 37%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

.projects {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 54%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

.contact {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 71%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

.home:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

.about:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

.projects:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

.contact:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

@keyframes fadein {
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}
@-webkit-keyframes fadein { /* Safari and Chrome */
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Home</title>

    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro|Play" rel="stylesheet">

    <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css'>
    <link rel='stylesheet prefetch' href='http://rawgit.com/fralec/elegantShareJS/master/css/elegant.css'>

    <link rel="stylesheet" type="text/css" href="css/style.css">

    <button class="home">Home</button>
    <button class="about">About</button>
    <button class="projects">Projects</button>
    <button id="fadeContent" class="contact">Contact</button>

Body:
You should  register click event on each icon and cancel further event handling by calling stopPropagation method.

Exsample:

$(".fa").click(function(e) {
  e.stopPropagation();
})


答:
Intuitively, what you are asking should be equivalent to the interval between the first and last dates, divided by the number of dates minus 1.

Let me explain more thoroughly. Imagine the dates are points on a line (+ are dates present, - are dates missing, the first date is the 12th, and I changed the last date to Dec 24th for illustration purposes):

```<code>++----+---+-+
</code>```

Now, what you really want to do, is evenly space your dates out between these lines, and find how long it is between each of them:

```<code>+--+--+--+--+
</code>```

To do that, you simply take the number of days between the last and first days, in this case 24 - 12 = 12, and divide it by the number of intervals you have to space out, in this case 4: 12 / 4 = 3.

With a MySQL query

```<code>SELECT DATEDIFF(MAX(dt), MIN(dt)) / (COUNT(dt) - 1) FROM a;
</code>```

This works on this table (with your values it returns 2.75):

```<code>CREATE TABLE IF NOT EXISTS `a` (
  `dt` date NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `a` (`dt`) VALUES
('2010-12-12'),
('2010-12-13'),
('2010-12-18'),
('2010-12-22'),
('2010-12-24');
</code>```

ContentLicense: CC BY-SA 2.5

Title: MySQL: Average interval between records

Body:
Assume this table:

id    date
----------------
1     2010-12-12
2     2010-12-13
3     2010-12-18
4     2010-12-22
5     2010-12-23

How do I find the average intervals between these dates, using MySQL queries only?

For instance, the calculation on this table will be

  (
    ( 2010-12-13 - 2010-12-12 )
  + ( 2010-12-18 - 2010-12-13 )
  + ( 2010-12-22 - 2010-12-18 )
  + ( 2010-12-23 - 2010-12-22 )
  ) / 4
----------------------------------
= ( 1 DAY + 5 DAY + 4 DAY + 1 DAY ) / 4
= 2.75 DAY

Body:
Intuitively, what you are asking should be equivalent to the interval between the first and last dates, divided by the number of dates minus 1.

Let me explain more thoroughly. Imagine the dates are points on a line (+ are dates present, - are dates missing, the first date is the 12th, and I changed the last date to Dec 24th for illustration purposes):

++----+---+-+

Now, what you really want to do, is evenly space your dates out between these lines, and find how long it is between each of them:

+--+--+--+--+

To do that, you simply take the number of days between the last and first days, in this case 24 - 12 = 12, and divide it by the number of intervals you have to space out, in this case 4: 12 / 4 = 3.

With a MySQL query

SELECT DATEDIFF(MAX(dt), MIN(dt)) / (COUNT(dt) - 1) FROM a;

This works on this table (with your values it returns 2.75):

CREATE TABLE IF NOT EXISTS `a` (
  `dt` date NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `a` (`dt`) VALUES
('2010-12-12'),
('2010-12-13'),
('2010-12-18'),
('2010-12-22'),
('2010-12-24');


问:
Understanding Javascript scope with modules
I am trying to understand how scope works with node modules. I have an IIFE to initialize a LinkedList, which uses Node object for each element.

using IIFE to avoid polluting global scope

After IIFE, where does the Node go? Is there any way I can access Node in require object i.e. test class?

linkedList.js

(function LinkedListInit() {
    module.exports = new LinkedList();

    function LinkedList() {
        this.head;
    }

    // LinkedList Node
    function Node(data, next) {
        this.data = data;
        this.next = next;
    }

    LinkedList.prototype.insert = insert;

    function insert(data) {
        var curr = this.head,
            newNode = new Node(data);

        if (this.head == null) {
            this.head = newNode;
        } else {
            while (curr.next != null) {
                curr = curr.next;
            }
            curr.next = newNode;
        }
        return this;
    }
}());```
</div>
</div>
</p>

<h2>linkedListTest.js</h2>

```var linkedList = require('../../js/ds/linkedList');
// Test cases for linkedList.insert(val); works fine.

// Can I access Node here?
```

答:
You're scope is already contained within the module - except for what you choose to export, so you don't really need the IIFE.

If you wanted it to work with an IIFE, you would have to attach the IIFE to module.exports rather than wrapping your IIFE around it. Something like...

```<code>module.exports = (function LinkedListInit() {
    function LinkedList() {
        this.head;
    }
    return new LinkedList();
// ...
</code>```

Body:
I am trying to understand how scope works with node modules. I have an IIFE to initialize a LinkedList, which uses Node object for each element.

using IIFE to avoid polluting global scope

After IIFE, where does the Node go? Is there any way I can access Node in require object i.e. test class?

linkedList.js

(function LinkedListInit() {
    module.exports = new LinkedList();

    function LinkedList() {
        this.head;
    }

    // LinkedList Node
    function Node(data, next) {
        this.data = data;
        this.next = next;
    }

    LinkedList.prototype.insert = insert;

    function insert(data) {
        var curr = this.head,
            newNode = new Node(data);

        if (this.head == null) {
            this.head = newNode;
        } else {
            while (curr.next != null) {
                curr = curr.next;
            }
            curr.next = newNode;
        }
        return this;
    }
}());

linkedListTest.js

var linkedList = require('../../js/ds/linkedList');
// Test cases for linkedList.insert(val); works fine.

// Can I access Node here?

Body:
You're scope is already contained within the module - except for what you choose to export, so you don't really need the IIFE.

If you wanted it to work with an IIFE, you would have to attach the IIFE to module.exports rather than wrapping your IIFE around it. Something like...

module.exports = (function LinkedListInit() {
    function LinkedList() {
        this.head;
    }
    return new LinkedList();
// ...


问:
JMeter: check result after batch processing
I am currently trying to measure the performance of a TCP server, and I have the following issue:

The request are ingested by the server, and the server synchronously answers to the tcp client.
After this first step the data is processed (some kind of batch processing), and written to a table.

With Jmeter, is it possible to implement some kind of probe that will check the creation of the entries in the table?

答:
What "table?

If it is SQL Table, you can use JDBC Request sampler which allows executing arbitrary SQL queries and storing the results into JMeter Variables. See The Real Secret to Building a Database Test Plan With JMeter article for detailed information on configuring JMeter for database connectivity.

If you are getting some form of table as response data you can use Response Assertion to verify whether expected data is present in the server response or not and conditionally fail the sampler.


问:
How to show a Default view or simply a white screen when the NSPageController arrangedObjects count goes from one to zero?
Mac App Using Xcode:7.3 on Sierra 10.12.2

I have a panel with a TabView that has a tab that enables adding and deleting photos. There is an NSPageController in Book mode which allows navigation of the photos. The arrangedObjects of the NSPageController are contained in a mutable array that supports the addition and deletion of photos. The pageController.view is an NSBox.

```<code>_editRecipeController.pageController.arrangedObjects = _mutPhotoImageArray;
</code>```

I am writing to ask how I should handle the removal of the last remaining photo.

If the mutable array has more than one photo, when I click on the Delete button, the photo is removed from _mutPhotoImageArray, and the code navigates to one of the remaining photos in the pageController.

When I delete the final photo, I want the last photo to disappear and the
header to say something like "No Photos Found"

What actually happens following the click on the Delete button when only one photo is in the PageController, is the photo does NOT disappear, so I am forced to display the rather kludgy message, "Press the Done Button to Delete the Final Photo."

How do I make the pageController display a blank screen?

答:
When you want to display no images, set arrangedObjects to ["empty"] (an array with a single object of any type/value except your normal data type).

In pageController(_ pageController: NSPageController, identifierFor object: Any), guard on the object being of your data type. If it isn't, return an identifier of "empty".

In pageController(_ pageController: NSPageController, viewControllerForIdentifier identifier: String), if the identifier is "empty", return a view controller that displays your "no photos found" view.

I'm not sure if this is necessary, but in pageController(_ pageController: NSPageController, didTransitionTo object: Any) if the object is "empty", I call my method to reset to an "empty" array. Not sure if necessary, but it doesn't hurt to have 1 extra guard there.

Body:
Mac App Using Xcode:7.3 on Sierra 10.12.2

I have a panel with a TabView that has a tab that enables adding and deleting photos. There is an NSPageController in Book mode which allows navigation of the photos. The arrangedObjects of the NSPageController are contained in a mutable array that supports the addition and deletion of photos. The pageController.view is an NSBox.

_editRecipeController.pageController.arrangedObjects = _mutPhotoImageArray;

I am writing to ask how I should handle the removal of the last remaining photo.

If the mutable array has more than one photo, when I click on the Delete button, the photo is removed from _mutPhotoImageArray, and the code navigates to one of the remaining photos in the pageController.

When I delete the final photo, I want the last photo to disappear and the
header to say something like "No Photos Found"

What actually happens following the click on the Delete button when only one photo is in the PageController, is the photo does NOT disappear, so I am forced to display the rather kludgy message, "Press the Done Button to Delete the Final Photo."

How do I make the pageController display a blank screen?


问:
Enabling blocked text selection using JavaScript
I recently came across a website that disabled text selection, preventing anyone from easily copying and pasting text. I have a bookmarklet that disables similar attempts to block context menus using JavaScript, and I'm wondering if it would be possible to do something similar for text selection.

```<code>function disableSelection(target){
if (typeof target.onselectstart!="undefined") //For IE
    target.onselectstart=function(){return false}
else if (typeof target.style.MozUserSelect!="undefined") //For Firefox
    target.style.MozUserSelect="none"
else //All other route (For Opera)
    target.onmousedown=function(){return false}
target.style.cursor = "default"
}
</code>```

Elsewhere the function is called with disableSelection(document.body).

The solution from my context menu bookmarklet is also probably necessary:

```<code>javascript:void(document.onmousedown=null);
void(document.onclick=null);
void(document.oncontextmenu=null)
</code>```

Finally, I had seen elsewhere on StackOverflow that CSS could also be used:

```<code>-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;
</code>```

Is there a method to fight all of these at once and end this tyranny over my browser? How would I both enable MozUserSelect/SelectStart for all elements and set the CSS properties?

答:
Seen the same annoying js and more on another site:

```<code><script type="text/javascript" language="JavaScript">
function disableText(e){
  return false
}
function reEnable(){
  return true
}
//For browser IE4+
document.onselectstart = new Function ("return false")

//For browser NS6
if (window.sidebar){
  document.onmousdown = disableText
  document.onclick = reEnable
}
</script>
<script language="JavaScript1.2">
var msgpopup="";
function pmb(){
      if(alertVis == "1") alert(message);
          if(closeWin == "1") self.close();
          return false;
}
function IE() {
     if (event.button == "2" || event.button == "3"){pmb();}
}
function NS(e) {
     if (document.layers || (document.getElementById && !document.all)){
          if (e.which == "2" || e.which == "3"){ pmb();}
     }
}
document.onmousedown=IE;document.onmouseup=NS;document.oncontextmenu=new Function("alert(msgpopup);return false")

</script>
<script type="text/javascript">
function disableSelection(target){
if (typeof target.onselectstart!="undefined") //For IE
    target.onselectstart=function(){return false}
else if (typeof target.style.MozUserSelect!="undefined") //For Firefox
    target.style.MozUserSelect="none"
else //All other route (For Opera)
    target.onmousedown=function(){return false}
target.style.cursor = "default"
}

</script>
</code>```

Note that all the event handlers are either attached to document manually and disableSelection(document.body). So the script referenced by @alan-h that allows mouse events also needs to be updated to run on document and document.body. (re: el.onselectstart = el.ondragstart = el.ondrag = el.oncontextmenu = el.onmousedown = el.onmouseup = function(){return true};)

Body:
I recently came across a website that disabled text selection, preventing anyone from easily copying and pasting text. I have a bookmarklet that disables similar attempts to block context menus using JavaScript, and I'm wondering if it would be possible to do something similar for text selection.

function disableSelection(target){
if (typeof target.onselectstart!="undefined") //For IE
    target.onselectstart=function(){return false}
else if (typeof target.style.MozUserSelect!="undefined") //For Firefox
    target.style.MozUserSelect="none"
else //All other route (For Opera)
    target.onmousedown=function(){return false}
target.style.cursor = "default"
}

Elsewhere the function is called with disableSelection(document.body).

The solution from my context menu bookmarklet is also probably necessary:

javascript:void(document.onmousedown=null);
void(document.onclick=null);
void(document.oncontextmenu=null)

Finally, I had seen elsewhere on StackOverflow that CSS could also be used:

-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;

Is there a method to fight all of these at once and end this tyranny over my browser? How would I both enable MozUserSelect/SelectStart for all elements and set the CSS properties?

Body:
Seen the same annoying js and more on another site:

<script type="text/javascript" language="JavaScript">
function disableText(e){
  return false
}
function reEnable(){
  return true
}
//For browser IE4+
document.onselectstart = new Function ("return false")

//For browser NS6
if (window.sidebar){
  document.onmousdown = disableText
  document.onclick = reEnable
}
</script>
<script language="JavaScript1.2">
var msgpopup="";
function pmb(){
      if(alertVis == "1") alert(message);
          if(closeWin == "1") self.close();
          return false;
}
function IE() {
     if (event.button == "2" || event.button == "3"){pmb();}
}
function NS(e) {
     if (document.layers || (document.getElementById && !document.all)){
          if (e.which == "2" || e.which == "3"){ pmb();}
     }
}
document.onmousedown=IE;document.onmouseup=NS;document.oncontextmenu=new Function("alert(msgpopup);return false")

</script>
<script type="text/javascript">
function disableSelection(target){
if (typeof target.onselectstart!="undefined") //For IE
    target.onselectstart=function(){return false}
else if (typeof target.style.MozUserSelect!="undefined") //For Firefox
    target.style.MozUserSelect="none"
else //All other route (For Opera)
    target.onmousedown=function(){return false}
target.style.cursor = "default"
}

</script>

Note that all the event handlers are either attached to document manually and disableSelection(document.body). So the script referenced by @alan-h that allows mouse events also needs to be updated to run on document and document.body. (re: el.onselectstart = el.ondragstart = el.ondrag = el.oncontextmenu = el.onmousedown = el.onmouseup = function(){return true};)


问:
Call sequential m-files batch file?
I want to write a batch file that calls sequentially 2 m-files. I want the second m-file (f.m) not to start before the end of the first m-file (main.m). The second m-file is repeated 4 times (4 tasks).

I have tried to use the wait option as below but it does not work.

```<code>#$ -S /bin/bash
#$ -l h_vmem=2G
#$ -l tmem=2G
#$ -cwd
#$ -j y
#$ -N example
#$ -t 1-4
echo "Task ID is $SGE_TASK_ID"

matlab -wait -nodisplay -nodesktop -nojvm -nosplash < main.m

matlab -nodisplay -nodesktop -nojvm -nosplash < f.m
</code>```

What am I doing wrong?

答:
You can either concatenate the contents of main.m and f.m together prior to piping them to MATLAB

```<code>cat main.m f.m | matlab -nodisplay -nodesktop -nojvm -nosplash
</code>```

Or you can call the scripts by passing a command to MATLAB using the -r flag

```<code>matlab -nodisplay -nodesktop -nojvm -nosplash -r 'main; f; exit'
</code>```

These are both going to be more performant than your approach since here we're only launching one instance of MATLAB.

Title: Call sequential m-files batch file?

Body:
I want to write a batch file that calls sequentially 2 m-files. I want the second m-file (f.m) not to start before the end of the first m-file (main.m). The second m-file is repeated 4 times (4 tasks).

I have tried to use the wait option as below but it does not work.

#$ -S /bin/bash
#$ -l h_vmem=2G
#$ -l tmem=2G
#$ -cwd
#$ -j y
#$ -N example
#$ -t 1-4
echo "Task ID is $SGE_TASK_ID"

matlab -wait -nodisplay -nodesktop -nojvm -nosplash < main.m

matlab -nodisplay -nodesktop -nojvm -nosplash < f.m

What am I doing wrong?

Body:
You can either concatenate the contents of main.m and f.m together prior to piping them to MATLAB

cat main.m f.m | matlab -nodisplay -nodesktop -nojvm -nosplash

Or you can call the scripts by passing a command to MATLAB using the -r flag

matlab -nodisplay -nodesktop -nojvm -nosplash -r 'main; f; exit'

These are both going to be more performant than your approach since here we're only launching one instance of MATLAB.


问:
SSL for local networking without changing router or client systems
The Setup

Imagine a server placed in a local network. I need the clients (a browser) to connect to that local server.

I want to ship that server (the actual hardware preconfigured with the server code on it) to any customer.

It should then be plugged in to the local network and the customer has to do a quick setup routine.

The server is not allowed to connect to the internet.

All communication between the client and the server has to be made via https.

So right now I am thinking about solutions for that problem.

Options I ruled out because they are to unpractical for a user / admin to do

Installing a self signed cert issued by the server locally on every
client OS (especially not working for mobile browsers)

Accepting the "this is an unsafe cert" thing in the browser
with self signed certs since its just unprofessional

Native applications as clients are no option

I would really appreciate your help, thank you.

答:
TLS supports 3 primary means of Key Exchange

Certificate Based (RSA, ECDSA-ECDHE etc)

Anonymous (DH based)

Pre-Shared Key (PSK)

Given your scenario, where you need to ship a Server Box and many clients having pre-installed browsers will connect to your Server using HTTPS and assuming that you have no control over those clients, you cannot use PSK or Anonymous mechanisms. I suggest the following:

A unique Private-Key / Public Key Pair should be installed in each of the Server Box which you intend to sell. The Public Key should be certified (i.e. issued as a certificate) from a well-known Certificate Authority whose self-signed certs are usually installed in browsers. This should help you in seamless TLS connection getting established between the Server and Client.

The certificate does have a validity period, but, you can try to request for a fairly longer validity period and should the need arise the certificate should be updated in a similar fashion as you might be updating your software in those boxes.


问:
How to add values from an array as an object in a mutable dictionary with objective-c?
I'm in the beginning stages of learning how to code, and I'm trying to figure out a problem.  I created an array with 4 objects in it, then created an empty mutable dictionary.  And now I have to add the values in my array as objects in my mutable dictionary, and I can't figure out how to do it.  This is what I have come up with that is coming back with errors, I know its just simple syntax but I can't find the answer online.

```<code>NSArray *shoeOrder = @[@"Charles Smith", @(9.5), @"loafer", @"brown"];

NSMutableDictionary *shoeOrderDict = [[NSMutableDictionary alloc] init];

[shoeOrderDict setObject: @[shoeOrder objectAtIndex: 0] forKey: @"customer"];
[shoeOrderDict setObject: @[shoeOrder objectAtIndex: 1] forKey: @"size"];
[shoeOrderDict setObject: @[shoeOrder objectAtIndex: 2] forKey: @"style"];
[shoeOrderDict setObject: @[shoeOrder objectAtIndex: 3] forKey: @"color"];
</code>```

Thank you for your help!

答:
well, please remove @  in @[shoeOrder objectAtIndex: 0].
....

```<code>[shoeOrderDict setObject:[shoeOrder objectAtIndex: 0] forKey: @"customer"];
[shoeOrderDict setObject:[shoeOrder objectAtIndex: 1] forKey: @"size"];
[shoeOrderDict setObject:[shoeOrder objectAtIndex: 2] forKey: @"style"];
[shoeOrderDict setObject:[shoeOrder objectAtIndex: 3] forKey: @"color"];
</code>```

....

Body:
I'm in the beginning stages of learning how to code, and I'm trying to figure out a problem.  I created an array with 4 objects in it, then created an empty mutable dictionary.  And now I have to add the values in my array as objects in my mutable dictionary, and I can't figure out how to do it.  This is what I have come up with that is coming back with errors, I know its just simple syntax but I can't find the answer online.

NSArray *shoeOrder = @[@"Charles Smith", @(9.5), @"loafer", @"brown"];

NSMutableDictionary *shoeOrderDict = [[NSMutableDictionary alloc] init];

[shoeOrderDict setObject: @[shoeOrder objectAtIndex: 0] forKey: @"customer"];
[shoeOrderDict setObject: @[shoeOrder objectAtIndex: 1] forKey: @"size"];
[shoeOrderDict setObject: @[shoeOrder objectAtIndex: 2] forKey: @"style"];
[shoeOrderDict setObject: @[shoeOrder objectAtIndex: 3] forKey: @"color"];

Thank you for your help!

Body:
well, please remove @  in @[shoeOrder objectAtIndex: 0].
....

[shoeOrderDict setObject:[shoeOrder objectAtIndex: 0] forKey: @"customer"];
[shoeOrderDict setObject:[shoeOrder objectAtIndex: 1] forKey: @"size"];
[shoeOrderDict setObject:[shoeOrder objectAtIndex: 2] forKey: @"style"];
[shoeOrderDict setObject:[shoeOrder objectAtIndex: 3] forKey: @"color"];

....


问:
Trying to examine contents of a variable with if/else in Ruby
I am using the following code to check if a process is running using ps and grep and storing the PID in a variable.

Then I am checking if there is a value within that variable with an if/else statement. The goal is to run whats in the if block if the condition is true and if not, execute what is in else

```<code>fisheye_pid = `ps -ef | grep fisheyeboot | grep -v grep | awk '{print $2}'`
kill_fisheye = `kill #{fisheye_pid}`

if "#{fisheye_pid}" != nil or 0
  puts ''
  puts  '--------------------'
  puts '|  Stopping Fisheye  |'
  puts  '--------------------'
  puts kill_fisheye
  sleep(5)
    if "#{fisheye_pid}" == nil or 0
      puts 'Fisheye has been stopped..'
      puts ''
    end
else
  puts 'Fisheye is not running, proceeding.'

end
</code>```

If anything sticks out let me know. Its probably something small i am overlooking.

答:
Kills process "fisheyeboot"

```<code>fisheye_pid = `ps -ef | grep fisheyeboot | grep -v grep | awk '{print $2}'`.to_i

if fisheye_pid > 0
  puts ''
  puts  '--------------------'
  puts '|  Stopping Fisheye  |'
  puts  '--------------------'
  `kill #{fisheye_pid}`
  # TODO: sleep 5 seconds and recheck process by running "ps" again
else
  puts 'Fisheye is not running, proceeding.'
end
</code>```

You could also just use killall and discard the output:

```<code>`killall fisheyeboot`
</code>```

Body:
I am using the following code to check if a process is running using ps and grep and storing the PID in a variable.

Then I am checking if there is a value within that variable with an if/else statement. The goal is to run whats in the if block if the condition is true and if not, execute what is in else

fisheye_pid = `ps -ef | grep fisheyeboot | grep -v grep | awk '{print $2}'`
kill_fisheye = `kill #{fisheye_pid}`

if "#{fisheye_pid}" != nil or 0
  puts ''
  puts  '--------------------'
  puts '|  Stopping Fisheye  |'
  puts  '--------------------'
  puts kill_fisheye
  sleep(5)
    if "#{fisheye_pid}" == nil or 0
      puts 'Fisheye has been stopped..'
      puts ''
    end
else
  puts 'Fisheye is not running, proceeding.'

end

If anything sticks out let me know. Its probably something small i am overlooking.

Body:
Kills process "fisheyeboot"

fisheye_pid = `ps -ef | grep fisheyeboot | grep -v grep | awk '{print $2}'`.to_i

if fisheye_pid > 0
  puts ''
  puts  '--------------------'
  puts '|  Stopping Fisheye  |'
  puts  '--------------------'
  `kill #{fisheye_pid}`
  # TODO: sleep 5 seconds and recheck process by running "ps" again
else
  puts 'Fisheye is not running, proceeding.'
end

You could also just use killall and discard the output:

`killall fisheyeboot`


问:
unable to get correct user id to remove list-element in vue.js
I am trying to delete a user from the database by select the user from a list, and then click a button to remove the user. I've tried to implement the method to remove the user, but I am unable to get the id from the selected user.

Does anyone know how I can access the user id to the selected user within the removeUser method?

my html code:

```<code><template id="user-template">
    <div>
        <ul class="collection">
            <a class=" collection-item avatar" v-for="user in users" v-on:click="userClicked(user, $event)">
                <span class="name">{{ user.firstName }}</span>
            </a>
        </ul>

        <div id="removeUser" class="modal">
            <div class="modal-footer">
                <a class=" modal-action modal-close btn-flat" v-on:click="removeUser">yes</a>
            </div>
        </div>
    </div>
</template>

<div id="app">
  <a class="btn-floating red" data-target="removeUser"></a>
  <user @selected-user="setSelected"></user>
</div>
</code>```

My vue component:

```<code>user: {
    template: '#user-template',
    data: function () {
        return {
            users: [],
        }
    },
    methods: {
        removeUser: function (user) {
            this.$http.delete('/user/', user).then(function (data) {
            this.users.$remove(user)
        });
    }
}
</code>```

答:
Try :

```<code><a class=" collection-item avatar" v-for="(user, index) in users"
   :key="user" v-on:click="userClicked(user, index, $event)">

user: {
    template: '#user-template',
    data: function () {
        return {
            users: [],
            userSelected: { id: -1, index: -1 }
        }
    },
    methods: {
        userClicked: function (user, index, event) {
            this.userSelected.id = user.id;//If user has an id property
            this.userSelected.index = index;
        });
        removeUser: function () {
            if( this.userSelected.id > -1 ) {
                this.$http.delete('/user/' + this.userSelected.id).then(function (data) {
                this.users.splice(this.userSelected.index, 1);
                this.userSelected.id = -1;
                this.userSelected.index = -1;
            }
        });
    }
}
</code>```

And you can disable remove button if no user selected :

```<code><div :disabled="userSelected.id === -1" id="removeUser" class="modal">
  <div class="modal-footer">
  <a class=" modal-action modal-close btn-flat" v-on:click="removeUser">yes</a>
  </div>
</div>
</code>```

Or if you don't want to use index to remove the user in the users array, you can use the id :

```<code>methods: {
   removeUserWithId: function( id ) {
       for( var i = 0, length = this.users.length; i < length; i++ ) {
           if( this.users[i].id === id ) {
              this.users.splice(i, 1);
              return;
          }
      }
   }
}
</code>```

Note :

key is required in v-for since Vue 2.2.0+ link

$remove is deprecated : link

Body:
I am trying to delete a user from the database by select the user from a list, and then click a button to remove the user. I've tried to implement the method to remove the user, but I am unable to get the id from the selected user.

Does anyone know how I can access the user id to the selected user within the removeUser method?

my html code:

<template id="user-template">

                {{ user.firstName }}

                yes

</template>

  <user @selected-user="setSelected"></user>

My vue component:

user: {
    template: '#user-template',
    data: function () {
        return {
            users: [],
        }
    },
    methods: {
        removeUser: function (user) {
            this.$http.delete('/user/', user).then(function (data) {
            this.users.$remove(user)
        });
    }
}

Body:
Try :

<a class=" collection-item avatar" v-for="(user, index) in users"
   :key="user" v-on:click="userClicked(user, index, $event)">

user: {
    template: '#user-template',
    data: function () {
        return {
            users: [],
            userSelected: { id: -1, index: -1 }
        }
    },
    methods: {
        userClicked: function (user, index, event) {
            this.userSelected.id = user.id;//If user has an id property
            this.userSelected.index = index;
        });
        removeUser: function () {
            if( this.userSelected.id > -1 ) {
                this.$http.delete('/user/' + this.userSelected.id).then(function (data) {
                this.users.splice(this.userSelected.index, 1);
                this.userSelected.id = -1;
                this.userSelected.index = -1;
            }
        });
    }
}

And you can disable remove button if no user selected :

<div :disabled="userSelected.id === -1" id="removeUser" class="modal">
  <div class="modal-footer">
  <a class=" modal-action modal-close btn-flat" v-on:click="removeUser">yes</a>
  </div>
</div>

Or if you don't want to use index to remove the user in the users array, you can use the id :

methods: {
   removeUserWithId: function( id ) {
       for( var i = 0, length = this.users.length; i < length; i++ ) {
           if( this.users[i].id === id ) {
              this.users.splice(i, 1);
              return;
          }
      }
   }
}

Note :

key is required in v-for since Vue 2.2.0+ link

$remove is deprecated : link


问:
Printing pointer's address in C
I'm reproducing printf from scrap and I need to store pointers address into a string then print it, so first I cast void* into an unsigned int then itoa it to hexadecimal but the last three char are wrong.

```<code>int     main(void)
{
    char    str[] = "printf from scrap!";

    my_printf("MY_PRINTF:'%p'", (void*)str);
    printf("\n   PRINTF:'%p'\n\n", (void*)str);

    return (0);
}

int     conv_p(va_list args)
{
    void    *ptr;
    unsigned int        ptrint;

    ptr = va_arg(args, void*);
    ptrint = (unsigned int)&ptr;
    my_putstr("0x7fff");
    my_putstr(my_itoa_base_uint(ptrint, 16));

    return (1);
}
</code>```

Output:

```<code>MY_PRINTF:'0x7fff505247b0'
   PRINTF:'0x7fff50524a20'
</code>```

As you can see the last three char are wrong, is there any documentation about that?

答:
In the second case, you're converting the address of the variable ptr to an int, rather than its value (the pointer you're interested in).

Replacing (unsigned int)&ptr; with (unsigned int)ptr; will give you consistent values.

And an additional aside: there's no guarantee unsigned int is large enough to represent the pointer value: you should use intptr_t or uintptr_t from <stdint.h>.

Title: Printing pointer's address in C

Body:
I'm reproducing printf from scrap and I need to store pointers address into a string then print it, so first I cast void* into an unsigned int then itoa it to hexadecimal but the last three char are wrong.

int     main(void)
{
    char    str[] = "printf from scrap!";

    my_printf("MY_PRINTF:'%p'", (void*)str);
    printf("\n   PRINTF:'%p'\n\n", (void*)str);

    return (0);
}

int     conv_p(va_list args)
{
    void    *ptr;
    unsigned int        ptrint;

    ptr = va_arg(args, void*);
    ptrint = (unsigned int)&ptr;
    my_putstr("0x7fff");
    my_putstr(my_itoa_base_uint(ptrint, 16));

    return (1);
}

Output:

MY_PRINTF:'0x7fff505247b0'
   PRINTF:'0x7fff50524a20'

As you can see the last three char are wrong, is there any documentation about that?


问:
How to split text per paragraph based on length?
Hi I am using RedCloth, Rails 3.

Currently I splitling a long text based based on string "-BREAK-".
How do I split text based on character length without splitting in the middle of a sentence.

E.g.,

```<code>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas at purus eu nisl consequat mattis. Morbi pretium eros eget erat ornare elementum.

Vivamus in dui sit amet tellus bibendum volutpat. Sed lorem sem, porttitor at mattis quis, volutpat sed quam. Vestibulum eu justo nec dui ullamcorper molestie. Sed eleifend malesuada mattis. Curabitur eleifend elit vitae justo feugiat iaculis. Etiam sed lectus eu quam suscipit fermentum id a sem.

Phasellus sed odio eu urna gravida venenatis venenatis non justo. Praesent tincidunt velit adipiscing ligula pretium commodo. Cras blandit, nibh ac sagittis egestas, enim odio rutrum metus, vel hendrerit felis urna cursus odio. Maecenas elementum erat et arcu vulputate eu fermentum orci semper. Proin luctus purus sit amet nibh blandit cursus.
</code>```

That will be comprise one page. It's about 794 characters.

答:
First you should split your text to single sentences.

Here's a simple, far-from-perfect way for doing this (I'm sure you could find plenty of more complete patterns elsewhere):

```<code>'Gsda asd. Gasd sasd. Tfed fdd.'.scan(/(.+?\.) ?/).map(&:first)
#=> ["Gsda asd.", "Gasd sasd.", "Tfed fdd."]
</code>```

Then, you should join these sentences, keeping an eye of the paragraph length. You can use something like this:

```<code># using words as units, but sentences are just the same:
s = ['foo', 'bar', 'beef', 'baz', 'hello', 'chunky', 'bacon']
LEN = 7 # minimum length of a paragraph
s.inject([]){|a,i|
  if !a.last || a.last.length > LEN
    a << i
  else
    a.last << " #{i}"
  end
  a
}
#=> ["foo bar beef", "baz hello", "chunky bacon"]
</code>```

Body:
Hi I am using RedCloth, Rails 3.

Currently I splitling a long text based based on string "-BREAK-".
How do I split text based on character length without splitting in the middle of a sentence.

E.g.,

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas at purus eu nisl consequat mattis. Morbi pretium eros eget erat ornare elementum.

Vivamus in dui sit amet tellus bibendum volutpat. Sed lorem sem, porttitor at mattis quis, volutpat sed quam. Vestibulum eu justo nec dui ullamcorper molestie. Sed eleifend malesuada mattis. Curabitur eleifend elit vitae justo feugiat iaculis. Etiam sed lectus eu quam suscipit fermentum id a sem.

Phasellus sed odio eu urna gravida venenatis venenatis non justo. Praesent tincidunt velit adipiscing ligula pretium commodo. Cras blandit, nibh ac sagittis egestas, enim odio rutrum metus, vel hendrerit felis urna cursus odio. Maecenas elementum erat et arcu vulputate eu fermentum orci semper. Proin luctus purus sit amet nibh blandit cursus.

That will be comprise one page. It's about 794 characters.

Body:
First you should split your text to single sentences.

Here's a simple, far-from-perfect way for doing this (I'm sure you could find plenty of more complete patterns elsewhere):

'Gsda asd. Gasd sasd. Tfed fdd.'.scan(/(.+?\.) ?/).map(&:first)
#=> ["Gsda asd.", "Gasd sasd.", "Tfed fdd."]

Then, you should join these sentences, keeping an eye of the paragraph length. You can use something like this:

# using words as units, but sentences are just the same:
s = ['foo', 'bar', 'beef', 'baz', 'hello', 'chunky', 'bacon']
LEN = 7 # minimum length of a paragraph
s.inject([]){|a,i|
  if !a.last || a.last.length > LEN
    a << i
  else
    a.last << " #{i}"
  end
  a
}
#=> ["foo bar beef", "baz hello", "chunky bacon"]


问:
How to stream a generated PDF file to a reader inside a DIV and not the browser?
I have the following code that after a PDF is generated submitting a query to SQL will display in browser. But I am looking is to display the file in a PDF viewer in the page and not using the browser reader. The viewer is inside a DIV. You can see the example shown in the image attached, which I run as test to show the file from the local system and not streaming. This function Response.BinaryWrite(bytes); sends the generated PDF to the browser viewer. How can I do for it to display in the viewer inside the DIV instead?

```<code>string reportLabel = lbReports.Text;

document.Add(table);
document.Close();
byte[] bytes = memoryStream.ToArray();

Response.Clear();
Response.AddHeader("Content-Disposition", "inline");

Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
</code>```

This is the code that should show the generated PDF file in the DIV:

```<code>string embed = "<object data=\"{0}\" type=\"application/pdf\" width=\"698px\" height=\"450px\">";
embed += "If you are unable to view file, you can download from <a href = \"{0}\">here</a>";
embed += " or download <a target = \"_blank\" href = \"http://get.adobe.com/reader/\">Adobe PDF Reader</a> to view the file.";
embed += "</object>";
ltEmbed.Text = string.Format(embed, ("blabla.pdf")); /*it shows this PDF as local file just for test*/
memoryStream.Close();
this.Context.ApplicationInstance.CompleteRequest();
</code>```

Image here: sample

The idea is to have the file generated temporarily and the user will decide if saving it or not. I have tried other options, but none seems to work, especially if it is inside a DIV. In other words, I am looking to display the dynamic PDF file using ltEmbed.Text = string.Format(embed, ...);

答:
After long research, I was suggested some workaround, so here I share this link with the solution, that to me it works perfect.

How to stream a generated PDF file to a reader inside a DIV and not the browser

Body:
I have the following code that after a PDF is generated submitting a query to SQL will display in browser. But I am looking is to display the file in a PDF viewer in the page and not using the browser reader. The viewer is inside a DIV. You can see the example shown in the image attached, which I run as test to show the file from the local system and not streaming. This function Response.BinaryWrite(bytes); sends the generated PDF to the browser viewer. How can I do for it to display in the viewer inside the DIV instead?

string reportLabel = lbReports.Text;

document.Add(table);
document.Close();
byte[] bytes = memoryStream.ToArray();

Response.Clear();
Response.AddHeader("Content-Disposition", "inline");

Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);

This is the code that should show the generated PDF file in the DIV:

string embed = "<object data=\"{0}\" type=\"application/pdf\" width=\"698px\" height=\"450px\">";
embed += "If you are unable to view file, you can download from here";
embed += " or download Adobe PDF Reader to view the file.";
embed += "</object>";
ltEmbed.Text = string.Format(embed, ("blabla.pdf")); /*it shows this PDF as local file just for test*/
memoryStream.Close();
this.Context.ApplicationInstance.CompleteRequest();

Image here: sample

The idea is to have the file generated temporarily and the user will decide if saving it or not. I have tried other options, but none seems to work, especially if it is inside a DIV. In other words, I am looking to display the dynamic PDF file using ltEmbed.Text = string.Format(embed, ...);


问:
Extracting values from listbox
I created a UserForm in VBA with 2 ListBoxes.

What I want to do is extract values from the right ListBox (and keep them in temp) and delete every row in another sheet which contains these names.

Writing a code to delete rows is not an issues. I have no clue how to use these selected items in another VBA module. Any ideas?

答: You can save them in a Collection, and then use that Collection as argument in other Procedure.</p>

Title: Extracting values from listbox


问:
How to hide Caution: Changing any part of an object name could break scripts and stored procedures
In my database I am renaming a table. I tried to rename it by using

```<code>exec sp_rename Student,Students
</code>```

but I got the message:

Caution: Changing any part of an object name could break scripts and stored procedures.

How can I avoid getting this message?

答:
Unfortunately, this message cannot be suppressed.*

There was a Microsoft Connect ticket submitted by our very own Aaron Bertrand, but it was closed as won't fix.

Keep in mind that this message isn't an error - it's not even a warning - it's just a cautionary message saying, "Be careful."

*Okay, it can be suppressed, but it involves modifying the source code of sp_rename, which is not recommended.

Body:
In my database I am renaming a table. I tried to rename it by using

exec sp_rename Student,Students

but I got the message:

Caution: Changing any part of an object name could break scripts and stored procedures.

How can I avoid getting this message?


问:
define a function alias in VBA, possible?
I am using VBA behind MS Access
Say I have global methods foo1 and foo2 that gets the same arguments but do different things.
I know that in C++ I can assign a function an alias. Something like:
instead of:

```<code>If (term) then
   foo1 arg1, arg2, arg3
else
   foo2 arg1, arg2, arg3
End If
</code>```

I want to write:

```<code>Var new_func = Iff (term, foo1,foo2)
new_func arg1, arg2, arg3
</code>```

Can I do this on vba?

答:
Try this:

http://oreilly.com/catalog/vbanut/chapter/booklet.html#sect5

The AddressOf operator.

However as noted on http://discuss.fogcreek.com/joelonsoftware4/default.asp?cmd=show&ixPost=140196&ixReplies=19

"AddressOf is really a cheap hack.  VB doesn't support first-class function values like most other languages, but with AddressOf is supports it halfway.  Yes you can get the address of a function but you can't invoke a function by address (unless that function is a message processor and only then with the Win32 function CallWndProc).  All you can do to simulate this behavior is take generic dispatch objects instead of function pointers and ensure that the objects support the necessary functions. "

Unfortunately, that's about as close as you'll get, I believe.

For more info on AddressOf, see here.

Body:
I am using VBA behind MS Access
Say I have global methods foo1 and foo2 that gets the same arguments but do different things.
I know that in C++ I can assign a function an alias. Something like:
instead of:

If (term) then
   foo1 arg1, arg2, arg3
else
   foo2 arg1, arg2, arg3
End If

I want to write:

Var new_func = Iff (term, foo1,foo2)
new_func arg1, arg2, arg3

Can I do this on vba?


问:
Is destructured es6 export a valid syntax?
I am wondering about the following syntax:

```<code>export const { foo, bar } = {
  foo: 123,
  bar: 234,
}
</code>```

I can't find it described in any es2015 documentation, but it is supported by Babel's es2015 preset.

Is this syntax truly standard, as babel seems to think? Out of standard?

答:
There are several things going on here.

```<code>export const { foo, bar } = {
  foo: 123,
  bar: 234,
};
</code>```

is equivalent to

```<code>const { foo, bar } = {
  foo: 123,
  bar: 234,
};

// Export all the names in the variable declaration.
export { foo as foo, bar as bar };
</code>```

export can be used on many declarations and will export whatever variables are created by that declaration.

Then this is simplified further if you don't understand destructuring, it is essentially

```<code>const _tmp = {
  foo: 123,
  bar: 234,
};
const foo = _tmp.foo,
      bar = _tmp.bar;

// Export all the names in the variable declaration.
export { foo as foo, bar as bar };
</code>```

Body:
I am wondering about the following syntax:

export const { foo, bar } = {
  foo: 123,
  bar: 234,
}

I can't find it described in any es2015 documentation, but it is supported by Babel's es2015 preset.

Is this syntax truly standard, as babel seems to think? Out of standard?

Body:
There are several things going on here.

export const { foo, bar } = {
  foo: 123,
  bar: 234,
};

is equivalent to

const { foo, bar } = {
  foo: 123,
  bar: 234,
};

// Export all the names in the variable declaration.
export { foo as foo, bar as bar };

export can be used on many declarations and will export whatever variables are created by that declaration.

Then this is simplified further if you don't understand destructuring, it is essentially

const _tmp = {
  foo: 123,
  bar: 234,
};
const foo = _tmp.foo,
      bar = _tmp.bar;

// Export all the names in the variable declaration.
export { foo as foo, bar as bar };


问:
How one can store user's settings in Calibre's plugin?
I am developing a Calibre's plugin and I want to store user settings (e.g. if the plugin should make a post-import conversion from one format to another - in my
case: pdf to djvu).

How can I store user settings? Does Calibre have a build-in method to do this?

For example I have a dictionary prefs_org_dict with keys and values representing preferences set by an user. How can I store this data reliably and read it later?

答:
The method suggested by the manual is to create the JSONConfig object and store user preferences in it.

Basically just:

```<code>import os
from calibre.utils.config import JSONConfig

prefs = JSONConfig(os.path('plugins', 'PLUGINNAME'))
# JSONConfig inherits after Dict so use it as dictionary

for key, val in prefs_org_dict.iteritems():
    prefs[key] = val
prefs.commit() # explanation in 3rd section of this post
</code>```

But this method has some caveats:

Name of the settings file. Paraphrasing manual:

Remember that this name (i.e. 'plugins/PLUGINNAME') is also in a global namespace, so make it as unique as possible. You should always prefix your config file name with plugins/, so as to ensure you don't accidentally clobber a calibre config file.

After you save anything to this object you can see your PLUGINNAME.json file inside Calibre's plugin's config folder (for Windows: %APPDATA%\calibre\plugins) (you can get this path programmatically using: from calibre.utils.config import config_dir and appending /plugins).

Default settings.

prefs.defaults is a dictionary which value is returned if given key doesn't exist in your prefs object. So you can create some default values for your plugin's settings, e.g.:

```<code>prefs.defaults['postimport'] = False
</code>```

The main problem is when you trying to use other dict methods like .values(), .items() or .iteritems() they return "real" prefs, not defaults, i.e. for our example, if prefs['postimport'] was not further defined:

```<code>>>> prefs.defaults['postimport']
False
>>> prefs.defaults.items()
[('postimport', False)]
>>> prefs['postimport']
False
>>> prefs.items()
[]
</code>```

Committing nested dict.

If you want to use JSONConfig object as real .json storage you probably want to use nested dictionaries. For example:

```<code>prefs['pdf'] = {}
prefs['pdf']['convert'] = True
</code>```

But if you set (or delete) value to nested dictionary prefs['pdf'] it will not be saved to .json file. You have to:

```<code>prefs.commit()
</code>```

to save data to file after setting them to nested dict.

Constraints of JSON format.

A few of Python features cannot be translated to JSON format, e.g. JSON has not tuples, so json.dumps translates tuples to arrays. Also in Python you can have an every hashable object (e.g. tuple, or frozenset) as a key. JSON accepts only strings.

Body:
The method suggested by the manual is to create the JSONConfig object and store user preferences in it.

Basically just:

import os
from calibre.utils.config import JSONConfig

prefs = JSONConfig(os.path('plugins', 'PLUGINNAME'))
# JSONConfig inherits after Dict so use it as dictionary

for key, val in prefs_org_dict.iteritems():
    prefs[key] = val
prefs.commit() # explanation in 3rd section of this post

But this method has some caveats:

Name of the settings file. Paraphrasing manual:

Remember that this name (i.e. 'plugins/PLUGINNAME') is also in a global namespace, so make it as unique as possible. You should always prefix your config file name with plugins/, so as to ensure you don't accidentally clobber a calibre config file.

After you save anything to this object you can see your PLUGINNAME.json file inside Calibre's plugin's config folder (for Windows: %APPDATA%\calibre\plugins) (you can get this path programmatically using: from calibre.utils.config import config_dir and appending /plugins).

Default settings.

prefs.defaults is a dictionary which value is returned if given key doesn't exist in your prefs object. So you can create some default values for your plugin's settings, e.g.:

prefs.defaults['postimport'] = False

The main problem is when you trying to use other dict methods like .values(), .items() or .iteritems() they return "real" prefs, not defaults, i.e. for our example, if prefs['postimport'] was not further defined:

>>> prefs.defaults['postimport']
False
>>> prefs.defaults.items()
[('postimport', False)]
>>> prefs['postimport']
False
>>> prefs.items()
[]

Committing nested dict.

If you want to use JSONConfig object as real .json storage you probably want to use nested dictionaries. For example:

prefs['pdf'] = {}
prefs['pdf']['convert'] = True

But if you set (or delete) value to nested dictionary prefs['pdf'] it will not be saved to .json file. You have to:

prefs.commit()

to save data to file after setting them to nested dict.

Constraints of JSON format.

A few of Python features cannot be translated to JSON format, e.g. JSON has not tuples, so json.dumps translates tuples to arrays. Also in Python you can have an every hashable object (e.g. tuple, or frozenset) as a key. JSON accepts only strings.


问:
Multiple heroku accounts
I'm having trouble when working with multiple Heroku accounts on my computer.

The thing is that it's worked great before by switching accounts with the heroku gem. But now (even though I've generated new SSH keys) it wont work.

When I do a git push heroku master it just says:

my@email.com not authorized to access my_app_name

Does anyone have any advice on how I could solve this?

答: I used nano .git/config then replaced value of url of remote "heroku" with heroku.com > apps > settings > Reveal config vars > Heroku Git URL</p>

Title: Multiple heroku accounts


问:
compare colums of two table if table1.row > table2.row
TABLE1

```<code>mybb_users
(id gcoins)
 1    150
 2    10
</code>```

TABLE2

```<code>servercoins
(id prezzo)
 1    150
 2    70
</code>```

I should compare this table for control if users have enough "gcoins" for buy "prezzo". If "gcoins" > "prezzo" it's ok but "gcoins" < "prezzo" print an alert with "You don't have enough gocins for this"

答:
Try this...

```<code>SELECT
   CASE WHEN ((SELECT gcoins
               FROM TABLA1
               WHERE  TABLA1.id = <ID_USER>
                      AND gcoins >0) < ( SELECT prezzo
                                          FROM TABLA2
                                          WHERE TABLA2.id = <ID_PREZZO>))
        THEN 'You dont have enough gocins for this'
        ELSE 'something else...'
   END
</code>```

<ID_USER> and <ID_PREZZO> replace with your variables.

HERE you can test!

Hope this help!

Body:
TABLE1

mybb_users
(id gcoins)
 1    150
 2    10

TABLE2

servercoins
(id prezzo)
 1    150
 2    70

I should compare this table for control if users have enough "gcoins" for buy "prezzo". If "gcoins" > "prezzo" it's ok but "gcoins" < "prezzo" print an alert with "You don't have enough gocins for this"

Body:
Try this...

SELECT
   CASE WHEN ((SELECT gcoins
               FROM TABLA1
               WHERE  TABLA1.id = <ID_USER>
                      AND gcoins >0) < ( SELECT prezzo
                                          FROM TABLA2
                                          WHERE TABLA2.id = <ID_PREZZO>))
        THEN 'You dont have enough gocins for this'
        ELSE 'something else...'
   END

<ID_USER> and <ID_PREZZO> replace with your variables.

HERE you can test!

Hope this help!


问:
How to Change Global Variable With Function?
I am trying to create a "Choose your own adventure" style game in Python where the user inserts various numbers that correspond with an action that will dictate what part of the story is told next. When the user inserts an invalid option, nothing I tried to make a function to simplify the endless if/else statements but I am having difficulties. I have a "step" variable that changes and leads to different circumstances and my function successfully changes the step variable but then the if/else statements don't trigger. Any help would be greatly appreciated!</p>

```<code>step = 7

def stepchange():
  global step
  b = step
  while step == b:
    a = input()
    if a == 1:
      global step
      step = b + .1
    if a == 2:
      global step
      step = b + .2
    if a ==3:
      global step
      step = b + .3

global step
if step == 7.1:
   print("Step 7.1")

global step
if step == 7.2:
    print("Step 7.2")

global step
if step ==7.3:
    print("Step 7.3")
</code>```

答:
You don't call the function, so no step changes happen. After calling, you may still have problems with later compares. float  is actually a binary fraction that is estimated, but not quite equal, in decimal. So, for instance, 7.1 is really 7.099999999999999644728632119949907064437866210937500000. Since you are doing some math on those numbers you may find that rounding errors cause them to be a little different so the compare fails.

You can trim out extra unneeded global statements and use the decimal module:

```<code>from decimal import Decimal

step = Decimal('7')

def stepchange():
  global step
  b = step
  while step == b:
    a = Decimal(input())
    if a == 1:
      step = b + Decimal('.1')
    if a == 2:
      step = b + Decimal('.2')
    if a ==3:
      step = b + Decimal('.3')

stepchange()

if step == Decimal('7.1'):
   print("Step 7.1")
elif step == Decimal('7.2'):
    print("Step 7.2")
if step == Decimal('7.3'):
    print("Step 7.3")
</code>```

I don't know exactly what step is supposed to be, but if you are thinking step plus substep, a list may be a better choice:

```<code>step = [7, 0]

def stepchange():
  global step
  while True:
    a = int(input())
    if a in (1, 2, 3):
      step[1] = a
      break

stepchange()

if step == [7, 1]:
   print("Step 7.1")
elif step == [7, 2]:
    print("Step 7.2")
if step == [7, 3]:
    print("Step 7.3")
</code>```

Body:
I am trying to create a "Choose your own adventure" style game in Python where the user inserts various numbers that correspond with an action that will dictate what part of the story is told next. When the user inserts an invalid option, nothing I tried to make a function to simplify the endless if/else statements but I am having difficulties. I have a "step" variable that changes and leads to different circumstances and my function successfully changes the step variable but then the if/else statements don't trigger. Any help would be greatly appreciated!

step = 7

def stepchange():
  global step
  b = step
  while step == b:
    a = input()
    if a == 1:
      global step
      step = b + .1
    if a == 2:
      global step
      step = b + .2
    if a ==3:
      global step
      step = b + .3

global step
if step == 7.1:
   print("Step 7.1")

global step
if step == 7.2:
    print("Step 7.2")

global step
if step ==7.3:
    print("Step 7.3")

Body:
You don't call the function, so no step changes happen. After calling, you may still have problems with later compares. float  is actually a binary fraction that is estimated, but not quite equal, in decimal. So, for instance, 7.1 is really 7.099999999999999644728632119949907064437866210937500000. Since you are doing some math on those numbers you may find that rounding errors cause them to be a little different so the compare fails.

You can trim out extra unneeded global statements and use the decimal module:

from decimal import Decimal

step = Decimal('7')

def stepchange():
  global step
  b = step
  while step == b:
    a = Decimal(input())
    if a == 1:
      step = b + Decimal('.1')
    if a == 2:
      step = b + Decimal('.2')
    if a ==3:
      step = b + Decimal('.3')

stepchange()

if step == Decimal('7.1'):
   print("Step 7.1")
elif step == Decimal('7.2'):
    print("Step 7.2")
if step == Decimal('7.3'):
    print("Step 7.3")

I don't know exactly what step is supposed to be, but if you are thinking step plus substep, a list may be a better choice:

step = [7, 0]

def stepchange():
  global step
  while True:
    a = int(input())
    if a in (1, 2, 3):
      step[1] = a
      break

stepchange()

if step == [7, 1]:
   print("Step 7.1")
elif step == [7, 2]:
    print("Step 7.2")
if step == [7, 3]:
    print("Step 7.3")


问:
Fail Safe Fail Fast Example
```<code>    ConcurrentHashMap<String, Integer> hm = new ConcurrentHashMap<>();
    hm.put("1", 1);
    hm.put("2", 2);
    hm.put("3", 3);
    Iterator<String> itr = hm.keySet().iterator();
    while(itr.hasNext()){
        String key = itr.next();
        System.out.println(key + " : " + hm.get(key));
        hm.put("4", 4);
    }
    System.out.println(hm);

    ConcurrentHashMap<String, Integer> hm1 = new ConcurrentHashMap<>();
    hm1.put("One", 1);
    hm1.put("Two", 2);
    hm1.put("Three", 3);
    Iterator<String> itr1 = hm1.keySet().iterator();
    while(itr1.hasNext()){
        String key = itr1.next();
        System.out.println(key + " : " + hm1.get(key));
        hm1.put("Four", 4);
    }
    System.out.println(hm1);
</code>```

Output:
1 : 1
2 : 2
3 : 3
4 : 4
{1=1, 2=2, 3=3, 4=4}
One : 1
Two : 2
Three : 3
{One=1, Four=4, Two=2, Three=3}

Why so?

答:
The interator() call has this documentation:
https://docs.oracle.com/javase/8/docs/api/java/util/Set.html#iterator--

"The elements are returned in no particular order"

hm.put("4", 4)

Adds it to the end of the list (by chance?)

hm1.put("Four", 4)

Adds it between One and Four.  However the next() operator is evidently already past this point in the Iterator, so the next call to next() is already at Two=2.

Answer:

Changing an unordered list as you're iterating over the same list is not a good idea.

Title: Fail Safe Fail Fast Example

Body:
    ConcurrentHashMap<String, Integer> hm = new ConcurrentHashMap<>();
    hm.put("1", 1);
    hm.put("2", 2);
    hm.put("3", 3);
    Iterator<String> itr = hm.keySet().iterator();
    while(itr.hasNext()){
        String key = itr.next();
        System.out.println(key + " : " + hm.get(key));
        hm.put("4", 4);
    }
    System.out.println(hm);

    ConcurrentHashMap<String, Integer> hm1 = new ConcurrentHashMap<>();
    hm1.put("One", 1);
    hm1.put("Two", 2);
    hm1.put("Three", 3);
    Iterator<String> itr1 = hm1.keySet().iterator();
    while(itr1.hasNext()){
        String key = itr1.next();
        System.out.println(key + " : " + hm1.get(key));
        hm1.put("Four", 4);
    }
    System.out.println(hm1);

Output:
1 : 1
2 : 2
3 : 3
4 : 4
{1=1, 2=2, 3=3, 4=4}
One : 1
Two : 2
Three : 3
{One=1, Four=4, Two=2, Three=3}

Why so?


问:
Swift ISO 20022 open source parser
I am working on project using Java and I'm looking for open source library to parse swift messages: ISO 15022 and 20022.
for 15022 I already find a solution which is Prowidesoftware, but for 20022 I didn't find anything.
any ideas?
thanks.</p>

答: We have searched a lot for this about a year ago, but could not find, so we have made our own parser using XPath.It is a tiresome job, but will be helpful in understanding the structure more closely.</p>

Title: Swift ISO 20022 open source parser


问:
Javascript method always returns same value
I have two methods in my class. One method randomizes values, another one returns those values in a string that represents CSS color. Yet after randomization it still returns same string all the time, even though values in created object are changed. Can you please explain why?

Here's jsfiddle: https://jsfiddle.net/wpem1j9e/

```<code>function Color(r, g, b) {
    this.r = r;
    this.g = g;
    this.b = b;
    this.randomize = function(){
        this.r = Math.floor(Math.random() * 100);
        this.g = Math.floor(Math.random() * 100);
        this.b = Math.floor(Math.random() * 100);
        return this;
    }
    this.toString = function(){
        var cssColor = "rgb(" + r + "%," + g + "%," + b + "%)";
        return cssColor;
    }
}
var color1 = new Color (1, 1, 1);
color1.randomize().toString(); // still returns "rgb(1%,1%,1%)";
</code>```

答:
```<code>function Color(r, g, b) {
this.r = r;
this.g = g;
this.b = b;
    this.randomize = function(){
        this.r = Math.floor(Math.random() * 100);
        this.g = Math.floor(Math.random() * 100);
        this.b = Math.floor(Math.random() * 100);
        return this;
    }

    this.toString = function(){
    var cssColor = "rgb(" + this.r + "%," + this.g + "%," + this.b + "%)"; //new
        return cssColor;
    }
}
var color1 = new Color (1, 1, 1);
output = function () {
    var outputDiv = document.getElementById("output");
    outputDiv.innerHTML = outputDiv.innerHTML + "<br>" + color1.r + "   " + color1.g + "   " + "   " + color1.b + "<br>" + color1.toString() + "<br>";
}
output();
document.getElementById("input").onclick = function(){
    color1.randomize();
  output();
};
</code>```

Body:
I have two methods in my class. One method randomizes values, another one returns those values in a string that represents CSS color. Yet after randomization it still returns same string all the time, even though values in created object are changed. Can you please explain why?

Here's jsfiddle: https://jsfiddle.net/wpem1j9e/

function Color(r, g, b) {
    this.r = r;
    this.g = g;
    this.b = b;
    this.randomize = function(){
        this.r = Math.floor(Math.random() * 100);
        this.g = Math.floor(Math.random() * 100);
        this.b = Math.floor(Math.random() * 100);
        return this;
    }
    this.toString = function(){
        var cssColor = "rgb(" + r + "%," + g + "%," + b + "%)";
        return cssColor;
    }
}
var color1 = new Color (1, 1, 1);
color1.randomize().toString(); // still returns "rgb(1%,1%,1%)";


问:
Suitescript - Is there a way to check to see if the current record has an attachment?
Is there a way to check to see if the current record has an attachment through Suitescript? I know you can do this through a search. However, I need to check if the current record on create has an attachment before saving.

答:
As long as you are attaching files using the built-in file attachments sublist, you can call

```<code>nlapiGetLineItemCount('mediaitem');
</code>```

to see how many files have been attached to a record. This works on both client-side and server-side SuiteScript and for custom and standard NetSuite records.

Body:
As long as you are attaching files using the built-in file attachments sublist, you can call

nlapiGetLineItemCount('mediaitem');

to see how many files have been attached to a record. This works on both client-side and server-side SuiteScript and for custom and standard NetSuite records.


问:
ASP.net MVC Tempdata getting DataSet's values out of it
Hey all I am new to the MVC world and was wanting to get a few values from the TempData that I made that houses 3 DataSet's inside it.

The values that are inside the TempData are these:

then selecting tTrip then rows then Results View:

finally seeing the DataSet values for tTrip:

I populate the TempData like so (simplify):

```<code>allData.Merge("tEvents"); //Gathers data and places it into tEvents
allData.Merge("tTrip"); //Gathers data and places it into tTrip
allData.Merge("tExternalTrainingMain"); //Gathers data and places it into tExternalTrainingMain

TempData["jsonData"] = allData;
</code>```

I've tried:

string blah = TempData["jsonData"][0]["somename"].toString();

string blah = TempData["jsonData"][0].somename.toString();

string blah = TempData["jsonData"][0][0].somename.toString();

string blah = TempData["jsonData"][0][0][0].toString();

But only get errors. What is the proper way of getting the dataset values out of the TempData array?

UPDATE for DavidG

答:
The indexed property that gives you the value from TempData returns a object of type object. You need to cast your value to the desired type. For example:

```<code>var myDataSet = TempData["jsonData"] as DataSet;
if(myDataSet != null)
{
    We have a dataset now!
    string blah = myDataSet.Tables[0]["somename"].toString();
}
</code>```

Body:
Hey all I am new to the MVC world and was wanting to get a few values from the TempData that I made that houses 3 DataSet's inside it.

The values that are inside the TempData are these:

then selecting tTrip then rows then Results View:

finally seeing the DataSet values for tTrip:

I populate the TempData like so (simplify):

allData.Merge("tEvents"); //Gathers data and places it into tEvents
allData.Merge("tTrip"); //Gathers data and places it into tTrip
allData.Merge("tExternalTrainingMain"); //Gathers data and places it into tExternalTrainingMain

TempData["jsonData"] = allData;

I've tried:

string blah = TempData["jsonData"][0]["somename"].toString();

string blah = TempData["jsonData"][0].somename.toString();

string blah = TempData["jsonData"][0][0].somename.toString();

string blah = TempData["jsonData"][0][0][0].toString();

But only get errors. What is the proper way of getting the dataset values out of the TempData array?

UPDATE for DavidG

Body:
The indexed property that gives you the value from TempData returns a object of type object. You need to cast your value to the desired type. For example:

var myDataSet = TempData["jsonData"] as DataSet;
if(myDataSet != null)
{
    We have a dataset now!
    string blah = myDataSet.Tables[0]["somename"].toString();
}


问:
on_load method doesn't work as expected
Here is simple test for on_load method.

import sublime_plugin

class OnLoadTest(sublime_plugin.EventListener):
    def on_load(self, view):
        print("Tested")
```

If I open some file, then close this file (Ctrl-W), and then reopen it (Ctrl-Shift-T), the plugin works fine.

However, if I open some file, then close the editor, and then reopen the editor, the plugin will not be launched. (Despite that the file was successfully reopened, thanks to "hot_exit": true and "remember_open_files": true in my preferences).

Is it some bug or just my lack of skills?

I use ST3, build 3126.

答:
Whether this is a bug or a conscious design decision has been debated quite a bit over the years, but is fairly well known.

When restoring from the previous session, all open files are put back to the state they were in, which includes things such as the selected text, unsaved changes, modified settings and so on. Sublime starts up and performs those tasks before or while it's actively loading in plugin code in order to make startup as fast as possible.

If on_load is doing something that you need to be done again while coming back from a restored session, you can detect when your plugin is being loaded by defining a module level plugin_loaded() function, which Sublime will call once everything is loaded. In it you can scan through all of the windows and files and take some action.

An example might be:

import sublime
import sublime_plugin
import os

def plugin_loaded ():
    # Show project in all views of all windows
    for window in sublime.windows ():
        for view in window.views ():
            show_project (view)

def show_project(view):
    # Sometimes a view is not associated with a window
    if view.window() is None:
        return

    # Is there a project file defined?
    project_file = view.window ().project_file_name ()
    if project_file is not None:
        # Get the project filename without path or extension
        project_name = os.path.splitext (os.path.basename (project_file))[0]
        view.set_status ("00ProjectName", "[" + project_name + "]")

# Display the current project name in the status bar
class ProjectInStatusbar(sublime_plugin.EventListener):
    # When you create a new empty file
    def on_new(self, view):
        show_project (view)

    # When you load an existing file
    def on_load(self, view):
        show_project (view)

    # When you use File > New view into file on an existing file
    def on_clone(self, view):
        show_project (view)
```

Title: on_load method doesn't work as expected

Body:
Here is simple test for on_load method.

import sublime_plugin

class OnLoadTest(sublime_plugin.EventListener):
    def on_load(self, view):
        print("Tested")

If I open some file, then close this file (Ctrl-W), and then reopen it (Ctrl-Shift-T), the plugin works fine.

However, if I open some file, then close the editor, and then reopen the editor, the plugin will not be launched. (Despite that the file was successfully reopened, thanks to "hot_exit": true and "remember_open_files": true in my preferences).

Is it some bug or just my lack of skills?

I use ST3, build 3126.


问:
Freeing a double pointer from a struct
I have a problem with my delete_table function. So i have 2 structs

```<code>struct _entry_ {
    int key;
    int data;
    struct _entry_* next;
    struct _entry_* prev;
};
typedef struct _entry_ entry;

struct _table_ {
    entry** entries;
    int size;
};
typedef struct _table_ table;
</code>```

I initialise my table with calloc.

```<code>void table_init(table* ht, int initial_size) {
    ht->entries = (entry**)calloc(initial_size, sizeof(entry*));
    if (ht->entries) {
        ht->size = initial_size;
    }
}
</code>```

Now my free function that i wrote

```<code>void table_destroy(htable* ht) {

    entry *el, *temp;
    int i;
    for(i = 0; i < ht->size; i++) {
      el = ht->entries[i];
      while(el != NULL){
        temp = el;
        el = el->next;
        free(temp);
      }
      free(ht->entries[i]);
    }
    free(ht); // <- don't know do i need this.
}
</code>```

When i test it with valgrind i got this error

```<code>==13560== Invalid free() / delete / delete[] / realloc()
==13560==    at 0x4C2BDEC: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==13560==    by 0x400783: htable_destroy (htable.c:46)
==13560==    by 0x400A24: main (main.c:25)
==13560==  Address 0xffefffae0 is on thread 1's stack
==13560==  in frame #2, created by main (main.c:7)
</code>```

Any help would be great, thank you for your time!

答:
```<code>void table_destroy(htable* ht) {

    entry *del;
    int i;
    for(i = 0; i < ht->size; i++) {
      while( (del = ht->entries[i]) ) {
        ht->entries[i] = del->next;
        free(del);
      }
    }
    free(ht->entries);
    free(ht);
}
</code>```

Title: Freeing a double pointer from a struct

Body:
I have a problem with my delete_table function. So i have 2 structs

struct _entry_ {
    int key;
    int data;
    struct _entry_* next;
    struct _entry_* prev;
};
typedef struct _entry_ entry;

struct _table_ {
    entry** entries;
    int size;
};
typedef struct _table_ table;

I initialise my table with calloc.

void table_init(table* ht, int initial_size) {
    ht->entries = (entry**)calloc(initial_size, sizeof(entry*));
    if (ht->entries) {
        ht->size = initial_size;
    }
}

Now my free function that i wrote

void table_destroy(htable* ht) {

    entry *el, *temp;
    int i;
    for(i = 0; i < ht->size; i++) {
      el = ht->entries[i];
      while(el != NULL){
        temp = el;
        el = el->next;
        free(temp);
      }
      free(ht->entries[i]);
    }
    free(ht); // <- don't know do i need this.
}

When i test it with valgrind i got this error

==13560== Invalid free() / delete / delete[] / realloc()
==13560==    at 0x4C2BDEC: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==13560==    by 0x400783: htable_destroy (htable.c:46)
==13560==    by 0x400A24: main (main.c:25)
==13560==  Address 0xffefffae0 is on thread 1's stack
==13560==  in frame #2, created by main (main.c:7)

Any help would be great, thank you for your time!


问:
How to add values from an array as an object in a mutable dictionary with objective-c?
I'm in the beginning stages of learning how to code, and I'm trying to figure out a problem.  I created an array with 4 objects in it, then created an empty mutable dictionary.  And now I have to add the values in my array as objects in my mutable dictionary, and I can't figure out how to do it.  This is what I have come up with that is coming back with errors, I know its just simple syntax but I can't find the answer online.

```<code>NSArray *shoeOrder = @[@"Charles Smith", @(9.5), @"loafer", @"brown"];

NSMutableDictionary *shoeOrderDict = [[NSMutableDictionary alloc] init];

[shoeOrderDict setObject: @[shoeOrder objectAtIndex: 0] forKey: @"customer"];
[shoeOrderDict setObject: @[shoeOrder objectAtIndex: 1] forKey: @"size"];
[shoeOrderDict setObject: @[shoeOrder objectAtIndex: 2] forKey: @"style"];
[shoeOrderDict setObject: @[shoeOrder objectAtIndex: 3] forKey: @"color"];
</code>```

Thank you for your help!

答:
When you ask a question like this where you've tried something and the compiler "is coming back with errors", you should generally show the errors. It helps us help you.

That said, the issue in this case is extraneous "@" characters in the following lines:

```<code>[shoeOrderDict setObject: @[shoeOrder objectAtIndex: 0] forKey: @"customer"];
[shoeOrderDict setObject: @[shoeOrder objectAtIndex: 1] forKey: @"size"];
[shoeOrderDict setObject: @[shoeOrder objectAtIndex: 2] forKey: @"style"];
[shoeOrderDict setObject: @[shoeOrder objectAtIndex: 3] forKey: @"color"];
</code>```

An expression like [shoeOrder objectAtIndex: 0] is a message-send expression. It's sending the message objectAtIndex: with parameter 0 to the object shoeOrder. The expression does not require and should not have a leading @.

So, your code should have been:

```<code>[shoeOrderDict setObject: [shoeOrder objectAtIndex: 0] forKey: @"customer"];
[shoeOrderDict setObject: [shoeOrder objectAtIndex: 1] forKey: @"size"];
[shoeOrderDict setObject: [shoeOrder objectAtIndex: 2] forKey: @"style"];
[shoeOrderDict setObject: [shoeOrder objectAtIndex: 3] forKey: @"color"];
</code>```

Body:
I'm in the beginning stages of learning how to code, and I'm trying to figure out a problem.  I created an array with 4 objects in it, then created an empty mutable dictionary.  And now I have to add the values in my array as objects in my mutable dictionary, and I can't figure out how to do it.  This is what I have come up with that is coming back with errors, I know its just simple syntax but I can't find the answer online.

NSArray *shoeOrder = @[@"Charles Smith", @(9.5), @"loafer", @"brown"];

NSMutableDictionary *shoeOrderDict = [[NSMutableDictionary alloc] init];

[shoeOrderDict setObject: @[shoeOrder objectAtIndex: 0] forKey: @"customer"];
[shoeOrderDict setObject: @[shoeOrder objectAtIndex: 1] forKey: @"size"];
[shoeOrderDict setObject: @[shoeOrder objectAtIndex: 2] forKey: @"style"];
[shoeOrderDict setObject: @[shoeOrder objectAtIndex: 3] forKey: @"color"];

Thank you for your help!

Body:
When you ask a question like this where you've tried something and the compiler "is coming back with errors", you should generally show the errors. It helps us help you.

That said, the issue in this case is extraneous "@" characters in the following lines:

[shoeOrderDict setObject: @[shoeOrder objectAtIndex: 0] forKey: @"customer"];
[shoeOrderDict setObject: @[shoeOrder objectAtIndex: 1] forKey: @"size"];
[shoeOrderDict setObject: @[shoeOrder objectAtIndex: 2] forKey: @"style"];
[shoeOrderDict setObject: @[shoeOrder objectAtIndex: 3] forKey: @"color"];

An expression like [shoeOrder objectAtIndex: 0] is a message-send expression. It's sending the message objectAtIndex: with parameter 0 to the object shoeOrder. The expression does not require and should not have a leading @.

So, your code should have been:

[shoeOrderDict setObject: [shoeOrder objectAtIndex: 0] forKey: @"customer"];
[shoeOrderDict setObject: [shoeOrder objectAtIndex: 1] forKey: @"size"];
[shoeOrderDict setObject: [shoeOrder objectAtIndex: 2] forKey: @"style"];
[shoeOrderDict setObject: [shoeOrder objectAtIndex: 3] forKey: @"color"];