问:
AES use same IV for encryption and decryption
I'm having some issues with my code whereby I am not using the same IV for encryption and decryption. I know in order to do this correctly I have to write the IV to my output file before the data however I am struggling implementing this. Could anyone help me with this issue?

Edited code code again to show full scope

```<code>public class TestFileEncryption {
    private static void mainCrypto(int cipherMode, File inputFile, File outputFile) throws Exception{
        //Let the user enter the key they wish to use
        Key secretKey = new SecretKeySpec(UITest.getStoreKey().getBytes(), UITest.getSendAlg()); //Generates a key based on the default keysize for the specified algorithm

        //Generate an Initialization Vector (IV)
        final int ALG_KEYLENGTH = UITest.getStoreKey().length(); //Change this as desired for the security level you want
        byte[] iv = new byte[ALG_KEYLENGTH]; //Save the IV bytes or send it in plaintext with the encrypted data so you can decrypt the data later
        SecureRandom prng = new SecureRandom(); //Use SecureRandom to generate random bits. The size of the IV matches the blocksize of the cipher
        prng.nextBytes(iv); //Construct the appropriate IvParameterSpec object for the data to pass to Cipher's init() method

        //Create a Cipher by specifying the following parameters: Alg name, Mode (CBC), Padding (PKC7/PKCS5)
        Cipher cipherForEncryption = Cipher.getInstance(UITest.getSendAlg() + "/CBC/PKCS5PADDING"); // Must specify the mode explicitly as most JCE providers default to ECB mode

        //Initialize the Cipher for Encryption
        cipherForEncryption.init(cipherMode, secretKey, new IvParameterSpec(iv));

        //Declare / Initialize the Data, Convert the Input to Bytes and encrypt or decrypt using doFinal.
        FileInputStream inputStream = new FileInputStream(inputFile);
        byte[] inputBytes = new byte[(int) inputFile.length() - ALG_KEYLENGTH];
        inputStream.read(iv);
        inputStream.read(inputBytes);
        byte[] outputBytes = cipherForEncryption.doFinal(inputBytes);
        FileOutputStream outputStream = new FileOutputStream(outputFile);
        outputStream.write(iv);
        outputStream.write(outputBytes);
        inputStream.close();
        outputStream.close();
    }

    public static void encrypt(File inputFile, File outputFile) throws Exception {
        mainCrypto(Cipher.ENCRYPT_MODE, inputFile, outputFile); //ENC_MODE = Constant used to initialize cipher to encryption mode.
    }

    public static void decrypt(File inputFile, File outputFile) throws Exception {
        mainCrypto(Cipher.DECRYPT_MODE, inputFile, outputFile); //ENC_MODE = Constant used to initialize cipher to encryption mode.
    }

    public static void main(String[] args) {}
}
</code>```

答:
Just extending answer of @Javier.

it looks like you'd like to use the same method for encryption and decrpytion (depending on the mode) however there's a difference in handling the IV.

You generated a random IV, then you overwrote it with the input of the (plain) input and at the end you wrote it to the output (regardless it's decryption).

So you have to distinguish if the mode is

encryption - the IV is generated and written to the output before ciphertext

decryption - the IV is read from the input and used for decryption, but not written to the output

something like that:

```<code>private void encrypt(File inputFile, File outputFile)  {
    //Declare / Initialize the Data, Convert the Input to Bytes and encrypt or decrypt using doFinal.
    FileInputStream inputStream = new FileInputStream(inputFile);
    byte[] inputBytes = new byte[(int) inputFile.length()];
    byte[] iv = new byte[16]; // 16 for AES-CBC
    SecureRandom prng = new SecureRandom(); //Use SecureRandom to generate random bits. The size of the IV matches the blocksize of the cipher
    prng.nextBytes(iv); //Construct the appropriate IvParameterSpec object for the data to pass to Cipher's init() method

    //Create a Cipher by specifying the following parameters: Alg name, Mode (CBC), Padding (PKC7/PKCS5)
    Cipher cipherForEncryption = Cipher.getInstance(UITest.getSendAlg() + "/CBC/PKCS5PADDING"); // Must specify the mode explicitly as most JCE providers default to ECB mode

    //Initialize the Cipher for Encryption
    cipherForEncryption.init(cipherMode, secretKey, new IvParameterSpec(iv));
        inputStream.read(inputBytes);
        byte[] outputBytes = cipherForEncryption.doFinal(inputBytes);
        FileOutputStream outputStream = new FileOutputStream(outputFile);
        outputStream.write(iv);
        outputStream.write(outputBytes);
        outputStream.flush();
        inputStream.close();
        outputStream.close();
    }
}

private void decrypt(File inputFile, File outputFile) {
    //Declare / Initialize the Data, Convert the Input to Bytes and encrypt or decrypt using doFinal.
    FileInputStream inputStream = new FileInputStream(inputFile);
    byte[] inputBytes = new byte[(int) inputFile.length()-16];
    byte[] iv = new byte[16]; // 16 for AES-CBC

    //Create a Cipher by specifying the following parameters: Alg name, Mode (CBC), Padding (PKC7/PKCS5)
    Cipher cipherForEncryption = Cipher.getInstance(UITest.getSendAlg() + "/CBC/PKCS5PADDING"); // Must specify the mode explicitly as most JCE providers default to ECB mode

    //Initialize the Cipher for Encryption
    cipherForEncryption.init(cipherMode, secretKey, new IvParameterSpec(iv));
    inputStream.read(iv);
    inputStream.read(inputBytes);
    byte[] outputBytes = cipherForEncryption.doFinal(inputBytes);
    FileOutputStream outputStream = new FileOutputStream(outputFile);
    outputStream.write(outputBytes);
    outputStream.flush();
    inputStream.close();
    outputStream.close();
}
</code>```

To leave out some detail, maybe you could directly use Java CipherOutputStream and CiptherInputStream and the implementation will handle these details for you (if you don't care about exact format).

Next what are you missing is an authentication tag, at least hash of the plaintext assuring integrity of the ciphertext. (it's called authenticated encryption)

Body:
I'm having some issues with my code whereby I am not using the same IV for encryption and decryption. I know in order to do this correctly I have to write the IV to my output file before the data however I am struggling implementing this. Could anyone help me with this issue?

Edited code code again to show full scope

public class TestFileEncryption {
    private static void mainCrypto(int cipherMode, File inputFile, File outputFile) throws Exception{
        //Let the user enter the key they wish to use
        Key secretKey = new SecretKeySpec(UITest.getStoreKey().getBytes(), UITest.getSendAlg()); //Generates a key based on the default keysize for the specified algorithm

        //Generate an Initialization Vector (IV)
        final int ALG_KEYLENGTH = UITest.getStoreKey().length(); //Change this as desired for the security level you want
        byte[] iv = new byte[ALG_KEYLENGTH]; //Save the IV bytes or send it in plaintext with the encrypted data so you can decrypt the data later
        SecureRandom prng = new SecureRandom(); //Use SecureRandom to generate random bits. The size of the IV matches the blocksize of the cipher
        prng.nextBytes(iv); //Construct the appropriate IvParameterSpec object for the data to pass to Cipher's init() method

        //Create a Cipher by specifying the following parameters: Alg name, Mode (CBC), Padding (PKC7/PKCS5)
        Cipher cipherForEncryption = Cipher.getInstance(UITest.getSendAlg() + "/CBC/PKCS5PADDING"); // Must specify the mode explicitly as most JCE providers default to ECB mode

        //Initialize the Cipher for Encryption
        cipherForEncryption.init(cipherMode, secretKey, new IvParameterSpec(iv));

        //Declare / Initialize the Data, Convert the Input to Bytes and encrypt or decrypt using doFinal.
        FileInputStream inputStream = new FileInputStream(inputFile);
        byte[] inputBytes = new byte[(int) inputFile.length() - ALG_KEYLENGTH];
        inputStream.read(iv);
        inputStream.read(inputBytes);
        byte[] outputBytes = cipherForEncryption.doFinal(inputBytes);
        FileOutputStream outputStream = new FileOutputStream(outputFile);
        outputStream.write(iv);
        outputStream.write(outputBytes);
        inputStream.close();
        outputStream.close();
    }

    public static void encrypt(File inputFile, File outputFile) throws Exception {
        mainCrypto(Cipher.ENCRYPT_MODE, inputFile, outputFile); //ENC_MODE = Constant used to initialize cipher to encryption mode.
    }

    public static void decrypt(File inputFile, File outputFile) throws Exception {
        mainCrypto(Cipher.DECRYPT_MODE, inputFile, outputFile); //ENC_MODE = Constant used to initialize cipher to encryption mode.
    }

    public static void main(String[] args) {}
}

Body:
Just extending answer of @Javier.

it looks like you'd like to use the same method for encryption and decrpytion (depending on the mode) however there's a difference in handling the IV.

You generated a random IV, then you overwrote it with the input of the (plain) input and at the end you wrote it to the output (regardless it's decryption).

So you have to distinguish if the mode is

encryption - the IV is generated and written to the output before ciphertext

decryption - the IV is read from the input and used for decryption, but not written to the output

something like that:

private void encrypt(File inputFile, File outputFile)  {
    //Declare / Initialize the Data, Convert the Input to Bytes and encrypt or decrypt using doFinal.
    FileInputStream inputStream = new FileInputStream(inputFile);
    byte[] inputBytes = new byte[(int) inputFile.length()];
    byte[] iv = new byte[16]; // 16 for AES-CBC
    SecureRandom prng = new SecureRandom(); //Use SecureRandom to generate random bits. The size of the IV matches the blocksize of the cipher
    prng.nextBytes(iv); //Construct the appropriate IvParameterSpec object for the data to pass to Cipher's init() method

    //Create a Cipher by specifying the following parameters: Alg name, Mode (CBC), Padding (PKC7/PKCS5)
    Cipher cipherForEncryption = Cipher.getInstance(UITest.getSendAlg() + "/CBC/PKCS5PADDING"); // Must specify the mode explicitly as most JCE providers default to ECB mode

    //Initialize the Cipher for Encryption
    cipherForEncryption.init(cipherMode, secretKey, new IvParameterSpec(iv));
        inputStream.read(inputBytes);
        byte[] outputBytes = cipherForEncryption.doFinal(inputBytes);
        FileOutputStream outputStream = new FileOutputStream(outputFile);
        outputStream.write(iv);
        outputStream.write(outputBytes);
        outputStream.flush();
        inputStream.close();
        outputStream.close();
    }
}

private void decrypt(File inputFile, File outputFile) {
    //Declare / Initialize the Data, Convert the Input to Bytes and encrypt or decrypt using doFinal.
    FileInputStream inputStream = new FileInputStream(inputFile);
    byte[] inputBytes = new byte[(int) inputFile.length()-16];
    byte[] iv = new byte[16]; // 16 for AES-CBC

    //Create a Cipher by specifying the following parameters: Alg name, Mode (CBC), Padding (PKC7/PKCS5)
    Cipher cipherForEncryption = Cipher.getInstance(UITest.getSendAlg() + "/CBC/PKCS5PADDING"); // Must specify the mode explicitly as most JCE providers default to ECB mode

    //Initialize the Cipher for Encryption
    cipherForEncryption.init(cipherMode, secretKey, new IvParameterSpec(iv));
    inputStream.read(iv);
    inputStream.read(inputBytes);
    byte[] outputBytes = cipherForEncryption.doFinal(inputBytes);
    FileOutputStream outputStream = new FileOutputStream(outputFile);
    outputStream.write(outputBytes);
    outputStream.flush();
    inputStream.close();
    outputStream.close();
}

To leave out some detail, maybe you could directly use Java CipherOutputStream and CiptherInputStream and the implementation will handle these details for you (if you don't care about exact format).

Next what are you missing is an authentication tag, at least hash of the plaintext assuring integrity of the ciphertext. (it's called authenticated encryption)


来源: stackexchange

问:
How to create a selector ID from a variable
In my HTML document, I want to have 9 checkboxes. When a checkbox is selected, I want a corresponding block of text to show. I'm trying to create a single function for this, that uses a parameter to select the corresponding box, but I've been unsuccesfull so far. I'm not experienced with HTML of jQuery at all, so I've got no idea what the problem is.

The code I currently have is as follows:

$(document).ready(function() {
    for ($i = 0; $i < 9; $i++) {
        $("input[name=checkbox" + $i + "]").click(function () {
            $('#box' + $i).toggle();
        });
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox1" value="alpha"> Checkbox 1 <br>
<input type="checkbox" name="checkbox2" value="beta"> Checkbox 2 <br>

<div id = "box1" style="display:none">Checkbox 1 is selected</div>
<div id = "box2" style="display:none">Checkbox 2 is selected</div></code>```

Can anyone please help me understand why the .toggle doesn't work correctly?

答:
What you are looking for is jQuery this, which can be used to get the current element clicked on. Say all the checkboxes have the class "checkbox". All the boxes have the class "box". You can use .index() to get the index of the .checkbox clicked on, and find the .box with the same index. Then all you have to do is .toggle() it.

$('.checkbox').click(function() {
  var index_number = $('.checkbox').index(this);
  $('.box').eq(index_number).toggle();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="checkbox" class="checkbox"> Checkbox 1<br>
<input type="checkbox" class="checkbox"> Checkbox 2<br>

<div style="display:none" class="box">Checkbox 1 is selected</div>
<div style="display:none" class="box">Checkbox 2 is selected</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
In my HTML document, I want to have 9 checkboxes. When a checkbox is selected, I want a corresponding block of text to show. I'm trying to create a single function for this, that uses a parameter to select the corresponding box, but I've been unsuccesfull so far. I'm not experienced with HTML of jQuery at all, so I've got no idea what the problem is.

The code I currently have is as follows:

$(document).ready(function() {
    for ($i = 0; $i < 9; $i++) {
        $("input[name=checkbox" + $i + "]").click(function () {
            $('#box' + $i).toggle();
        });
    }
});

<input type="checkbox" name="checkbox1" value="alpha"> Checkbox 1

<input type="checkbox" name="checkbox2" value="beta"> Checkbox 2

Checkbox 1 is selected

Checkbox 2 is selected

Can anyone please help me understand why the .toggle doesn't work correctly?

Body:
What you are looking for is jQuery this, which can be used to get the current element clicked on. Say all the checkboxes have the class "checkbox". All the boxes have the class "box". You can use .index() to get the index of the .checkbox clicked on, and find the .box with the same index. Then all you have to do is .toggle() it.

$('.checkbox').click(function() {
  var index_number = $('.checkbox').index(this);
  $('.box').eq(index_number).toggle();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="checkbox" class="checkbox"> Checkbox 1<br>
<input type="checkbox" class="checkbox"> Checkbox 2<br>

<div style="display:none" class="box">Checkbox 1 is selected</div>
<div style="display:none" class="box">Checkbox 2 is selected</div>


问:
"alert" is not defined when running www.jshint.com
I fixed this by simply adding var alert;  However, is this what I should be doing to get the pesky error message to go away?  Here is the fix.  Here is the fail on www.jshint.com.

I'm trying to learn from the error it throws..not necessarily make them go away.

```<code>(function () {

"use strict";

var alert;  //  added this in to fix

function initialize_page()
  {
  alert ("hi");
  }

addEventListener('load', initialize_page);

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

答:
Instead of:

```<code>alert('message')
</code>```

I use:

```<code>var alert = window['alert'];
</code>```

Body:
I fixed this by simply adding var alert;  However, is this what I should be doing to get the pesky error message to go away?  Here is the fix.  Here is the fail on www.jshint.com.

I'm trying to learn from the error it throws..not necessarily make them go away.

(function () {

"use strict";

var alert;  //  added this in to fix

function initialize_page()
  {
  alert ("hi");
  }

addEventListener('load', initialize_page);

})();

Body:
Instead of:

alert('message')

I use:

var alert = window['alert'];


问:
SDN-4 connection pooling
I am using spring-data-neo4j 4.1.3.RELEASE with spring boot application. Using neo4j in server mode, community edition - version 3.1.0 with http driver ( would be changing to bolt driver soon)

I am using neo4j session with request scope

```<code>    @Bean
    @Override
    @Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
    public Session getSession() throws Exception {
        return super.getSession();
    }
</code>```

I would like know how to enable connection pooling with http driver or bolt driver.

答:
Connection pooling is enabled by default in SDN/OGM for both http and bolt driver. The default pool size is 50.

To modify the pool size you can set following property in ogm.properties:

```<code>connection.pool.size=50
</code>```

or if you use java configuration:

OGM 2.0.x (used by SDN 4.1.x)

```<code>org.neo4j.ogm.config.DriverConfiguration#setConnectionPoolSize
</code>```

OGM 2.1.x (used by SDN 4.2.x)

```<code>org.neo4j.ogm.config.Configuration.Builder#connectionPoolSize
</code>```

Title: SDN-4 connection pooling

Body:
I am using spring-data-neo4j 4.1.3.RELEASE with spring boot application. Using neo4j in server mode, community edition - version 3.1.0 with http driver ( would be changing to bolt driver soon)

I am using neo4j session with request scope

    @Bean
    @Override
    @Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
    public Session getSession() throws Exception {
        return super.getSession();
    }

I would like know how to enable connection pooling with http driver or bolt driver.

Body:
Connection pooling is enabled by default in SDN/OGM for both http and bolt driver. The default pool size is 50.

To modify the pool size you can set following property in ogm.properties:

connection.pool.size=50

or if you use java configuration:

OGM 2.0.x (used by SDN 4.1.x)

org.neo4j.ogm.config.DriverConfiguration#setConnectionPoolSize

OGM 2.1.x (used by SDN 4.2.x)

org.neo4j.ogm.config.Configuration.Builder#connectionPoolSize


问:
subscribe getting called after below codes execution?
I have a code that looks like this -

```<code>ngOnInit(){
          console.log("ngOnInit before service call");
          this._blockCreditCardService.getAccountList().
              subscribe(
                (data)=> {
                          this.accountList=data;
                          console.log("account-list-"+this.accountList[0])
                          console.log(this.accountList.length);
                          if(this.accountList.length>0){
                            this.nonEmptyAccountList=true;
                          }
                          this.options=[];
                          for (let i = 0; i < this.accountList.length; i++) {
                            this.options.push({ value: this.accountList[i], label:this.accountList[i].accountNumber});
                          }
                },
                error=> console.log("Error"),
                ()=> console.info("Completed")
               );
          this.selectedCardFromVerify=[];
          console.log("ngOnInit this.cardDetails-"+this.cardDetails);
          (this.cardDetails) ? this.reSelected(this.cardDetails) : this.isAccountSelected=false;

        }
</code>```

and the result is

```<code>ngOnInit before service call
capture.component.ts?dfa9:125 ngOnInit this.cardDetails-undefined
core.es5.js?0445:3231 Angular is running in the development mode. Call enableProdMode() to enable the production mode.
capture.component.ts?dfa9:111 account-list-[object Object]
</code>```

on browser's console. What am i missing here. Why this is happening. i am new to angular 2 and would like someone to shed some light over here. Thanks.

答:
The subscribe is asynchronous, so that service call starts and the rest of the function continues while the subscribe is waiting for data, and then that thread continues when the data comes back, so your ngOnInit console log runs first because the service hasn't finished returning data yet.

If you want the remaining instructions to happen after the data comes back, you need to move them into the subscription block after you've assigned the data to this.accountList=data.

```<code>ngOnInit(){
          console.log("ngOnInit before service call");
          this._blockCreditCardService.getAccountList().
              subscribe(
                (data)=> {
                          this.accountList=data;
                          console.log("account-list-"+this.accountList[0])
                          console.log(this.accountList.length);
                          if(this.accountList.length>0){
                            this.nonEmptyAccountList=true;
                          }
                          this.options=[];
                          for (let i = 0; i < this.accountList.length; i++) {
                            this.options.push({ value: this.accountList[i], label:this.accountList[i].accountNumber});
                          }
                          this.selectedCardFromVerify=[];
                          console.log("ngOnInit this.cardDetails-"+this.cardDetails);
                          (this.cardDetails) ? this.reSelected(this.cardDetails) : this.isAccountSelected=false;

                },
                error=> console.log("Error"),
                ()=> console.info("Completed")
               );

        }
</code>```

Body:
I have a code that looks like this -

ngOnInit(){
          console.log("ngOnInit before service call");
          this._blockCreditCardService.getAccountList().
              subscribe(
                (data)=> {
                          this.accountList=data;
                          console.log("account-list-"+this.accountList[0])
                          console.log(this.accountList.length);
                          if(this.accountList.length>0){
                            this.nonEmptyAccountList=true;
                          }
                          this.options=[];
                          for (let i = 0; i < this.accountList.length; i++) {
                            this.options.push({ value: this.accountList[i], label:this.accountList[i].accountNumber});
                          }
                },
                error=> console.log("Error"),
                ()=> console.info("Completed")
               );
          this.selectedCardFromVerify=[];
          console.log("ngOnInit this.cardDetails-"+this.cardDetails);
          (this.cardDetails) ? this.reSelected(this.cardDetails) : this.isAccountSelected=false;

        }

and the result is

ngOnInit before service call
capture.component.ts?dfa9:125 ngOnInit this.cardDetails-undefined
core.es5.js?0445:3231 Angular is running in the development mode. Call enableProdMode() to enable the production mode.
capture.component.ts?dfa9:111 account-list-[object Object]

on browser's console. What am i missing here. Why this is happening. i am new to angular 2 and would like someone to shed some light over here. Thanks.

Body:
The subscribe is asynchronous, so that service call starts and the rest of the function continues while the subscribe is waiting for data, and then that thread continues when the data comes back, so your ngOnInit console log runs first because the service hasn't finished returning data yet.

If you want the remaining instructions to happen after the data comes back, you need to move them into the subscription block after you've assigned the data to this.accountList=data.

ngOnInit(){
          console.log("ngOnInit before service call");
          this._blockCreditCardService.getAccountList().
              subscribe(
                (data)=> {
                          this.accountList=data;
                          console.log("account-list-"+this.accountList[0])
                          console.log(this.accountList.length);
                          if(this.accountList.length>0){
                            this.nonEmptyAccountList=true;
                          }
                          this.options=[];
                          for (let i = 0; i < this.accountList.length; i++) {
                            this.options.push({ value: this.accountList[i], label:this.accountList[i].accountNumber});
                          }
                          this.selectedCardFromVerify=[];
                          console.log("ngOnInit this.cardDetails-"+this.cardDetails);
                          (this.cardDetails) ? this.reSelected(this.cardDetails) : this.isAccountSelected=false;

                },
                error=> console.log("Error"),
                ()=> console.info("Completed")
               );

        }


问:
Django : Role based Access Control
How to implemet role based access control in Django?

Managing different users based on their roles in a project like User, Admin, Manager ,Teacher ,etc., Is there any open source library available?

I have read about User authentication in Django. Which deals with roles and groups. Can I define access for different type of users.

答:
Use Django groups for manage all the roles you need.

After that from Django admin assign the relative permissions

Docs:

https://docs.djangoproject.com/en/1.11/topics/auth/
  https://docs.djangoproject.com/en/1.11/topics/auth/default/#topic-authorization

Title: Django : Role based Access Control


问:
Angular 4 Http GET method is not working on localhost(127.0.0.1) to get JSON data
I am trying to get JSON data from my local server that is 127.0.0.1 by using Angular 4 services, but I can't get them to my Angular App.  I got this error.
this is my JSON data on 127.0.0.1

Note: I used XAMPP for my server [localhost (127.0.0.1)]

This is my app.component.ts

```<code>import { Component } from '@angular/core';
import { Http, Response } from '@angular/http';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {

constructor(private http: Http){}
ngOnInit()
{
this.http.get('http://127.0.0.1/wordpress/getdata.php?Name=json')
.subscribe(
 (res: Response)=>
 {
  const name = res.json();
  console.log("This is the response", name);
 }
 )
 }
 }
</code>```

This is app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

import { HttpModule } from '@angular/http';

 @NgModule({
 declarations: [
  AppComponent
 ],
imports: [
 BrowserModule,
 HttpModule
 ],
 providers: [],
 bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

答:
Since you are calling 127.0.0.1:80 from 127.0.0.1:4200 they are thought of as separate hosts. This in term means that CORS apply.

Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources (e.g. fonts) on a web page to be requested from another domain outside the domain from which the first resource was served.

To get around this proxy the requests to 127.0.0.1:80 with webpacks devserver.

https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md

proxy.conf.json

{
  "/wordpress": {
    "target": "http://localhost:80",
    "secure": false
  }
}

and then call it from the same host

http://localhost:4200/wordpress/getdata.php?Name=json

Body:
I am trying to get JSON data from my local server that is 127.0.0.1 by using Angular 4 services, but I can't get them to my Angular App.  I got this error.
this is my JSON data on 127.0.0.1

Note: I used XAMPP for my server [localhost (127.0.0.1)]

This is my app.component.ts

import { Component } from '@angular/core';
import { Http, Response } from '@angular/http';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {

constructor(private http: Http){}
ngOnInit()
{
this.http.get('http://127.0.0.1/wordpress/getdata.php?Name=json')
.subscribe(
 (res: Response)=>
 {
  const name = res.json();
  console.log("This is the response", name);
 }
 )
 }
 }

This is app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

import { HttpModule } from '@angular/http';

 @NgModule({
 declarations: [
  AppComponent
 ],
imports: [
 BrowserModule,
 HttpModule
 ],
 providers: [],
 bootstrap: [AppComponent]
})
export class AppModule { }


问:
Form validation losing variables
Let's say I enter a registration form with this ending URL: registration.php?accountType=a
The form is parsed on the same page (registration.php).  If the user doesn't pass form validation they are taken to registration.php with error messages.  So you see I lost my variable accountType=a.  My question:

Can I submit a form for validation and retain the accountType variable?  I'm aware that this could easily be done using a cookie.  I just want a further understanding.

Solution: Although all of the answers below were valid, I went with a Session variable and <form action="registration.php?<?php print 'accountType=' . $_SESSION['accountType']; ?>" etc.  Thanks for the help.

答:
You should use this in your form:

```<code><form action="registration.php?accountType=a">
</code>```

You should use this in your php:

```<code>if ($validation_success) {
    header('sucess.php')
} else {
    // don't do anything. The page(registration.php?accountType=a) loads
}
</code>```

I'm just giving you the idea.

ContentLicense: CC BY-SA 2.5

Title: Form validation losing variables

Body:
You should use this in your form:

<form action="registration.php?accountType=a">

You should use this in your php:

if ($validation_success) {
    header('sucess.php')
} else {
    // don't do anything. The page(registration.php?accountType=a) loads
}

I'm just giving you the idea.


问:
ImagickDraw Rectangle - image cannot be displayed error
I have two sites(same server) where a simple rectangle is drawn using ImagickDraw and it work fine on one and fails on second with the error -

The image "http://site_name/imagick/img?method=placeholder&params=258,150" cannot be displayed because it contains error.

Basically what code does is it take method and params(height & width) from the url and draw the image.

```<code>$params = explode(",", $_GET["params"]);
$width = (int) $params[0]; //258
$height = (int) $params[1]; //150

if ($method == "placeholder") { //This is true $method is set to placeholder
  $image = new Imagick();
  $image->newImage($width, $height, "#707070");
  $image->setImageFormat("png");

  $x = 0;
  $y = 0;
  $size = 40;
  $draw = new ImagickDraw();

  while ($y < $height) {
    $draw->setFillColor("#808080");

    $points = array(
      array("x" => $x, "y" => $y),
      array("x" => $x + $size, "y" => $y),
      array("x" => $x + $size * 2, "y" => $y + $size),
      array("x" => $x + $size * 2, "y" => $y + $size * 2),
    );
    $draw->polygon($points);

    $points = array(
      array("x" => $x, "y" => $y + $size),
      array("x" => $x + $size, "y" => $y + $size * 2),
      array("x" => $x, "y" => $y + $size * 2),
    );
    $draw->polygon($points);

    $x += $size * 2;
    if ($x > $width) {
      $x = 0;
      $y += $size * 2;
    }
  }

  $draw->setFillColor("#B0B0B0");
  $draw->setFontSize($width / 5);
  $draw->setFontWeight(800);
  $draw->setGravity(Imagick::GRAVITY_CENTER);
  $draw->annotation(0, 0, $width . " x " . $height);

  $image->drawImage($draw);

  header("Content-type: image/png");
  echo $image;
}
</code>```

I've checked the buffer before header and it is empty also tried ob_clean() - still doesn't work.

Checked for white-spaces in the file as I've found it to be affecting the image file - but there is no white-space present.

Any ideas what might be wrong here or anyway to track the errors?

答:
It was indeed the whitespace but not in the same file (weird weird weird).

Checked for all the php files included in the project with -

```<code>include_once('file_name.php');
</code>```

From multiple files, there was one such file(setting file which contains the db_name, base url, etc)  which had a space before <?php tag. So if someone gets this error, make sure all the php files are whitespace free. It messes the png image generated.

Body:
I have two sites(same server) where a simple rectangle is drawn using ImagickDraw and it work fine on one and fails on second with the error -

The image "http://site_name/imagick/img?method=placeholder&params=258,150" cannot be displayed because it contains error.

Basically what code does is it take method and params(height & width) from the url and draw the image.

$params = explode(",", $_GET["params"]);
$width = (int) $params[0]; //258
$height = (int) $params[1]; //150

if ($method == "placeholder") { //This is true $method is set to placeholder
  $image = new Imagick();
  $image->newImage($width, $height, "#707070");
  $image->setImageFormat("png");

  $x = 0;
  $y = 0;
  $size = 40;
  $draw = new ImagickDraw();

  while ($y < $height) {
    $draw->setFillColor("#808080");

    $points = array(
      array("x" => $x, "y" => $y),
      array("x" => $x + $size, "y" => $y),
      array("x" => $x + $size * 2, "y" => $y + $size),
      array("x" => $x + $size * 2, "y" => $y + $size * 2),
    );
    $draw->polygon($points);

    $points = array(
      array("x" => $x, "y" => $y + $size),
      array("x" => $x + $size, "y" => $y + $size * 2),
      array("x" => $x, "y" => $y + $size * 2),
    );
    $draw->polygon($points);

    $x += $size * 2;
    if ($x > $width) {
      $x = 0;
      $y += $size * 2;
    }
  }

  $draw->setFillColor("#B0B0B0");
  $draw->setFontSize($width / 5);
  $draw->setFontWeight(800);
  $draw->setGravity(Imagick::GRAVITY_CENTER);
  $draw->annotation(0, 0, $width . " x " . $height);

  $image->drawImage($draw);

  header("Content-type: image/png");
  echo $image;
}

I've checked the buffer before header and it is empty also tried ob_clean() - still doesn't work.

Checked for white-spaces in the file as I've found it to be affecting the image file - but there is no white-space present.

Any ideas what might be wrong here or anyway to track the errors?

Body:
It was indeed the whitespace but not in the same file (weird weird weird).

Checked for all the php files included in the project with -

include_once('file_name.php');

From multiple files, there was one such file(setting file which contains the db_name, base url, etc)  which had a space before <?php tag. So if someone gets this error, make sure all the php files are whitespace free. It messes the png image generated.


问:
Update progress bar from async method
I am trying to understand better how can I update a windows forms progress bar from an async operation but I am getting some unexpected behavior from that.

Basically I am having a button which should after is being clicked to update a progress bar and then set it back to 0 once the progress bar gets 100% updated.

This is my code:

```<code>    private async void button1_Click(object sender, EventArgs e)
    {
        await CallMethodAsync().ContinueWith((prevTask) =>
        {
            prevTask.Wait();
            progressBar1.Invoke(new Action(() => { progressBar1.Value = 0; }));
        });
    }

    private static async Task ExecuteMethodAsync(IProgress<double> progress = null)
    {
        double percentComplete = 0;
        bool done = false;

        while (!done)
        {
            if (progress != null)
            {
                progress.Report(percentComplete);
            }

            percentComplete += 10;

            if(percentComplete == 100)
            {
                done = true;
            }
        }
    }

    private async Task CallMethodAsync()
    {
        var progress = new Progress<double>();
        progress.ProgressChanged += (sender, args) => { progressBar1.Increment(10); };
        await ExecuteMethodAsync(progress);
    }
</code>```

Having this implementation the progress bar is not being updated at all even if I call "Wait()" on the operation that should update the value of the progress bar.

If i remove this part of code:

```<code>progressBar1.Invoke(new Action(() => { progressBar1.Value = 0; }));
</code>```

the progress bar gets updated but it remains all the time like that, and I want to set it back to 0 once it was entirely filled so that I can update it again when I click again the button.

Could someone please explain me what am I doing wrong ?

答:
One of the reasons async-await syntax was invented because it was difficult to follow the sequence of instructions when tasks were concatenated using functions like ContinueWith.

If you use async-await it is seldom necessary to use statements like ContinueWith. After an await, the thread already continues with the statements after the await.

If the button is clicked, you want to call ExcecuteMethodAsync. This function takes an IProgress, because it wants to report progress regularly. You want to call this function asynchronously, so whenever the function has to wait for something, it doesn't really wait, but returns control to you so you could do other things instead of really waiting, until you encounter an await, in which case your caller continues processing until he encounters an await, etc.

The nice thing with async-await is that the thread that continues after your call to an async function has the same context as the calling thread. This means that you can regard it as your original thread. No InvokeRequired, no need to protect data with mutexes etc.

Your function could be simplified as follows:

```<code>async Task CallMethodAsync()
{
    var progress = new Progress<double>();
    progress.ProgressChanged += OnProgressReported;

    await ExecuteMethodAsync(progress);
}

private void OnProgressReported(object sender, ...)
{
    // because this thread has the context of the main thread no InvokeRequired!
    this.progressBar1.Increment(...);
}

private async void button1_Click(object sender, EventArgs e)
{
    await CallMethodAsync();
}
</code>```

So when the button is clicked, CallMethodAsync is called. This function will create A Progress object and subscribes on its Report event. Note that this is still your UI-thread. Then it calls ExecuteMethodAsync, which will regularly raise event Report, which is handled by OnProgressReported.

Because ExecuteMethodAsync is async, you can be sure there is somewhere an await in it. This means that whenever it has to await, control returns to the caller, which is CallMethodAsync, until is encounters an await, which in this case is immediately.

Control goes up the call stack to the caller, which is button1_click, where it immediately encounters an await, so control goes up the call stack, etc.

All these controls have the same context: it is as if they are the same thread.

An article that helped me a lot to understand async-await is this interview with Eric Lippert. Search somewhere in the middle for async await

Another articel that helped me a lot to learn good practices were this article by the ever so helpful Stephen Cleary and Async/Await - Best Practices in Asynchronous Programming also by Stephen Cleary

Title: Update progress bar from async method

Body:
I am trying to understand better how can I update a windows forms progress bar from an async operation but I am getting some unexpected behavior from that.

Basically I am having a button which should after is being clicked to update a progress bar and then set it back to 0 once the progress bar gets 100% updated.

This is my code:

    private async void button1_Click(object sender, EventArgs e)
    {
        await CallMethodAsync().ContinueWith((prevTask) =>
        {
            prevTask.Wait();
            progressBar1.Invoke(new Action(() => { progressBar1.Value = 0; }));
        });
    }

    private static async Task ExecuteMethodAsync(IProgress<double> progress = null)
    {
        double percentComplete = 0;
        bool done = false;

        while (!done)
        {
            if (progress != null)
            {
                progress.Report(percentComplete);
            }

            percentComplete += 10;

            if(percentComplete == 100)
            {
                done = true;
            }
        }
    }

    private async Task CallMethodAsync()
    {
        var progress = new Progress<double>();
        progress.ProgressChanged += (sender, args) => { progressBar1.Increment(10); };
        await ExecuteMethodAsync(progress);
    }

Having this implementation the progress bar is not being updated at all even if I call "Wait()" on the operation that should update the value of the progress bar.

If i remove this part of code:

progressBar1.Invoke(new Action(() => { progressBar1.Value = 0; }));

the progress bar gets updated but it remains all the time like that, and I want to set it back to 0 once it was entirely filled so that I can update it again when I click again the button.

Could someone please explain me what am I doing wrong ?

Body:
One of the reasons async-await syntax was invented because it was difficult to follow the sequence of instructions when tasks were concatenated using functions like ContinueWith.

If you use async-await it is seldom necessary to use statements like ContinueWith. After an await, the thread already continues with the statements after the await.

If the button is clicked, you want to call ExcecuteMethodAsync. This function takes an IProgress, because it wants to report progress regularly. You want to call this function asynchronously, so whenever the function has to wait for something, it doesn't really wait, but returns control to you so you could do other things instead of really waiting, until you encounter an await, in which case your caller continues processing until he encounters an await, etc.

The nice thing with async-await is that the thread that continues after your call to an async function has the same context as the calling thread. This means that you can regard it as your original thread. No InvokeRequired, no need to protect data with mutexes etc.

Your function could be simplified as follows:

async Task CallMethodAsync()
{
    var progress = new Progress<double>();
    progress.ProgressChanged += OnProgressReported;

    await ExecuteMethodAsync(progress);
}

private void OnProgressReported(object sender, ...)
{
    // because this thread has the context of the main thread no InvokeRequired!
    this.progressBar1.Increment(...);
}

private async void button1_Click(object sender, EventArgs e)
{
    await CallMethodAsync();
}

So when the button is clicked, CallMethodAsync is called. This function will create A Progress object and subscribes on its Report event. Note that this is still your UI-thread. Then it calls ExecuteMethodAsync, which will regularly raise event Report, which is handled by OnProgressReported.

Because ExecuteMethodAsync is async, you can be sure there is somewhere an await in it. This means that whenever it has to await, control returns to the caller, which is CallMethodAsync, until is encounters an await, which in this case is immediately.

Control goes up the call stack to the caller, which is button1_click, where it immediately encounters an await, so control goes up the call stack, etc.

All these controls have the same context: it is as if they are the same thread.

An article that helped me a lot to understand async-await is this interview with Eric Lippert. Search somewhere in the middle for async await

Another articel that helped me a lot to learn good practices were this article by the ever so helpful Stephen Cleary and Async/Await - Best Practices in Asynchronous Programming also by Stephen Cleary


问:
Read comma separated string in Sql server in loop
I have nvarchar data like this:

'20030,20031,20033,20034,20065,20045,20044'

I want to read all this by spliting into array or read one by one in spliting process and do further process.

I have tried this good article but not able to do it.

答:
Another approach using String Split And Xml

```<code>DECLARE @string nvarchar(max)='20030,20031,20033,20034,20065,20045,20044'
DECLARE @Table AS TABLE (String nvarchar(max))
INSERT INTO @Table
SELECT @string

SELECT Row_NUmber ()OVER(ORDER BY (SELECT 1) )AS Seq, Split.a.value('.', 'VARCHAR(1000)') AS String
            FROM  (
                SELECT   CAST('<S>' + REPLACE(String, ',', '</S><S>') + '</S>' AS XML) AS String
                FROM @Table
                ) AS A
            CROSS APPLY String.nodes('/S') AS Split(a)
</code>```

The above code can be incorporated in function to return split string

```<code>CREATE FUNCTION dbo.udf_Split (
    @String NVARCHAR(4000)
    ,@Delimiter CHAR(1)
    )
RETURNS @Results TABLE (Items NVARCHAR(4000))
AS
BEGIN
    DECLARE @Table AS TABLE (String NVARCHAR(max))

    INSERT INTO @Table
    SELECT @String

    INSERT INTO @Results
    SELECT Split.a.value('.', 'VARCHAR(1000)') AS String
    FROM (
        SELECT CAST('<S>' + REPLACE(String, @Delimiter, '</S><S>') + '</S>' AS XML) AS String
        FROM @Table
        ) AS A
    CROSS APPLY String.nodes('/S') AS Split(a)

    RETURN
END

SELECT ROW_NUMBER()OVER(ORDER BY (SELECT 1))AS Seq,
    * FROM dbo.udf_Split('20030,20031,20033,20034,20065,20045,20044',',')
</code>```

Result

```<code>Seq String
----------
1   20030
2   20031
3   20033
4   20034
5   20065
6   20045
7   20044
</code>```

Body:
Another approach using String Split And Xml

DECLARE @string nvarchar(max)='20030,20031,20033,20034,20065,20045,20044'
DECLARE @Table AS TABLE (String nvarchar(max))
INSERT INTO @Table
SELECT @string

SELECT Row_NUmber ()OVER(ORDER BY (SELECT 1) )AS Seq, Split.a.value('.', 'VARCHAR(1000)') AS String
            FROM  (
                SELECT   CAST('<S>' + REPLACE(String, ',', '</S><S>') + '</S>' AS XML) AS String
                FROM @Table
                ) AS A
            CROSS APPLY String.nodes('/S') AS Split(a)

The above code can be incorporated in function to return split string

CREATE FUNCTION dbo.udf_Split (
    @String NVARCHAR(4000)
    ,@Delimiter CHAR(1)
    )
RETURNS @Results TABLE (Items NVARCHAR(4000))
AS
BEGIN
    DECLARE @Table AS TABLE (String NVARCHAR(max))

    INSERT INTO @Table
    SELECT @String

    INSERT INTO @Results
    SELECT Split.a.value('.', 'VARCHAR(1000)') AS String
    FROM (
        SELECT CAST('<S>' + REPLACE(String, @Delimiter, '</S><S>') + '</S>' AS XML) AS String
        FROM @Table
        ) AS A
    CROSS APPLY String.nodes('/S') AS Split(a)

    RETURN
END

SELECT ROW_NUMBER()OVER(ORDER BY (SELECT 1))AS Seq,
    * FROM dbo.udf_Split('20030,20031,20033,20034,20065,20045,20044',',')

Result

Seq String
----------
1   20030
2   20031
3   20033
4   20034
5   20065
6   20045
7   20044


问:
Dice Rolling Application Typescript
at the moment I am doing a tutorial on edx.org about Typescript2.
But I need some help with the Self Assessment Lab:

"Now that you have learned the basics of how to use TypeScript, you are going to make a simple dice rolling application to the following parameters:

Use the following types in your application: Array, number, string, Boolean.

Use an enum to declare the possible rolled values (Hint: They don't have to be numbers).

Use a class to create your die, including typed properties for the CSS styles needed (length, width, border, color), and for the value contained within the die.

Create an interface to describe your die's types.

Extend the class with a dieRoller class to create a method for rolling the die.

Create a function to instantiate dice using the dieRoller class, binding elements using the constructor() function.

Create a button to roll all the dice at once.

The finished product should end up looking something like this, and should randomly generate a different value from the enum for each individual die when the "Roll Dice" button is pressed."

There should be four dices and afterwards a button (all in one line).

My problem is that I am not able to create only one button or that i cannot use rolleDice() (if i declare the button outside of the class... usually one would probably declare it outside and create an instance of the class... but no idea how to do this, because the class has a constructor with a parameter).
So maybe you have an idea... Or i just missunderstood the task? :/

Thank your!

```<code>class diceRoller {
    span: Element;
    constructor(span: Element) {
        this.span = span;
    }
    rolleDice(diceValue: number): boolean {
        (<HTMLElement>this.span).textContent = diceValues[diceValue];
        return true;
    }
}
class dice extends diceRoller {
    button: Element = document.createElement('button');
    constructor(span: Element) {
        super(span);
        (<HTMLElement>span).style.cssText = "border: 5px solid black; display: inline-block; height: 50px;  width: 50px; margin: 2px";
        this.button.textContent = "Role Dice";
        document.body.appendChild(this.button);
    }
}
enum diceValues {
    one,
    two,
    three,
    four,
    five,
    six
}
interface diceTypes {
    span: Element;
}
let Elements: Array<diceTypes> = [];
for (let index: number = 0; index < 5; index++) {
    Elements.push({
        'span': document.createElement('span'),
    });
}
let getRandomIntInclusive: Function = (min, max) => {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
Elements.map((elem, index) => {
    let cube = new dice(elem.span);
    let button: Element = document.createElement('button');
    document.body.appendChild(elem.span);
});
</code>```

答:
In task said that dieRoller extends die, not die extends dieRoller. Die is just a cube, dieRoller is a cube with a method.

Also I created a separate class for RollButton, it has method that get array with all dice and firing it's rollDice methods.

One thing I'm not sure is there more beauty way not use two separate arrays - for Elements and for diceCollection but just for diceCollection.

In more idealy way I see big class wich contains array of Dice instances and RollButton.

Also it's cool for DiceValues to start from 1.

Anyway it works but refactoring are welcome. http://jsbin.com/rahewuhije/edit?js,output

```<code>class Dice {
    span: Element;
    constructor(span: Element) {
        this.span = span;
    }
}
class DiceRoller extends Dice {
    // button: Element = document.createElement('button');
    constructor(span: Element) {
        super(span);
        (<HTMLElement>span).style.cssText = "border: 5px solid black; display: inline-block; height: 50px;  width: 50px; margin: 2px";
        // this.button.textContent = "Role Dice";
        // document.body.appendChild(this.button);
    }
    rolleDice(diceValue: number): boolean {
        (<HTMLElement>this.span).textContent = DiceValues[diceValue];
        return true;
    }
}

class DiceRollerButton {
  button: Element;
  constructor(button: Element) {
    this.button = button;
    (<HTMLElement>this.button).style.cssText = "display: inline-block;";
    this.button.textContent = "Roll!";
    document.body.appendChild(this.button);
  }

  roll(diceCollection: Array<DiceRoller>) {
    diceCollection.forEach((item) => {
      item.span.textContent = DiceValues[getRandomIntInclusive(1, 6)];
    });
  }
}

enum DiceValues {
    one = 1,
    two,
    three,
    four,
    five,
    six
}
interface DiceTypes {
    span: Element;
}
let Elements: Array<DiceTypes> = [];

let diceCollection: Array<DiceRoller> = [];

for (let index: number = 0; index < 5; index++) {
    Elements.push({
        'span': document.createElement('span'),
    });
}
let getRandomIntInclusive: Function = (min, max) => {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
Elements.map((elem, index) => {
    let cube = new DiceRoller(elem.span);
    // let button: Element = document.createElement('button');
    document.body.appendChild(elem.span);

    diceCollection.push(cube);
});

let diceRollerButton = new DiceRollerButton(document.createElement('button'));

diceRollerButton.button.onclick = (event): void => {
  diceRollerButton.roll(diceCollection);
}
</code>```

Title: Dice Rolling Application Typescript

Body:
at the moment I am doing a tutorial on edx.org about Typescript2.
But I need some help with the Self Assessment Lab:

"Now that you have learned the basics of how to use TypeScript, you are going to make a simple dice rolling application to the following parameters:

Use the following types in your application: Array, number, string, Boolean.

Use an enum to declare the possible rolled values (Hint: They don't have to be numbers).

Use a class to create your die, including typed properties for the CSS styles needed (length, width, border, color), and for the value contained within the die.

Create an interface to describe your die's types.

Extend the class with a dieRoller class to create a method for rolling the die.

Create a function to instantiate dice using the dieRoller class, binding elements using the constructor() function.

Create a button to roll all the dice at once.

The finished product should end up looking something like this, and should randomly generate a different value from the enum for each individual die when the "Roll Dice" button is pressed."

There should be four dices and afterwards a button (all in one line).

My problem is that I am not able to create only one button or that i cannot use rolleDice() (if i declare the button outside of the class... usually one would probably declare it outside and create an instance of the class... but no idea how to do this, because the class has a constructor with a parameter).
So maybe you have an idea... Or i just missunderstood the task? :/

Thank your!

class diceRoller {
    span: Element;
    constructor(span: Element) {
        this.span = span;
    }
    rolleDice(diceValue: number): boolean {
        (<HTMLElement>this.span).textContent = diceValues[diceValue];
        return true;
    }
}
class dice extends diceRoller {
    button: Element = document.createElement('button');
    constructor(span: Element) {
        super(span);
        (<HTMLElement>span).style.cssText = "border: 5px solid black; display: inline-block; height: 50px;  width: 50px; margin: 2px";
        this.button.textContent = "Role Dice";
        document.body.appendChild(this.button);
    }
}
enum diceValues {
    one,
    two,
    three,
    four,
    five,
    six
}
interface diceTypes {
    span: Element;
}
let Elements: Array<diceTypes> = [];
for (let index: number = 0; index < 5; index++) {
    Elements.push({
        'span': document.createElement('span'),
    });
}
let getRandomIntInclusive: Function = (min, max) => {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
Elements.map((elem, index) => {
    let cube = new dice(elem.span);
    let button: Element = document.createElement('button');
    document.body.appendChild(elem.span);
});

Body:
In task said that dieRoller extends die, not die extends dieRoller. Die is just a cube, dieRoller is a cube with a method.

Also I created a separate class for RollButton, it has method that get array with all dice and firing it's rollDice methods.

One thing I'm not sure is there more beauty way not use two separate arrays - for Elements and for diceCollection but just for diceCollection.

In more idealy way I see big class wich contains array of Dice instances and RollButton.

Also it's cool for DiceValues to start from 1.

Anyway it works but refactoring are welcome. http://jsbin.com/rahewuhije/edit?js,output

class Dice {
    span: Element;
    constructor(span: Element) {
        this.span = span;
    }
}
class DiceRoller extends Dice {
    // button: Element = document.createElement('button');
    constructor(span: Element) {
        super(span);
        (<HTMLElement>span).style.cssText = "border: 5px solid black; display: inline-block; height: 50px;  width: 50px; margin: 2px";
        // this.button.textContent = "Role Dice";
        // document.body.appendChild(this.button);
    }
    rolleDice(diceValue: number): boolean {
        (<HTMLElement>this.span).textContent = DiceValues[diceValue];
        return true;
    }
}

class DiceRollerButton {
  button: Element;
  constructor(button: Element) {
    this.button = button;
    (<HTMLElement>this.button).style.cssText = "display: inline-block;";
    this.button.textContent = "Roll!";
    document.body.appendChild(this.button);
  }

  roll(diceCollection: Array<DiceRoller>) {
    diceCollection.forEach((item) => {
      item.span.textContent = DiceValues[getRandomIntInclusive(1, 6)];
    });
  }
}

enum DiceValues {
    one = 1,
    two,
    three,
    four,
    five,
    six
}
interface DiceTypes {
    span: Element;
}
let Elements: Array<DiceTypes> = [];

let diceCollection: Array<DiceRoller> = [];

for (let index: number = 0; index < 5; index++) {
    Elements.push({
        'span': document.createElement('span'),
    });
}
let getRandomIntInclusive: Function = (min, max) => {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
Elements.map((elem, index) => {
    let cube = new DiceRoller(elem.span);
    // let button: Element = document.createElement('button');
    document.body.appendChild(elem.span);

    diceCollection.push(cube);
});

let diceRollerButton = new DiceRollerButton(document.createElement('button'));

diceRollerButton.button.onclick = (event): void => {
  diceRollerButton.roll(diceCollection);
}


问:
Hide for comprehension
I´m working in a DSL using monads and for comprenhension. Since my client has no idea of Scala I´m trying to hide so much syntax as I can. So far I have this DSL

```<code>  (for {
    * <- Given("A message", message(path = "esb", version = TWO))
    * <- And("With version 2.0", *)
    * <- And("I make esb return 300", *)
    * <- When("I make a request", *)
    * <- Then("The return code is 500", *)
  } yield ()).foldMap(scenario)
</code>```

This is far better than make them implement scalaTest, but still this for comprehension can scare them.

There´s any way to hide the for/yield using implicit u other mechanism and just leave the DSL?

Regards.

答:
Does it have to be monads?

Something like this might be easier to work with:

```<code> case class Given(
    what: String,
    ands: Seq[String] = Nil,
    when: Option[String] = None,
    then: Option[String] = None
 ) {
    def And(s: String) = copy(ands = ands :+ s)
    def When(s: String) = copy(when = Some(s))
    def Then(s: String) = copy(then = Some(s))
    def Run(scenario: Scenario) = ???
 }
</code>```

You can just write something like

```<code> Given("foo") And "bar" And "bat" When "baz" Then "bam" Run scenario
</code>```

Title: Hide for comprehension

Body:
I´m working in a DSL using monads and for comprenhension. Since my client has no idea of Scala I´m trying to hide so much syntax as I can. So far I have this DSL

  (for {
    * <- Given("A message", message(path = "esb", version = TWO))
    * <- And("With version 2.0", *)
    * <- And("I make esb return 300", *)
    * <- When("I make a request", *)
    * <- Then("The return code is 500", *)
  } yield ()).foldMap(scenario)

This is far better than make them implement scalaTest, but still this for comprehension can scare them.

There´s any way to hide the for/yield using implicit u other mechanism and just leave the DSL?

Regards.

Body:
Does it have to be monads?

Something like this might be easier to work with:

 case class Given(
    what: String,
    ands: Seq[String] = Nil,
    when: Option[String] = None,
    then: Option[String] = None
 ) {
    def And(s: String) = copy(ands = ands :+ s)
    def When(s: String) = copy(when = Some(s))
    def Then(s: String) = copy(then = Some(s))
    def Run(scenario: Scenario) = ???
 }

You can just write something like

 Given("foo") And "bar" And "bat" When "baz" Then "bam" Run scenario


问:
jQuery UI tab shows next tab's content when CSS overflow is enabled

I'm using jQquery UI (1.12.1). When I add "overflow-y: scroll;" to the Theme tab shown in the image, the content of the Image tab (Find Images etc) is visible beneath it.

I'm also using the Image Picker plugin (https://rvera.github.io/image-picker/).

Here's my code:

```<code><div id=videos_slide_config style='width:100%;height:400px;'>
    <ul>
        <li> <a href='#videos_slide_themes'>Theme</a> </li>
        <li> <a href='#videos_slide_images'>Image</a> </li>
        <li> <a href='#videos_slide_layouts'>Layout</a> </li>
    </ul>

    <div id=videos_slide_themes style='height:320px;overflow-y:scroll;overflow-x:hidden;'>
        <select id=videos_slide_theme>{$themes}</select>
    </div>

    <div id=videos_slide_image style='text-align:left;'>
        <p align=center>
            <b>Find Images:</b>
            <input type=text id=videos_images_q width=20>
            <button class='ui-button ui-widget ui-corner-all' onclick='videos_images_search();' title='Find Images'><i class='fa fa-search' aria-hidden='true'></i></button>
            <button class='ui-button ui-widget ui-corner-all' onclick='videos_imags_upload();' 'title='Upload Images'><i class='fa fa-upload' aria-hidden='true'></i></button>
        </p>
    </div>

    <div id=videos_slide_layout>
    </div>

</div>
</code>```

答: Nevermind. My id attributes were wrong. Fixed.</p>

Body:
I'm using jQquery UI (1.12.1). When I add "overflow-y: scroll;" to the Theme tab shown in the image, the content of the Image tab (Find Images etc) is visible beneath it.

I'm also using the Image Picker plugin (https://rvera.github.io/image-picker/).

Here's my code:

 Theme

 Image

 Layout

        <select id=videos_slide_theme>{$themes}</select>

            Find Images:
            <input type=text id=videos_images_q width=20>
            <button class='ui-button ui-widget ui-corner-all' onclick='videos_images_search();' title='Find Images'></button>
            <button class='ui-button ui-widget ui-corner-all' onclick='videos_imags_upload();' 'title='Upload Images'></button>


问:
Angular2 [src] causing 404 error when loading image dynamically
i´ll try to load an image after the page is loaded into a modal form that opens on click.

My image Tag looks like this:

```<code><img src="/src/files/bstand{{detailEntry.bearbeitungsstand}}.png">
</code>```

The image source is correct. But when i load the page my variable detailentry is empty because i am fill it on click of a button.
so the console shows me a 404 error with url:
"/src/files/bstand.png"
which does not exist
Wehen ic Click the button the image is loaded properly.

I remember that i used ng_src in angular 1 and the equivalent shout be [src] i thought but it does not work.

Thank you for any answer!

答:
You can wait for the detailEntry with ngIf</p>

```<code><img *ngIf="detailEntry.bearbeitungsstand" src="/src/files/bstand{{detailEntry.bearbeitungsstand}}.png">
</code>```

Body:
i´ll try to load an image after the page is loaded into a modal form that opens on click.

My image Tag looks like this:

The image source is correct. But when i load the page my variable detailentry is empty because i am fill it on click of a button.
so the console shows me a 404 error with url:
"/src/files/bstand.png"
which does not exist
Wehen ic Click the button the image is loaded properly.

I remember that i used ng_src in angular 1 and the equivalent shout be [src] i thought but it does not work.

Thank you for any answer!

Body:
You can wait for the detailEntry with ngIf

<img *ngIf="detailEntry.bearbeitungsstand" src="/src/files/bstand{{detailEntry.bearbeitungsstand}}.png">


问:
when is echo after done in a while loop executed
I came across the following simple time-returning script and wonder how and when the echo part can be triggered since it is placed after a while loop is done:</p>

```<code># !/ bin / bash while ! test -f / tmp / stop ; do date sleep 1 done echo " halted ! "
</code>```

答: Because the echo " halted ! " is called after done, it is outside of the while loop. This means that "halted!" will only be echoed on the condition that we have broken out of the time-keeping loop, which would happen anytime the script goes back to the "top" of the loop, and checks if test -f /tmp/stop is true. If it is, the time-keeping stops, leading the script to the echo statement, and announcing the time-keeping has stopped (as we aren't in the loop anymore).

Body:
I came across the following simple time-returning script and wonder how and when the echo part can be triggered since it is placed after a while loop is done:

# !/ bin / bash while ! test -f / tmp / stop ; do date sleep 1 done echo " halted ! "


问:
How to display particular records first in a for reach loop in xsl
I have requirement to display particular string records first , for example here i want to display all Rehman records first then all others in no particular order.

XML

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<catalog>
  <cd>
    <title>Empire Burlesque</title>
    <artist>Bob Dylan</artist>
    <country>USA</country>
    <company>Columbia</company>
    <price>10.90</price>
    <year>1985</year>
  </cd>
  <cd>
    <title>Hide your heart</title>
    <artist>Bonnie Tyler</artist>
    <country>UK</country>
    <company>CBS Records</company>
    <price>9.90</price>
    <year>1988</year>
  </cd>
  <cd>
    <title>Roja</title>
    <artist>Rehman</artist>
    <country>USA</country>
    <company>RCA</company>
    <price>9.90</price>
    <year>1982</year>
  </cd>
  <cd>
    <title>Still got the blues</title>
    <artist>Gary Moore</artist>
    <country>UK</country>
    <company>Virgin records</company>
    <price>10.20</price>
    <year>1990</year>
  </cd>
  <cd>
    <title>Eros</title>
    <artist>Zack</artist>
    <country>EU</country>
    <company>BMG</company>
    <price>9.90</price>
    <year>1997</year>
  </cd>
  <cd>
    <title>Rockstar</title>
    <artist>Rehman</artist>
    <country>UK</country>
    <company>Polydor</company>
    <price>10.90</price>
    <year>1998</year>
  </cd>
  <cd>
    <title>Sylvias Mother</title>
    <artist>Dr.Hook</artist>
    <country>UK</country>
    <company>CBS</company>
    <price>8.10</price>
    <year>1973</year>
  </cd>

</catalog>
</code>```

XSL

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
  <html>
  <body>
    <h2>My CD Collection</h2>
    <table border="1">
      <tr bgcolor="#9acd32">
        <th>Title</th>
        <th>Artist</th>
      </tr>
      <xsl:for-each select="catalog/cd">
      <xsl:sort select="artist" order ="descending"/>
      <tr>
        <td><xsl:value-of select="title"/></td>
        <td><xsl:value-of select="artist"/></td>
      </tr>
      </xsl:for-each>
    </table>
  </body>
  </html>
</xsl:template>

</xsl:stylesheet>
</code>```

Result

My CD Collection

Title Artist

```<code>Empire Burlesque    Bob Dylan
Hide your heart Bonnie Tyler
Sylvias Mother  Dr.Hook
Still got the blues Gary Moore
Roja    Rehman
Rockstar    Rehman
Eros    Zack
</code>```

答:
You seem to already have most of the pieces you need; it's just a question of assembling them in a way that works.  In particular, you can do this via a well chosen xsl:sort key.

You want the CDs with artist Rehman to be output before all the others, so let's start with an XPath expression that expresses that condition when evaluated with a <cd> element as the current node:

```<code>artist = 'Rehman'
</code>```

A sort key can be any XPath expression; its value will be converted to a string (and possibly afterward reinterpreted as a number).  The expression above evaluates to a boolean, and when converted to a string that will result in either 'true' or 'false'.  Since 'true' comes lexicographically after 'false', and you want the CDs for which the expression is true to be output first, you'll want to specify descending order for that key:

```<code>      <xsl:for-each select="catalog/cd">
      <xsl:sort select="artist = 'Rehman'" order="descending"/>
      <tr>
        <td><xsl:value-of select="title"/></td>
        <td><xsl:value-of select="artist"/></td>
      </tr>
      </xsl:for-each>
</code>```

If you wanted to further refine the order, e.g. to present the remaining records in alphabetical order by artist, then you could add any number of additional sort keys; multiple keys applying to the same scope are ascribed significance from greatest to least according to the order in which they appear.

Body:
I have requirement to display particular string records first , for example here i want to display all Rehman records first then all others in no particular order.

XML

    <?xml version="1.0" encoding="UTF-8"?>
<catalog>
  <cd>
    <title>Empire Burlesque</title>
    <artist>Bob Dylan</artist>
    <country>USA</country>
    <company>Columbia</company>
    <price>10.90</price>
    <year>1985</year>
  </cd>
  <cd>
    <title>Hide your heart</title>
    <artist>Bonnie Tyler</artist>
    <country>UK</country>
    <company>CBS Records</company>
    <price>9.90</price>
    <year>1988</year>
  </cd>
  <cd>
    <title>Roja</title>
    <artist>Rehman</artist>
    <country>USA</country>
    <company>RCA</company>
    <price>9.90</price>
    <year>1982</year>
  </cd>
  <cd>
    <title>Still got the blues</title>
    <artist>Gary Moore</artist>
    <country>UK</country>
    <company>Virgin records</company>
    <price>10.20</price>
    <year>1990</year>
  </cd>
  <cd>
    <title>Eros</title>
    <artist>Zack</artist>
    <country>EU</country>
    <company>BMG</company>
    <price>9.90</price>
    <year>1997</year>
  </cd>
  <cd>
    <title>Rockstar</title>
    <artist>Rehman</artist>
    <country>UK</country>
    <company>Polydor</company>
    <price>10.90</price>
    <year>1998</year>
  </cd>
  <cd>
    <title>Sylvias Mother</title>
    <artist>Dr.Hook</artist>
    <country>UK</country>
    <company>CBS</company>
    <price>8.10</price>
    <year>1973</year>
  </cd>

</catalog>

XSL

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">

My CD Collection

        Title
        Artist

      <xsl:for-each select="catalog/cd">
      <xsl:sort select="artist" order ="descending"/>

        <xsl:value-of select="title"/>
        <xsl:value-of select="artist"/>

      </xsl:for-each>

</xsl:template>

</xsl:stylesheet>

Result

My CD Collection

Title Artist

Empire Burlesque    Bob Dylan
Hide your heart Bonnie Tyler
Sylvias Mother  Dr.Hook
Still got the blues Gary Moore
Roja    Rehman
Rockstar    Rehman
Eros    Zack

Body:
You seem to already have most of the pieces you need; it's just a question of assembling them in a way that works.  In particular, you can do this via a well chosen xsl:sort key.

You want the CDs with artist Rehman to be output before all the others, so let's start with an XPath expression that expresses that condition when evaluated with a <cd> element as the current node:

artist = 'Rehman'

A sort key can be any XPath expression; its value will be converted to a string (and possibly afterward reinterpreted as a number).  The expression above evaluates to a boolean, and when converted to a string that will result in either 'true' or 'false'.  Since 'true' comes lexicographically after 'false', and you want the CDs for which the expression is true to be output first, you'll want to specify descending order for that key:

      <xsl:for-each select="catalog/cd">
      <xsl:sort select="artist = 'Rehman'" order="descending"/>
      <tr>
        <td><xsl:value-of select="title"/></td>
        <td><xsl:value-of select="artist"/></td>
      </tr>
      </xsl:for-each>

If you wanted to further refine the order, e.g. to present the remaining records in alphabetical order by artist, then you could add any number of additional sort keys; multiple keys applying to the same scope are ascribed significance from greatest to least according to the order in which they appear.


问:
Backslash in endpoint
I need to consume an endpoint from SoapUI which contains a backslash like:

mydomain/myservice/{id_resource}

and the assignment:

id_resource = numbers\numbers

The problem here is that when I executed the request, the consumed url is mydomain/myservice/numbers%40%5Cnumbers, and if I check the option of disabling the URL-encoding, it ignores the backslash () between the numbers of the id_resource, going to an url like mydomain/myservice/numbersnumbers.

I've tried to scape the character with another backslash, like java or other languages, but it doesn´t work.

It works fine if I consume the service with postman, so it is not a problem of the logic consumed.

So, is it possible to consume an url containing a backslash from SoapUI?

答:
There is an option to disable URL encoding for the selected parameter which would assist with this.

https://www.soapui.org/rest-testing/reference/method-window.html

Title: Backslash in endpoint


答:
You could use *ngIf to keep the image tag from being rendered without a valid src.</p>

```<code><img *ngIf="detailEntry.bearbeitungsstand" src="/src/files/bstand{{detailEntry.bearbeitungsstand}}.png">
</code>```

Title: Angular2 [src] causing 404 error when loading image dynamically

Body:
You could use *ngIf to keep the image tag from being rendered without a valid src.

<img *ngIf="detailEntry.bearbeitungsstand" src="/src/files/bstand{{detailEntry.bearbeitungsstand}}.png">


问:
How can I modify the Ionic 2 slider so that it has multiple rows (grid type 4x4, 16 per page)?
I'm using the Ionic2 slider, from its components: http://ionicframework.com/docs/v2/api/components/slides/Slides/.
I can't figure out how to make the slider show items on multiple rows, 4x4 = 16 items per slide.

This is the code I have. The generated html code in the actual page looks diferent.

```<code>            <ion-slides pager slidesPerView="16" spaceBetween="20">
                <ion-slide style="background-color: green">
                     <h2>Slide 1</h2>
                </ion-slide>
                <ion-slide style="background-color: blue">
                    <h2>Slide 2</h2>
                </ion-slide>
                <ion-slide style="background-color: red">
                    <h2>Slide 3</h2>
                </ion-slide>
                <ion-slide style="background-color: green">
                     <h2>Slide 1</h2>
                </ion-slide>
                <ion-slide style="background-color: blue">
                    <h2>Slide 2</h2>
                </ion-slide>
                <ion-slide style="background-color: red">
                    <h2>Slide 3</h2>
                </ion-slide>
            </ion-slides>
</code>```

答:
Try nesting an ion-grid Components in each slide.
Here's the API docs for the grid</p>

Body:
I'm using the Ionic2 slider, from its components: http://ionicframework.com/docs/v2/api/components/slides/Slides/.
I can't figure out how to make the slider show items on multiple rows, 4x4 = 16 items per slide.

This is the code I have. The generated html code in the actual page looks diferent.

            <ion-slides pager slidesPerView="16" spaceBetween="20">
                <ion-slide style="background-color: green">

Slide 1

                </ion-slide>
                <ion-slide style="background-color: blue">

Slide 2

                </ion-slide>
                <ion-slide style="background-color: red">

Slide 3

                </ion-slide>
                <ion-slide style="background-color: green">

Slide 1

                </ion-slide>
                <ion-slide style="background-color: blue">

Slide 2

                </ion-slide>
                <ion-slide style="background-color: red">

Slide 3

                </ion-slide>
            </ion-slides>


问:
C# LINQ OrderBy several clauses
I'm currently working on an application in ASP.NET MVC 4.5. I need to write a LINQ query to order a list of Projects by different StatusIds.

Given is a list of Projects with this ViewModel:

```<code>public class ProjectVm
{
   public int ProjectId { get; set; }
   public string Title { get; set; }
   public Status StatusId { get; set; }
}
</code>```

My project status enum:

```<code>public enum Status : byte
{
    Draft = 1,
    Pending = 2,
    Validated = 3,
    Refused = 4
}
</code>```

The idea is to bring the List<ProjectVm> in a certain order, thus first ordered by 1 Draft, second by 2 Pending, third by 4 Refused and fourth by 3 Validated.

My current query looks like this:

```<code>projects = projects.OrderBy(x => x.StatusId).ToList();
</code>```

Unfortunately this query doesn't respect the desired order (4 comes before 3).

Do you know how to apply a condition on this query to bring the projects into the right order (1, 2, 4, 3) ?

Thanks!

答:
```<code>projects.OrderBy(x => x.StatusId == Status.Validated).ThenBy(x => x.StatusId)
</code>```

Puts all the pending at the end, then sorts within that rule by StatusID. Two simple operations and likely to be processed well by any provider.

```<code>projects.OrderBy(x => x.StatusId == Status.Validated ? int.MaxValue : (int)x.StatusId)
</code>```

A single operation, which is hence likely faster, that re-assigns the 3 for Pending to int.MaxValue before the sort.

I'd try the second first as the likely more efficient, but the second is worth noting as a general approach too.

Title: C# LINQ OrderBy several clauses

Body:
I'm currently working on an application in ASP.NET MVC 4.5. I need to write a LINQ query to order a list of Projects by different StatusIds.

Given is a list of Projects with this ViewModel:

public class ProjectVm
{
   public int ProjectId { get; set; }
   public string Title { get; set; }
   public Status StatusId { get; set; }
}

My project status enum:

public enum Status : byte
{
    Draft = 1,
    Pending = 2,
    Validated = 3,
    Refused = 4
}

The idea is to bring the List<ProjectVm> in a certain order, thus first ordered by 1 Draft, second by 2 Pending, third by 4 Refused and fourth by 3 Validated.

My current query looks like this:

projects = projects.OrderBy(x => x.StatusId).ToList();

Unfortunately this query doesn't respect the desired order (4 comes before 3).

Do you know how to apply a condition on this query to bring the projects into the right order (1, 2, 4, 3) ?

Thanks!

Body:
projects.OrderBy(x => x.StatusId == Status.Validated).ThenBy(x => x.StatusId)

Puts all the pending at the end, then sorts within that rule by StatusID. Two simple operations and likely to be processed well by any provider.

projects.OrderBy(x => x.StatusId == Status.Validated ? int.MaxValue : (int)x.StatusId)

A single operation, which is hence likely faster, that re-assigns the 3 for Pending to int.MaxValue before the sort.

I'd try the second first as the likely more efficient, but the second is worth noting as a general approach too.


问:
Run-time Error 424 Object Required UserForm doesnt exist
I'm attempting to do the things written on this site www.excel-easy.com but when I click the commandbutton (from ActiveX controls) in the worksheet just like what the website instructed, nothing happens. I tried to use a button from form controls, but it says that the error is in this
---> DinnerPlannerUserForm.Show

My Code:

```<code>Sub Button2_Click()
    DinnerPlannerUserForm.Show
End Sub
</code>```

When I used F8, it said the error is here --> Private Sub UserForm_Initialize()

```<code>Private Sub UserForm_Initialize()

    'Empty NameTextBox
    NameTextBox.Value = ""

    'Empty PhoneTextBox
    PhoneTextBox.Value = ""

    'Empty CityListBox
    CityListBox.Clear

    'Fill CityListBox
    With CityListBox
        .AddItem "San Francisco"
        .AddItem "Oakland"
        .AddItem "Richmond"
    End With

    'Empty DinnerComboBox
    DinnerComboBox.Clear

    'Fill DinnerComboBox
    With DinnerComboBox
        .AddItem "Italian"
        .AddItem "Chinese"
        .AddItem "Frites and Meat"
    End With

    'Uncheck DataCheckBoxes
    DateCheckBox1.Value = False
    DateCheckBox2.Value = False
    DateCheckBox3.Value = False

    'Set no car as default
    CarOptionButton2.Value = True

    'Empty MoneyTextBox
    MoneyTextBox.Value = ""

    'Set Focus on NameTextBox
    NameTextBox.SetFocus

End Sub
</code>```

答:
This error can also occur when you remove or delete a textbox from your form, but forget to remove it from a line in initialization for eg:</p>

```<code>Private Sub UserForm_Initialize()
    CommandButton2.Enabled = False
    TextBox4.Enabled = False    'textbox deleted from form
End sub
</code>```

Body:
I'm attempting to do the things written on this site www.excel-easy.com but when I click the commandbutton (from ActiveX controls) in the worksheet just like what the website instructed, nothing happens. I tried to use a button from form controls, but it says that the error is in this
---> DinnerPlannerUserForm.Show

My Code:

Sub Button2_Click()
    DinnerPlannerUserForm.Show
End Sub

When I used F8, it said the error is here --> Private Sub UserForm_Initialize()

Private Sub UserForm_Initialize()

    'Empty NameTextBox
    NameTextBox.Value = ""

    'Empty PhoneTextBox
    PhoneTextBox.Value = ""

    'Empty CityListBox
    CityListBox.Clear

    'Fill CityListBox
    With CityListBox
        .AddItem "San Francisco"
        .AddItem "Oakland"
        .AddItem "Richmond"
    End With

    'Empty DinnerComboBox
    DinnerComboBox.Clear

    'Fill DinnerComboBox
    With DinnerComboBox
        .AddItem "Italian"
        .AddItem "Chinese"
        .AddItem "Frites and Meat"
    End With

    'Uncheck DataCheckBoxes
    DateCheckBox1.Value = False
    DateCheckBox2.Value = False
    DateCheckBox3.Value = False

    'Set no car as default
    CarOptionButton2.Value = True

    'Empty MoneyTextBox
    MoneyTextBox.Value = ""

    'Set Focus on NameTextBox
    NameTextBox.SetFocus

End Sub

Body:
This error can also occur when you remove or delete a textbox from your form, but forget to remove it from a line in initialization for eg:

Private Sub UserForm_Initialize()
    CommandButton2.Enabled = False
    TextBox4.Enabled = False    'textbox deleted from form
End sub


问:
IIS Virtual Directory map to network drive (with drive letter) but fail to create file
I am using C#/ASP.NET, IIS6 on Windows Server 2003.

Map the data server shared folder to the WebServer with driver letter V:\

On the WebServer, IIS created a virtual directory and pointed to 'local location' with V:\ . Since there is no 'Connect As', not sure which USER will be used

In my WebMethod, I want to create file on the shared folder with FileStream.Write().

I got IO Exception on the action, any hint?

P.S. I have added ASPNET/NETWORK SERVICE on the data server shared folder.

thanks!
Gavin

答:
The website in IIS has a corresponding app pool and this should tell you the user under which your code wil be running.
You'll the have to grant the appropriate permissions for that share for that user.</p>


问:
Accessing base member from derived class in function
I have created Angular2 + Typescript project. I have there alot of tables so I want to have something like base component for that.

There is my base component:

```<code>export abstract class ManagementComponent<T> implements BaseComponent {

    protected selectedItem: T;

    protected items: Array<T>;

}
</code>```

Now there is my child component. I would like to get all items from http and then assign it into base class

```<code>export class CompetencesComponent extends ManagementComponent<Competence> implements OnInit {

    thisField: string;

    constructor(private service: CompetencesService) {
        super();

    }

    ngOnInit(): void {
        this.getCompetences();
    }

    private getCompetences() {
        this.service.getCompetences().subscribe(function (competences: Array<Competence>) {
            this.thisField // ok
            this.items  // not ok
        })
    }
}
</code>```

Any idea how I can access base fields from subscribe methods?

答:
You can set list of competencies to parent class as follow:

```<code>    private getCompetences() {
            var self = this;
            this.service.getCompetences().subscribe(function (competences: Array<Competence>) {
                this.thisField // ok
                self.items =  competences; // not ok
            })
        }
</code>```

The reason you are unable to access items property through this binding is the scope. Inside callback this binding is bound to something else and you loose the context.

Body:
I have created Angular2 + Typescript project. I have there alot of tables so I want to have something like base component for that.

There is my base component:

export abstract class ManagementComponent<T> implements BaseComponent {

    protected selectedItem: T;

    protected items: Array<T>;

}

Now there is my child component. I would like to get all items from http and then assign it into base class

export class CompetencesComponent extends ManagementComponent<Competence> implements OnInit {

    thisField: string;

    constructor(private service: CompetencesService) {
        super();

    }

    ngOnInit(): void {
        this.getCompetences();
    }

    private getCompetences() {
        this.service.getCompetences().subscribe(function (competences: Array<Competence>) {
            this.thisField // ok
            this.items  // not ok
        })
    }
}

Any idea how I can access base fields from subscribe methods?

Body:
You can set list of competencies to parent class as follow:

    private getCompetences() {
            var self = this;
            this.service.getCompetences().subscribe(function (competences: Array<Competence>) {
                this.thisField // ok
                self.items =  competences; // not ok
            })
        }

The reason you are unable to access items property through this binding is the scope. Inside callback this binding is bound to something else and you loose the context.


问:
Jsoup: How to select direct parents until the root without their siblings?
I'm trying to get all direct parents of element, but also I get their siblings.

For example, I have this DOM structure...

```<code><div class="html">
  <div class="head"></div>
  <div class="body">
    <a href="seznam.cz">seznam</a>
    <h2>Foo</h2>
    <a href="google.com">google</a>
    <p>
      <img class="first">
    </p>
    <img class="second">
    <ol>
      <li>1</li>
      <li>2</li>
    </ol>
  </div>
</div>
</code>```

So I want get all direct parents of img element with class first until a div with class html.

I've tried using the following code

```<code>Element element = document.select("img").first();
Node root = element.root();
</code>```

But in the root var I get whole DOM structure also with all siblings.

UPDATE

After this in root var I have the whole DOM structure again:

```<code><div class="html">
  <div class="head"></div>
  <div class="body">
    <a href="seznam.cz">seznam</a>
    <h2>Foo</h2>
    <a href="google.com">google</a>
    <p>
      <img class="first">
    </p>
    <img class="second">
    <ol>
      <li>1</li>
      <li>2</li>
    </ol>
  </div>
</div>
</code>```

But I want something like this:

```<code><div class="html">
  <div class="body">
    <p>
      <img class="first">
    </p>
  </div>
</div>
</code>```

答:
If you are interested in path only, use Element.cssSelector()

It gives you whole DOM path e.g. html > body > img

"Path" returned by Darshit Chokshi approach is not unique.

Body:
I'm trying to get all direct parents of element, but also I get their siblings.

For example, I have this DOM structure...

    seznam

Foo

    google

1

2

So I want get all direct parents of img element with class first until a div with class html.

I've tried using the following code

Element element = document.select("img").first();
Node root = element.root();

But in the root var I get whole DOM structure also with all siblings.

UPDATE

After this in root var I have the whole DOM structure again:

    seznam

Foo

    google

1

2

But I want something like this: