问:
Send HTTP Request and properly ignore the Response in Javascript
Examples abound of methods to initiate a web (HTTP) request in Javascript. But, when I initiate a web request and the server return a blank response, Firefox at least throws an error:

XML Parsing Error: no root element found Location: http://example.com/service Line Number 1, Column 1: 1 service:1:1

I am using a function similar to:

```<code>function RequestGET(url) {
    var req = new XMLHttpRequest();
    req.open("GET", url, true);
    req.send();
}
</code>```

In this particular case, the server has nothing to return and I expect that. So, how do I structure my client-side script to handle this response without throwing this error? Or, more generally, how can I handle a non-XML response properly?

答:
Or, more generally, how can I handle a non-XML response properly?

I would give the Try...Catch a go.

```<code>try {
  // parse response data
}
catch(error){
 // handle parsing exception
}
finally{
 // buy me a beer
}
</code>```

Perhaps this would work, but around which block would I wrap the exception handling?

```<code>function RequestGET(url) {
    var req = new XMLHttpRequest();

    // set callback for xhr state change events
    xhr.onreadystatechange  = function() {

        if (req.readyState === 4) {
            // request is completed

            if(req.status === 200) {
                // The request succeed!
                try {
                    // parse response data
                    var parser = new DOMParser();
                    var xmlDoc = parser.parseFromString(req.responseText,"text/xml");

                    // here your xml document object...
                    // > xmlDoc
                }
                catch(error){
                 // handle parsing exception
                }
                finally{
                 // buy me a beer
                }

            } else {
                // The request did not succeed!
            }
        }
    }

    req.open("GET", url, true);
    req.send();
}
</code>```

Body:
Examples abound of methods to initiate a web (HTTP) request in Javascript. But, when I initiate a web request and the server return a blank response, Firefox at least throws an error:

XML Parsing Error: no root element found Location: http://example.com/service Line Number 1, Column 1: 1 service:1:1

I am using a function similar to:

function RequestGET(url) {
    var req = new XMLHttpRequest();
    req.open("GET", url, true);
    req.send();
}

In this particular case, the server has nothing to return and I expect that. So, how do I structure my client-side script to handle this response without throwing this error? Or, more generally, how can I handle a non-XML response properly?

Body:
Or, more generally, how can I handle a non-XML response properly?

I would give the Try...Catch a go.

try {
  // parse response data
}
catch(error){
 // handle parsing exception
}
finally{
 // buy me a beer
}

Perhaps this would work, but around which block would I wrap the exception handling?

function RequestGET(url) {
    var req = new XMLHttpRequest();

    // set callback for xhr state change events
    xhr.onreadystatechange  = function() {

        if (req.readyState === 4) {
            // request is completed

            if(req.status === 200) {
                // The request succeed!
                try {
                    // parse response data
                    var parser = new DOMParser();
                    var xmlDoc = parser.parseFromString(req.responseText,"text/xml");

                    // here your xml document object...
                    // > xmlDoc
                }
                catch(error){
                 // handle parsing exception
                }
                finally{
                 // buy me a beer
                }

            } else {
                // The request did not succeed!
            }
        }
    }

    req.open("GET", url, true);
    req.send();
}


来源: stackexchange

问:
Access Polymer paper-toast outside the app class
I have a project, where I need to access a paper toast with the id toastNewVersion from outside the ES6 app class which extends the polymer Element

```<code>class WascApp extends Polymer.Element {
     _buttonOnTap() {
     this.$.toastNewVersion.open();
}
</code>```

This code works just finde, as expected. But I want to open the toast from outside this class, in a basic

答:
I actually found a way myself.

This opens a regular paper-toast from the index.html file, if the toast is inside the app-elements shadow-root:

document.querySelector('app-element').shadowRoot.querySelector('#toastNewVersion').open();

ContentLicense: CC BY-SA 3.0

Body:
I have a project, where I need to access a paper toast with the id toastNewVersion from outside the ES6 app class which extends the polymer Element

class WascApp extends Polymer.Element {
     _buttonOnTap() {
     this.$.toastNewVersion.open();
}

This code works just finde, as expected. But I want to open the toast from outside this class, in a basic


问:
Google Apps Script not properly updating
I'm working on creating a system for other teachers to easily track their students' progress. I've got a spreadsheet with individual sheets for each student and then a sheet for an overview of all students. The spreadsheet has the following script attached to it:

```<code>function SheetNames() {
try {
  var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets()
  var out = new Array( sheets.length+1) ;
  for (var i = 1 ; i < sheets.length ; i++ ) {
    out[i] = [sheets[i-1].getName()];
  }
  return out
}
catch( err ) {
  return "#ERROR!"
}
}

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Student List')
      .addItem('Update Student List', 'SheetNames')
      .addToUi();
}
</code>```

In the "Overview" sheet, I have a cell that just contains =SheetNames(). When I first enter the custom function, the list populates. When I open the spreadsheet, the menu is added as it should be. However, when I click the menu item, the list of students on the "Overview" sheet is not updated. Is there anyway to make this function automatically update?

答:
It will not update because all that function does is return an array. When you use the =SheetNames() notation, you are giving it a range to write to (the cell where you put the formula).

When you run the function via menu click, it doesn't know anything about the target range in the spreadsheet. It simply creates a variable ('out'), stores it in memory, then destroys it when the function finishes executing.

If you'd like to write to specific range, you should reference it in your function. Here's a quick example of the function that writes a random number from 0 to 100 to cell A1 of the first sheet

```<code>function populateCell() {

var number = Math.random() * 100;
var cell = SpreadsheetApp.getActiveSpreadsheet()
                         .getSheets()[0]
                         .getRange("A1");

cell.setValue(number);

}

function onOpen() {

SpreadsheetApp.getUi()
              .createMenu('menu')
              .addItem('run', 'populateCell')
              .addToUi();

}
</code>```

It will not work as a custom function though. As per GAS documentation, if a function is being called from a cell (is custom), that function is read-only and can't set values https://developers.google.com/apps-script/guides/sheets/functions

Also, there's no need to use custom function because you seem to only need this code for specific range. If you intend to write to whatever cell the cursor is currently in, you should remove the reference to specific cell and use sheet.getActiveCell() instead. Only use custom functions for general functionality not tied to specific range.

Body:
I'm working on creating a system for other teachers to easily track their students' progress. I've got a spreadsheet with individual sheets for each student and then a sheet for an overview of all students. The spreadsheet has the following script attached to it:

function SheetNames() {
try {
  var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets()
  var out = new Array( sheets.length+1) ;
  for (var i = 1 ; i < sheets.length ; i++ ) {
    out[i] = [sheets[i-1].getName()];
  }
  return out
}
catch( err ) {
  return "#ERROR!"
}
}

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Student List')
      .addItem('Update Student List', 'SheetNames')
      .addToUi();
}

In the "Overview" sheet, I have a cell that just contains =SheetNames(). When I first enter the custom function, the list populates. When I open the spreadsheet, the menu is added as it should be. However, when I click the menu item, the list of students on the "Overview" sheet is not updated. Is there anyway to make this function automatically update?

Body:
It will not update because all that function does is return an array. When you use the =SheetNames() notation, you are giving it a range to write to (the cell where you put the formula).

When you run the function via menu click, it doesn't know anything about the target range in the spreadsheet. It simply creates a variable ('out'), stores it in memory, then destroys it when the function finishes executing.

If you'd like to write to specific range, you should reference it in your function. Here's a quick example of the function that writes a random number from 0 to 100 to cell A1 of the first sheet

function populateCell() {

var number = Math.random() * 100;
var cell = SpreadsheetApp.getActiveSpreadsheet()
                         .getSheets()[0]
                         .getRange("A1");

cell.setValue(number);

}

function onOpen() {

SpreadsheetApp.getUi()
              .createMenu('menu')
              .addItem('run', 'populateCell')
              .addToUi();

}

It will not work as a custom function though. As per GAS documentation, if a function is being called from a cell (is custom), that function is read-only and can't set values https://developers.google.com/apps-script/guides/sheets/functions

Also, there's no need to use custom function because you seem to only need this code for specific range. If you intend to write to whatever cell the cursor is currently in, you should remove the reference to specific cell and use sheet.getActiveCell() instead. Only use custom functions for general functionality not tied to specific range.


问:
Can I access the virtual method of a base class via an instance of its subclass?
I have a subclass which overrides a virtual method in its base class which is abstract.
Can i access the virtual method of the base class via an subclass instance?

Thanks.

For example

```<code>public abstract class BaseClass{
    public virtual void MyMethod(){...}
}

public Class SubClass{
    public override void MyMethod(){...}
}

public static void Main(string[] args)
{
    SubClass MyObject = new SubClass();
    MyObject.MyMethod(); // need a way to refer to BaseClass.MyMethod, instead of SubClass.MyMethod().
}
</code>```

答:
Yes. </p>

```<code>public class SubClass : BaseClass
{
    public override void MyMethod()
    {
        base.MyMethod();
    }
}
</code>```

Body:
I have a subclass which overrides a virtual method in its base class which is abstract.
Can i access the virtual method of the base class via an subclass instance?

Thanks.

For example

public abstract class BaseClass{
    public virtual void MyMethod(){...}
}

public Class SubClass{
    public override void MyMethod(){...}
}

public static void Main(string[] args)
{
    SubClass MyObject = new SubClass();
    MyObject.MyMethod(); // need a way to refer to BaseClass.MyMethod, instead of SubClass.MyMethod().
}

Body:
Yes.

public class SubClass : BaseClass
{
    public override void MyMethod()
    {
        base.MyMethod();
    }
}


答:
No, there is no reasonable way to call just base virtual method from outside the class.

The easiest way if you control derived class is to expose base.MyMethod via some other method. If you can't change derived class I think you are out of luck.

Even if you can try to get exact method via reflection and invoke it with given instance, it will still perform virtual call to derived method.

```<code>var d = new SubClass();
var m = typeof(BaseClass).GetMethod("MyMethod");
m.Invoke(d, new object[0]); // calls SubClass.MyMethod
</code>```

Title: Can I access the virtual method of a base class via an instance of its subclass?

Body:
No, there is no reasonable way to call just base virtual method from outside the class.

The easiest way if you control derived class is to expose base.MyMethod via some other method. If you can't change derived class I think you are out of luck.

Even if you can try to get exact method via reflection and invoke it with given instance, it will still perform virtual call to derived method.

var d = new SubClass();
var m = typeof(BaseClass).GetMethod("MyMethod");
m.Invoke(d, new object[0]); // calls SubClass.MyMethod


问:
What's the Swift equivalent of declaring `typedef SomeClass<SomeProtocol> MyType`?
I’m currently writing some Swift code in a project that is predominately Objective-C. In our ObjC code, we have a header that declares typedef GPUImageOutput<GPUImageInput> MyFilter;. We can then declare e.g. a @property that can only be a GPUImageOutput subclass that implements GPUImageInput.

(NOTE: GPUImageOutput and GPUImageInput are not defined by me; they are part of the GPUImage library)

Our Swift code doesn't seem to recognize this, even though the header is #imported in our Bridging Header. I’ve tried to replicate the declaration in Swift, but neither of these are proper syntax:

typealias MyFilter = GPUImageOutput, GPUImageInput

typealias MyFilter = GPUImageOutput : GPUImageInput

答:
In Swift 4 you can achieve this with the new & sign (Below an example of a parameter confirming to UIViewController and UITableViewDataSource:</p>

```<code>func foo(vc: UIViewController & UITableViewDataSource) {
    // access UIViewController property
    let view = vc.view
    // call UITableViewDataSource method
    let sections = vc.numberOfSectionsInTableView?(tableView)
}
</code>```

Body:
In Swift 4 you can achieve this with the new & sign (Below an example of a parameter confirming to UIViewController and UITableViewDataSource:

func foo(vc: UIViewController & UITableViewDataSource) {
    // access UIViewController property
    let view = vc.view
    // call UITableViewDataSource method
    let sections = vc.numberOfSectionsInTableView?(tableView)
}


问:
List of zsh bindkey commands
Where can I find a list of zsh commands that I can use with bindkey, with descriptions?

Each time that I look for name of some standard action (e.g., end-of-line), I need to google and guess that the command found is what I look for.

Related:

Interpret zsh bindkey escaped sequences (SO)

The Z-Shell Line Editor (doc)

答:
```<code>zle -al
</code>```

lists all registered zle commands

Title: List of zsh bindkey commands

Body:
zle -al

lists all registered zle commands


问:
How can a GpioCallback register "false" twice in a row?
I have a very simple setup android-things setup where a GPIO (output) generates very short (10u) pulse, and I'm trying to read that pulse through another GPIO (input).

However, my logs are weirding me out: how could I get two "false" readings in a row?  If I have a light switch, I can't turn it off twice in a row... I need to turn it on in between, right?  Can the GpioCallback drop events?  Is my time too short?  Can there be a soft ramp between voltages that doesn't ever count as an "edge"?

```<code>val gpioIn = PeripheralManagerService().openGpio(gpioPinName)
gpioIn.setEdgeTriggerType(Gpio.EDGE_NONE) // reset for Android Things bug
gpioIn.setDirection(Gpio.DIRECTION_IN)
gpioIn.setActiveType(Gpio.ACTIVE_HIGH)
gpioIn.setEdgeTriggerType(Gpio.EDGE_BOTH) // I should get all changes, right?
gpioIn.registerGpioCallback(object : GpioCallback() {
    override fun onGpioEdge(gpio: Gpio?): Boolean {
        netLog((gpio?.value  ?: "null").toString())
        return true
    }
    override fun onGpioError(gpio: Gpio?, error: Int) {
        netLog("GPIO $gpio Error event $error")
    }
})
</code>```

results in

```<code>06-02 06:33:37.052 I/NetGpioListener: NET GPIO LISTENER: 118730013 true
06-02 06:33:37.091 I/NetGpioListener: NET GPIO LISTENER: 118769152 false
06-02 06:33:37.094 I/NetGpioListener: NET GPIO LISTENER: 118772102 false
</code>```

答:
Yes, this is fairly common with noisy input signals like pushbuttons, relay contacts, and "wiggly wires". The signal bounce that occurs during contact closure can happen very rapidly such that not every edge trigger event is captured by the input registers.

This is true of all GPIO systems (not just Android Things), and one reason why signal debounce is such a common practice. The debounce code in the button driver was actually written to handle cases like this to ensure they didn't generate false events.

Body:
I have a very simple setup android-things setup where a GPIO (output) generates very short (10u) pulse, and I'm trying to read that pulse through another GPIO (input).

However, my logs are weirding me out: how could I get two "false" readings in a row?  If I have a light switch, I can't turn it off twice in a row... I need to turn it on in between, right?  Can the GpioCallback drop events?  Is my time too short?  Can there be a soft ramp between voltages that doesn't ever count as an "edge"?

val gpioIn = PeripheralManagerService().openGpio(gpioPinName)
gpioIn.setEdgeTriggerType(Gpio.EDGE_NONE) // reset for Android Things bug
gpioIn.setDirection(Gpio.DIRECTION_IN)
gpioIn.setActiveType(Gpio.ACTIVE_HIGH)
gpioIn.setEdgeTriggerType(Gpio.EDGE_BOTH) // I should get all changes, right?
gpioIn.registerGpioCallback(object : GpioCallback() {
    override fun onGpioEdge(gpio: Gpio?): Boolean {
        netLog((gpio?.value  ?: "null").toString())
        return true
    }
    override fun onGpioError(gpio: Gpio?, error: Int) {
        netLog("GPIO $gpio Error event $error")
    }
})

results in

06-02 06:33:37.052 I/NetGpioListener: NET GPIO LISTENER: 118730013 true
06-02 06:33:37.091 I/NetGpioListener: NET GPIO LISTENER: 118769152 false
06-02 06:33:37.094 I/NetGpioListener: NET GPIO LISTENER: 118772102 false


问:
Java confused on how to arrange "if" statements
```<code>int i = 1;
int answer;
int d;
int e;
boolean alive = true;

System.out.println("\n");

System.out.println(enemies[i].getName() + " has appeared!");

System.out.print("\n");

while (alive == true) {

    System.out.println("Hitpoints[HP]: " + enemies[i].getHP());
    System.out.println("Attack[ATK]  : " + enemies[i].getATK());
    System.out.println("Mana[MANA]   : " + enemies[i].getMANA());

    System.out.println("\n");

    System.out.println("[1 - Attack]");
    System.out.println("[2 - Flee]");

    answer = In.getInt();

    System.out.println("\n");

    if (answer == 1) {

        if (user.getP_HP() > 0) {
            d = enemies[i].getHP() - user.getP_ATK();
            enemies[i].setHP(d);

            System.out.println(user.getP_Name() + " strikes the " + enemies[i].getName() + " for " + user.getP_ATK() + " damage.");
            System.out.println(enemies[i].getName() + " has " + enemies[i].getHP() + " HP remaining.");
            System.out.println("\n");
        } else if (user.getP_HP() <= 0) {
            System.out.println(user.getP_Name() + " has been slain by the " + enemies[i].getName() + "!");
            alive = false;
        }

        if (enemies[i].getHP() > 0) {
            e = user.getP_HP() - enemies[i].getATK();
            user.setP_HP(e);

            System.out.println("The " + enemies[i].getName() + " attacked you for " + enemies[i].getATK() + " damage.");
            System.out.println(user.getP_Name() + " has " + user.getP_HP() + " HP remaining.");
            System.out.println("\n");
        } else if (enemies[1].getHP() <= 0) {
            System.out.println(user.getP_Name() + " has slain the " + enemies[i].getName() + "!");
            alive = false;
        }

    } else if (answer == 2) {
        System.out.println("You try to run, but fall into a pit of spikes and die!");
        alive = false;
    }
}
</code>```

Hello, I'm having problems solving this issue for about 2 hours now. What I want to do is for the enemy to die immediately after its HP reaches 0 or below, and same for the player.

This works only if the player kills the goblin first, and not vice versa.

Whenever the enemy kills the player first, it does not output that you have been killed. Instead, it gives you the option to choose if you want to attack or flee again. After choosing the attack option, it only then states that you have been killed. That's not all though, after that the goblin attacks you again before the program stops.

Here is the sample output if the enemy kills you first:

```<code>stackoverflow strikes the Goblin for 1 damage.
Goblin has 12 HP remaining.

The Goblin attacked you for 3 damage.
stackoverflow has 1 HP remaining.

Hitpoints[HP]: 12
Attack[ATK]  : 3
Mana[MANA]   : 1

[1 - Attack]
[2 - Flee]
1

stackoverflow strikes the Goblin for 1 damage.
Goblin has 11 HP remaining.

The Goblin attacked you for 3 damage.
stackoverflow has -2 HP remaining.

Hitpoints[HP]: 11
Attack[ATK]  : 3
Mana[MANA]   : 1

[1 - Attack]
[2 - Flee]
1

stackoverflow has been slain by the Goblin!
The Goblin attacked you for 3 damage.
stackoverflow has -5 HP remaining.
</code>```

答:
try this:

```<code>int i = 1;
int answer;
int d;
int e;
boolean alive = true;

System.out.println("\n");

System.out.println(enemies[i].getName() + " has appeared!");

System.out.print("\n");

while (alive == true) {

    System.out.println("Hitpoints[HP]: " + enemies[i].getHP());
    System.out.println("Attack[ATK]  : " + enemies[i].getATK());
    System.out.println("Mana[MANA]   : " + enemies[i].getMANA());

    System.out.println("\n");
    if (user.getP_HP() > 0) {
        System.out.println("[1 - Attack]");
        System.out.println("[2 - Flee]");

        answer = In.getInt();

        System.out.println("\n");
    } else if (user.getP_HP() <= 0) {
            System.out.println(user.getP_Name() + " has been slain by the " + enemies[i].getName() + "!");
            alive = false;
            answer = 0; //so it won't execute the rest of the code
            }

    if (answer == 1) {

        d = enemies[i].getHP() - user.getP_ATK();
        enemies[i].setHP(d);

        System.out.println(user.getP_Name() + " strikes the " + enemies[i].getName() + " for " + user.getP_ATK() + " damage.");
        System.out.println(enemies[i].getName() + " has " + enemies[i].getHP() + " HP remaining.");
        System.out.println("\n");

        if (enemies[i].getHP() > 0) {
            e = user.getP_HP() - enemies[i].getATK();
            user.setP_HP(e);

            System.out.println("The " + enemies[i].getName() + " attacked you for " + enemies[i].getATK() + " damage.");
            System.out.println(user.getP_Name() + " has " + user.getP_HP() + " HP remaining.");
            System.out.println("\n");
        } else if (enemies[1].getHP() <= 0) {
            System.out.println(user.getP_Name() + " has slain the " + enemies[i].getName() + "!");
            alive = false;
        }

    } else if (answer == 2) {
        System.out.println("You try to run, but fall into a pit of spikes and die!");
        alive = false;
    }
}
</code>```

you need to check if you're alive BEFORE asking for an input. Might not be the best solution, but it's a fast one and I hope it points you in the right direction

Body:
int i = 1;
int answer;
int d;
int e;
boolean alive = true;

System.out.println("\n");

System.out.println(enemies[i].getName() + " has appeared!");

System.out.print("\n");

while (alive == true) {

    System.out.println("Hitpoints[HP]: " + enemies[i].getHP());
    System.out.println("Attack[ATK]  : " + enemies[i].getATK());
    System.out.println("Mana[MANA]   : " + enemies[i].getMANA());

    System.out.println("\n");

    System.out.println("[1 - Attack]");
    System.out.println("[2 - Flee]");

    answer = In.getInt();

    System.out.println("\n");

    if (answer == 1) {

        if (user.getP_HP() > 0) {
            d = enemies[i].getHP() - user.getP_ATK();
            enemies[i].setHP(d);

            System.out.println(user.getP_Name() + " strikes the " + enemies[i].getName() + " for " + user.getP_ATK() + " damage.");
            System.out.println(enemies[i].getName() + " has " + enemies[i].getHP() + " HP remaining.");
            System.out.println("\n");
        } else if (user.getP_HP() <= 0) {
            System.out.println(user.getP_Name() + " has been slain by the " + enemies[i].getName() + "!");
            alive = false;
        }

        if (enemies[i].getHP() > 0) {
            e = user.getP_HP() - enemies[i].getATK();
            user.setP_HP(e);

            System.out.println("The " + enemies[i].getName() + " attacked you for " + enemies[i].getATK() + " damage.");
            System.out.println(user.getP_Name() + " has " + user.getP_HP() + " HP remaining.");
            System.out.println("\n");
        } else if (enemies[1].getHP() <= 0) {
            System.out.println(user.getP_Name() + " has slain the " + enemies[i].getName() + "!");
            alive = false;
        }

    } else if (answer == 2) {
        System.out.println("You try to run, but fall into a pit of spikes and die!");
        alive = false;
    }
}

Hello, I'm having problems solving this issue for about 2 hours now. What I want to do is for the enemy to die immediately after its HP reaches 0 or below, and same for the player.

This works only if the player kills the goblin first, and not vice versa.

Whenever the enemy kills the player first, it does not output that you have been killed. Instead, it gives you the option to choose if you want to attack or flee again. After choosing the attack option, it only then states that you have been killed. That's not all though, after that the goblin attacks you again before the program stops.

Here is the sample output if the enemy kills you first:

stackoverflow strikes the Goblin for 1 damage.
Goblin has 12 HP remaining.

The Goblin attacked you for 3 damage.
stackoverflow has 1 HP remaining.

Hitpoints[HP]: 12
Attack[ATK]  : 3
Mana[MANA]   : 1

[1 - Attack]
[2 - Flee]
1

stackoverflow strikes the Goblin for 1 damage.
Goblin has 11 HP remaining.

The Goblin attacked you for 3 damage.
stackoverflow has -2 HP remaining.

Hitpoints[HP]: 11
Attack[ATK]  : 3
Mana[MANA]   : 1

[1 - Attack]
[2 - Flee]
1

stackoverflow has been slain by the Goblin!
The Goblin attacked you for 3 damage.
stackoverflow has -5 HP remaining.

Body:
try this:

int i = 1;
int answer;
int d;
int e;
boolean alive = true;

System.out.println("\n");

System.out.println(enemies[i].getName() + " has appeared!");

System.out.print("\n");

while (alive == true) {

    System.out.println("Hitpoints[HP]: " + enemies[i].getHP());
    System.out.println("Attack[ATK]  : " + enemies[i].getATK());
    System.out.println("Mana[MANA]   : " + enemies[i].getMANA());

    System.out.println("\n");
    if (user.getP_HP() > 0) {
        System.out.println("[1 - Attack]");
        System.out.println("[2 - Flee]");

        answer = In.getInt();

        System.out.println("\n");
    } else if (user.getP_HP() <= 0) {
            System.out.println(user.getP_Name() + " has been slain by the " + enemies[i].getName() + "!");
            alive = false;
            answer = 0; //so it won't execute the rest of the code
            }

    if (answer == 1) {

        d = enemies[i].getHP() - user.getP_ATK();
        enemies[i].setHP(d);

        System.out.println(user.getP_Name() + " strikes the " + enemies[i].getName() + " for " + user.getP_ATK() + " damage.");
        System.out.println(enemies[i].getName() + " has " + enemies[i].getHP() + " HP remaining.");
        System.out.println("\n");

        if (enemies[i].getHP() > 0) {
            e = user.getP_HP() - enemies[i].getATK();
            user.setP_HP(e);

            System.out.println("The " + enemies[i].getName() + " attacked you for " + enemies[i].getATK() + " damage.");
            System.out.println(user.getP_Name() + " has " + user.getP_HP() + " HP remaining.");
            System.out.println("\n");
        } else if (enemies[1].getHP() <= 0) {
            System.out.println(user.getP_Name() + " has slain the " + enemies[i].getName() + "!");
            alive = false;
        }

    } else if (answer == 2) {
        System.out.println("You try to run, but fall into a pit of spikes and die!");
        alive = false;
    }
}

you need to check if you're alive BEFORE asking for an input. Might not be the best solution, but it's a fast one and I hope it points you in the right direction


问:
Creating zip files with PCLZIP.LIB: invalid variable type error
Trying to make an auto directory lister with a download function for every subdirectory. I'd like to make these subdirectories available as .zip files to allow for easier downloading and to use less bandwith on the server.

The following script was working fine until I added the pclzip.lib and tried to let it create a zip file.

```<code><html>
<head>
<?php require_once("pclzip.lib.php");?>
<?php require_once("filesize_lib.php"); ?>

<style type="text/css">

.readme{
width:500px;
height:150px;
background: silver;
overflow-x: hidden;
overflow-y: scroll;
}

</style>

</head>
<body>
<?php
    $readme = "/readme.txt";
    $download = "downloads";
  // Openen
    $dir = new DirectoryIterator('.');
  // Doorlopen
?>
<table width="960px" border="1px"><tr><td width="185px"><strong>Name</strong></td><td width="50px"><strong>Type</strong></td><td width="50px"><strong>Size</strong></td><td width="125px"><strong>Last Modified</strong></td><td><strong>Short description</strong></td><td width="50px"><strong>Download</strong></td></tr>
<?php
    foreach ($dir as $file)
      {
        if (! $file->isDot()
               && $file != ".."
            && $file != "index.php"
            && $file != "filesize_lib.php"
            && $file != "downloads"
            )
        {        ?><tr><td><?php
                  echo '<a href="'.$file.'">'.$file.'</a>';
                ?></td><td><?php
                echo filetype($file);
                  ?></td><td><?php
                  echo fileORdirSize($file).'<br/>';
                 ?></td><td><?php
                  echo date("M j, Y", filemtime($file));
                  ?></td><?php
                      if (filetype($file) == "dir"){
                          ?>
                          <td><div class="readme"><?php
                          echo file_get_contents($file.$readme);
                          ?></div></td><?php
                      } else {
                          ?><td>Files don't have descriptions, but can be tested directly from this page.</td><?php
                      }
                  ?><td><?php
                    $zip = new PclZip("tmp/archief.zip");
                        if($zip->create($file) == 0)
                          die("Error : " . $zip->errorInfo(true));
                  echo '<a href="'.$zip.'">'.$zip.'</a>';
                  ?></td></tr><?php
        }
  }
?>
</table>
</body>
</html>
</code>```

The error I'm receiving is the following:

```<code>Invalid variable type p_filelist [code -3]
</code>```

Which I believe is due to the fact that I'm feeding pclzip.lib a single variable and not an array. Unfortunately, I don't know how to solve this problem. See the piece of code that is responsible for the problem (according to me) below:

```<code><?php    // ----- Init
    $v_string_list = array();
    $v_att_list = array();
    $v_filedescr_list = array();
    $p_result_list = array();

    // ----- Look if the $p_filelist is really an array
    if (is_array($p_filelist)) {

      // ----- Look if the first element is also an array
      //       This will mean that this is a file description entry
      if (isset($p_filelist[0]) && is_array($p_filelist[0])) {
        $v_att_list = $p_filelist;
      }

      // ----- The list is a list of string names
      else {
        $v_string_list = $p_filelist;
      }
    }

    // ----- Look if the $p_filelist is a string
    else if (is_string($p_filelist)) {
      // ----- Create a list from the string
      $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist);
    }

    // ----- Invalid variable type for $p_filelist
    else {
      PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_filelist");
      return 0;
    }?>
</code>```

答:
Try instantiating your zip class before the start of the loop, and using the add() method rather than the create() method, otherwise you'll just be overwriting each archive with the next.

If you want to add a whole series of files in a single call, then either method expects an array of files, or a comma-separated list of files.

Ensure that $file is cast to string before calling the create() or add() method, you're passing an object

Also ensure that you're passing $file including any directory reference, else PCLZip won't find the file

ContentLicense: CC BY-SA 2.5

Body:
Trying to make an auto directory lister with a download function for every subdirectory. I'd like to make these subdirectories available as .zip files to allow for easier downloading and to use less bandwith on the server.

The following script was working fine until I added the pclzip.lib and tried to let it create a zip file.

<?php require_once("pclzip.lib.php");?>
<?php require_once("filesize_lib.php"); ?>

<?php
    $readme = "/readme.txt";
    $download = "downloads";
  // Openen
    $dir = new DirectoryIterator('.');
  // Doorlopen
?>

Name	Type	Size	Last Modified	Short description	Download

<?php
    foreach ($dir as $file)
      {
        if (! $file->isDot()
               && $file != ".."
            && $file != "index.php"
            && $file != "filesize_lib.php"
            && $file != "downloads"
            )
        {        ?>
<?php
                  echo ''.$file.'';
                ?>	<?php
                echo filetype($file);
                  ?>	<?php
                  echo fileORdirSize($file).'
';
                 ?>	<?php
                  echo date("M j, Y", filemtime($file));
                  ?>	<?php
                      if (filetype($file) == "dir"){
                          ?>

<?php
                          echo file_get_contents($file.$readme);
                          ?>
	<?php
                      } else {
                          ?>Files don't have descriptions, but can be tested directly from this page.	<?php
                      }
                  ?><?php
                    $zip = new PclZip("tmp/archief.zip");
                        if($zip->create($file) == 0)
                          die("Error : " . $zip->errorInfo(true));
                  echo ''.$zip.'';
                  ?>
<?php
        }
  }
?>

The error I'm receiving is the following:

Invalid variable type p_filelist [code -3]

Which I believe is due to the fact that I'm feeding pclzip.lib a single variable and not an array. Unfortunately, I don't know how to solve this problem. See the piece of code that is responsible for the problem (according to me) below:

<?php    // ----- Init
    $v_string_list = array();
    $v_att_list = array();
    $v_filedescr_list = array();
    $p_result_list = array();

    // ----- Look if the $p_filelist is really an array
    if (is_array($p_filelist)) {

      // ----- Look if the first element is also an array
      //       This will mean that this is a file description entry
      if (isset($p_filelist[0]) && is_array($p_filelist[0])) {
        $v_att_list = $p_filelist;
      }

      // ----- The list is a list of string names
      else {
        $v_string_list = $p_filelist;
      }
    }

    // ----- Look if the $p_filelist is a string
    else if (is_string($p_filelist)) {
      // ----- Create a list from the string
      $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist);
    }

    // ----- Invalid variable type for $p_filelist
    else {
      PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_filelist");
      return 0;
    }?>


问:
AIR Native Process works on Mac, but not Windows
I'm building an AIR application with Flash CC, so that I can use Native Processes. Before I even got to integrating it into my full project, I created a small test project to see if it would work. I tried it in Windows and it didn't work. I switched over to Mac and got it to work there, though.

The Native Process is triggered by a key press. The file is published as a Windows installer, not an Air package. I have made sure to include extendedDesktop in the xml file. I have double checked the file paths. Are there any other reasons this wouldn't work?

```<code>package  {

    import flash.display.MovieClip;
    import flash.filesystem.File;
    import flash.events.KeyboardEvent;
    import flash.desktop.NativeProcess;
    import flash.desktop.NativeProcessStartupInfo;

    public class Main extends MovieClip {

        var exe:File = new File("C:\Windows\System32\notepad.exe");
        var nativeProcess:NativeProcess = new NativeProcess();
        var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
        var args:Vector.<String> = new Vector.<String>();

        public function startProcess(event:KeyboardEvent):void
        {
            if (event.keyCode == 65) {
                nativeProcessStartupInfo.executable = exe;
                args.push("C:/Users/Tristan/Documents/TVCR/airTestFile.rtf");
                nativeProcessStartupInfo.arguments = args;
                nativeProcess.start(nativeProcessStartupInfo);
            }
        }
    }
}
</code>```

答:
How to output some debug information. The following code will show some messages if the keyboard events really trigger the handler method.

```<code>public function startProcess(event:KeyboardEvent):void
{
    // LogText:TextField
     LogText.appendText("\n\nKey Pressed: " + event.keyCode);
}
</code>```

How to output and diagnose an exception:

```<code>try
{
    nativeProcess.start(nativeProcessStartupInfo);
    LogText.appendText("\n\nThe process has been started without exceptions.");
}
catch (fail:Error)
{
    // LogText:TextField
    LogText.appendText("\n\n" + fail.getStackTrace());
}
</code>```

Body:
I'm building an AIR application with Flash CC, so that I can use Native Processes. Before I even got to integrating it into my full project, I created a small test project to see if it would work. I tried it in Windows and it didn't work. I switched over to Mac and got it to work there, though.

The Native Process is triggered by a key press. The file is published as a Windows installer, not an Air package. I have made sure to include extendedDesktop in the xml file. I have double checked the file paths. Are there any other reasons this wouldn't work?

package  {

    import flash.display.MovieClip;
    import flash.filesystem.File;
    import flash.events.KeyboardEvent;
    import flash.desktop.NativeProcess;
    import flash.desktop.NativeProcessStartupInfo;

    public class Main extends MovieClip {

        var exe:File = new File("C:\Windows\System32\notepad.exe");
        var nativeProcess:NativeProcess = new NativeProcess();
        var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
        var args:Vector.<String> = new Vector.<String>();

        public function startProcess(event:KeyboardEvent):void
        {
            if (event.keyCode == 65) {
                nativeProcessStartupInfo.executable = exe;
                args.push("C:/Users/Tristan/Documents/TVCR/airTestFile.rtf");
                nativeProcessStartupInfo.arguments = args;
                nativeProcess.start(nativeProcessStartupInfo);
            }
        }
    }
}

Body:
How to output some debug information. The following code will show some messages if the keyboard events really trigger the handler method.

public function startProcess(event:KeyboardEvent):void
{
    // LogText:TextField
     LogText.appendText("\n\nKey Pressed: " + event.keyCode);
}

How to output and diagnose an exception:

try
{
    nativeProcess.start(nativeProcessStartupInfo);
    LogText.appendText("\n\nThe process has been started without exceptions.");
}
catch (fail:Error)
{
    // LogText:TextField
    LogText.appendText("\n\n" + fail.getStackTrace());
}


问:
Swift -- Require classes implementing protocol to be subclasses of a certain class
I'm creating several NSView classes, all of which support a special operation, which we'll call transmogrify.  At first glance, this seems like the perfect place for a protocol:

```<code>protocol TransmogrifiableView {
    func transmogrify()
}
</code>```

However, this protocol does not enforce that every TransmogrifiableView be an NSView as well.  This means that any NSView methods I call on a TransmogrifiableView will not type check:

```<code>let myView: TransmogrifiableView = getTransmogrifiableView()
let theSuperView = myView.superView // error: TransmogrifiableView does not have a property called 'superview'
</code>```

I don't know how to require that all classes implementing my protocol are also subclasses of NSView.  I tried this:

```<code>protocol TransmogrifiableView: NSView {
    func transmogrify()
}
</code>```

but Swift complains that protocols cannot inherit from classes.  It does not help to turn the protocol into a class-only protocol using

```<code>protocol TransmogrifiableView: class, NSView {
    func transmogrify()
}
</code>```

I cannot make TransmogrifiableView a superclass rather than a protocol, because some of my TransmogrifiableView classes must be subclasses of other, non-transmogrifiable views.

How should I require that all TransmogrifiableView's also be NSView's?  I really don't want to pepper my code with "as" conversions, which are bad form and distracting.

答:
Starting from Swift 4 you can now define this as followed:

```<code>let myView: NSView & TransmogrifiableView
</code>```

For more information, checkout issue #156 Subclass Existentials

Body:
I'm creating several NSView classes, all of which support a special operation, which we'll call transmogrify.  At first glance, this seems like the perfect place for a protocol:

protocol TransmogrifiableView {
    func transmogrify()
}

However, this protocol does not enforce that every TransmogrifiableView be an NSView as well.  This means that any NSView methods I call on a TransmogrifiableView will not type check:

let myView: TransmogrifiableView = getTransmogrifiableView()
let theSuperView = myView.superView // error: TransmogrifiableView does not have a property called 'superview'

I don't know how to require that all classes implementing my protocol are also subclasses of NSView.  I tried this:

protocol TransmogrifiableView: NSView {
    func transmogrify()
}

but Swift complains that protocols cannot inherit from classes.  It does not help to turn the protocol into a class-only protocol using

protocol TransmogrifiableView: class, NSView {
    func transmogrify()
}

I cannot make TransmogrifiableView a superclass rather than a protocol, because some of my TransmogrifiableView classes must be subclasses of other, non-transmogrifiable views.

How should I require that all TransmogrifiableView's also be NSView's?  I really don't want to pepper my code with "as" conversions, which are bad form and distracting.

Body:
Starting from Swift 4 you can now define this as followed:

let myView: NSView & TransmogrifiableView

For more information, checkout issue #156 Subclass Existentials


问:
ruby Split lines using selective tags that appear multiple times in file in any order
I have a file that has the contents as below:

```<code>this is test line 1
this is testing purpose
<public>
am inside of public
doing lot of stuffs and priting result here
</public>
<public>
am inside of another public
doing another set of stuffs and priting here
</public>
</code>```

I want to split this file into three different sections:

The lines which are not inside any of the   section

The lines which are inside of first   section

The lines which are inside of second   section

I tried with take_while and drop_while,

```<code>File.open(filename).each_line.take_while do |l|
  !l.include?('</public>')
end.drop_while do |l|
  !l.include?('<public>')
end.drop(1))
</code>```

but it extracts only the first <public>...</public> section.

In some situation the order might change, like the public section will come first and the remaining content will come at last or middle. If the content order is same as above template then I can follow the below mothod

```<code>File.read(filename).split(/<\/?public>/)
                   .map(&:strip)
                   .reject(&:empty?)
</code>```

which I got answer from Split lines using tags that appear multiple times in file.

But looking some generic method where I can handle the data if the order is in anyway.

I am looking for a better solution. Any suggestion would be appreciated.

答:
You can use Ruby's flip-flop operator here.

Code

```<code>def dissect(str)
  arr = str.lines.map(&:strip)
  grp, ungrp = [], []
  arr.each { |line| line=='<public>'..line=='</public>' ? (grp << line) : ungrp << line }
  [grp.slice_when { |s,t| s == '</public>' && t == '<public>' }.
       map { |a| a[1..-2] },
   ungrp]
end
</code>```

The last statement of the method, which constructs the array returned by the method, could be replaced with the following.

```<code>b = grp.count('<public>').times.with_object([]) do |_,a|
  ndx = grp.index('</public>')
  a << grp[1..ndx-1]
  grp = grp[ndx+1..-1] if ndx < grp.size-1
end
[b, ungrp]
</code>```

Example

```<code>str =<<-EOS
this is test line 1
this is testing purpose
<public>
am inside of public
doing lot of stuffs and printing result here
</public>
let's stick another line here
<public>
am inside of another public
doing another set of stuffs and printing here
</public>
and another line here
EOS
</code>```

```<code>grouped, ungrouped = dissect(str)
  #=> [
  #     [ ["am inside of public",
  #        "doing lot of stuffs and printing result here"],
  #       ["am inside of another public",
  #        "doing another set of stuffs and printing here"]
  #     ],
  #     [
  #       "this is test line 1",
  #       "this is testing purpose",
  #       "let's stick another line here",
  #       "and another line here"]
  #     ]
  #   ]
grouped
  #=> [ ["am inside of public",
  #      "doing lot of stuffs and printing result here"],
  #     ["am inside of another public",
  #      "doing another set of stuffs and printing here"]
  #   ]
ungrouped
  #=> ["this is test line 1",
  #    "this is testing purpose",
  #    "let's stick another line here",
  #    "and another line here"]
</code>```

Explanation

For the example above the steps are as follows.

```<code>arr = str.lines.map(&:strip)
  #=> ["this is test line 1", "this is testing purpose", "<public>",
  #    "am inside of public", "doing lot of stuffs and printing result here",
  #    "</public>", "let's stick another line here", "<public>",
  #    "am inside of another public", "doing another set of stuffs and printing here",
  #    "</public>", "and another line here"]

ungrp, grp = [], []
arr.each { |line| line=='<public>'..line=='</public>' ? (grp << line) : ungrp << line }
</code>```

The flip-flop returns false until line=='<public>' is true. It then returns true and continues to return true until after line=='</public>' is true. It then returns false until it once again encounters a line for which line=='<public>' is true, and so on.

```<code>ungrp
  #=> <returns the value of 'ungrouped' in the example>
grp
  #=> ["<public>",
  #    "am inside of public",
  #    "doing lot of stuffs and printing result here",
  #    "</public>",
  #    "<public>",
  #    "am inside of another public",
  #    "doing another set of stuffs and printing here",
  #    "</public>"]
enum = grp.slice_when { |s,t| s == '</public>' && t == '<public>' }
  #=> #<Enumerator: #<Enumerator::Generator:0x00000
</code>```

See Enumerable#slice_when, which made its debut in Ruby v2.2.

We can see the elements that will be generated by this enumerator by converting it to an array.

```<code>enum.to_a
  #=> [["<public>", "am inside of public",
  #     "doing lot of stuffs and printing result here", "</public>"],
  #    ["<public>", "am inside of another public",
  #     "doing another set of stuffs and printing here", "</public>"]]
</code>```

Lastly,

```<code>enum.map { |a| a[1..-2] }
  #=> <returns the array 'grouped' in the example>
</code>```

Body:
I have a file that has the contents as below:

this is test line 1
this is testing purpose
<public>
am inside of public
doing lot of stuffs and priting result here
</public>
<public>
am inside of another public
doing another set of stuffs and priting here
</public>

I want to split this file into three different sections:

The lines which are not inside any of the   section

The lines which are inside of first   section

The lines which are inside of second   section

I tried with take_while and drop_while,

File.open(filename).each_line.take_while do |l|
  !l.include?('</public>')
end.drop_while do |l|
  !l.include?('<public>')
end.drop(1))

but it extracts only the first <public>...</public> section.

In some situation the order might change, like the public section will come first and the remaining content will come at last or middle. If the content order is same as above template then I can follow the below mothod

File.read(filename).split(/<\/?public>/)
                   .map(&:strip)
                   .reject(&:empty?)

which I got answer from Split lines using tags that appear multiple times in file.

But looking some generic method where I can handle the data if the order is in anyway.

I am looking for a better solution. Any suggestion would be appreciated.

Body:
You can use Ruby's flip-flop operator here.

Code

def dissect(str)
  arr = str.lines.map(&:strip)
  grp, ungrp = [], []
  arr.each { |line| line=='<public>'..line=='</public>' ? (grp << line) : ungrp << line }
  [grp.slice_when { |s,t| s == '</public>' && t == '<public>' }.
       map { |a| a[1..-2] },
   ungrp]
end

The last statement of the method, which constructs the array returned by the method, could be replaced with the following.

b = grp.count('<public>').times.with_object([]) do |_,a|
  ndx = grp.index('</public>')
  a << grp[1..ndx-1]
  grp = grp[ndx+1..-1] if ndx < grp.size-1
end
[b, ungrp]

Example

str =<<-EOS
this is test line 1
this is testing purpose
<public>
am inside of public
doing lot of stuffs and printing result here
</public>
let's stick another line here
<public>
am inside of another public
doing another set of stuffs and printing here
</public>
and another line here
EOS

grouped, ungrouped = dissect(str)
  #=> [
  #     [ ["am inside of public",
  #        "doing lot of stuffs and printing result here"],
  #       ["am inside of another public",
  #        "doing another set of stuffs and printing here"]
  #     ],
  #     [
  #       "this is test line 1",
  #       "this is testing purpose",
  #       "let's stick another line here",
  #       "and another line here"]
  #     ]
  #   ]
grouped
  #=> [ ["am inside of public",
  #      "doing lot of stuffs and printing result here"],
  #     ["am inside of another public",
  #      "doing another set of stuffs and printing here"]
  #   ]
ungrouped
  #=> ["this is test line 1",
  #    "this is testing purpose",
  #    "let's stick another line here",
  #    "and another line here"]

Explanation

For the example above the steps are as follows.

arr = str.lines.map(&:strip)
  #=> ["this is test line 1", "this is testing purpose", "<public>",
  #    "am inside of public", "doing lot of stuffs and printing result here",
  #    "</public>", "let's stick another line here", "<public>",
  #    "am inside of another public", "doing another set of stuffs and printing here",
  #    "</public>", "and another line here"]

ungrp, grp = [], []
arr.each { |line| line=='<public>'..line=='</public>' ? (grp << line) : ungrp << line }

The flip-flop returns false until line=='<public>' is true. It then returns true and continues to return true until after line=='</public>' is true. It then returns false until it once again encounters a line for which line=='<public>' is true, and so on.

ungrp
  #=> <returns the value of 'ungrouped' in the example>
grp
  #=> ["<public>",
  #    "am inside of public",
  #    "doing lot of stuffs and printing result here",
  #    "</public>",
  #    "<public>",
  #    "am inside of another public",
  #    "doing another set of stuffs and printing here",
  #    "</public>"]
enum = grp.slice_when { |s,t| s == '</public>' && t == '<public>' }
  #=> #<Enumerator: #<Enumerator::Generator:0x00000

See Enumerable#slice_when, which made its debut in Ruby v2.2.

We can see the elements that will be generated by this enumerator by converting it to an array.

enum.to_a
  #=> [["<public>", "am inside of public",
  #     "doing lot of stuffs and printing result here", "</public>"],
  #    ["<public>", "am inside of another public",
  #     "doing another set of stuffs and printing here", "</public>"]]

Lastly,

enum.map { |a| a[1..-2] }
  #=> <returns the array 'grouped' in the example>


问:
Javascript array push
I am trying to iterate through an array and push the contents from the array to another array if they satisfy some basic condition. Really simple stuff. PLease help me.

Getting list of DBs in MongoDB

```<code>>>var dbs = db.getMongo().getDBNames();

>>dbs
[ "admin", "newdb", "newdb2", "local", "test" ]
</code>```

Get array length:

```<code>var arrayLength = dbs.length;
</code>```

Creating an empty array

```<code>var databases = []
</code>```

Pushing to the databases array content from dbs array if content is not equal to 'admin','local' or 'test'

```<code>for (var i = 0 ; i < arrayLength; i++) {
  if (!(dbs[i] == "admin") || !(dbs[i] == "local") || !(dbs[i] == "test")) {
    databases.push(dbs[i]);
  }
}
</code>```

Expecting only "newdb" and "newdb2" to be in the databases array. But everything is being pushed

```<code>>databases
[ "admin", "newdb", "newdb2", "local", "test" ]
</code>```

What's going on here? Only newdb and newdb2 needs to be in the "databases" array.

答:
You should use && rather than || in this condition:

```<code>(!(dbs[i] == "admin") || !(dbs[i] == "local") || !(dbs[i] == "test"))
</code>```

The way it is written above, it is "value is not A OR not B OR not C" which will be true for everything. (A is not B, for example.)

You mean it to say "value is not A AND not B AND not C".

```<code>(!(dbs[i] == "admin") && !(dbs[i] == "local") && !(dbs[i] == "test"))
</code>```

Title: Javascript array push

Body:
I am trying to iterate through an array and push the contents from the array to another array if they satisfy some basic condition. Really simple stuff. PLease help me.

Getting list of DBs in MongoDB

>>var dbs = db.getMongo().getDBNames();

>>dbs
[ "admin", "newdb", "newdb2", "local", "test" ]

Get array length:

var arrayLength = dbs.length;

Creating an empty array

var databases = []

Pushing to the databases array content from dbs array if content is not equal to 'admin','local' or 'test'

for (var i = 0 ; i < arrayLength; i++) {
  if (!(dbs[i] == "admin") || !(dbs[i] == "local") || !(dbs[i] == "test")) {
    databases.push(dbs[i]);
  }
}

Expecting only "newdb" and "newdb2" to be in the databases array. But everything is being pushed

>databases
[ "admin", "newdb", "newdb2", "local", "test" ]

What's going on here? Only newdb and newdb2 needs to be in the "databases" array.

Body:
You should use && rather than || in this condition:

(!(dbs[i] == "admin") || !(dbs[i] == "local") || !(dbs[i] == "test"))

The way it is written above, it is "value is not A OR not B OR not C" which will be true for everything. (A is not B, for example.)

You mean it to say "value is not A AND not B AND not C".

(!(dbs[i] == "admin") && !(dbs[i] == "local") && !(dbs[i] == "test"))


问:
Name all sheets in w orkbook based on the cell value of each sheet
I have used this code before but just changed it to a different cell and am now receiving a Run-Time error '1004' Method 'Name' of object '_Worksheet' failed . Not sure what is causing this</p>

```<code> Dim ws As Worksheet
 For Each ws In ActiveWorkbook.Worksheets
 ws.Name = ws.Range("FW1")
 Next
</code>```

答:
The name of the sheet must be a string and you are assigning a range object to it, so you have to do this instead:</p>

```<code> ws.Name = ws.Range("FW1").value
</code>```

Body:
I have used this code before but just changed it to a different cell and am now receiving a Run-Time error '1004' Method 'Name' of object '_Worksheet' failed . Not sure what is causing this

 Dim ws As Worksheet
 For Each ws In ActiveWorkbook.Worksheets
 ws.Name = ws.Range("FW1")
 Next

Body:
The name of the sheet must be a string and you are assigning a range object to it, so you have to do this instead:

 ws.Name = ws.Range("FW1").value


问:
VBA - Run Macro from Word to paste values into Excel
I am relatively new to VBA, and am at a loss as to why I cannot paste into Excel from Word.  The following macro ends up pasting the value into Word, even though I think I'm activating the Excel document.

The macro is meant to be run from Word; values from various FormFields then need to be pasted into cells in an existing Excel file.
I searched for a similar issue, though what was returned seemed to be variations of what I am experiencing, and I could not modify those answers to this.
Any help would be appreciated.

```<code>Sub Transfer()

Dim WD As Object
Dim ED As Excel.Application
Dim EDS As Excel.Workbook

Set WD = ActiveDocument
Set ED = CreateObject("excel.application")
ED.Visible = True
Workbooks.Open FileName:= _
"C:\Users\Documents\AppealData.xlsx"
ActiveWorkbook.Activate
Set EDS = ActiveWorkbook

WD.FormFields("AppNum").Copy
EDS.Activate
EDS.Sheets("Sheet1").Range("A1").Select
Selection.Paste

End Sub
</code>```

答:
This here should work for you. </p>

```<code>Sub Transfer()
   Dim oExcel As Excel.Application
   Dim oWB As Workbook

   Set oExcel = New Excel.Application
   Set oWB = oExcel.Workbooks.Open("C:\Users\Documents\AppealData.xlsx")

   oExcel.Visible = True

   Workbooks("Book1").Worksheets("Sheet1").Cells(1, 1).Value = _
      CStr(Documents("Document1").FormFields("AppNum").Result)
End Sub
</code>```

Body:
I am relatively new to VBA, and am at a loss as to why I cannot paste into Excel from Word.  The following macro ends up pasting the value into Word, even though I think I'm activating the Excel document.

The macro is meant to be run from Word; values from various FormFields then need to be pasted into cells in an existing Excel file.
I searched for a similar issue, though what was returned seemed to be variations of what I am experiencing, and I could not modify those answers to this.
Any help would be appreciated.

Sub Transfer()

Dim WD As Object
Dim ED As Excel.Application
Dim EDS As Excel.Workbook

Set WD = ActiveDocument
Set ED = CreateObject("excel.application")
ED.Visible = True
Workbooks.Open FileName:= _
"C:\Users\Documents\AppealData.xlsx"
ActiveWorkbook.Activate
Set EDS = ActiveWorkbook

WD.FormFields("AppNum").Copy
EDS.Activate
EDS.Sheets("Sheet1").Range("A1").Select
Selection.Paste

End Sub

Body:
This here should work for you.

Sub Transfer()
   Dim oExcel As Excel.Application
   Dim oWB As Workbook

   Set oExcel = New Excel.Application
   Set oWB = oExcel.Workbooks.Open("C:\Users\Documents\AppealData.xlsx")

   oExcel.Visible = True

   Workbooks("Book1").Worksheets("Sheet1").Cells(1, 1).Value = _
      CStr(Documents("Document1").FormFields("AppNum").Result)
End Sub


问:
How do I limit one pop up per user, using JavaScript
Well I found this code for my blog:

```<code><script type="text/javascript">
document.body.onclick= function(){ window.open('My site', 'poppage', 'toolbars=0, scrollbars=1, location=0, statusbars=0, menubars=0, resizable=1, width=950, height=650, left = 300, top = 50'); }
</script>
</code>```

But since I know nothing about JS, I can't really edit it much.

答:
```<code>document.body.onclick= function(){ window.open('My site', 'poppage', 'toolbars=0, scrollbars=1, location=0, statusbars=0, menubars=0, resizable=1, width=950, height=650, left = 300, top = 50');document.body.onclick=function(){} }
</code>```

Reset the onclick attribute once it has been clicked once

Body:
Well I found this code for my blog:

But since I know nothing about JS, I can't really edit it much.

Body:
document.body.onclick= function(){ window.open('My site', 'poppage', 'toolbars=0, scrollbars=1, location=0, statusbars=0, menubars=0, resizable=1, width=950, height=650, left = 300, top = 50');document.body.onclick=function(){} }

Reset the onclick attribute once it has been clicked once


问:
Python reload pip doesn't work
I am currently trying to upgrade pip and then install paramiko inside a python script because the script itself makes use of paramiko. Below is a simple case of what I am trying to accomplish

```<code>import pip

try:
        import paramiko
except ImportError:
        pip.main(["install", "--upgrade", "pip"])
        reload(pip)
        pip.main(["install", "--user", "paramiko"])
        import paramiko

ssh = paramiko.SSHClient()
</code>```

I am running this script in an Ubuntu 16.04 VM with python 2.7 which doesn't have paramiko and pip version 8.1.1. For the output of the pip upgrade after running the script, I get:

Collecting pip   Downloading pip-9.0.1-py2.py3-none-any.whl (1.3MB)
      100% |████████████████████████████████| 1.3MB 712kB/s Installing collected packages: pip Successfully installed pip-8.1.1 You are using
  pip version 8.1.1, however version 9.0.1 is available. You should
  consider upgrading via the 'pip install --upgrade pip' command.

After that, it tries to install paramiko as expected, but it fails because it basically can't install the Cryptography dependency that paramiko uses. However, if it was using the upgraded pip, this would not be a problem. I have reverted the VM back to a previous snapshot to manually install paramiko by doing

```<code>pip install --upgrade pip
pip install --user paramiko
</code>```

in the shell and it works, but I need to be able to perform this in a script.

Note, I also reverted the VM to a previous snapshot and tried installing paramiko with the above command in the shell, but without performing the pip upgrade first, and as expected I get the same error as what the script gives when trying to install paramiko.
Now I have done a bit of testing by trying to having this in the script:

```<code>pip.main(["install", "--upgrade", "pip"])
reload(pip)
pip.main(["install", "--upgrade", "pip"])
reload(pip)
</code>```

and as for the output I get this:

Collecting pip

  Downloading pip-9.0.1-py2.py3-none-any.whl (1.3MB)

```<code>100% |████████████████████████████████| 1.3MB 712kB/s Installing collected packages: pip Successfully installed pip-8.1.1 You are using pip version 8.1.1, however version 9.0.1 is available.
</code>```

You should consider upgrading via the 'pip install --upgrade pip' command.

Collecting pip

  Using cached pip-9.0.1-py2.py3-none-any.whl

Installing collected packages: pip Successfully installed pip-8.1.1

You are using pip version 8.1.1, however version 9.0.1 is available.

You should consider upgrading via the 'pip install --upgrade pip' command.

Notice how it says using cached pip-9.0.1 at the second pip upgrade. Does this mean after the reload, the script is using pip 9.0.1? If so then why is the paramiko install not using the upgraded pip? How can I get the paramiko to use the upgraded pip?

答:
Do you try to remove the pip package from the sys.modules array?

import pip
import sys
import site

print ('PIP Version: ' + pip.__version__)

pip.main(["install", "--upgrade", "pip"])

user_path  = site.getusersitepackages()
sytem_path = site.getsitepackages()

sys.path = [user_path] + system_path + sys.path

pips = [module for module in sys.modules if module.startswith('pip')]
for pip_module in pips:
    sys.modules.pop(pip_module)

del pip

import pip
print ('PIP Version: ' + pip.__version__)
```

<p>Runinng on my machine with pip 8.1.1 installed, the output I get was:</p>

``` begnini@coffee-machine:~# python update.py
 PIP Version: 8.1.1
 Collecting pip
  Downloading pip-9.0.1-py2.py3-none-any.whl (1.3MB)
    100% |████████████████████████████████| 1.3MB 651kB/s
 Installing collected packages: pip
  Found existing installation: pip 8.1.1
    Uninstalling pip-8.1.1:
      Successfully uninstalled pip-8.1.1
 Successfully installed pip-9.0.1
 PIP Version: 9.0.1
```

EDIT: Like we discussed, the problem was with pip trying to search first in the main python lib directory instead /usr/local/lib dir. To fix this, I added the local lib dir in the first position of the system path array. With this modification, the bug should be fixed.

EDIT 2: Added site paths instead use hardcoded dirs.

Title: Python reload pip doesn't work

Body:
I am currently trying to upgrade pip and then install paramiko inside a python script because the script itself makes use of paramiko. Below is a simple case of what I am trying to accomplish

import pip

try:
        import paramiko
except ImportError:
        pip.main(["install", "--upgrade", "pip"])
        reload(pip)
        pip.main(["install", "--user", "paramiko"])
        import paramiko

ssh = paramiko.SSHClient()

I am running this script in an Ubuntu 16.04 VM with python 2.7 which doesn't have paramiko and pip version 8.1.1. For the output of the pip upgrade after running the script, I get:

Collecting pip   Downloading pip-9.0.1-py2.py3-none-any.whl (1.3MB)
      100% |████████████████████████████████| 1.3MB 712kB/s Installing collected packages: pip Successfully installed pip-8.1.1 You are using
  pip version 8.1.1, however version 9.0.1 is available. You should
  consider upgrading via the 'pip install --upgrade pip' command.

After that, it tries to install paramiko as expected, but it fails because it basically can't install the Cryptography dependency that paramiko uses. However, if it was using the upgraded pip, this would not be a problem. I have reverted the VM back to a previous snapshot to manually install paramiko by doing

pip install --upgrade pip
pip install --user paramiko

in the shell and it works, but I need to be able to perform this in a script.

Note, I also reverted the VM to a previous snapshot and tried installing paramiko with the above command in the shell, but without performing the pip upgrade first, and as expected I get the same error as what the script gives when trying to install paramiko.
Now I have done a bit of testing by trying to having this in the script:

pip.main(["install", "--upgrade", "pip"])
reload(pip)
pip.main(["install", "--upgrade", "pip"])
reload(pip)

and as for the output I get this:

Collecting pip

  Downloading pip-9.0.1-py2.py3-none-any.whl (1.3MB)

100% |████████████████████████████████| 1.3MB 712kB/s Installing collected packages: pip Successfully installed pip-8.1.1 You are using pip version 8.1.1, however version 9.0.1 is available.

You should consider upgrading via the 'pip install --upgrade pip' command.

Collecting pip

  Using cached pip-9.0.1-py2.py3-none-any.whl

Installing collected packages: pip Successfully installed pip-8.1.1

You are using pip version 8.1.1, however version 9.0.1 is available.

You should consider upgrading via the 'pip install --upgrade pip' command.

Notice how it says using cached pip-9.0.1 at the second pip upgrade. Does this mean after the reload, the script is using pip 9.0.1? If so then why is the paramiko install not using the upgraded pip? How can I get the paramiko to use the upgraded pip?

Body:
Do you try to remove the pip package from the sys.modules array?

import pip
import sys
import site

print ('PIP Version: ' + pip.__version__)

pip.main(["install", "--upgrade", "pip"])

user_path  = site.getusersitepackages()
sytem_path = site.getsitepackages()

sys.path = [user_path] + system_path + sys.path

pips = [module for module in sys.modules if module.startswith('pip')]
for pip_module in pips:
    sys.modules.pop(pip_module)

del pip

import pip
print ('PIP Version: ' + pip.__version__)

Runinng on my machine with pip 8.1.1 installed, the output I get was:

 begnini@coffee-machine:~# python update.py
 PIP Version: 8.1.1
 Collecting pip
  Downloading pip-9.0.1-py2.py3-none-any.whl (1.3MB)
    100% |████████████████████████████████| 1.3MB 651kB/s
 Installing collected packages: pip
  Found existing installation: pip 8.1.1
    Uninstalling pip-8.1.1:
      Successfully uninstalled pip-8.1.1
 Successfully installed pip-9.0.1
 PIP Version: 9.0.1

EDIT: Like we discussed, the problem was with pip trying to search first in the main python lib directory instead /usr/local/lib dir. To fix this, I added the local lib dir in the first position of the system path array. With this modification, the bug should be fixed.

EDIT 2: Added site paths instead use hardcoded dirs.


问:
Class and Protocol Inheritance in Swift
Let's say I have a protocol in Swift

```<code>protocol SearchCompletionProtocol {
    func searchSuccessful(results: [AnyObject])
    func searchCancelled()
}
</code>```

Now let's say that I have a class and in the init method I want to pass in a single argument. The restriction is that I want this argument to be of type UIViewController and also conform to the SearchCompletionProtocol protocol. How would I go about doing that? Here are some examples of things I've tried and they all don't work.

```<code>class SearchDelegate: UISearchDisplayController, UISearchBarDelegate {

    let completionDelegate: SearchCompletionProtocol

    init<T: SearchCompletionProtocol where T: UIViewController>(completionDelegate: T) {
        self.completionDelegate = completionDelegate
        let _searchBar = UISearchBar()
        super.init(searchBar: _searchBar, contentsController: completionDelegate)
    }
}
</code>```

I've also tried restricting inheritance on the protocol to only classes of type UIViewController, but that also does not work.

```<code>protocol SearchCompletionProtocol: class, UIViewController {
    func searchSuccessful(results: [AnyObject])
    func searchCancelled()
}
</code>```

Of course I could easily just pass in two arguments to this method, one conforming to the search protocol and one being of type UIViewController, but that just seems not very Swifty.

答:
In Swift 4 you can achieve this with the new & sign:</p>

```<code>func foo(vc: UIViewController & SearchCompletionProtocol) {
    vc.searchCancelled()
}
</code>```

Title: Class and Protocol Inheritance in Swift

Body:
Let's say I have a protocol in Swift

protocol SearchCompletionProtocol {
    func searchSuccessful(results: [AnyObject])
    func searchCancelled()
}

Now let's say that I have a class and in the init method I want to pass in a single argument. The restriction is that I want this argument to be of type UIViewController and also conform to the SearchCompletionProtocol protocol. How would I go about doing that? Here are some examples of things I've tried and they all don't work.

class SearchDelegate: UISearchDisplayController, UISearchBarDelegate {

    let completionDelegate: SearchCompletionProtocol

    init<T: SearchCompletionProtocol where T: UIViewController>(completionDelegate: T) {
        self.completionDelegate = completionDelegate
        let _searchBar = UISearchBar()
        super.init(searchBar: _searchBar, contentsController: completionDelegate)
    }
}

I've also tried restricting inheritance on the protocol to only classes of type UIViewController, but that also does not work.

protocol SearchCompletionProtocol: class, UIViewController {
    func searchSuccessful(results: [AnyObject])
    func searchCancelled()
}

Of course I could easily just pass in two arguments to this method, one conforming to the search protocol and one being of type UIViewController, but that just seems not very Swifty.

Body:
In Swift 4 you can achieve this with the new & sign:

func foo(vc: UIViewController & SearchCompletionProtocol) {
    vc.searchCancelled()
}


问:
calling .lib from .DLL in c++
I would like to use a c++ library given by a company. I only have the .lib and the .h files. I would like to use it in unity. So I need a DLL. So I want to create a DLL that permit me to access the functions I need in the .lib .

To do so I created a visual studio c++ DLL project with a c++ file that call the desired functions from the library. The .lib is linked to visual studio in linker/input/additional dependences.

In order to make it simple I am trying to call fonctions of my DLL from a normal c++ file instead of unity.

My test file look like this :

```<code>#include <windows.h>
#include <iostream>

void CallMyDLL(void)
{
 HINSTANCE hGetProcIDDLL = LoadLibrary("C:\\path\\museDLL.dll");
 FARPROC lpfnGetProcessID = GetProcAddress(HMODULE (hGetProcIDDLL),"startConnection");
   typedef void (__stdcall * pICFUNC)();
   pICFUNC startConnection;
   startConnection = pICFUNC(lpfnGetProcessID);

  //std::cout << test<< std::endl;

  startConnection();

  FreeLibrary(hGetProcIDDLL);

}
int main () {
CallMyDLL();
}
</code>```

and my main DLL file look like this :

```<code>#include "dllmain.h"
#include <iostream>
#include <fstream>
#include "main_muse.h"
namespace museDLL
{
    MainPage* mp;
      void startConnection()
    {
           mp = new  MainPage();
    }

    double getValue()
    {
        return mp->getValueEEG();
    }

    double test()
    {
        return 1.2f;
    }

}
</code>```

dllmain.h

```<code>#pragma once

#ifdef DLL_EXPORTS
#define DLL_API __declspec(dllexport)
#else
#define DLL_API __declspec(dllimport)
#endif

namespace museDLL
{
    extern "C" {
        DLL_API void __cdecl startConnection();
        DLL_API double __cdecl getValue();
        DLL_API double __cdecl test();

    }
}
</code>```

If I call the test function in my DLL it works. However If I call the startConnection function that use functions from the original .lib it crashes ( no error messages ) .

so to make it clear , I want test file-> calling my custom DLL -> calling the downloaded .lib .

I don't understand what I am doing wrong?

I wonder if the initial .lib is included in the .DLL or do I need to link it somehow?

答:
You only have the .lib file and header files.
It seems, you have a static library. So you could be able to build your application and link the library as static library.
In other words, you are not able to somehow create a .dll library from the given .lib until you do not have an access to a source code of the library.
Just include the header files, set the linker options and call the functions in your application.

On the other hand, the .lib file could contain symbols to allow the linker to link to a .dll, but as I mentioned above, you need the .dll - then the .lib file is useless. As you can't build the .dll without original source code of the library, you can write your own library (using the given header) and build it as .dll.

More about the libraries you can find under What's the differences between .dll , .lib, .h files?

Microsoft has some walkthrough guides as well:

Walkthrough: Creating and Using a Static Library (C++):

Walkthrough: Creating and Using a Dynamic Link Library (C++)

Title: calling .lib from .DLL in c++

Body:
I would like to use a c++ library given by a company. I only have the .lib and the .h files. I would like to use it in unity. So I need a DLL. So I want to create a DLL that permit me to access the functions I need in the .lib .

To do so I created a visual studio c++ DLL project with a c++ file that call the desired functions from the library. The .lib is linked to visual studio in linker/input/additional dependences.

In order to make it simple I am trying to call fonctions of my DLL from a normal c++ file instead of unity.

My test file look like this :

#include <windows.h>
#include <iostream>

void CallMyDLL(void)
{
 HINSTANCE hGetProcIDDLL = LoadLibrary("C:\\path\\museDLL.dll");
 FARPROC lpfnGetProcessID = GetProcAddress(HMODULE (hGetProcIDDLL),"startConnection");
   typedef void (__stdcall * pICFUNC)();
   pICFUNC startConnection;
   startConnection = pICFUNC(lpfnGetProcessID);

  //std::cout << test<< std::endl;

  startConnection();

  FreeLibrary(hGetProcIDDLL);

}
int main () {
CallMyDLL();
}

and my main DLL file look like this :

#include "dllmain.h"
#include <iostream>
#include <fstream>
#include "main_muse.h"
namespace museDLL
{
    MainPage* mp;
      void startConnection()
    {
           mp = new  MainPage();
    }

    double getValue()
    {
        return mp->getValueEEG();
    }

    double test()
    {
        return 1.2f;
    }

}

dllmain.h

#pragma once

#ifdef DLL_EXPORTS
#define DLL_API __declspec(dllexport)
#else
#define DLL_API __declspec(dllimport)
#endif

namespace museDLL
{
    extern "C" {
        DLL_API void __cdecl startConnection();
        DLL_API double __cdecl getValue();
        DLL_API double __cdecl test();

    }
}

If I call the test function in my DLL it works. However If I call the startConnection function that use functions from the original .lib it crashes ( no error messages ) .

so to make it clear , I want test file-> calling my custom DLL -> calling the downloaded .lib .

I don't understand what I am doing wrong?

I wonder if the initial .lib is included in the .DLL or do I need to link it somehow?


问:
c# - Download the contents of an online file to a string
I want to download the content of a .txt file located on my website to a string using c#.
I've tried with DownloadStringAsync(Uri, String), but it doesn't work and the string stays blank. If I try with string_name = DownloadStringAsync(Uri), it gives me the "cannot convert a void to a string" error.
I'm using the .NET Framework 3.5

答:
Check System.Net.WebClient.DownloadString(url).

If you use Encoding you can set the WebClient's property inbefore to get the right result, and use .Dispose() on the webclient afterwards.


答:
Use this instead:

var dbs = [ "admin", "newdb", "newdb2", "local", "test" ];
var arrayLength = dbs.length;
var databases = [];
for (var i = 0 ; i < arrayLength; i++){
    if ((dbs[i] != "admin") && (dbs[i] != "local") && (dbs[i] != "test"))
        {
         databases.push(dbs[i])
        }
}
console.log(databases);```

Title: Javascript array push


问:
Is there any markdown tools that support task lists
I have googled for a long time but can not find any tools that support task lists in GFM.

I tested this line in the tools:

```<code>- [x] This is a complete item
</code>```

StackEdit, misaka, marked and so on, NONE of them worked while most of them claim support GFM.

Is there any tools support task lists?

PS：I know we can add this feature to StackEdit by Custom but just preview not export.

答:
Here's some more info on the solution the OP refers to:

https://github.com/benweet/stackedit/issues/324#issuecomment-82646808

To enable it, follow these steps:

StackEdit > Settings > Extensions

Expand the UserCustom extension (bottom of the list)

Paste this code in the JavaScript code field:

```<code>userCustom.onPreviewFinished = function() {
    $('#preview-contents dd').each(function() {
        $(this).html(function(index,html){
            return html.replace(/\[ ?\]/g,'<i class="icon-check-empty"></i>');
        });
        $(this).html(function(index,html){
            return html.replace(/\[X\]/ig,'<i class="icon-check"></i>');
        });
    });
    $('#preview-contents li').each(function() {
        $(this).html(function(index,html){
            return html.replace(/\[ ?\]/g,'<i class="icon-check-empty"></i>');
        });
        $(this).html(function(index,html){
            return html.replace(/\[X\]/ig,'<i class="icon-check"></i>');
        });
    });
};
</code>```

Click OK to save the changes

Body:
I have googled for a long time but can not find any tools that support task lists in GFM.

I tested this line in the tools:

- [x] This is a complete item

StackEdit, misaka, marked and so on, NONE of them worked while most of them claim support GFM.

Is there any tools support task lists?

PS：I know we can add this feature to StackEdit by Custom but just preview not export.

Body:
Here's some more info on the solution the OP refers to:

https://github.com/benweet/stackedit/issues/324#issuecomment-82646808

To enable it, follow these steps:

StackEdit > Settings > Extensions

Expand the UserCustom extension (bottom of the list)

Paste this code in the JavaScript code field:

userCustom.onPreviewFinished = function() {
    $('#preview-contents dd').each(function() {
        $(this).html(function(index,html){
            return html.replace(/\[ ?\]/g,'<i class="icon-check-empty"></i>');
        });
        $(this).html(function(index,html){
            return html.replace(/\[X\]/ig,'<i class="icon-check"></i>');
        });
    });
    $('#preview-contents li').each(function() {
        $(this).html(function(index,html){
            return html.replace(/\[ ?\]/g,'<i class="icon-check-empty"></i>');
        });
        $(this).html(function(index,html){
            return html.replace(/\[X\]/ig,'<i class="icon-check"></i>');
        });
    });
};

Click OK to save the changes


问:
How to rollback a postgresql connection when using cherrypy
I use cherrypy to run an api and use thread_data to attach a postgresql cursor to each thread.

```<code>def connect_pg(thread_index):
    cherrypy.thread_data.pgdb = connect(**cherrypy.config['pgargs'])
    dict_cur = cherrypy.thread_data.pgdb.cursor(cursor_factory=psycopg2.extras.DictCursor)
    dict_cur.close()
</code>```

I then create a cursor using

cherrypy.thread_data.pgdb.cursor(cursor_factory=psycopg2.extras.DictCursor)

Occasionally a bad request may be made, which results in the error message

InternalError: current transaction is aborted, commands ignored until end of transaction block

The standard solution for this is to do a rollback (http://initd.org/psycopg/docs/faq.html).

However, rollback is a connection method and not a cursor method.

What are some good ways to deal with this error when using cherrpy's thread_data?

答:
I used autocommit within cherrypy and that has done the job nicely (How do I properly use psycopg2 with cherrypy?). I now create the cursor as follows:</p>

```<code>def connect_pg(thread_index):
   cherrypy.thread_data.pgdb = connect(**cherrypy.config['pgargs'])
   cherrypy.thread_data.pgdb.autocommit=True
   dict_cur = cherrypy.thread_data.pgdb.cursor(cursor_factory=psycopg2.extras.DictCursor)
   dict_cur.close()
</code>```

Body:
I use cherrypy to run an api and use thread_data to attach a postgresql cursor to each thread.

def connect_pg(thread_index):
    cherrypy.thread_data.pgdb = connect(**cherrypy.config['pgargs'])
    dict_cur = cherrypy.thread_data.pgdb.cursor(cursor_factory=psycopg2.extras.DictCursor)
    dict_cur.close()

I then create a cursor using

cherrypy.thread_data.pgdb.cursor(cursor_factory=psycopg2.extras.DictCursor)

Occasionally a bad request may be made, which results in the error message

InternalError: current transaction is aborted, commands ignored until end of transaction block

The standard solution for this is to do a rollback (http://initd.org/psycopg/docs/faq.html).

However, rollback is a connection method and not a cursor method.

What are some good ways to deal with this error when using cherrpy's thread_data?

Body:
I used autocommit within cherrypy and that has done the job nicely (How do I properly use psycopg2 with cherrypy?). I now create the cursor as follows:

def connect_pg(thread_index):
   cherrypy.thread_data.pgdb = connect(**cherrypy.config['pgargs'])
   cherrypy.thread_data.pgdb.autocommit=True
   dict_cur = cherrypy.thread_data.pgdb.cursor(cursor_factory=psycopg2.extras.DictCursor)
   dict_cur.close()


问:
How to run nuxt.js in real service?
I used vue-cli in

vue init nuxt/express myProject

and,

npm run dev

developed.

but,

npm run build

after, was created dist file.

How i can run in real service in pm2?

(I will use ubuntu in AWS EC.)

答:
you just need to start your app like that:

```<code>pm2 start npm --name "your-project-name" -- start
</code>```

Check the status:

```<code>pm2 status
</code>```

and after you can restart / stop:

```<code>pm2 restart your-project-name
pm2 stop your-project-name
</code>```

Title: How to run nuxt.js in real service?

Body:
you just need to start your app like that:

pm2 start npm --name "your-project-name" -- start

Check the status:

pm2 status

and after you can restart / stop:

pm2 restart your-project-name
pm2 stop your-project-name


答:
Check for a localStorage item before the popup displays, and when you display it, set the localStorage item. Since this won't work in the SO sandbox, here's a codepen https://codepen.io/mcoker/pen/PjqQqw

document.body.onclick = function() {
  if (!localStorage.popup) {
    localStorage.popup = 1;
    window.open(
      "My site",
      "poppage",
      "toolbars=0, scrollbars=1, location=0, statusbars=0, menubars=0, resizable=1, width=950, height=650, left = 300, top = 50"
    );
  }
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  min-height: 100vh;
}</code>```

Title: How do I limit one pop up per user, using JavaScript

Body:
Check for a localStorage item before the popup displays, and when you display it, set the localStorage item. Since this won't work in the SO sandbox, here's a codepen https://codepen.io/mcoker/pen/PjqQqw

document.body.onclick = function() {
  if (!localStorage.popup) {
    localStorage.popup = 1;
    window.open(
      "My site",
      "poppage",
      "toolbars=0, scrollbars=1, location=0, statusbars=0, menubars=0, resizable=1, width=950, height=650, left = 300, top = 50"
    );
  }
};

body {
  min-height: 100vh;
}


问:
Access all variables in an array
I'm sure this is a simple question but I'm asking it anyways. Basically I'm trying to do the following in javascript (no jquery) with less code:

```<code>var Ground = [];

function gameLoop()
{
    Gravity += 0.2

    if(Ground[0].isCollided(Player))
    {
        Player.dy = 0;
        Gravity = 0;
    }
    if(Ground[1].isCollided(Player))
    {
        Player.dy = 0;
        Gravity = 0;
    }
    if(Ground[2].isCollided(Player))
    {
        Player.dy = 0;
        Gravity = 0;
    }

    Player.dy = Gravity;
}
</code>```

I've simplified the code extremely from the code in my game I'm making using javascript and the html5 canvas.
What you see is my Ground mechanic as it stands. When the player collides with the Ground Block, the Player's .dy value will no longer change along with the Gravity.

What you saw above is how I would normally do it however this can take up a large amount of space if I have 50 FallingM variables. Is it possible to do something like:

```<code>if(Ground[i].isCollided(Player))
{
    Player.dy = 0;
    Gravity = 0;
}
</code>```

So that the function will still run no matter how many Ground variables I add? Thanks ahead of time!

答:
Remember, a Jedi's strength flows from the loops. But beware. Map,
  reduce, some. The dark side are they. Once you start down the dark
  path, forever will it dominate your destiny.

```<code>if (grounds.some(ground => ground.isCollided(player))) {
  player.dy = 0;
  gravity = 0;
}
</code>```

Title: Access all variables in an array

Body:
I'm sure this is a simple question but I'm asking it anyways. Basically I'm trying to do the following in javascript (no jquery) with less code:

var Ground = [];

function gameLoop()
{
    Gravity += 0.2

    if(Ground[0].isCollided(Player))
    {
        Player.dy = 0;
        Gravity = 0;
    }
    if(Ground[1].isCollided(Player))
    {
        Player.dy = 0;
        Gravity = 0;
    }
    if(Ground[2].isCollided(Player))
    {
        Player.dy = 0;
        Gravity = 0;
    }

    Player.dy = Gravity;
}

I've simplified the code extremely from the code in my game I'm making using javascript and the html5 canvas.
What you see is my Ground mechanic as it stands. When the player collides with the Ground Block, the Player's .dy value will no longer change along with the Gravity.

What you saw above is how I would normally do it however this can take up a large amount of space if I have 50 FallingM variables. Is it possible to do something like:

if(Ground[i].isCollided(Player))
{
    Player.dy = 0;
    Gravity = 0;
}

So that the function will still run no matter how many Ground variables I add? Thanks ahead of time!

Body:
Remember, a Jedi's strength flows from the loops. But beware. Map,
  reduce, some. The dark side are they. Once you start down the dark
  path, forever will it dominate your destiny.

if (grounds.some(ground => ground.isCollided(player))) {
  player.dy = 0;
  gravity = 0;
}


问:
Assign char to array of chars inside an struct thats inside a array of structs thats inside a array of structs thats inside a array of struct
I need to simulate a hard disk for a college assignment. I have a char array inside a struct, another struct has an array of the last struct and so on. The teacher asked for it to be done this way.

```<code>typedef struct block {
    unsigned char bytes_s[512];
} block;

typedef struct  sectror_array {
   block sector[60];
} sectror_array;

typedef struct track_array {
    sectror_array track[5];
} track_array;
</code>```

All of that in a

```<code>track_array cylinder[10];
</code>```

declared as global.

my problem is that i can't seem to access any of these. In my code, i use a loop to assign a variable to the "byte" and then try to print it

```<code>int c=0, t=0, s=0, b=0;
  while(c<11){
    if(b==512){
      b=0;
      s++;
      if(s==60){
        s=0;
        t++;
        if(t==5){
          t=0;
          c++;
          if(c==10){
            return;
          }
        }
      }
    }
    cylinder[c].track[t].sector[s].bytes_s[b]=0;
    b++;
    printf("%d %d %d %d, %c\n",c, t, s ,b,
    cylinder[c].track[t].sector[s].bytes_s[b]);
</code>```

But it shows nothing even as i tryed to assign 'a' to every byte.

Yet it compiles and runs without crashes.

Never had to work with such before and i'm out of ideas of how to fix this.

https://github.com/diceEviscerator/trabOA

code is my_drive.cpp

saved as cpp but is pure c (needed to save as cpp to run gtest)

答:
while (cylinder[j].track[t].sector[s * 4].bytes_s[0] != 0) {

The program just won't simply enter the loop.

I tried to "initialize" the struct by making a loop that would assign 0 to every byte

So, an extremely simplified version of what you describe looks like this?

```<code>int main (void)
{
   int x = 0;          // Initialize to 0

   while ( x != 0 )    // While not 0, do some work
   {
      x = 1;
   }
}
</code>```

Break your problem down into small parts and code it in small increments, verifying each as you go.  "Big Bang" coding adds too much complexity at once and makes problems much harder to find.

Body:
I need to simulate a hard disk for a college assignment. I have a char array inside a struct, another struct has an array of the last struct and so on. The teacher asked for it to be done this way.

typedef struct block {
    unsigned char bytes_s[512];
} block;

typedef struct  sectror_array {
   block sector[60];
} sectror_array;

typedef struct track_array {
    sectror_array track[5];
} track_array;

All of that in a

track_array cylinder[10];

declared as global.

my problem is that i can't seem to access any of these. In my code, i use a loop to assign a variable to the "byte" and then try to print it

int c=0, t=0, s=0, b=0;
  while(c<11){
    if(b==512){
      b=0;
      s++;
      if(s==60){
        s=0;
        t++;
        if(t==5){
          t=0;
          c++;
          if(c==10){
            return;
          }
        }
      }
    }
    cylinder[c].track[t].sector[s].bytes_s[b]=0;
    b++;
    printf("%d %d %d %d, %c\n",c, t, s ,b,
    cylinder[c].track[t].sector[s].bytes_s[b]);

But it shows nothing even as i tryed to assign 'a' to every byte.

Yet it compiles and runs without crashes.

Never had to work with such before and i'm out of ideas of how to fix this.

https://github.com/diceEviscerator/trabOA

code is my_drive.cpp

saved as cpp but is pure c (needed to save as cpp to run gtest)

Body:
while (cylinder[j].track[t].sector[s * 4].bytes_s[0] != 0) {

The program just won't simply enter the loop.

I tried to "initialize" the struct by making a loop that would assign 0 to every byte

So, an extremely simplified version of what you describe looks like this?

int main (void)
{
   int x = 0;          // Initialize to 0

   while ( x != 0 )    // While not 0, do some work
   {
      x = 1;
   }
}

Break your problem down into small parts and code it in small increments, verifying each as you go.  "Big Bang" coding adds too much complexity at once and makes problems much harder to find.


问:
Swift Typealias for Class and Protocol
I have a variable that must be a UIView that also implements the protocol MTMathKeyboard.

I've tried,

```<code>var keyboard: (UIView & MTMathKeyboard)
var keyboard: UIView<MTMathKeyboard>
</code>```

What's the syntax for a non-generic class instance that implements a protocol?

答:
In Swift 4 you can use:</p>

```<code>let keyboard: UIView & MTMathKeyboard
</code>```

Title: Swift Typealias for Class and Protocol

Body:
I have a variable that must be a UIView that also implements the protocol MTMathKeyboard.

I've tried,

var keyboard: (UIView & MTMathKeyboard)
var keyboard: UIView<MTMathKeyboard>

What's the syntax for a non-generic class instance that implements a protocol?

Body:
In Swift 4 you can use:

let keyboard: UIView & MTMathKeyboard


问:
How to find records that don't have a value in SQL Server 2014?
I have a table 'FinTrans' that has data that looks like this:

```<code>---------------------------------
|AcctID     |TransCode |TransAmt|
---------------------------------
|1234567    |TOLL      |    4:30|
---------------------------------
|1234567    |PYMT      |    5:30|
---------------------------------
|1234567    |RFND      |    1:00|
---------------------------------
|2345678    |TOLL      |    4:30|
---------------------------------
|2345678    |TOLL      |    4:30|
---------------------------------
|2345678    |RFND      |    4:30|
---------------------------------
|3456789    |TOLL      |    4:30|
---------------------------------
</code>```

And I have an 'Account' Table that gives the account number for each AcctID.

I need to  find Account Numbers that don't have 'PYMT' as the TransCode.

I have tried the following code but clearly that didn't work.

```<code>SELECT DISTINCT(A.AccountNumber)
      ,TransCode
      ,SUM(TransAmt)

  FROM FinTrans F
  INNER JOIN Account A ON F.AcctID = A.AccountID

  WHERE TransCode = 'TOLL'
    AND TransCode != 'PYMT'

  GROUP BY A.AccountNumber, TransCode
</code>```

答:
I need to find Account Numbers that don't have 'PYMT' as the TransCode

You can try this... using group by having

```<code>SELECT A.AccountNumber
      ,TransCode
      ,SUM(TransAmt)

  FROM FinTrans F
  INNER JOIN Account A ON F.AcctID = A.AccountID
  where TransCode IN ('PYMT', 'TOLL')
  GROUP BY A.AccountNumber, TransCode
  HAVING SUM(IIF(TransCode = 'PYMT',1,0)) = 0
</code>```

Body:
I have a table 'FinTrans' that has data that looks like this:

---------------------------------
|AcctID     |TransCode |TransAmt|
---------------------------------
|1234567    |TOLL      |    4:30|
---------------------------------
|1234567    |PYMT      |    5:30|
---------------------------------
|1234567    |RFND      |    1:00|
---------------------------------
|2345678    |TOLL      |    4:30|
---------------------------------
|2345678    |TOLL      |    4:30|
---------------------------------
|2345678    |RFND      |    4:30|
---------------------------------
|3456789    |TOLL      |    4:30|
---------------------------------

And I have an 'Account' Table that gives the account number for each AcctID.

I need to  find Account Numbers that don't have 'PYMT' as the TransCode.

I have tried the following code but clearly that didn't work.

SELECT DISTINCT(A.AccountNumber)
      ,TransCode
      ,SUM(TransAmt)

  FROM FinTrans F
  INNER JOIN Account A ON F.AcctID = A.AccountID

  WHERE TransCode = 'TOLL'
    AND TransCode != 'PYMT'

  GROUP BY A.AccountNumber, TransCode

Body:
I need to find Account Numbers that don't have 'PYMT' as the TransCode

You can try this... using group by having

SELECT A.AccountNumber
      ,TransCode
      ,SUM(TransAmt)

  FROM FinTrans F
  INNER JOIN Account A ON F.AcctID = A.AccountID
  where TransCode IN ('PYMT', 'TOLL')
  GROUP BY A.AccountNumber, TransCode
  HAVING SUM(IIF(TransCode = 'PYMT',1,0)) = 0