问:
Problems decrypting data in node.js (RSA PKCS 1.5)
I am having great difficulty implementing some encryption for a node.js project. I am using node-rsa which in turn uses the built in node crypto module.

My code appears to encrypt the data just fine and I can decrypt it. Unfortunately, the system I am sending the data to cannot. Having hit a bit of a wall I've tried decryption some data generated the other end. That also fails.

What is unusual in this case is that the data has to be encrypted using the PRIVATE key and decrypted using the PUBLIC key. As stupid as this is, I had no say in the decision to use this mechanism and it is already in wide use in a UK pubic transport ticketing system. So there is no possibility of doing anything different.

The specification [only] says:

The payload data (Appendix A) is encrypted using the TIS private key,
  using 1024Bit RSA PKCS#1v1.5. (This is a freely available public
  standard). This protects a payload of up to 116 bytes, or 928Bits,
  creating a 128 byte or 1024Bit encrypted output. The RSA encryption
  algorithm adds a header of length 12 bytes to the payload before
  encryption to improve security. For decryption purposes, this header
  should be removed to get the correct payload.

The format of this header is: 0x00 [10 non-zero bytes which are
  padding] 0x00 [content]. This is often done automatically by
  encryption/decryption software.

Here is an example public key:

```<code>-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDriuvWAKiTKFgmjHjHYjWK4IZ6
W1UOdrntxFAGT1szZlbKJfWGeBOPSk6MnW6AeX54zEta74Dnoj4MBT+MlekVQ2zp
G3qIZpp4DR+kF6eVRlguUg9l/Fgr9ZrFgkumCKIx/ccc6rvZcNvPnOVdPCBVoMRr
3X59WlLmH4d+RAivAQIDAQAB
-----END PUBLIC KEY-----
</code>```

I've derived this from the Modules / Exponent listed below... I think it is correct...?

Which is [supposedly] valid to decode this encrypted data:

```<code>1f876b22ea8af4341c4198347aabf1b1ba40649ad6918bbe26ebfcf4633786a2669ee499d796cf438a76ff0d4f6efc43f605994330e6fb88c8117eea6aad1a12c2525940f7b9946b3f6cbd674e2740070400ae6f2cf1ed6d36f610822a23d5a8a4717ecf671bf0530200f75a269951020be9f69a992d423f55eb6fefe6caa449
</code>```

I get the following error:

```<code>decryptData error Error: Error during decryption (probably incorrect key). Original error: Error: error:0407006A:rsa routines:RSA_padding_check_PKCS1_type_1:block type is not 01
</code>```

I hate to say it, but I am now completely stumped. If anyone is able to decrypt that data using the supplied key and can explain how I would be very grateful.

Just to save the usual response to this sort of question that I see whenever anyone else has asked a similar question in the past. Please do not comment if all you want to say is the process is wrong. That is not helpful in any way. Just to confirm, whilst encryption with the private key is unusual, it is not impossible....It is supported by the RSA specification.

There are several ticket retailers who are encrypting their data this way and several scanning equipment manufacturers who are producing equipment that decrypts in this way. It's out there, it's working.

The only issue seems to be that there is some small mismatch between the encrypted data I am seeing from node-rsa (node.js crypto library) and the example data I have been given.

This is the original format the keys were given to me.....

Appendix D - Example Security Keys for Tickets
All example tickets are encrypted using the following fixed 1024Bit RSA key

(Never use these keys in production, you must generate your own key pair for this purpose as this private key cannot be considered secure and is for testing only)

```<code>Modulus = 16540368155253773454125654483794538435594869143015457768150677916704644349481001621163 93533906833356026635527060528398017212524170789714748325265707476885395169247950736258 76338137535298120673942399072260833758038152595105311260002268650951968659366409471762 707986435753824060971148933772149012757770173722369
= HEX [00eb8aeb d600a893 2858268c 78c76235 8ae0867a 5b550e76 b9edc450 064f5b33 6656ca25 f5867813 8f4a4e8c 9d6e8079 7e78cc4b 5aef80e7 a23e0c05 3f8c95e9 15436ce9 1b7a8866 9a780d1f a417a795 46582e52 0f65fc58 2bf59ac5 824ba608 a231fdc7 1ceabbd9 70dbcf9c e55d3c20 55a0c46b dd7e7d5a 52e61f87 7e4408af 01]
Public Exponent = 65537
= HEX [010001]
Private Exponent = 23262061627321059848127951748956201956280865601289878122136319690902346303487555417896 45421978315004119428666694674801184773156427997741861134011936129888508204465790901818 10860126020371138225614906842567831455763314175530505369901364910691824152015094858350 72189773434923487177372245370361799421231555208773
= HEX [21205394 b0590501 3a8c895a ff2797c2 255ba45f adf1afce ec5a9caa 96848c11 0b89b896 f44774f0 c5119103 1f246071 e209515b c3ad4c66 6bf582d3 72312f2b 7250fe61 f6abed7f e219c08d c3985ae1 3f6b6db2 0e3c040b df7a817d 14a5a6f1 20d94047 08512132 aca00baa 29805440 4ad5dec2 1bd544bb 8938c74b 2904e645]
</code>```

答: Just to confirm... I was given incorrect data.</p>

Body:
I am having great difficulty implementing some encryption for a node.js project. I am using node-rsa which in turn uses the built in node crypto module.

My code appears to encrypt the data just fine and I can decrypt it. Unfortunately, the system I am sending the data to cannot. Having hit a bit of a wall I've tried decryption some data generated the other end. That also fails.

What is unusual in this case is that the data has to be encrypted using the PRIVATE key and decrypted using the PUBLIC key. As stupid as this is, I had no say in the decision to use this mechanism and it is already in wide use in a UK pubic transport ticketing system. So there is no possibility of doing anything different.

The specification [only] says:

The payload data (Appendix A) is encrypted using the TIS private key,
  using 1024Bit RSA PKCS#1v1.5. (This is a freely available public
  standard). This protects a payload of up to 116 bytes, or 928Bits,
  creating a 128 byte or 1024Bit encrypted output. The RSA encryption
  algorithm adds a header of length 12 bytes to the payload before
  encryption to improve security. For decryption purposes, this header
  should be removed to get the correct payload.

The format of this header is: 0x00 [10 non-zero bytes which are
  padding] 0x00 [content]. This is often done automatically by
  encryption/decryption software.

Here is an example public key:

-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDriuvWAKiTKFgmjHjHYjWK4IZ6
W1UOdrntxFAGT1szZlbKJfWGeBOPSk6MnW6AeX54zEta74Dnoj4MBT+MlekVQ2zp
G3qIZpp4DR+kF6eVRlguUg9l/Fgr9ZrFgkumCKIx/ccc6rvZcNvPnOVdPCBVoMRr
3X59WlLmH4d+RAivAQIDAQAB
-----END PUBLIC KEY-----

I've derived this from the Modules / Exponent listed below... I think it is correct...?

Which is [supposedly] valid to decode this encrypted data:

1f876b22ea8af4341c4198347aabf1b1ba40649ad6918bbe26ebfcf4633786a2669ee499d796cf438a76ff0d4f6efc43f605994330e6fb88c8117eea6aad1a12c2525940f7b9946b3f6cbd674e2740070400ae6f2cf1ed6d36f610822a23d5a8a4717ecf671bf0530200f75a269951020be9f69a992d423f55eb6fefe6caa449

I get the following error:

decryptData error Error: Error during decryption (probably incorrect key). Original error: Error: error:0407006A:rsa routines:RSA_padding_check_PKCS1_type_1:block type is not 01

I hate to say it, but I am now completely stumped. If anyone is able to decrypt that data using the supplied key and can explain how I would be very grateful.

Just to save the usual response to this sort of question that I see whenever anyone else has asked a similar question in the past. Please do not comment if all you want to say is the process is wrong. That is not helpful in any way. Just to confirm, whilst encryption with the private key is unusual, it is not impossible....It is supported by the RSA specification.

There are several ticket retailers who are encrypting their data this way and several scanning equipment manufacturers who are producing equipment that decrypts in this way. It's out there, it's working.

The only issue seems to be that there is some small mismatch between the encrypted data I am seeing from node-rsa (node.js crypto library) and the example data I have been given.

This is the original format the keys were given to me.....

Appendix D - Example Security Keys for Tickets
All example tickets are encrypted using the following fixed 1024Bit RSA key

(Never use these keys in production, you must generate your own key pair for this purpose as this private key cannot be considered secure and is for testing only)

Modulus = 16540368155253773454125654483794538435594869143015457768150677916704644349481001621163 93533906833356026635527060528398017212524170789714748325265707476885395169247950736258 76338137535298120673942399072260833758038152595105311260002268650951968659366409471762 707986435753824060971148933772149012757770173722369
= HEX [00eb8aeb d600a893 2858268c 78c76235 8ae0867a 5b550e76 b9edc450 064f5b33 6656ca25 f5867813 8f4a4e8c 9d6e8079 7e78cc4b 5aef80e7 a23e0c05 3f8c95e9 15436ce9 1b7a8866 9a780d1f a417a795 46582e52 0f65fc58 2bf59ac5 824ba608 a231fdc7 1ceabbd9 70dbcf9c e55d3c20 55a0c46b dd7e7d5a 52e61f87 7e4408af 01]
Public Exponent = 65537
= HEX [010001]
Private Exponent = 23262061627321059848127951748956201956280865601289878122136319690902346303487555417896 45421978315004119428666694674801184773156427997741861134011936129888508204465790901818 10860126020371138225614906842567831455763314175530505369901364910691824152015094858350 72189773434923487177372245370361799421231555208773
= HEX [21205394 b0590501 3a8c895a ff2797c2 255ba45f adf1afce ec5a9caa 96848c11 0b89b896 f44774f0 c5119103 1f246071 e209515b c3ad4c66 6bf582d3 72312f2b 7250fe61 f6abed7f e219c08d c3985ae1 3f6b6db2 0e3c040b df7a817d 14a5a6f1 20d94047 08512132 aca00baa 29805440 4ad5dec2 1bd544bb 8938c74b 2904e645]


来源: stackexchange

问:
Laravel 5.4! FatalThrowable Error
trying to make a photo upload but It gives me the following error, even though it worked a while back! what is should I change? I am using larval 5.4

FatalThrowableError Call to a member function getClientOriginalName()
  on null

```<code>use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

    public function uploadPhoto(Request $request){

        $file = $request->file('pic');
        $filename = $file->getClientOriginalName();

        $path ='public/img';

        $file->move($path,$filename);
        $user_id = Auth::user()->id;

        DB::table('users')->where('id',$user_id)->update(['pic' => $filename]);
        return back();
    }
}
</code>```

答:
It seems like in your request the file does not exist, You may determine if a file is present on the request using the hasFile method:

```<code>if ($request->hasFile('pic')) {
    //
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Laravel 5.4! FatalThrowable Error

Body:
trying to make a photo upload but It gives me the following error, even though it worked a while back! what is should I change? I am using larval 5.4

FatalThrowableError Call to a member function getClientOriginalName()
  on null

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

    public function uploadPhoto(Request $request){

        $file = $request->file('pic');
        $filename = $file->getClientOriginalName();

        $path ='public/img';

        $file->move($path,$filename);
        $user_id = Auth::user()->id;

        DB::table('users')->where('id',$user_id)->update(['pic' => $filename]);
        return back();
    }
}

Body:
It seems like in your request the file does not exist, You may determine if a file is present on the request using the hasFile method:

if ($request->hasFile('pic')) {
    //
}


问:
Could not find or load main class org.gradle.wrapper.GradleWrapperMain
I cleaned the whole project by deleting local directories like ~/.gradle, ~/.m2 ~./android and ~/workspace/project/.gradle and chosing File -> Invalidate Caches / Restart... in Android Studio.
Now execution of the command ./gradlew leads to the following output:

```<code>usr$ ./gradlew tasks
Error: Could not find or load main class org.gradle.wrapper.GradleWrapperMain
</code>```

Needless to say, I deleted too much, the question is how can it be repaired again? Do you have any ideas how to fix this?

答: In my case gradle-wrapper.jar got corrupted after replacing a bunch of files. Reverting to original one resolved the problem.</p>

Body:
I cleaned the whole project by deleting local directories like ~/.gradle, ~/.m2 ~./android and ~/workspace/project/.gradle and chosing File -> Invalidate Caches / Restart... in Android Studio.
Now execution of the command ./gradlew leads to the following output:

usr$ ./gradlew tasks
Error: Could not find or load main class org.gradle.wrapper.GradleWrapperMain

Needless to say, I deleted too much, the question is how can it be repaired again? Do you have any ideas how to fix this?


问:
C++ conversion from unsigned char to std::string
Intro: Consider that I have no experience with C++, but can find my way around any language to do basic tasks.
Most of my experience is with .net languages (vn.net and C#), php and js, so please explain as if you were teaching a complete noob.

Here is the problem: I receive data in an unsigned char characters[12]; and I have to then append that data to a std::string

data is always 12 characters long, and is not null terminated, because it is gathered by selecting specific bytes received from serial port.

Long story short:

```<code>std::string stroutput = "some text ";
unsigned char characters[12];
characters[0]=64; //demo data to shorten the code
characters[1]=72;
stroutput.append(characters[0]);
stroutput.append(characters[1]);
....
</code>```

The result i want is to have the string value

```<code>some text @H...
</code>```

But what i get is an error while compiling

```<code>error: invalid conversion from ‘unsigned char’ to ‘const char*’ [-fpermissive]
stroutput.append(characters[0]);
                 ~~~~~~~~~~~~^
</code>```

Logic behind this thinking is that output of:

```<code>printf("%c%c",characters[0],characters[1]);
</code>```

and

```<code>std::cout << characters[0] << characters[0] << std::endl;
</code>```

results in

```<code>@H
</code>```

So: How do I convert unsigned char something[12] to std::string?

Thanks

Edit: Sorry for the duplicate, search didn't return that question.
Thanks everyone - too bad I can't mark multiple answers!

答:
To append a character you have to use the following overloaded method append

```<code>basic_string& append(size_type n, charT c);
</code>```

For example

```<code>stroutput.append(1, characters[0]);
stroutput.append(1, characters[1]);
</code>```

Otherwise use method push_back or the operator +=. For example

```<code>stroutput += characters[0];
stroutput += characters[1];
</code>```

If you want to append the whole array or its part then you can write

```<code>stroutput.append( reinterpret_cast<char *>( characters ), sizeof( characters ) );

stroutput.append( reinterpret_cast<char *>( characters ), n );
</code>```

where n is the number of characters of the array to append.

Body:
Intro: Consider that I have no experience with C++, but can find my way around any language to do basic tasks.
Most of my experience is with .net languages (vn.net and C#), php and js, so please explain as if you were teaching a complete noob.

Here is the problem: I receive data in an unsigned char characters[12]; and I have to then append that data to a std::string

data is always 12 characters long, and is not null terminated, because it is gathered by selecting specific bytes received from serial port.

Long story short:

std::string stroutput = "some text ";
unsigned char characters[12];
characters[0]=64; //demo data to shorten the code
characters[1]=72;
stroutput.append(characters[0]);
stroutput.append(characters[1]);
....

The result i want is to have the string value

some text @H...

But what i get is an error while compiling

error: invalid conversion from ‘unsigned char’ to ‘const char*’ [-fpermissive]
stroutput.append(characters[0]);
                 ~~~~~~~~~~~~^

Logic behind this thinking is that output of:

printf("%c%c",characters[0],characters[1]);

and

std::cout << characters[0] << characters[0] << std::endl;

results in

@H

So: How do I convert unsigned char something[12] to std::string?

Thanks

Edit: Sorry for the duplicate, search didn't return that question.
Thanks everyone - too bad I can't mark multiple answers!

Body:
To append a character you have to use the following overloaded method append

basic_string& append(size_type n, charT c);

For example

stroutput.append(1, characters[0]);
stroutput.append(1, characters[1]);

Otherwise use method push_back or the operator +=. For example

stroutput += characters[0];
stroutput += characters[1];

If you want to append the whole array or its part then you can write

stroutput.append( reinterpret_cast<char *>( characters ), sizeof( characters ) );

stroutput.append( reinterpret_cast<char *>( characters ), n );

where n is the number of characters of the array to append.


问:
How to Handle Alerts Using Headless Browsers (HtmlUnitDriver/Phantomjs Driver)
I am using PhantomJs Driver for Headless Testing , I am getting below exception

Sample code:

```<code>import static org.testng.Assert.assertEquals;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class TestLogin {
WebDriver d;
@BeforeMethod
    public void launh_Browser() {
System.setProperty("phantomjs.binary.path", "D:\\Selenium\\driver\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
         Capabilities caps = new DesiredCapabilities();
         ((DesiredCapabilities) caps).setJavascriptEnabled(true);
         ((DesiredCapabilities) caps).setCapability("takesScreenshot", true);
         d=new PhantomJSDriver(caps);
    }
    @Test
    public void guru_banking_login_excel() throws Exception {
        d.get("http://www.demo.guru99.com/V4/");
        d.findElement(By.name("uid")).sendKeys("TestUser");
        d.findElement(By.name("password")).sendKeys("testpwd");
        d.findElement(By.name("btnLogin")).click();
        try{
            Alert alt = d.switchTo().alert();
            String actualBoxMsg = alt.getText(); // get content of the Alter Message
            assertEquals(actualBoxMsg,"User or Password is not valid");
            alt.accept();
        }
        catch (NoAlertPresentException Ex){
            String hometitle=d.getTitle();
            assertEquals(hometitle,"Guru99 Bank Manager HomePage");
  }
d.quit
}
</code>```

Error Observed :

```<code> Exception : org.openqa.selenium.UnsupportedCommandException: Invalid Command Method - {"headers":{"Accept-Encoding":"gzip,deflate","Cache-Control":"no-cache","Connection":"Keep-Alive","
</code>```

I am trying to handle popup using phantomjs as a driver
 Please help on This .........

Thanks in Advance..!!!!

答:
You have to take care of a lot of points here in your code :

While working with PhantomJS when you mention System.setProperty use the following code lines instead :

```<code>File src = new File("C:\\Utility\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
System.setProperty("phantomjs.binary.path", src.getAbsolutePath());
</code>```

DesiredCapabilities type of objects must be initiated with reference to DesiredCapabilities class only. So change to :

```<code>DesiredCapabilities caps = new DesiredCapabilities();
</code>```

While using assertEquals use Assert.assertEquals as follows :

```<code>Assert.assertEquals(actualBoxMsg,"User or Password is not valid");
//
Assert.assertEquals(hometitle,"Guru99 Bank Manager HomePage");
</code>```

As you are using TestNG, for Assert, use org.testng.Assert; instead of static org.testng.Assert.assertEquals; as an import :

```<code>import org.testng.Assert;
</code>```

You need to wrap up the line d.quit() within a separate TestNG Annotated function too as follows :

```<code>    @AfterMethod
    public void tearDown() {
        d.quit();
    }
</code>```

Here is your own code block which executes successfully :

```<code>package headlessBrowserTesting;

import java.io.File;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class PhantomJS_webdriver_binary
{

    WebDriver d;

    @BeforeMethod
    public void launh_Browser() {
        File src = new File("C:\\Utility\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
        System.setProperty("phantomjs.binary.path", src.getAbsolutePath());
        DesiredCapabilities caps = new DesiredCapabilities();
        ((DesiredCapabilities) caps).setJavascriptEnabled(true);
        ((DesiredCapabilities) caps).setCapability("takesScreenshot", true);
        d=new PhantomJSDriver(caps);
      }

    @Test
    public void guru_banking_login_excel() throws Exception {
        d.get("http://www.demo.guru99.com/V4/");
        d.findElement(By.name("uid")).sendKeys("TestUser");
        d.findElement(By.name("password")).sendKeys("testpwd");
        d.findElement(By.name("btnLogin")).click();
        try{
            Alert alt = d.switchTo().alert();
            String actualBoxMsg = alt.getText();
            Assert.assertEquals(actualBoxMsg,"User or Password is not valid");
            alt.accept();
        }
        catch (NoAlertPresentException Ex){
            String hometitle=d.getTitle();
            Assert.assertEquals(hometitle,"Guru99 Bank Manager HomePage");
        }
    }

    @AfterMethod
    public void tearDown() {
        d.quit();
    }

}
</code>```

Body:
I am using PhantomJs Driver for Headless Testing , I am getting below exception

Sample code:

import static org.testng.Assert.assertEquals;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class TestLogin {
WebDriver d;
@BeforeMethod
    public void launh_Browser() {
System.setProperty("phantomjs.binary.path", "D:\\Selenium\\driver\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
         Capabilities caps = new DesiredCapabilities();
         ((DesiredCapabilities) caps).setJavascriptEnabled(true);
         ((DesiredCapabilities) caps).setCapability("takesScreenshot", true);
         d=new PhantomJSDriver(caps);
    }
    @Test
    public void guru_banking_login_excel() throws Exception {
        d.get("http://www.demo.guru99.com/V4/");
        d.findElement(By.name("uid")).sendKeys("TestUser");
        d.findElement(By.name("password")).sendKeys("testpwd");
        d.findElement(By.name("btnLogin")).click();
        try{
            Alert alt = d.switchTo().alert();
            String actualBoxMsg = alt.getText(); // get content of the Alter Message
            assertEquals(actualBoxMsg,"User or Password is not valid");
            alt.accept();
        }
        catch (NoAlertPresentException Ex){
            String hometitle=d.getTitle();
            assertEquals(hometitle,"Guru99 Bank Manager HomePage");
  }
d.quit
}

Error Observed :

 Exception : org.openqa.selenium.UnsupportedCommandException: Invalid Command Method - {"headers":{"Accept-Encoding":"gzip,deflate","Cache-Control":"no-cache","Connection":"Keep-Alive","

I am trying to handle popup using phantomjs as a driver
 Please help on This .........

Thanks in Advance..!!!!

Body:
You have to take care of a lot of points here in your code :

While working with PhantomJS when you mention System.setProperty use the following code lines instead :

File src = new File("C:\\Utility\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
System.setProperty("phantomjs.binary.path", src.getAbsolutePath());

DesiredCapabilities type of objects must be initiated with reference to DesiredCapabilities class only. So change to :

DesiredCapabilities caps = new DesiredCapabilities();

While using assertEquals use Assert.assertEquals as follows :

Assert.assertEquals(actualBoxMsg,"User or Password is not valid");
//
Assert.assertEquals(hometitle,"Guru99 Bank Manager HomePage");

As you are using TestNG, for Assert, use org.testng.Assert; instead of static org.testng.Assert.assertEquals; as an import :

import org.testng.Assert;

You need to wrap up the line d.quit() within a separate TestNG Annotated function too as follows :

    @AfterMethod
    public void tearDown() {
        d.quit();
    }

Here is your own code block which executes successfully :

package headlessBrowserTesting;

import java.io.File;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class PhantomJS_webdriver_binary
{

    WebDriver d;

    @BeforeMethod
    public void launh_Browser() {
        File src = new File("C:\\Utility\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
        System.setProperty("phantomjs.binary.path", src.getAbsolutePath());
        DesiredCapabilities caps = new DesiredCapabilities();
        ((DesiredCapabilities) caps).setJavascriptEnabled(true);
        ((DesiredCapabilities) caps).setCapability("takesScreenshot", true);
        d=new PhantomJSDriver(caps);
      }

    @Test
    public void guru_banking_login_excel() throws Exception {
        d.get("http://www.demo.guru99.com/V4/");
        d.findElement(By.name("uid")).sendKeys("TestUser");
        d.findElement(By.name("password")).sendKeys("testpwd");
        d.findElement(By.name("btnLogin")).click();
        try{
            Alert alt = d.switchTo().alert();
            String actualBoxMsg = alt.getText();
            Assert.assertEquals(actualBoxMsg,"User or Password is not valid");
            alt.accept();
        }
        catch (NoAlertPresentException Ex){
            String hometitle=d.getTitle();
            Assert.assertEquals(hometitle,"Guru99 Bank Manager HomePage");
        }
    }

    @AfterMethod
    public void tearDown() {
        d.quit();
    }

}


问:
Why does my Android app keep telling me I need to define a ListView id when it is already defined?
Whenever I try to run my app, the following exception is thrown:

01-22 00:40:51.868: ERROR/AndroidRuntime(2219): java.lang.RuntimeException: Unable to start activity ComponentInfo{[Redacted]}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'

Here is the markup for the ListView in question:

```<code><ListView
 android:id="@+id/list"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:dividerHeight="1px"></ListView>
</code>```

So, since the id is clearly defined as "list," what gives here? I've run through my code multiple times in the past couple of hours trying to track down the cause of this and I'm stumped. Can anyone offer any pointers?

答:
Actually there is a difference between "android.R.id.list" and simply "R.id.list"

```<code><ListView android:id="@android:id/list" />
</code>```

is not the same list as

```<code><ListView android:id="@+id/list" />
</code>```

The first one has a predefined id in the android framework which means that some things are made automatically in the background for you. Consider the example below:

```<code><LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="match_parent"
    android:height="match_parent">

    <ListView
        android:width="match_parent"
        android:height="match_parent"
        android:id="@android:id/list" />

    <TextView
        android:width="wrap_content"
        android:height="wrap_content"
        android:id="@android:id/empty"
        android:text="You don\'t have any items yet." />
</LinearLayout>
</code>```

Given the above layout in your XML and that your corresponding java class extends the ListActivity, the TextView will automatically be shown for you when your list doesn't have any items and it will also automatically be hidden when the list get its first item.

ContentLicense: CC BY-SA 2.5

Body:
Whenever I try to run my app, the following exception is thrown:

01-22 00:40:51.868: ERROR/AndroidRuntime(2219): java.lang.RuntimeException: Unable to start activity ComponentInfo{[Redacted]}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'

Here is the markup for the ListView in question:

<ListView
 android:id="@+id/list"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:dividerHeight="1px"></ListView>

So, since the id is clearly defined as "list," what gives here? I've run through my code multiple times in the past couple of hours trying to track down the cause of this and I'm stumped. Can anyone offer any pointers?

Body:
Actually there is a difference between "android.R.id.list" and simply "R.id.list"

<ListView android:id="@android:id/list" />

is not the same list as

<ListView android:id="@+id/list" />

The first one has a predefined id in the android framework which means that some things are made automatically in the background for you. Consider the example below:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="match_parent"
    android:height="match_parent">

    <ListView
        android:width="match_parent"
        android:height="match_parent"
        android:id="@android:id/list" />

    <TextView
        android:width="wrap_content"
        android:height="wrap_content"
        android:id="@android:id/empty"
        android:text="You don\'t have any items yet." />
</LinearLayout>

Given the above layout in your XML and that your corresponding java class extends the ListActivity, the TextView will automatically be shown for you when your list doesn't have any items and it will also automatically be hidden when the list get its first item.


答:
Try using Input facade to check if your request has file object

```<code>use Illuminate\Support\Facades\Input;

$file = $request->file('pic');
if (Input::hasFile('pic')) {
    $filename = Input::file('pic')->getClientOriginalName();
   // .. rest of the code
}
</code>```

Title: Laravel 5.4! FatalThrowable Error

Body:
Try using Input facade to check if your request has file object

use Illuminate\Support\Facades\Input;

$file = $request->file('pic');
if (Input::hasFile('pic')) {
    $filename = Input::file('pic')->getClientOriginalName();
   // .. rest of the code
}


问:
PHP Syntax error in INSERT INTO statement., SQL state 37000 in SQLExecDirect
Error

Warning: odbc_exec(): SQL error: [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement., SQL state 37000 in SQLExecDirect in E:\DEP\Prog\PHP6\starcraft\starcraft\personnage_traitement.php on line 61
  [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement.

SQL query when using the Ajouter action (ADD in english)

```<code>$nom =$_POST["nom"];
$faction = $_POST["faction"];
$age = $_POST["age"];
$race = $_POST["race"];
$description = $_POST["description"];
$fichier = $_POST["image"];

if ($_POST["action"] == "Ajouter") {

  $sql="Insert into personnage (nom,  faction, race, age, description, image) values ('$nom', $faction, $race, $age,'$description', '$fichier')";

  odbc_exec($odbc, $sql) or die(odbc_error($odbc));
</code>```

My code

```<code><fieldset>
    <legend>New hero</legend>
                    <label for="nom">Nom : </label><input type="text"     name="nom" id="nom" size="40" required><br>
                    <label for="age">Âge : </label><input type="number" name="age" id="age" size="40" required><br>
                    <label for="race">Race : </label><select name="race" id="race" size="1" >
                        <?php
                        $sql2 = "SELECT NomRace FROM Race;";
                        $resultat2 = odbc_exec($odbc, $sql2) or die(odbc_error($odbc));

                        odbc_fetch_row($resultat2, 0);

                        while (odbc_fetch_row($resultat2)) {

                            $idS = odbc_result($resultat2, "IDRace");

                            $race = utf8_encode(odbc_result($resultat2, "NomRace"));

                            echo "<OPTION VALUE=\"$idS\">$race</OPTION>";
                        }
                        ?>
                    </select> <a href="race.php">Édition des races</a><br>
                    <label for="faction">Faction : </label><select name="faction" id="faction" size="1" >
                        <?php

                        $sql3 = "SELECT NomFaction FROM Faction;";
                        $resultat3 = odbc_exec($odbc, $sql3) or die(odbc_error($odbc));

                        odbc_fetch_row($resultat3, 0);

                        while (odbc_fetch_row($resultat3)) {

                            $idS = odbc_result($resultat3, "IDFaction");

                            $faction = utf8_encode(odbc_result($resultat3, "NomFaction"));

                            echo "<OPTION VALUE=\"$idS\">$faction</OPTION>";
                        }
                        ?>
                    </select> <a href="faction.php">Édition des factions</a><br>
                    <label for="description">Description : </label><input type="text" name="description" id="description" size="40" required>
                    <br>
                    <br>
                    <input type="hidden" name="MAX_FILE_SIZE" value="100000">
                    <label for="fichier">Fichier d'image : </label>
                    <input type="file" onchange="readURL(this);" name="fichier" id="fichier">
                    <img alt="Image" id="preview" title="image" src="#" />
                    <br>
                    <br>
                    <input type="submit" name="action" value="Ajouter">
                </fieldset>
</code>```

答:
```<code><?php
$sql="INSERT INTO personnage(nom,faction,race,age,description,image)values('$nom','$faction','$race','$age','$description','$fichier')";odbc_exec($odbc,$sql)ordie(odbc_error($odbc));

or in mysql

$sql=mysql_query("INSERT INTO personnage(nom,faction,race,age,description,image)values('$nom','$faction','$race','$age','$description','$fichier')")or die("Could not execute the insert query:".mysql_error());
?>
</code>```

Body:
Error

Warning: odbc_exec(): SQL error: [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement., SQL state 37000 in SQLExecDirect in E:\DEP\Prog\PHP6\starcraft\starcraft\personnage_traitement.php on line 61
  [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement.

SQL query when using the Ajouter action (ADD in english)

$nom =$_POST["nom"];
$faction = $_POST["faction"];
$age = $_POST["age"];
$race = $_POST["race"];
$description = $_POST["description"];
$fichier = $_POST["image"];

if ($_POST["action"] == "Ajouter") {

  $sql="Insert into personnage (nom,  faction, race, age, description, image) values ('$nom', $faction, $race, $age,'$description', '$fichier')";

  odbc_exec($odbc, $sql) or die(odbc_error($odbc));

My code

<fieldset>
    <legend>New hero</legend>
                    Nom : <input type="text"     name="nom" id="nom" size="40" required>

                    Âge : <input type="number" name="age" id="age" size="40" required>

                    Race : <select name="race" id="race" size="1" >
                        <?php
                        $sql2 = "SELECT NomRace FROM Race;";
                        $resultat2 = odbc_exec($odbc, $sql2) or die(odbc_error($odbc));

                        odbc_fetch_row($resultat2, 0);

                        while (odbc_fetch_row($resultat2)) {

                            $idS = odbc_result($resultat2, "IDRace");

                            $race = utf8_encode(odbc_result($resultat2, "NomRace"));

                            echo "<OPTION VALUE=\"$idS\">$race</OPTION>";
                        }
                        ?>
                    </select> Édition des races

                    Faction : <select name="faction" id="faction" size="1" >
                        <?php

                        $sql3 = "SELECT NomFaction FROM Faction;";
                        $resultat3 = odbc_exec($odbc, $sql3) or die(odbc_error($odbc));

                        odbc_fetch_row($resultat3, 0);

                        while (odbc_fetch_row($resultat3)) {

                            $idS = odbc_result($resultat3, "IDFaction");

                            $faction = utf8_encode(odbc_result($resultat3, "NomFaction"));

                            echo "<OPTION VALUE=\"$idS\">$faction</OPTION>";
                        }
                        ?>
                    </select> Édition des factions

                    Description : <input type="text" name="description" id="description" size="40" required>

                    <input type="hidden" name="MAX_FILE_SIZE" value="100000">
                    Fichier d'image :
                    <input type="file" onchange="readURL(this);" name="fichier" id="fichier">

                    <input type="submit" name="action" value="Ajouter">
                </fieldset>


问:
Python on Raspbian - "TypeError: 'numpy.int32' object is not iterable'"
The following code runs on my desktop (Mint 17) with no issues, but when I try to run it on a RPi running Raspbian I get the above mentioned error message at line 58. The only thing I can think that's causing it is the Python version:

Mint uses Python 2.7.6

```<code>$ python -V
    Python 2.7.6
</code>```

The RPi uses 2.7.3, but I've installed 2.7.8 and aliased it

```<code>$ python -V
    Python 2.7.3
$ alias python=/usr/local/bin/python2.7
$ python -V
    Python 2.7.8
</code>```

I know there's similar questions on here, but the issue seems to be code related in those cases. I know this code's OK, so it must be an environment issue, right?

Here's the program anyway:

```<code>#!/usr/bin/env python

# Determines if a set of three images contains at least one person
# Images are taken in quick succession, the 2nd and 3rd are diff images of the first
# Adapted from sample file: /opencv/samples/python2/peopledetect.py
#
# Example:  ./pdTriple.py IMG_000.JPG IMG_001.JPG IMG_002.JPG

import numpy as np
import cv2
import sys
from glob import glob
import itertools as it
from array import *

def inside(r, q):
    rx, ry, rw, rh = r
    qx, qy, qw, qh = q
    return rx > qx and ry > qy and rx + rw < qx + qw and ry + rh < qy + qh

def draw_detections(img, rects, thickness = 1):
    for x, y, w, h in rects:
        # the HOG detector returns slightly larger rectangles than the real objects.
        # so we slightly shrink the rectangles to get a nicer output.
        pad_w, pad_h = int(0.15*w), int(0.05*h)
        cv2.rectangle(img, (x+pad_w, y+pad_h), (x+w-pad_w, y+h-pad_h), (0, 255, 0), thickness)

if __name__ == '__main__':

    hog = cv2.HOGDescriptor()
    hog.setSVMDetector( cv2.HOGDescriptor_getDefaultPeopleDetector() )

    count = 0
    results = np.array([0,0,0])

    for fn in it.chain(*map(glob, sys.argv[1:])):
        print fn, ' - ',

        try:
            img = cv2.imread(fn)
            if img is None:
                print 'Failed to load image file:', fn
                continue
        except:
            print 'loading error'
            continue

        # modify winstride and padding values to optimise results
        found, w = hog.detectMultiScale(img, winStride=(4,4), padding=(8,8), scale=1.05)

        found_filtered = []
        for ri, r in enumerate(found):
            for qi, q in enumerate(found):
                if ri != qi and inside(r, q):uname # errors here
                    break
            else:
                found_filtered.append(r)

        print '%d found (%d filtered)' % (len(found_filtered), len(found))
        results[count] = len(found_filtered)
        count += 1

if np.all(results>0):
    print '\n--------------', fn, 'contains a person --------------\n'
</code>```

答:
if you delete 'uname', it'll work;</p>

```<code>for ri, r in enumerate(found):
        for qi, q in enumerate(found):
            if ri != qi and inside(r, q): # errors here
                break
        else:
            found_filtered.append(r)
</code>```

Body:
The following code runs on my desktop (Mint 17) with no issues, but when I try to run it on a RPi running Raspbian I get the above mentioned error message at line 58. The only thing I can think that's causing it is the Python version:

Mint uses Python 2.7.6

$ python -V
    Python 2.7.6

The RPi uses 2.7.3, but I've installed 2.7.8 and aliased it

$ python -V
    Python 2.7.3
$ alias python=/usr/local/bin/python2.7
$ python -V
    Python 2.7.8

I know there's similar questions on here, but the issue seems to be code related in those cases. I know this code's OK, so it must be an environment issue, right?

Here's the program anyway:

#!/usr/bin/env python

# Determines if a set of three images contains at least one person
# Images are taken in quick succession, the 2nd and 3rd are diff images of the first
# Adapted from sample file: /opencv/samples/python2/peopledetect.py
#
# Example:  ./pdTriple.py IMG_000.JPG IMG_001.JPG IMG_002.JPG

import numpy as np
import cv2
import sys
from glob import glob
import itertools as it
from array import *

def inside(r, q):
    rx, ry, rw, rh = r
    qx, qy, qw, qh = q
    return rx > qx and ry > qy and rx + rw < qx + qw and ry + rh < qy + qh

def draw_detections(img, rects, thickness = 1):
    for x, y, w, h in rects:
        # the HOG detector returns slightly larger rectangles than the real objects.
        # so we slightly shrink the rectangles to get a nicer output.
        pad_w, pad_h = int(0.15*w), int(0.05*h)
        cv2.rectangle(img, (x+pad_w, y+pad_h), (x+w-pad_w, y+h-pad_h), (0, 255, 0), thickness)

if __name__ == '__main__':

    hog = cv2.HOGDescriptor()
    hog.setSVMDetector( cv2.HOGDescriptor_getDefaultPeopleDetector() )

    count = 0
    results = np.array([0,0,0])

    for fn in it.chain(*map(glob, sys.argv[1:])):
        print fn, ' - ',

        try:
            img = cv2.imread(fn)
            if img is None:
                print 'Failed to load image file:', fn
                continue
        except:
            print 'loading error'
            continue

        # modify winstride and padding values to optimise results
        found, w = hog.detectMultiScale(img, winStride=(4,4), padding=(8,8), scale=1.05)

        found_filtered = []
        for ri, r in enumerate(found):
            for qi, q in enumerate(found):
                if ri != qi and inside(r, q):uname # errors here
                    break
            else:
                found_filtered.append(r)

        print '%d found (%d filtered)' % (len(found_filtered), len(found))
        results[count] = len(found_filtered)
        count += 1

if np.all(results>0):
    print '\n--------------', fn, 'contains a person --------------\n'

Body:
if you delete 'uname', it'll work;

for ri, r in enumerate(found):
        for qi, q in enumerate(found):
            if ri != qi and inside(r, q): # errors here
                break
        else:
            found_filtered.append(r)


问:
How to insert on runtime on odt document using jodreports and java
I need to insert various images in a doc or odt document using java, the images are generated on runtime. At the time I am tempted to use jodreports because it is very easy to generate the template of the final document, but I am stuck because I cannot find any kind of documentation telling me how to insert images. If you can answer my question please post a code snippet or tell me which other library I can use.

Thanks a lot for your help(and sorry for my bad English).

答:
In my page https://xbrowser.altervista.org/informatica-portata/odt-converter/
you can find step by step how to implement your question.

Libraries are:

```<code>import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import net.sf.jooreports.templates.DocumentTemplate;
import net.sf.jooreports.templates.DocumentTemplateException;
import net.sf.jooreports.templates.DocumentTemplateFactory;
import net.sf.jooreports.templates.image.FileImageSource;
</code>```

This is the method

```<code>private Map<String, Object> data = new HashMap<String, Object>();;
private Logger log = Logger.getLogger(this.getClass().getName());

private void createOdt() {

DocumentTemplateFactory documentTemplateFactory = new DocumentTemplateFactory();
DocumentTemplate template = null;

File inputFile = new File("/path/template.odt"); //inserire il path relativo alla posizione del template .odt
try {
template = documentTemplateFactory.getTemplate(inputFile);
log.debug("input file ok -> " + inputFile);
} catch (IOException e) {
log.error(e);
}
try {
tmpFile = File.createTempFile("odt_", ".odt");

data.put("qrcode", new FileImageSource(new File("/img/src/qrcode.jpg"))); //qui è possibile generare per esempio un qrcode
template.createDocument(data, new FileOutputStream(tmpFile));

log.debug("output file temporaneo creato ("+ tmpFile.getAbsolutePath() + ")..");
} catch (FileNotFoundException e) {
log.error(e);
} catch (IOException e) {
log.error(e);
} catch (DocumentTemplateException e) {
log.error(e);
}
}
</code>```

At this point it is necessary that in the .odt template an image is inserted with the following modality:

Insert an image

Double click on the image to go into properties of image

Select "options" tab

In the field "Name" insert: jooscript.image(qrcode)

As you can see the name of the image shows qrcode which is exactly the name of the hashmap key in our code(data.put("qrcode")).

In this way it is possible to show dynamically generated images from the java code in a template defined in .odt.

I hope you have been helpful

Body:
In my page https://xbrowser.altervista.org/informatica-portata/odt-converter/
you can find step by step how to implement your question.

Libraries are:

import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import net.sf.jooreports.templates.DocumentTemplate;
import net.sf.jooreports.templates.DocumentTemplateException;
import net.sf.jooreports.templates.DocumentTemplateFactory;
import net.sf.jooreports.templates.image.FileImageSource;

This is the method

private Map<String, Object> data = new HashMap<String, Object>();;
private Logger log = Logger.getLogger(this.getClass().getName());

private void createOdt() {

DocumentTemplateFactory documentTemplateFactory = new DocumentTemplateFactory();
DocumentTemplate template = null;

File inputFile = new File("/path/template.odt"); //inserire il path relativo alla posizione del template .odt
try {
template = documentTemplateFactory.getTemplate(inputFile);
log.debug("input file ok -> " + inputFile);
} catch (IOException e) {
log.error(e);
}
try {
tmpFile = File.createTempFile("odt_", ".odt");

data.put("qrcode", new FileImageSource(new File("/img/src/qrcode.jpg"))); //qui è possibile generare per esempio un qrcode
template.createDocument(data, new FileOutputStream(tmpFile));

log.debug("output file temporaneo creato ("+ tmpFile.getAbsolutePath() + ")..");
} catch (FileNotFoundException e) {
log.error(e);
} catch (IOException e) {
log.error(e);
} catch (DocumentTemplateException e) {
log.error(e);
}
}

At this point it is necessary that in the .odt template an image is inserted with the following modality:

Insert an image

Double click on the image to go into properties of image

Select "options" tab

In the field "Name" insert: jooscript.image(qrcode)

As you can see the name of the image shows qrcode which is exactly the name of the hashmap key in our code(data.put("qrcode")).

In this way it is possible to show dynamically generated images from the java code in a template defined in .odt.

I hope you have been helpful


问:
Nuget package cannot be installed
I set up a local nuget package repository and create a custom package.

I followed these two guides:

http://nuget.codeplex.com/wikipage?title=Hosting%20Your%20Own%20Local%20and%20Remote%20NuPack%20Feeds

http://nuget.codeplex.com/documentation?title=Creating%20a%20Package

and here is the nuspec file of my package:

```<code><?xml version="1.0" encoding="utf-8"?>
<package>
    <metadata>
        <id>NLog</id>
        <version>1.0.0.505</version>
        <authors>NLog</authors>
        <description>NLog</description>
    </metadata>
    <files>
        <file src="NLog.dll" target="lib"/>
    </files>
</package>
</code>```

the package was successfully created and the package shows up the package library.

But nothing happens when I click "INSTALL".

Can anyone help?

答: Looks like there was an issue with package building (Maybe the dll file didn't make it into lib). Try unzipping the package (rename to zip and extract) and seeing what's inside. We've updated nuget.exe and have added a -v flag to pack so that you can see the contents of your package after you build. You can install it from the ci machine http://ci.nuget.org:8080/guestAuth/repository/download/bt4/.lastSuccessful/Console/NuGet.exe).</p>

Title: Nuget package cannot be installed

Body:
I set up a local nuget package repository and create a custom package.

I followed these two guides:

http://nuget.codeplex.com/wikipage?title=Hosting%20Your%20Own%20Local%20and%20Remote%20NuPack%20Feeds

http://nuget.codeplex.com/documentation?title=Creating%20a%20Package

and here is the nuspec file of my package:

<?xml version="1.0" encoding="utf-8"?>
<package>
    <metadata>
        <id>NLog</id>
        <version>1.0.0.505</version>
        <authors>NLog</authors>
        <description>NLog</description>
    </metadata>
    <files>
        <file src="NLog.dll" target="lib"/>
    </files>
</package>

the package was successfully created and the package shows up the package library.

But nothing happens when I click "INSTALL".

Can anyone help?


问:
using simple queries in ASP.NET MVC
I checked google but found nothing good. I am searching for usinf Traditional SQL queries in MVC instead of Entity framework etc. So it would be good if you guys provide me some examples.

I started to learn MVC but lot of examples uses linq to SQL and EF etc which I don't want to use at all, I want to use simple old SQL queries in Model layer.

答:
Using entity framework it can be done</p>

```<code>Entitiesdb db = new Entitiesdb();
string query="delete from tableA where id=@id"
db.Database.ExecuteSqlCommand(query, @id);
</code>```

Title: using simple queries in ASP.NET MVC

Body:
Using entity framework it can be done

Entitiesdb db = new Entitiesdb();
string query="delete from tableA where id=@id"
db.Database.ExecuteSqlCommand(query, @id);


问:
Vertical-align/Valign not working
Basically, i'm making a newsletter for a company and i need the "Schrijf reactie" button to be in the middle, but vertical-align and valign aren't working and using media queries for top/bottom is not an option.

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

Schrijf uw bevindingen ook eens in ons gastenboek. Dat stellen wij, en andere klanten zeer op prijs.

                            SCHRIJF REACTIE

    ```

答:
The vertical-align property will not apply on nested table elements which have no containing table-cells of their own to maintain the typical tabular structure of a table.

Columns should be kept equal in height for the vertical-align property to result in the expected behaviour, you will require table-cells to do this.

Consider nesting your table elements in separated table cells (td) which you can then declare a vertical-align property value on:

rather this:

```<code><!-- better approach -->
<table>
   <tr>
      <td> <!-- now you can declare a vertical-align property -->
         <table></table>
      </td>
      <td> <!-- now you can declare a vertical-align property -->
         <table></table>
      </td>
   </tr>
</table>
</code>```

instead of this:

```<code><!-- wrong approach -->
<table>
   <tr>
      <td>
         <table></table>
         <table></table>
      </td>
   </tr>
</table>
</code>```

Code Snippet Demonstration:

Schrijf uw bevindingen ook eens in ons gastenboek. Dat stellen wij, en andere klanten zeer op prijs.

            SCHRIJF REACTIE

```

Title: Vertical-align/Valign not working

Body:
The vertical-align property will not apply on nested table elements which have no containing table-cells of their own to maintain the typical tabular structure of a table.

Columns should be kept equal in height for the vertical-align property to result in the expected behaviour, you will require table-cells to do this.

Consider nesting your table elements in separated table cells (td) which you can then declare a vertical-align property value on:

rather this:

<!-- better approach -->
<table>
   <tr>
      <td> <!-- now you can declare a vertical-align property -->
         <table></table>
      </td>
      <td> <!-- now you can declare a vertical-align property -->
         <table></table>
      </td>
   </tr>
</table>

instead of this:

<!-- wrong approach -->
<table>
   <tr>
      <td>
         <table></table>
         <table></table>
      </td>
   </tr>
</table>

Code Snippet Demonstration:

<table bgcolor="#4275A2" width="600" border="0" cellpadding="0" cellspacing="0" align="center" class="deviceWidth" style="margin:0 auto;">
  <tr>
    <td style="padding:10px 0;vertical-align: middle;width: 70%;">
      <table align="left" cellpadding="0" cellspacing="0" border="0" class="deviceWidth">
        <tr>
          <td style="font-size: 12px; color: white; font-weight: normal; text-align: left; font-family: Georgia, Times, serif; line-height: 24px; padding:10px 8px 10px 8px">
            <h2 style="mso-table-lspace:0;mso-table-rspace:0;margin:0;font-size:18px;color:white;">Schrijf uw bevindingen ook eens in ons gastenboek. Dat stellen wij, en andere klanten zeer op prijs.
              <br/><br/></h2>
          </td>
        </tr>
      </table>
    </td>
    <td style="padding:10px 0;vertical-align: middle;">
      <table style="veritcal-align:bottom;" cellpadding="0" cellspacing="0" border="0" class="deviceWidth">
        <tr>
          <td bgcolor="#542841" style="background-repeat:no-repeat;">
            <a href="#" style="border-radius: 5px;padding: 20px;color:#ffffff;font-size:13px;font-weight:bold;display:block;text-align:center;text-decoration:none;font-family:Arial, sans-serif;-webkit-text-size-adjust:none;">SCHRIJF REACTIE</a>
          </td>
        </tr>
      </table>
    </td>
  </tr>
</table>


问:
Is here any GUI tool that can show file with conflicts side-by-side?
I have a couple of conflicted files and I don't have access to source branches (these files are detached from the repository. There isn't any .git folder and I don't have original versions). There are some conflicts marked by git-merge:

```<code><<<<<<< HEAD
    sizeof(.......bla bla
||||||| merged common ancestors
    sizeof(.......ble ble
=======
    sizeof(.......blu blu
>>>>>>> refs/heads/TAGNAME
</code>```

Is there a way to see such file in human-readable mode, i.e. parse a single file with marked conflicts and split it to a side-by-side view?  I suppose Meld cannot do it, and KDiff3 seems to be unable to do the trick too.

git merge (tool) says that this isn't a Git repository.

git diff --no-index requires two parameters (two files to compare), and as mentioned before I don't have the input files.

答:
Meld can indeed handle visualising conflicts

Source: Resolving merge conflicts

ContentLicense: CC BY-SA 4.0

Body:
I have a couple of conflicted files and I don't have access to source branches (these files are detached from the repository. There isn't any .git folder and I don't have original versions). There are some conflicts marked by git-merge:

<<<<<<>>>>>> refs/heads/TAGNAME

Is there a way to see such file in human-readable mode, i.e. parse a single file with marked conflicts and split it to a side-by-side view?  I suppose Meld cannot do it, and KDiff3 seems to be unable to do the trick too.

git merge (tool) says that this isn't a Git repository.

git diff --no-index requires two parameters (two files to compare), and as mentioned before I don't have the input files.


问:
My Class in not an enclossing class
so I have class constructor:

```<code>public class HealthDataStore { // this class is 3rd party api - can't modify
    public HealthDataStore(Context context, HealthDataStore.ConnectionListener listener){ /* bla... */ }

    /* bla... */

    // with Listener Interface:
    public interface ConnectionListener {
        void onConnected();
        void onConnectionFailed(HealthConnectionErrorResult var1);
        void onDisconnected();
    }
}
</code>```

and in my repository class i have:

```<code>public class HealthRepository {
    private string DSConnectionStatus;

    public void connectDataStore(HealthDSConnectionListener listener) {
        mStore = new HealthDataStore(app, listener);
        mStore.connectService();
    }

    // with inner class:
    public class HealthDSConnectionListener implements HealthDataStore.ConnectionListener{
        @Override public void onConnected() { DSConnectionStatus = "Connected"; }

        @Override public void onConnectionFailed(HealthConnectionErrorResult healthConnectionErrorResult) { DSConnectionStatus = "Connection Failed"; }

        @Override public void onDisconnected() { DSConnectionStatus = "Disconnected"; }
    };
}
</code>```

and in my view model class i have below object:

```<code>public class SplashViewModel extends AndroidViewModel {

    public void connectRepoDataStore(){
        // repo is object of class HealthRepository
        repo.connectDataStore(mConnectionListener)
        // other things to do here
    }

    private final HealthRepository.HealthDSConnectionListener mConnectionListener = new HealthRepository.HealthDSConnectionListener(){
        @Override public void onConnected() {
            super.onConnected(); // i need this super to set DSConnectionStatus value
            // other things to do here
        }

        @Override public void onConnectionFailed(HealthConnectionErrorResult error) {
            super.onConnectionFailed(error); // i need this super to set DSConnectionStatus value
            // other things to do here
        }

        @Override public void onDisconnected() {
            super.onDisconnected(); // i need this super to set DSConnectionStatus value
            // other things to do here
        }
    }
</code>```

why is private final HealthRepository.HealthDSConnectionListener mConnectionListener = new HealthRepository.HealthDSConnectionListener() throw me error that the class is not enclosing class?

then how should i achieve this? to have my final listener class have capability to set DSConnectionStatus in healthrepository class?

答:
Always try to avoid using inner classes if you know you'll have to extend them. Instead use a separate class, and swap the outer class with a field. If you need to modify a private field that you do not want to expose then create a package-private setter.</p>

```<code>public class HealthRepository {
    private String DSConnectionStatus;

    public void connectDataStore(HealthDSConnectionListener listener) {
        mStore = new HealthDataStore(app, listener);
        mStore.connectService();
    }

    void setConnectionStatus(String status) {
        DSConnectionStatus = status;
    }
}
</code>```

```<code>// create another class in the same package
public class HealthDSConnectionListener implements HealthDataStore.ConnectionListener {
    private final HealthRepository repo;

    public HealthDSConnectionListener(HealthRepository repo) {
        this.repo = repo;
    }

    @Override public void onConnected() { repo.setConnectionStatus("Connected"); }
    @Override public void onDisconnected() { repo.setConnectionStatus("Disconnected"); }

    @Override public void onConnectionFailed(HealthConnectionErrorResult error) {
        repo.setConnectionStatus("Connection Failed");
    }
};
</code>```

```<code>public class SplashViewModel extends AndroidViewModel {
    private final HealthRepository repo;

    public void connectRepoDataStore() {
        // repo is object of class HealthRepository
        repo.connectDataStore(mConnectionListener)
        // other things to do here
    }

    private final HealthDSConnectionListener mConnectionListener = new HealthDSConnectionListener(repo) {
        @Override public void onConnected() {
            super.onConnected();
            // ...
        }

        @Override public void onConnectionFailed(HealthConnectionErrorResult error) {
            super.onConnectionFailed(error);
            // ...
        }

        @Override public void onDisconnected() {
            super.onDisconnected();
            // ...
        }
    }
}
</code>```

Title: My Class in not an enclossing class

Body:
so I have class constructor:

public class HealthDataStore { // this class is 3rd party api - can't modify
    public HealthDataStore(Context context, HealthDataStore.ConnectionListener listener){ /* bla... */ }

    /* bla... */

    // with Listener Interface:
    public interface ConnectionListener {
        void onConnected();
        void onConnectionFailed(HealthConnectionErrorResult var1);
        void onDisconnected();
    }
}

and in my repository class i have:

public class HealthRepository {
    private string DSConnectionStatus;

    public void connectDataStore(HealthDSConnectionListener listener) {
        mStore = new HealthDataStore(app, listener);
        mStore.connectService();
    }

    // with inner class:
    public class HealthDSConnectionListener implements HealthDataStore.ConnectionListener{
        @Override public void onConnected() { DSConnectionStatus = "Connected"; }

        @Override public void onConnectionFailed(HealthConnectionErrorResult healthConnectionErrorResult) { DSConnectionStatus = "Connection Failed"; }

        @Override public void onDisconnected() { DSConnectionStatus = "Disconnected"; }
    };
}

and in my view model class i have below object:

public class SplashViewModel extends AndroidViewModel {

    public void connectRepoDataStore(){
        // repo is object of class HealthRepository
        repo.connectDataStore(mConnectionListener)
        // other things to do here
    }

    private final HealthRepository.HealthDSConnectionListener mConnectionListener = new HealthRepository.HealthDSConnectionListener(){
        @Override public void onConnected() {
            super.onConnected(); // i need this super to set DSConnectionStatus value
            // other things to do here
        }

        @Override public void onConnectionFailed(HealthConnectionErrorResult error) {
            super.onConnectionFailed(error); // i need this super to set DSConnectionStatus value
            // other things to do here
        }

        @Override public void onDisconnected() {
            super.onDisconnected(); // i need this super to set DSConnectionStatus value
            // other things to do here
        }
    }

why is private final HealthRepository.HealthDSConnectionListener mConnectionListener = new HealthRepository.HealthDSConnectionListener() throw me error that the class is not enclosing class?

then how should i achieve this? to have my final listener class have capability to set DSConnectionStatus in healthrepository class?

Body:
Always try to avoid using inner classes if you know you'll have to extend them. Instead use a separate class, and swap the outer class with a field. If you need to modify a private field that you do not want to expose then create a package-private setter.

public class HealthRepository {
    private String DSConnectionStatus;

    public void connectDataStore(HealthDSConnectionListener listener) {
        mStore = new HealthDataStore(app, listener);
        mStore.connectService();
    }

    void setConnectionStatus(String status) {
        DSConnectionStatus = status;
    }
}

// create another class in the same package
public class HealthDSConnectionListener implements HealthDataStore.ConnectionListener {
    private final HealthRepository repo;

    public HealthDSConnectionListener(HealthRepository repo) {
        this.repo = repo;
    }

    @Override public void onConnected() { repo.setConnectionStatus("Connected"); }
    @Override public void onDisconnected() { repo.setConnectionStatus("Disconnected"); }

    @Override public void onConnectionFailed(HealthConnectionErrorResult error) {
        repo.setConnectionStatus("Connection Failed");
    }
};

public class SplashViewModel extends AndroidViewModel {
    private final HealthRepository repo;

    public void connectRepoDataStore() {
        // repo is object of class HealthRepository
        repo.connectDataStore(mConnectionListener)
        // other things to do here
    }

    private final HealthDSConnectionListener mConnectionListener = new HealthDSConnectionListener(repo) {
        @Override public void onConnected() {
            super.onConnected();
            // ...
        }

        @Override public void onConnectionFailed(HealthConnectionErrorResult error) {
            super.onConnectionFailed(error);
            // ...
        }

        @Override public void onDisconnected() {
            super.onDisconnected();
            // ...
        }
    }
}


问:
How to get number of uncommitted write commands in transaction in PostgreSQL?
Here is what I want to do

```<code>BEGIN;
INSERT INTO sample_table VALUES ('a','b')
INSERT INTO sample_table VALUES ('c','d')
</code>```

How can I get the number of commands in the transaction before committing? Like the number of uncommitted commands in above example is 2

答:
with some limitation you can use cmin +1 formula. Of course you have to know all tables where you insert. Also in my demo I show how to do it with inserts only, updates and deletes will require more logic, including xmax (if possible at all), anyway, here the code to give it a try...

sample:

```<code>t=# create table ut1(i int);
CREATE TABLE
t=# create table ut2(i int);
CREATE TABLE
t=# insert into ut1 select generate_series(1,10);
INSERT 0 10
t=# insert into ut2 select generate_series(1,10);
INSERT 0 10
</code>```

demo:

```<code>t=# begin;
BEGIN
t=# insert into ut1 select 1;
INSERT 0 1
t=# insert into ut2 select 1;
INSERT 0 1
t=# insert into ut2 select generate_series(1,2);
INSERT 0 2
t=#  insert into ut1 select generate_series(1,2);
INSERT 0 2
t=# select greatest(max(ut1.cmin::text::int),max(ut2.cmin::text::int)) from ut2 join ut1 on ut1.xmin = ut2.xmin and (ut1.xmin)::text::bigint = txid_current();
 greatest
----------
        3
(1 row)

t=# end;
COMMIT
t=# begin;
BEGIN
t=# insert into ut1 select generate_series(1,2);
INSERT 0 2
t=# insert into ut2 select generate_series(1,2);
INSERT 0 2
t=# select greatest(max(ut1.cmin::text::int),max(ut2.cmin::text::int)) from ut2 join ut1 on ut1.xmin = ut2.xmin and (ut1.xmin)::text::bigint = txid_current();
 greatest
----------
        1
(1 row)

t=# end;
COMMIT
</code>```

Body:
Here is what I want to do

BEGIN;
INSERT INTO sample_table VALUES ('a','b')
INSERT INTO sample_table VALUES ('c','d')

How can I get the number of commands in the transaction before committing? Like the number of uncommitted commands in above example is 2

Body:
with some limitation you can use cmin +1 formula. Of course you have to know all tables where you insert. Also in my demo I show how to do it with inserts only, updates and deletes will require more logic, including xmax (if possible at all), anyway, here the code to give it a try...

sample:

t=# create table ut1(i int);
CREATE TABLE
t=# create table ut2(i int);
CREATE TABLE
t=# insert into ut1 select generate_series(1,10);
INSERT 0 10
t=# insert into ut2 select generate_series(1,10);
INSERT 0 10

demo:

t=# begin;
BEGIN
t=# insert into ut1 select 1;
INSERT 0 1
t=# insert into ut2 select 1;
INSERT 0 1
t=# insert into ut2 select generate_series(1,2);
INSERT 0 2
t=#  insert into ut1 select generate_series(1,2);
INSERT 0 2
t=# select greatest(max(ut1.cmin::text::int),max(ut2.cmin::text::int)) from ut2 join ut1 on ut1.xmin = ut2.xmin and (ut1.xmin)::text::bigint = txid_current();
 greatest
----------
        3
(1 row)

t=# end;
COMMIT
t=# begin;
BEGIN
t=# insert into ut1 select generate_series(1,2);
INSERT 0 2
t=# insert into ut2 select generate_series(1,2);
INSERT 0 2
t=# select greatest(max(ut1.cmin::text::int),max(ut2.cmin::text::int)) from ut2 join ut1 on ut1.xmin = ut2.xmin and (ut1.xmin)::text::bigint = txid_current();
 greatest
----------
        1
(1 row)

t=# end;
COMMIT


问:
Kernel / Linux location is memory, how to verify
I'm running linux on a Atlas-SoC Kit/DE0-Nano-SoC Kit.
Through u-boot I've placed the kernel at a different location.

```<code>mcboot=setenv bootargs console=ttyS0,115200 root=${mmcroot} rw rootwait;bootz ${loadaddr} - ${fdtaddr}
mmcload=mmc rescan;${mmcloadcmd} mmc 0:${mmcloadpart} ${loadaddr} ${bootimage};${mmcloadcmd} mmc 0:${mmcloadpart} ${fdtaddr} ${fdtimage}
mmcloadcmd=fatload
mmcloadpart=1
mmcroot=/dev/mmcblk0p2 mem=744M memmap=744M$256M
</code>```

the last line, request 744M starting at 256M offset.

No my question is, how can i verify that this actually happend? This since i'm reading mixed solutions online between using device-tree and memmap configurations. And i want to make sure, before i continue on writing the device driver section.

My /proc/iomem:

```<code>root@cyclone5:~# cat /proc/iomem
00000000-2e7fffff : System RAM
  00008000-0077656f : Kernel code
  007d6000-00859433 : Kernel data
ff702000-ff703fff : /soc/ethernet@ff702000
ff704000-ff704fff : /soc/dwmmc0@ff704000
ffb40000-ffb4fffe : /soc/usb@ffb40000
ffc00000-ffc00fff : c_can_platform
ffc02000-ffc0201f : serial
ffc04000-ffc04fff : /soc/i2c@ffc04000
ffc05000-ffc05fff : /soc/i2c@ffc05000
ffd02000-ffd02fff : /soc/wd@ffd02000
ffe01000-ffe01fff : /soc/amba/pdma@ffe01000
fff01000-fff01fff : fff01000.spi
ffff0000-ffffffff : /soc/sram@ffff0000
</code>```

any detailed explanations would be highly appreciated,

regards Auke

答:
Device tree and kernel parameter memmap both helps in reserving memory that will not be used by linux kernel. Take a look at linux device tree memory documentation and kernel parameters.

You can use Emulator or high end debugger for example Trace32 to see memory contents.

Body:
I'm running linux on a Atlas-SoC Kit/DE0-Nano-SoC Kit.
Through u-boot I've placed the kernel at a different location.

mcboot=setenv bootargs console=ttyS0,115200 root=${mmcroot} rw rootwait;bootz ${loadaddr} - ${fdtaddr}
mmcload=mmc rescan;${mmcloadcmd} mmc 0:${mmcloadpart} ${loadaddr} ${bootimage};${mmcloadcmd} mmc 0:${mmcloadpart} ${fdtaddr} ${fdtimage}
mmcloadcmd=fatload
mmcloadpart=1
mmcroot=/dev/mmcblk0p2 mem=744M memmap=744M$256M

the last line, request 744M starting at 256M offset.

No my question is, how can i verify that this actually happend? This since i'm reading mixed solutions online between using device-tree and memmap configurations. And i want to make sure, before i continue on writing the device driver section.

My /proc/iomem:

root@cyclone5:~# cat /proc/iomem
00000000-2e7fffff : System RAM
  00008000-0077656f : Kernel code
  007d6000-00859433 : Kernel data
ff702000-ff703fff : /soc/ethernet@ff702000
ff704000-ff704fff : /soc/dwmmc0@ff704000
ffb40000-ffb4fffe : /soc/usb@ffb40000
ffc00000-ffc00fff : c_can_platform
ffc02000-ffc0201f : serial
ffc04000-ffc04fff : /soc/i2c@ffc04000
ffc05000-ffc05fff : /soc/i2c@ffc05000
ffd02000-ffd02fff : /soc/wd@ffd02000
ffe01000-ffe01fff : /soc/amba/pdma@ffe01000
fff01000-fff01fff : fff01000.spi
ffff0000-ffffffff : /soc/sram@ffff0000

any detailed explanations would be highly appreciated,

regards Auke


问:
Onclick text appears next to the div instead of being under
I have a problem with my code I want the text that appears onclick to be under the main div but instead it appears next to it. Can someone have a clue of the mistake I made or the thing that I can add to my code to correct this ? I have also another question how can I add space between my div because I put a blue background but I didn't want to be like one block . Thank you

SOCIETES: 400

Part SBF 120 : 120

Part Filiales +100M€: 280

fermer

CONTACTS: 25 400

Part CAC 40 : 15 700

Part Filiales +100M€: 9 700

% contacts IT: 21%

fermer

EMAILS NOMINATIFS: 400

OPT OUT: 3%

LIGNES DIRECTES: 35%

```

答:
just add the hidden divs in side the opener div it will appear under it, to add space between divs you can use border property for opener div, try the following code:

SOCIETES: 400

Part SBF 120 : 120

Part Filiales +100M€: 280

fermer

CONTACTS: 25 400

Part CAC 40 : 15 700

Part Filiales +100M€: 9 700

% contacts IT: 21%

fermer

EMAILS NOMINATIFS: 400

OPT OUT: 3%

LIGNES DIRECTES: 35%

```

Body:
just add the hidden divs in side the opener div it will appear under it, to add space between divs you can use border property for opener div, try the following code:

<style type="text/css">
  .link{text-decoration:none; color:white;}

  .link:visited{color:white}

.row {
  display: flex; /* equal height of the children */
}

.col {
  flex: 1; /* additionally, equal width */

  padding: 1em;
  border: solid;
}

div {font-family:'Varela Round';
}

  .opener {
  background-color: #07183d;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  border: 1px white solid;
}

.benefits {
  background-color: #07183d;
  border: none;
  color: white;
  padding: 15px 32px;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  width:300px;
}
</style>
<style type="text/css">}
a {
  text-decoration: none;
}
a:visited {
  text-decoration: none;
  color: white;
}
#upbutton {
  border: 1px dotted white;
}
</style>
<script>function show(id) {
        if(document.getElementById('b'+id).style.display=='none') {
            document.getElementById('b'+id).style.display='block';
        }
        return false;
    }
    function hide(id) {
        if(document.getElementById('b'+id).style.display=='block') {
            document.getElementById('b'+id).style.display='none';
        }
        return false;
    }
</script>
<div class="row">
<div class="opener col"><a href="#1" name="1" onclick=" show('1');" class="link">SOCIETES: 400</a>

<div class="benefits" id="b1" style="display:none;">Part SBF 120 : 120<br />
Part Filiales +100M€: 280
<div id="upbutton"><a onclick=" hide('1');" >fermer</a></div>
</div>
</div>

<div class="opener col"><a href="#1" name="1" onclick=" show('2');" class="link" >CONTACTS: 25 400</a>

<div class="benefits col" id="b2" style="display:none;">Part CAC 40 : 15 700<br />
Part Filiales +100M€: 9 700<br />
% contacts IT: 21%
<div id="upbutton"><a onclick=" hide('2');">fermer</a></div>
</div>
</div>
<div class="opener col">EMAILS NOMINATIFS: 400</div>

<div class="opener col">OPT OUT: 3%</div>

  <div class="opener col">LIGNES DIRECTES: 35%</div></div>


问:
Mediaplayer how to avoid playing multiple audios in a RecyclerView
i have built a list of my music (RecyclerView) in each item there are two buttons first to play the music and pause the second to stop but when i click play for two audios the two launches while i want the first one to stop. here is my adapter
(the flag is to change th image view from play to pause when the audio is played)

```<code>public class ViewAudioListAdapter extends RecyclerView.Adapter<ViewAudioListAdapter.ViewHolder>{
private List<Audio> values;
private Context context;
private MediaPlayer mediaPlayer;
private boolean flage = true;

public class ViewHolder extends RecyclerView.ViewHolder {
    public TextView textViewName;
    public ImageView ivPlay,ivStop;
    public View layout;

    public ViewHolder(View view) {
        super(view);
        this.textViewName = (TextView) view.findViewById(R.id.textViewName);
        this.ivPlay = (ImageView) view.findViewById(R.id.ivPlay);
        this.ivStop = (ImageView) view.findViewById(R.id.ivStop);

        this.layout = view;
    }
}

public void add(int position, Audio audio){
    values.add(position, audio);
    notifyItemInserted(position);
}

public void remove(int position){
    values.remove(position);
    notifyItemRemoved(position);
}

public ViewAudioListAdapter(List<Audio> myDataset, Context context) {
    values = myDataset;
    this.context=context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View v = inflater.inflate(R.layout.view_audio_item, parent, false);
    v.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        }
    });
    // set the view's size, margins, paddings and layout parameters
    ViewHolder vh = new ViewHolder(v);
    return vh;    }

@Override
public void onBindViewHolder(final ViewAudioListAdapter.ViewHolder holder, int position) {
    final Audio audio = new Audio(values.get(position));
    final String name = audio.getName();

    holder.textViewName.setText(name);

    holder.ivPlay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (flage){
                mediaPlayer = MediaPlayer.create(context , Uri.parse(url));
                flage = false ;
            }
            if (mediaPlayer.isPlaying()){
                mediaPlayer.pause();
                holder.ivPlay.setImageResource(R.drawable.icons_play);
            }else{
                mediaPlayer.start();
                holder.ivPlay.setImageResource(R.drawable.icons_pause);
            }
        }
    });

    holder.ivStop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (!flage){
                mediaPlayer.stop();
                mediaPlayer.release();
                flage = true;
            }
            holder.ivPlay.setImageResource(R.drawable.icons_play);
        }
    });
}

@Override
public int getItemCount() {
    return values.size();
}}
</code>```

thank you

答:
try add  mediaPlayer.stop(); and mediaPlayer.reset(); before start mediaPlayer use below code in click event

```<code> holder.ivPlay.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (flage){
            mediaPlayer = MediaPlayer.create(context , Uri.parse(url));
            flage = false ;
        }
        if (mediaPlayer.isPlaying()){
            mediaPlayer.pause();
            holder.ivPlay.setImageResource(R.drawable.icons_play);
        }else{
             mediaPlayer.stop();//add here
            mediaPlayer.reset();//update here
            mediaPlayer = MediaPlayer.create(context , Uri.parse(url));// new update here
            mediaPlayer.start();
            holder.ivPlay.setImageResource(R.drawable.icons_pause);
        }
    }
});
</code>```

this may help..

OR

```<code>holder.ivPlay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (flage){
                mediaPlayer = MediaPlayer.create(context , Uri.parse(url));
                flage = false ;
            }
            if (mediaPlayer.isPlaying()){
                mediaPlayer.pause();
                holder.ivPlay.setImageResource(R.drawable.icons_play);
            }else{

                 try {

                    if (mediaPlayer.isPlaying()) {
                     mediaPlayer.stop();
                    mediaPlayer.release();
                      mediaPlayer = MediaPlayer.create(context , Uri.parse(url));
                               }

                 mediaPlayer.start();
                holder.ivPlay.setImageResource(R.drawable.icons_pause);
} catch (Exception e) {
}

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

Body:
i have built a list of my music (RecyclerView) in each item there are two buttons first to play the music and pause the second to stop but when i click play for two audios the two launches while i want the first one to stop. here is my adapter
(the flag is to change th image view from play to pause when the audio is played)

public class ViewAudioListAdapter extends RecyclerView.Adapter<ViewAudioListAdapter.ViewHolder>{
private List<Audio> values;
private Context context;
private MediaPlayer mediaPlayer;
private boolean flage = true;

public class ViewHolder extends RecyclerView.ViewHolder {
    public TextView textViewName;
    public ImageView ivPlay,ivStop;
    public View layout;

    public ViewHolder(View view) {
        super(view);
        this.textViewName = (TextView) view.findViewById(R.id.textViewName);
        this.ivPlay = (ImageView) view.findViewById(R.id.ivPlay);
        this.ivStop = (ImageView) view.findViewById(R.id.ivStop);

        this.layout = view;
    }
}

public void add(int position, Audio audio){
    values.add(position, audio);
    notifyItemInserted(position);
}

public void remove(int position){
    values.remove(position);
    notifyItemRemoved(position);
}

public ViewAudioListAdapter(List<Audio> myDataset, Context context) {
    values = myDataset;
    this.context=context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View v = inflater.inflate(R.layout.view_audio_item, parent, false);
    v.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        }
    });
    // set the view's size, margins, paddings and layout parameters
    ViewHolder vh = new ViewHolder(v);
    return vh;    }

@Override
public void onBindViewHolder(final ViewAudioListAdapter.ViewHolder holder, int position) {
    final Audio audio = new Audio(values.get(position));
    final String name = audio.getName();

    holder.textViewName.setText(name);

    holder.ivPlay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (flage){
                mediaPlayer = MediaPlayer.create(context , Uri.parse(url));
                flage = false ;
            }
            if (mediaPlayer.isPlaying()){
                mediaPlayer.pause();
                holder.ivPlay.setImageResource(R.drawable.icons_play);
            }else{
                mediaPlayer.start();
                holder.ivPlay.setImageResource(R.drawable.icons_pause);
            }
        }
    });

    holder.ivStop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (!flage){
                mediaPlayer.stop();
                mediaPlayer.release();
                flage = true;
            }
            holder.ivPlay.setImageResource(R.drawable.icons_play);
        }
    });
}

@Override
public int getItemCount() {
    return values.size();
}}

thank you

Body:
try add  mediaPlayer.stop(); and mediaPlayer.reset(); before start mediaPlayer use below code in click event

 holder.ivPlay.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (flage){
            mediaPlayer = MediaPlayer.create(context , Uri.parse(url));
            flage = false ;
        }
        if (mediaPlayer.isPlaying()){
            mediaPlayer.pause();
            holder.ivPlay.setImageResource(R.drawable.icons_play);
        }else{
             mediaPlayer.stop();//add here
            mediaPlayer.reset();//update here
            mediaPlayer = MediaPlayer.create(context , Uri.parse(url));// new update here
            mediaPlayer.start();
            holder.ivPlay.setImageResource(R.drawable.icons_pause);
        }
    }
});

this may help..

OR

holder.ivPlay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (flage){
                mediaPlayer = MediaPlayer.create(context , Uri.parse(url));
                flage = false ;
            }
            if (mediaPlayer.isPlaying()){
                mediaPlayer.pause();
                holder.ivPlay.setImageResource(R.drawable.icons_play);
            }else{

                 try {

                    if (mediaPlayer.isPlaying()) {
                     mediaPlayer.stop();
                    mediaPlayer.release();
                      mediaPlayer = MediaPlayer.create(context , Uri.parse(url));
                               }

                 mediaPlayer.start();
                holder.ivPlay.setImageResource(R.drawable.icons_pause);
} catch (Exception e) {
}

            }
        }
    });


问:
JQuery Checkbox Treeview
I am looking for a JQuery Checkbox Treeview. Does anyone know if a good one exists?</p>

答:
The best treeview I've found for jQuery so far is Dynatree. Very comprehensive, and with great documentation.

Dynatree is now hosted on Google Code

original answer link is here.

Title: JQuery Checkbox Treeview


问:
options_for_select with multiple values

What I'm trying to get is a dropdown with 2 fields (name and account_code) as a value

<option value="1">ACC: John Doe</option>

But current code

```<code><%= select_tag :user_id, options_for_select(@users.map{|u| [u.name, u.account_code] }) %>
</code>```

outputs the following:
<option value="1">John Doe</option>

How do I make it display both user's account_code and name? Thanks!

答:
Worked like this:

@users.map{|u| ["#{u.account_code}:  #{u.name}", u.account_code] }

Title: options_for_select with multiple values

Body:
What I'm trying to get is a dropdown with 2 fields (name and account_code) as a value

<option value="1">ACC: John Doe</option>

But current code

<%= select_tag :user_id, options_for_select(@users.map{|u| [u.name, u.account_code] }) %>

outputs the following:
<option value="1">John Doe</option>

How do I make it display both user's account_code and name? Thanks!


问:
how to open excel using javascript
I tried the below code to open excel file using javascript.
I tried in IE, Chrome, and Firefox but it's not opening the file.

```<code><html>
<body>
<form name="form1">
  <input type=button onClick="test()" value="Open File">
  <br><br>
</form>
<script type="text/javascript">
  function test() {
    var Excel = new ActiveXObject("Excel.Application");
    Excel.Visible = true;
    Excel.Workbooks.Open("teste.xlsx");
  }
</script>
</body>
</html>
</code>```

Thanks in Advance!

答:
Try using Absolute Path of the file you are trying to open

eg:

```<code>Excel.Workbooks.Open("E:\\test.xlsx");
</code>```

Title: how to open excel using javascript

Body:
I tried the below code to open excel file using javascript.
I tried in IE, Chrome, and Firefox but it's not opening the file.

<form name="form1">
  <input type=button onClick="test()" value="Open File">

</form>

Thanks in Advance!

Body:
Try using Absolute Path of the file you are trying to open

eg:

Excel.Workbooks.Open("E:\\test.xlsx");