问:
How to scan a formatted string using fscanf()?
I have this file with multiple lines. Each line follows a format of

```<code>`userID:$An Integer$$String:`
</code>```

For example:

```<code>pyc1:$1$$Tnq7a6/C1wwyKyt0V/.BP/:
pyc2:$6$$Tnq7a6/C1wwyKyt0V/.BP/:
</code>```

How should I use fscanf() to retrieve the userID, the integer, and the string between $$ and :`?

This is what I have now, but it is not working.

```<code>int main(){
    FILE * file = fopen("shadow.txt", "r");
    char line[256] = {0};
    char userID[30] = {0};
    int hashType;
    char hash[256] = {0};
    int result = fscanf(file, "%s :$ %d $$ %s :", userID, &hashType, hash);
    printf("%s\n", userID );
    printf("%d\n", hashType );
    printf("%s\n", hash );

}
</code>```

I don't know much about the format I should specify for fscanf() to achieve this. Please help.

答:
Try a regex, like this for example:

```<code>fscanf (file, "%[^:]:$%d$$%[^:]:", userID, &hashType, hash);
</code>```

I created a regex101 link that explains the regex expression used above.

PS: Don't forget to check for the return value of fscanf(), in order to ensure that everything was read parsed correctly. You want to parse three elements, thus the return value should be 3.

Body:
I have this file with multiple lines. Each line follows a format of

`userID:$An Integer$$String:`

For example:

pyc1:$1$$Tnq7a6/C1wwyKyt0V/.BP/:
pyc2:$6$$Tnq7a6/C1wwyKyt0V/.BP/:

How should I use fscanf() to retrieve the userID, the integer, and the string between $$ and :`?

This is what I have now, but it is not working.

int main(){
    FILE * file = fopen("shadow.txt", "r");
    char line[256] = {0};
    char userID[30] = {0};
    int hashType;
    char hash[256] = {0};
    int result = fscanf(file, "%s :$ %d $$ %s :", userID, &hashType, hash);
    printf("%s\n", userID );
    printf("%d\n", hashType );
    printf("%s\n", hash );

}

I don't know much about the format I should specify for fscanf() to achieve this. Please help.

Body:
Try a regex, like this for example:

fscanf (file, "%[^:]:$%d$$%[^:]:", userID, &hashType, hash);

I created a regex101 link that explains the regex expression used above.

PS: Don't forget to check for the return value of fscanf(), in order to ensure that everything was read parsed correctly. You want to parse three elements, thus the return value should be 3.


来源: stackexchange

问:
Port Scanner Shows All Ports Closed
I'm new to Python and am confused as to why the script I've written below
isn't working right, I'm at the stage now where I can't see the wood for the
trees.

I've tried to create the port scanner from the 'Violent Python' book. I believe
the book uses Python 2.6 but I'm creating it using Python 3.7.

Using hints and tips in other posts on this website I've got the port scanner to
do scans of some of the computers on my lab setup, however, the scans always
show ports to be 'closed'. I used nmap to scan the computers to make sure I had
some open ports to use in my port scanner script.

My script is below.

```<code>import optparse
from socket import *
from threading import *
screenLock = Semaphore(value=1)

def connScan(tgtHost, tgtPort):
    try:
        connSkt = socket(AF_INET, SOCK_STREAM)
        connSkt.connect((tgtHost, tgtPort))
        connSkt.send('ViolentPython\r\n')
        results = connSkt.recv(100)
        screenLock.acquire()
        print('[+]%d/tcp open'% tgtPort)
        print('[+]' + str(results))
    except:
        screenLock.acquire()
        print('[-]%d/tcp closed'% tgtPort)
    finally:
        screenLock.release()
        connSkt.close()

def portScan(tgtHost, tgtPorts):
    try:
        tgtIP = gethostbyname(tgtHost)
    except:
        print("[-] Cannot resolve '%s': Unknown host"%tgtHost)
        return
    try:
        tgtName = gethostbyaddr(tgtIP)
        print('\n[+] scan results for: ' + tgtName[0])
    except:
        print('\n[+] Scan results for: ' + tgtIP)
    setdefaulttimeout(1)
    for tgtPort in tgtPorts:
        t = Thread(target=connScan, args=(tgtHost, int(tgtPort)))
        t.start()

def main():
    parser = optparse.OptionParser('usage %prog '+ '-H <target host> -p <target port>')

    parser.add_option('-H', dest='tgtHost', type='string', help='specify target host')
    parser.add_option('-p', dest='tgtPort', type='string', help='specify target port[s] seperated by comma')

    (options, args) = parser.parse_args()

    tgtHost = options.tgtHost
    tgtPorts = [p.strip() for p in options.tgtPort.split(',')]

    if (tgtHost == None) | (tgtPorts[0] is None):
        print(parser.usage)
        exit(0)

    portScan(tgtHost, tgtPorts)

if __name__ == '__main__':
    main()
</code>```

I run the script from Powershell with:

python 01_portscan_revA.py -H 192.168.0.207 -p 22,80,135,443,445

Which produces the following output:

```<code>[+] Scan results for: 192.168.0.207
[-]22/tcp closed
[-]135/tcp closed
[-]445/tcp closed
[-]139/tcp closed
[-]80/tcp closed
[-]443/tcp closed
</code>```

I'm sure it's not a million miles away, I'd be very greatful for any help
anyone can offer to try and solve this problem.

Many Thanks

Thank you all for getting back to me. I've had another look at my script and
done some changes to it, I'm not sure if these are correct.

I changed def connScan as follows to capture errors.

```<code>def connScan(tgtHost, tgtPort):
try:
    connSkt = socket(AF_INET, SOCK_STREAM)
    connSkt.connect((tgtHost, tgtPort))
    connSkt.send (b'ViolentPython\r\n')
    results = connSkt.recv(100)
    screenLock.acquire()
    print('[+]%d/tcp open'% tgtPort)
    print('[+]' + str(results))
except Exception as e:
    screenLock.acquire()
    print('Error: {0}'.format(str(e)))
    print('[-]%d/tcp closed'% tgtPort)
finally:
    screenLock.release()
    connSkt.close()
</code>```

Initially I was getting a 'expecting bytes type object' error so i put a 'b' in
front of the 'Violentpython' to convert to bytes.

Now the output looks like this:

```<code>[+] scan results for: Cheryls
[+]139/tcp open
[+]b'\x83\x00\x00\x01\x8f'
Error: [WinError 10054] An existing connection was forcibly closed by the
remote host
[-]445/tcp closed
Error: timed out
[-]80/tcp closed
Error: timed out
[-]443/tcp closed
Error: timed out
[-]135/tcp closed
Error: timed out
[-]1030/tcp closed
</code>```

I get timed out errors as suggested by Vovanrock2002.

答:
Most likely, applications on listed ports close the connection as soon as they realize 'ViolentPython\r\n' is not a part of a protocol they support. On the other hand, results = connSkt.recv(100) accompanied by setdefaulttimeout(1) will make recv throw socket.timeout exception.

According to python docs connSkt.connect can throw timeout as well. So you basically need:

To stop catching things via bare except. If you don't know what exception to wait for, temporarily catch just Exception, examine caught objects and then replace it with more specific things.

To split connect and send + recv into different try blocks.

ContentLicense: CC BY-SA 3.0

Title: Port Scanner Shows All Ports Closed

Body:
I'm new to Python and am confused as to why the script I've written below
isn't working right, I'm at the stage now where I can't see the wood for the
trees.

I've tried to create the port scanner from the 'Violent Python' book. I believe
the book uses Python 2.6 but I'm creating it using Python 3.7.

Using hints and tips in other posts on this website I've got the port scanner to
do scans of some of the computers on my lab setup, however, the scans always
show ports to be 'closed'. I used nmap to scan the computers to make sure I had
some open ports to use in my port scanner script.

My script is below.

import optparse
from socket import *
from threading import *
screenLock = Semaphore(value=1)

def connScan(tgtHost, tgtPort):
    try:
        connSkt = socket(AF_INET, SOCK_STREAM)
        connSkt.connect((tgtHost, tgtPort))
        connSkt.send('ViolentPython\r\n')
        results = connSkt.recv(100)
        screenLock.acquire()
        print('[+]%d/tcp open'% tgtPort)
        print('[+]' + str(results))
    except:
        screenLock.acquire()
        print('[-]%d/tcp closed'% tgtPort)
    finally:
        screenLock.release()
        connSkt.close()

def portScan(tgtHost, tgtPorts):
    try:
        tgtIP = gethostbyname(tgtHost)
    except:
        print("[-] Cannot resolve '%s': Unknown host"%tgtHost)
        return
    try:
        tgtName = gethostbyaddr(tgtIP)
        print('\n[+] scan results for: ' + tgtName[0])
    except:
        print('\n[+] Scan results for: ' + tgtIP)
    setdefaulttimeout(1)
    for tgtPort in tgtPorts:
        t = Thread(target=connScan, args=(tgtHost, int(tgtPort)))
        t.start()

def main():
    parser = optparse.OptionParser('usage %prog '+ '-H <target host> -p <target port>')

    parser.add_option('-H', dest='tgtHost', type='string', help='specify target host')
    parser.add_option('-p', dest='tgtPort', type='string', help='specify target port[s] seperated by comma')

    (options, args) = parser.parse_args()

    tgtHost = options.tgtHost
    tgtPorts = [p.strip() for p in options.tgtPort.split(',')]

    if (tgtHost == None) | (tgtPorts[0] is None):
        print(parser.usage)
        exit(0)

    portScan(tgtHost, tgtPorts)

if __name__ == '__main__':
    main()

I run the script from Powershell with:

python 01_portscan_revA.py -H 192.168.0.207 -p 22,80,135,443,445

Which produces the following output:

[+] Scan results for: 192.168.0.207
[-]22/tcp closed
[-]135/tcp closed
[-]445/tcp closed
[-]139/tcp closed
[-]80/tcp closed
[-]443/tcp closed

I'm sure it's not a million miles away, I'd be very greatful for any help
anyone can offer to try and solve this problem.

Many Thanks

Thank you all for getting back to me. I've had another look at my script and
done some changes to it, I'm not sure if these are correct.

I changed def connScan as follows to capture errors.

def connScan(tgtHost, tgtPort):
try:
    connSkt = socket(AF_INET, SOCK_STREAM)
    connSkt.connect((tgtHost, tgtPort))
    connSkt.send (b'ViolentPython\r\n')
    results = connSkt.recv(100)
    screenLock.acquire()
    print('[+]%d/tcp open'% tgtPort)
    print('[+]' + str(results))
except Exception as e:
    screenLock.acquire()
    print('Error: {0}'.format(str(e)))
    print('[-]%d/tcp closed'% tgtPort)
finally:
    screenLock.release()
    connSkt.close()

Initially I was getting a 'expecting bytes type object' error so i put a 'b' in
front of the 'Violentpython' to convert to bytes.

Now the output looks like this:

[+] scan results for: Cheryls
[+]139/tcp open
[+]b'\x83\x00\x00\x01\x8f'
Error: [WinError 10054] An existing connection was forcibly closed by the
remote host
[-]445/tcp closed
Error: timed out
[-]80/tcp closed
Error: timed out
[-]443/tcp closed
Error: timed out
[-]135/tcp closed
Error: timed out
[-]1030/tcp closed

I get timed out errors as suggested by Vovanrock2002.


问:
How to make a type with date field deserializable from json
I need to define data type that would have date field and deserialize it from json. Here's my attempt.

```<code>data Some = Some { date :: Data.Time.Calendar.Day } deriving (Show, Generic)

instance FromJSON Day where
     parseJSON (Object x) = parseTimeM True defaultTimeLocale "%F" <$> x .: (pack "date")
</code>```

Here's errors.

```<code>• Couldn't match type ‘m0 t0’ with ‘Day’
  Expected type: aeson-1.2.3.0:Data.Aeson.Types.Internal.Parser Day
    Actual type: aeson-1.2.3.0:Data.Aeson.Types.Internal.Parser
                   (m0 t0)
• In the expression:
    parseTimeM True defaultTimeLocale "%F" <$> x .: (pack "date")
  In an equation for ‘parseJSON’:
      parseJSON (Object x)
        = parseTimeM True defaultTimeLocale "%F" <$> x .: (pack "date")
  In the instance declaration for ‘FromJSON Day’
</code>```

I find it very strange that I can't find any data type with exposed constructor for creating Date objects. And I can't find the function that would parse Date from String

答:
And for reference a fully working code example:</p>

```<code>{-# LANGUAGE OverloadedStrings #-}
module Datetimetest where

import Data.Time.Format
import Data.Time.Calendar
import Data.Aeson
import Data.Text
import Data.Maybe

newtype Some = Some { date :: Day } deriving Show

instance FromJSON Some where
  parseJSON (Object x) = (x .: pack "date") >>= \v -> Some <$> parseTimeM True defaultTimeLocale "%F" v

test :: Some
test = fromJust $ (decode "{\"date\":\"1999-12-01\"}" :: Maybe Some)
</code>```

Body:
I need to define data type that would have date field and deserialize it from json. Here's my attempt.

data Some = Some { date :: Data.Time.Calendar.Day } deriving (Show, Generic)

instance FromJSON Day where
     parseJSON (Object x) = parseTimeM True defaultTimeLocale "%F" <$> x .: (pack "date")

Here's errors.

• Couldn't match type ‘m0 t0’ with ‘Day’
  Expected type: aeson-1.2.3.0:Data.Aeson.Types.Internal.Parser Day
    Actual type: aeson-1.2.3.0:Data.Aeson.Types.Internal.Parser
                   (m0 t0)
• In the expression:
    parseTimeM True defaultTimeLocale "%F" <$> x .: (pack "date")
  In an equation for ‘parseJSON’:
      parseJSON (Object x)
        = parseTimeM True defaultTimeLocale "%F" <$> x .: (pack "date")
  In the instance declaration for ‘FromJSON Day’

I find it very strange that I can't find any data type with exposed constructor for creating Date objects. And I can't find the function that would parse Date from String

Body:
And for reference a fully working code example:

{-# LANGUAGE OverloadedStrings #-}
module Datetimetest where

import Data.Time.Format
import Data.Time.Calendar
import Data.Aeson
import Data.Text
import Data.Maybe

newtype Some = Some { date :: Day } deriving Show

instance FromJSON Some where
  parseJSON (Object x) = (x .: pack "date") >>= \v -> Some <$> parseTimeM True defaultTimeLocale "%F" v

test :: Some
test = fromJust $ (decode "{\"date\":\"1999-12-01\"}" :: Maybe Some)


问:
Searching for an item within a ListBox using a TextBox and a Button
I am creating a system that includes a ListBox of integers inserted by the user. I have contained a search button and a search TextBox for the user to input the integer they want to search for within the ListBox. Once the user has inputted the integer, I want a message box to be displayed either informing the user that there is e.g. 1 integer of value '3' in the list box, or an error message box informing the user that the integer does not exist within the list box.

```<code>private void buttonSearch_Click(object sender, EventArgs e)
{
    listBoxAddedIntegers.SelectedItems.Clear();
    for (int i = listBoxAddedIntegers.Items.Count - 1;i>=0; i--) ;
    {
        if (listBoxAddedIntegers.Items[i].ToString().ToLower().Contains(textBoxSearch.Text.ToLower())) ;
        {
            listBoxAddedIntegers.SetSelected(i, true);
        }
    }

    // ...
}
</code>```

I am not really sure on the code that I am meant to include here, and the code that I have already inserted suggests that 'i' does not exist in the current content.

Can anyone help please?

答:
```<code>private void buttonSearch_Click(object sender, EventArgs e)
    {
        listBoxAddedIntegers.SelectedItems.Clear();

        var itemsFound = listBoxAddedIntegers.Items.Where(i=>i.ToString().ToLower().Contains(textBoxSearch.Text.ToLower())).ToList();

        if(itemsFound == null)
        {
            MessageBox.Show("No matches found.");
        }
        else
        {
            MessageBox.Show("Found " + itemsFound.Count + " matches.");
        }

    }
</code>```

Body:
I am creating a system that includes a ListBox of integers inserted by the user. I have contained a search button and a search TextBox for the user to input the integer they want to search for within the ListBox. Once the user has inputted the integer, I want a message box to be displayed either informing the user that there is e.g. 1 integer of value '3' in the list box, or an error message box informing the user that the integer does not exist within the list box.

private void buttonSearch_Click(object sender, EventArgs e)
{
    listBoxAddedIntegers.SelectedItems.Clear();
    for (int i = listBoxAddedIntegers.Items.Count - 1;i>=0; i--) ;
    {
        if (listBoxAddedIntegers.Items[i].ToString().ToLower().Contains(textBoxSearch.Text.ToLower())) ;
        {
            listBoxAddedIntegers.SetSelected(i, true);
        }
    }

    // ...
}

I am not really sure on the code that I am meant to include here, and the code that I have already inserted suggests that 'i' does not exist in the current content.

Can anyone help please?


问:
How to solve: cucumber.runtime.CucumberException: Failed to instantiate class AppiumdemoDj.SignUpDj
I have checked answers to other similar questions in stack overflow but none of that helped. Could you please help me resolve the issue. I am trying to automate a mobile app. Learning the android app automation stuff. My code is below:

The project structure

Feature File:

```<code>Feature: Register for Yammer

Scenario: Sign Up for Yammer App

Given The App is launched
When I click on SignUp button
Then I should see FirstName Lastname EmailId Password field
When I click on SignUp button
Then I should see error
</code>```

StringsDj.java class

```<code>package AppiumdemoDj;

public class StringsDj {
    public static String signUpButton = "com.yammer.v1:id/signup_button";
    public static String firstName = "com.yammer.v1:id/first_name_edittext";
    public static String lastName = "com.yammer.v1:id/last_name_edittext";
    public static String emailId = "com.yammer.v1:id/work_email_edittext";
    public static String password = "com.yammer.v1:id/password_edittext";

}
</code>```

SignUpDj.java class

```<code>package AppiumdemoDj;

import java.io.File;
import java.net.URL;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import io.appium.java_client.AppiumDriver;

public class SignUpDj {

    private WebDriver driver;
    File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); //Taking screenshot

     @Given("^The App is launched$")
        public void the_App_is_launched() throws Throwable
        {
            DesiredCapabilities capabilities = new DesiredCapabilities();
            //capabilities.setCapability("webdriver.gecko.driver", "/Applications/Automation/dependencies/geckodriver");
            capabilities.setCapability(CapabilityType.BROWSER_NAME, "");
            capabilities.setCapability("deviceName", "Pixel");
            capabilities.setCapability("platformVersion", "8.0.0");
            capabilities.setCapability("platformName", "Android");
            capabilities.setCapability("appPackage", "com.yammer.v1");
            capabilities.setCapability("appActivity", "com.yammer.droid.ui.LauncherActivity");

            //AppiumDriver wd = new AppiumDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
            //wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);

            driver = new RemoteWebDriver(new URL("http://127.0.0.1:4723/wd/hub"),capabilities);
            driver.manage().timeouts().implicitlyWait(80, TimeUnit.SECONDS);
        }

     @When("^I click on SignUp button$")
        public void i_click_on_SignUp_Button() throws Throwable
        {

            driver.findElement(By.id(StringsDj.signUpButton)).click();
            FileUtils.copyFile(scrFile, new File("./ScreenShots/"));

         }

     @Then("^I should see FirstName Lastname EmailId Password field$")
        public void i_should_see_FirstName_Lastname_EmailId_Password_field() throws Throwable
        {

            driver.findElement(By.id(StringsDj.firstName)).sendKeys("Test");
            FileUtils.copyFile(scrFile, new File("./ScreenShots/"));

            driver.findElement(By.id(StringsDj.lastName)).sendKeys("Dj");
            FileUtils.copyFile(scrFile, new File("./ScreenShots/"));

            driver.findElement(By.id(StringsDj.emailId)).sendKeys("reachdipanjan@gmail.com");
            FileUtils.copyFile(scrFile, new File("./ScreenShots/"));

            driver.findElement(By.id(StringsDj.password)).sendKeys("TestDj");
            FileUtils.copyFile(scrFile, new File("./ScreenShots/"));

         }

     @Then("^I should see error$")
        public void i_should_see_error() throws Throwable
        {

         System.out.println("error displayed");

        }
}
</code>```

The error received:

```<code>cucumber.runtime.CucumberException: Failed to instantiate class AppiumdemoDj.SignUpDj
    at cucumber.runtime.java.DefaultJavaObjectFactory.cacheNewInstance(DefaultJavaObjectFactory.java:47)
    at cucumber.runtime.java.DefaultJavaObjectFactory.getInstance(DefaultJavaObjectFactory.java:33)
    at cucumber.runtime.java.JavaStepDefinition.execute(JavaStepDefinition.java:38)
    at cucumber.runtime.StepDefinitionMatch.runStep(StepDefinitionMatch.java:37)
    at cucumber.runtime.Runtime.runStep(Runtime.java:300)
    at cucumber.runtime.model.StepContainer.runStep(StepContainer.java:44)
    at cucumber.runtime.model.StepContainer.runSteps(StepContainer.java:39)
    at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:44)
    at cucumber.runtime.junit.ExecutionUnitRunner.run(ExecutionUnitRunner.java:102)
    at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:63)
    at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:18)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at cucumber.runtime.junit.FeatureRunner.run(FeatureRunner.java:70)
    at cucumber.api.junit.Cucumber.runChild(Cucumber.java:95)
    at cucumber.api.junit.Cucumber.runChild(Cucumber.java:38)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at cucumber.api.junit.Cucumber.run(Cucumber.java:100)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at cucumber.runtime.java.DefaultJavaObjectFactory.cacheNewInstance(DefaultJavaObjectFactory.java:41)
    ... 32 more
Caused by: java.lang.NullPointerException
    at AppiumdemoDj.SignUpDj.<init>(SignUpDj.java:25)
    ... 37 more
</code>```

答:
The driver object is null on the line 25 of the SignUpDj class because it has not been initialized:

```<code>File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); //Taking screenshot
</code>```

You need to invoke that code whenever you want to take a screenshot, not on the class initialization. I am not sure what you are trying to achieve with the code below:

```<code>FileUtils.copyFile(scrFile, new File("./ScreenShots/"));
</code>```

But this will not take a screenshot. You need to wrap up the call to take a screenshot in a method and call that method instead.

Body:
I have checked answers to other similar questions in stack overflow but none of that helped. Could you please help me resolve the issue. I am trying to automate a mobile app. Learning the android app automation stuff. My code is below:

The project structure

Feature File:

Feature: Register for Yammer

Scenario: Sign Up for Yammer App

Given The App is launched
When I click on SignUp button
Then I should see FirstName Lastname EmailId Password field
When I click on SignUp button
Then I should see error

StringsDj.java class

package AppiumdemoDj;

public class StringsDj {
    public static String signUpButton = "com.yammer.v1:id/signup_button";
    public static String firstName = "com.yammer.v1:id/first_name_edittext";
    public static String lastName = "com.yammer.v1:id/last_name_edittext";
    public static String emailId = "com.yammer.v1:id/work_email_edittext";
    public static String password = "com.yammer.v1:id/password_edittext";

}

SignUpDj.java class

package AppiumdemoDj;

import java.io.File;
import java.net.URL;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import io.appium.java_client.AppiumDriver;

public class SignUpDj {

    private WebDriver driver;
    File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); //Taking screenshot

     @Given("^The App is launched$")
        public void the_App_is_launched() throws Throwable
        {
            DesiredCapabilities capabilities = new DesiredCapabilities();
            //capabilities.setCapability("webdriver.gecko.driver", "/Applications/Automation/dependencies/geckodriver");
            capabilities.setCapability(CapabilityType.BROWSER_NAME, "");
            capabilities.setCapability("deviceName", "Pixel");
            capabilities.setCapability("platformVersion", "8.0.0");
            capabilities.setCapability("platformName", "Android");
            capabilities.setCapability("appPackage", "com.yammer.v1");
            capabilities.setCapability("appActivity", "com.yammer.droid.ui.LauncherActivity");

            //AppiumDriver wd = new AppiumDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
            //wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);

            driver = new RemoteWebDriver(new URL("http://127.0.0.1:4723/wd/hub"),capabilities);
            driver.manage().timeouts().implicitlyWait(80, TimeUnit.SECONDS);
        }

     @When("^I click on SignUp button$")
        public void i_click_on_SignUp_Button() throws Throwable
        {

            driver.findElement(By.id(StringsDj.signUpButton)).click();
            FileUtils.copyFile(scrFile, new File("./ScreenShots/"));

         }

     @Then("^I should see FirstName Lastname EmailId Password field$")
        public void i_should_see_FirstName_Lastname_EmailId_Password_field() throws Throwable
        {

            driver.findElement(By.id(StringsDj.firstName)).sendKeys("Test");
            FileUtils.copyFile(scrFile, new File("./ScreenShots/"));

            driver.findElement(By.id(StringsDj.lastName)).sendKeys("Dj");
            FileUtils.copyFile(scrFile, new File("./ScreenShots/"));

            driver.findElement(By.id(StringsDj.emailId)).sendKeys("reachdipanjan@gmail.com");
            FileUtils.copyFile(scrFile, new File("./ScreenShots/"));

            driver.findElement(By.id(StringsDj.password)).sendKeys("TestDj");
            FileUtils.copyFile(scrFile, new File("./ScreenShots/"));

         }

     @Then("^I should see error$")
        public void i_should_see_error() throws Throwable
        {

         System.out.println("error displayed");

        }
}

The error received:

cucumber.runtime.CucumberException: Failed to instantiate class AppiumdemoDj.SignUpDj
    at cucumber.runtime.java.DefaultJavaObjectFactory.cacheNewInstance(DefaultJavaObjectFactory.java:47)
    at cucumber.runtime.java.DefaultJavaObjectFactory.getInstance(DefaultJavaObjectFactory.java:33)
    at cucumber.runtime.java.JavaStepDefinition.execute(JavaStepDefinition.java:38)
    at cucumber.runtime.StepDefinitionMatch.runStep(StepDefinitionMatch.java:37)
    at cucumber.runtime.Runtime.runStep(Runtime.java:300)
    at cucumber.runtime.model.StepContainer.runStep(StepContainer.java:44)
    at cucumber.runtime.model.StepContainer.runSteps(StepContainer.java:39)
    at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:44)
    at cucumber.runtime.junit.ExecutionUnitRunner.run(ExecutionUnitRunner.java:102)
    at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:63)
    at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:18)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at cucumber.runtime.junit.FeatureRunner.run(FeatureRunner.java:70)
    at cucumber.api.junit.Cucumber.runChild(Cucumber.java:95)
    at cucumber.api.junit.Cucumber.runChild(Cucumber.java:38)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at cucumber.api.junit.Cucumber.run(Cucumber.java:100)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at cucumber.runtime.java.DefaultJavaObjectFactory.cacheNewInstance(DefaultJavaObjectFactory.java:41)
    ... 32 more
Caused by: java.lang.NullPointerException
    at AppiumdemoDj.SignUpDj.<init>(SignUpDj.java:25)
    ... 37 more

Body:
The driver object is null on the line 25 of the SignUpDj class because it has not been initialized:

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); //Taking screenshot

You need to invoke that code whenever you want to take a screenshot, not on the class initialization. I am not sure what you are trying to achieve with the code below:

FileUtils.copyFile(scrFile, new File("./ScreenShots/"));

But this will not take a screenshot. You need to wrap up the call to take a screenshot in a method and call that method instead.


问:
Java: Curious ImmutableList add
I don't understand this method implementation. It's

```<code>public static <T> List<T> add(List<T> list, T element) {
    final int size = list.size();
    if (size == 0) {
        return ImmutableList.of(element);
    } else if (list instanceof ImmutableList) {
        if (size == 1) {
            final T val = list.get(0);
            list = Lists.newArrayList();
            list.add(val);
        } else {
            list = Lists.newArrayList(list);
        }
    }
    list.add(element);
    return list;
}
</code>```

Why not a straightforward list.add(element)?

答:
Addition for ImmutableList

Why not a strightforward list.add(element)?

You can't call that method if the given list is immutable. Actually you can but usually such a method will then throw an UnsupportedOperationException. The documentation of Guavas ImmutableList#add says

Deprecated. Unsupported operation.

Guaranteed to throw an exception and leave the list unmodified.

However the goal of the method seems to be to also support addition for ImmutableList by creating a mutable clone. So a straightforward implementation would be:

```<code>public static <T> List<T> add(List<T> list, T element) {
    if (list instanceof ImmutableList) {
        // Create mutable clone, ArrayList is mutable
        list = Lists.newArrayList(list);
    }
    list.add(element);
    return list;
}
</code>```

Other stuff

Note that the type may change. While the input may be an ImmutableList, the output definitely is not.

You could keep the type by creating a temporary clone, adding to it (as shown) and then again wrap some ImmutableList around. However that doesn't seem to be a goal of this method.

Also note that the method in same cases may add something to the given list and in some create a new instance instead. So the caller of the method must be aware of the method sometimes changing his argument and sometimes not. For me this is a very odd behavior, it definitely must be highlighted in the documentation but I would not recommend doing stuff like that.

It seems that another goal of the method is to keep the list immutable if it was empty at method call. This is a bit strange but probably highlighted in its documentation. Therefore they add this call:

```<code>if (size == 0) {
    return ImmutableList.of(element);
}
</code>```

Besides that they do some minor stuff by calling

```<code>Lists.newArrayList();
</code>```

instead of

```<code>Lists.newArrayList(list);
</code>```

if the list is currently of size 1. However I'm not sure why they do this step. In my opinion they could just leave it the way it was.

So all in all I would probably implement such a method as

```<code>/**
 * Creates a new list with the contents of the given list
 * and the given element added to the end.
 *
 * <T> The type of the lists elements
 *
 * @params list The list to use elements of, the list will not be changed
 * @params element The element to add to the end of the resulting list
 *
 * @return A new list with the contents of the given list and
 *   the given element added to the end. If the given list was
 *   of type {@link ImmutableList} the resulting list will
 *   also be of type {@link ImmutableList}.
**/
public static <T> List<T> add(List<T> list, T element) {
    List<T> result;

    // Create a Stream of all elements for the result
    Stream<T> elements = Stream.concat(list.stream(), Stream.of(element));

    // If the list was immutable, make the result also immutable
    if (list instanceof ImmutableList) {
        result = ImmutableList.of(elements.toArray(T[]::new));
    } else {
        result = elements.collect(Collectors.toList());
    }

    return result;
}
</code>```

By that you won't ever change the argument list and you will also keep the list ImmutableList if it was. Using the Stream#concat method makes things a bit more efficient here (it is a lazy method), otherwise we would need to create temporary clones in between.

However we do not know which goals your method has, so probably in the context of your specific method what it does it makes more sense.

Title: Java: Curious ImmutableList add

Body:
I don't understand this method implementation. It's

public static <T> List<T> add(List<T> list, T element) {
    final int size = list.size();
    if (size == 0) {
        return ImmutableList.of(element);
    } else if (list instanceof ImmutableList) {
        if (size == 1) {
            final T val = list.get(0);
            list = Lists.newArrayList();
            list.add(val);
        } else {
            list = Lists.newArrayList(list);
        }
    }
    list.add(element);
    return list;
}

Why not a straightforward list.add(element)?

Body:
Addition for ImmutableList

Why not a strightforward list.add(element)?

You can't call that method if the given list is immutable. Actually you can but usually such a method will then throw an UnsupportedOperationException. The documentation of Guavas ImmutableList#add says

Deprecated. Unsupported operation.

Guaranteed to throw an exception and leave the list unmodified.

However the goal of the method seems to be to also support addition for ImmutableList by creating a mutable clone. So a straightforward implementation would be:

public static <T> List<T> add(List<T> list, T element) {
    if (list instanceof ImmutableList) {
        // Create mutable clone, ArrayList is mutable
        list = Lists.newArrayList(list);
    }
    list.add(element);
    return list;
}

Other stuff

Note that the type may change. While the input may be an ImmutableList, the output definitely is not.

You could keep the type by creating a temporary clone, adding to it (as shown) and then again wrap some ImmutableList around. However that doesn't seem to be a goal of this method.

Also note that the method in same cases may add something to the given list and in some create a new instance instead. So the caller of the method must be aware of the method sometimes changing his argument and sometimes not. For me this is a very odd behavior, it definitely must be highlighted in the documentation but I would not recommend doing stuff like that.

It seems that another goal of the method is to keep the list immutable if it was empty at method call. This is a bit strange but probably highlighted in its documentation. Therefore they add this call:

if (size == 0) {
    return ImmutableList.of(element);
}

Besides that they do some minor stuff by calling

Lists.newArrayList();

instead of

Lists.newArrayList(list);

if the list is currently of size 1. However I'm not sure why they do this step. In my opinion they could just leave it the way it was.

So all in all I would probably implement such a method as

/**
 * Creates a new list with the contents of the given list
 * and the given element added to the end.
 *
 * <T> The type of the lists elements
 *
 * @params list The list to use elements of, the list will not be changed
 * @params element The element to add to the end of the resulting list
 *
 * @return A new list with the contents of the given list and
 *   the given element added to the end. If the given list was
 *   of type {@link ImmutableList} the resulting list will
 *   also be of type {@link ImmutableList}.
**/
public static <T> List<T> add(List<T> list, T element) {
    List<T> result;

    // Create a Stream of all elements for the result
    Stream<T> elements = Stream.concat(list.stream(), Stream.of(element));

    // If the list was immutable, make the result also immutable
    if (list instanceof ImmutableList) {
        result = ImmutableList.of(elements.toArray(T[]::new));
    } else {
        result = elements.collect(Collectors.toList());
    }

    return result;
}

By that you won't ever change the argument list and you will also keep the list ImmutableList if it was. Using the Stream#concat method makes things a bit more efficient here (it is a lazy method), otherwise we would need to create temporary clones in between.

However we do not know which goals your method has, so probably in the context of your specific method what it does it makes more sense.


问:
Excel VBA - Copy table data from website and put into excel?
I am trying to copy a table from a website and put this into excel.
My table can be identified by the elementID "VisibleReportContentctl32".

For some reason, my code produces this error:
'object required'

on this line: Range("A1").Text = dat

Here's my full code:

```<code>Option Explicit
Public Sub GetSSRSData()

    Dim IE            As Object: Set IE = New InternetExplorerMedium
    Dim TR_Elements   As Object
    Dim TR            As Object ' Table Row
    Dim TD_Elements   As Object
    Dim TD            As Object ' Table Data
    Dim RowNumb       As Integer
    Dim Columns       As Integer
    Dim ColumnNumb    As Integer
    Dim x As Integer
    Dim dat As String

    With IE
        .Visible = True
        .Navigate ("http://gbrlon02-sql-17/Reports/Pages/Report.aspx?ItemPath=%2fCutlass+Reports%2fManagement+Reporting%2fForwardOrdersSticksOnly+-+ForecastVariance+(Monthly+Report)")

         Do While IE.Busy Or IE.ReadyState <> 4
             DoEvents
         Loop

         If IsObject(.Document.getElementById("VisibleReportContentctl32_ctl09")) Then
            dat = IE.Document.getElementById("VisibleReportContentctl32_ctl09").innerHTML
            Range("A1").Text = dat
         Else
            MsgBox "doesn't"
         End If
   End With
End Sub
</code>```

please can someone show me where I am going wrong?

答: Use [Power Query][Table from web] is simple and stable</p>

Body:
I am trying to copy a table from a website and put this into excel.
My table can be identified by the elementID "VisibleReportContentctl32".

For some reason, my code produces this error:
'object required'

on this line: Range("A1").Text = dat

Here's my full code:

Option Explicit
Public Sub GetSSRSData()

    Dim IE            As Object: Set IE = New InternetExplorerMedium
    Dim TR_Elements   As Object
    Dim TR            As Object ' Table Row
    Dim TD_Elements   As Object
    Dim TD            As Object ' Table Data
    Dim RowNumb       As Integer
    Dim Columns       As Integer
    Dim ColumnNumb    As Integer
    Dim x As Integer
    Dim dat As String

    With IE
        .Visible = True
        .Navigate ("http://gbrlon02-sql-17/Reports/Pages/Report.aspx?ItemPath=%2fCutlass+Reports%2fManagement+Reporting%2fForwardOrdersSticksOnly+-+ForecastVariance+(Monthly+Report)")

         Do While IE.Busy Or IE.ReadyState <> 4
             DoEvents
         Loop

         If IsObject(.Document.getElementById("VisibleReportContentctl32_ctl09")) Then
            dat = IE.Document.getElementById("VisibleReportContentctl32_ctl09").innerHTML
            Range("A1").Text = dat
         Else
            MsgBox "doesn't"
         End If
   End With
End Sub

please can someone show me where I am going wrong?


问:
How to use the initializer with an rvalue reference param // Why not possible to initialize a C-style array with another C-style array variable
Preamble

Before reading this, please be aware I am a C++ beginner. I have not learnt all the (basic) concepts yet (like templates for example), but I am attempting the understand some fundamentals fully before moving on to something else.

So please do not mention std::string or std:array, vectors, boost::arrays, and their superiority to C-style arrays. I am sure their are, but that is not the point here :)

I also now that it is sometimes preferred to assign elements in the ctor body than using its member initializer list.

My Question

Considering the following example.
When I reached the moment I had to define a copy constructor to initialize my character2 declared in main(), I noticed, in Visual Studio 2017, that IntelliSense displays 3 different overloads to initialize the class members from the initializer list. For example, with the 'name' variable, the available listed overloads are:

char [50](const char [50] &)

char [50](char [50] &&)

char [50]()

Subsidiary question 1: Why IntelliSense allows to display these overloads only when the variable is declared as class member ? (nothing is shown with CTRL+SHIFT+SPACE if declared in main())

The one that intrigues me most is the one with an rvalue reference in it :

char [50](char [50] &&) for the 'name' variable

int [10](int [10] &&) for the 'data' variable

int(int &&) for the 'singledata' variable

Now, if I use name() in an initializer list, overload #3 appears to be used. If I use name("aaa"), overload #1 appears to be used. This got me to investigate on other concepts: I now understand the concepts of lvalue, rvalue, and lvalue references (but not this, too much complicated for me right now), and I fail to completely understand the concept of rvalue reference and move semantics.

Considering my partial understanding, I tried to declare an rvalue reference in my "parameterized constructor 2" (which then becomes an lvalue of type "rvalue reference to int") and to initialize the 'singledata' variable with it, hoping to see the initializer overload #3 poping up in IntelliSense, but it does not. The one with the lvalue reference parameter (overload #2) appears to be used again in this case. That I can't explain.

So here I am, stuck, and this is my MAIN QUESTION 1: When does the initializer with an rvalue reference parameter happen to be used for a class member?

MAIN QUESTION 2: Why is it not possible to initialize a char array using another char array while it is possible using string literal expressions?
 because there are pure rvalues (prvalues) while a variable could only be converted to an xvalue expression at best?

I know this is absolutely not standard, but if I look at the dissassembly, the initialization of an array of chars is quite simple:

```<code>     2:     const char arrchar1[10]("hello");
01142771 A1 38 9B 14 01       mov         eax,dword ptr [string "hello" (01149B38h)]
01142776 89 45 D8             mov         dword ptr [arrchar1],eax
01142779 66 8B 0D 3C 9B 14 01 mov         cx,word ptr ds:[1149B3Ch]
01142780 66 89 4D DC          mov         word ptr [ebp-24h],cx
01142784 33 C0                xor         eax,eax
01142786 89 45 DE             mov         dword ptr [ebp-22h],eax
</code>```

the stack-allocated space [arrchar1] (being [ebp-28h] in my case) in the current stack frame is simply filled by a MOV instruction set (2, really, in this case: 1 dword is moved for "hell", then 1 word is moved for the rest) with the contents of the static space containing the "hello" string literal.

Why is there no C++ way resulting in something similar once compiled, which would perform the same thing but 'moving' the contents of a stack-allocated space (another array variable), rather than 'moving' some static memory? I would expect something like this: char arrchar2[10](arrchar1)

Example:

```<code>#include <string.h> // for strcpy

class Character
{
public:
    //default constructor
    Character() {};

    //parameterized constructor 1
    Character(const char * pname) : // pointer to the string literal must be const (otherwise it is Undefined Behaviour)
        name(), data{ 1, 2, 3 } // mem-initializer-list:
                                // - name is initialized with value-initialization (empty expression-list in a pair of parentheses following identifier)
                                // - (C++11) data is initialized using list-initialization which becomes aggregate-initialization since it is an aggregate (array)
    {
        strcpy_s(name, pname);
    };

    //parameterized constructor 2
    Character(const char * pname, int &&val1) :
        name(), data{ 1, 2, 3 }, singledata(val1)
    {
        strcpy_s(name, pname);
    };

    //copy constructor
    Character(const Character & tocopy)
        // member initializer list

        //:name(),  // >> IntelliSense shows 3 initializer overloads: char [50](const char [50] &) || char [50](char [50] &&) || char [50]()
                    // >> (visible only if the array is declared in a class, no pop up in main...)

        : name("aaa"),

        //data()    // >> IntelliSense shows 3 initializer overloads: int [10](const int [10] &) || int [10](int [10] &&) || int [10]()
                    // >> (visible only if the array is declared in a class, no pop up in main...)

        data{ 1, 2, 3 }
    {
        // ctor body definition
    };
private:
    char name[50];
    int data[10];
    int singledata;
};

void main()
{

    Character character1("characterOne"); // the string literal has static storage duration (static memory), passed pointer allocated on stack memory
    Character character2(character1);
    Character character3("characterThree", 3);
}
</code>```

答:
Question number 1:

I believe you're asking why your singledata initialization is not invoking its r-value initialiser. Short answer: because you're not passing it an r-value.

In your constructor above, the parameter val1 has an r-value reference type. However, remember that the 'r-valueness' property is something that applies to expressions not types. In the initialization singledata(val1), the sub-expression val1 is an l-value, even though the variable val1 has an r-value reference type. It is an l-value as defined by the rules that make something an l-value. The rules, by the way, are literally just a list of conditions that if met make an expression an l-value. Roughly speaking though, you can explain that val1 is an l-value here because its an object whose address can be taken.

Is you wanted the r-value reference version of the initializer for singledata, you would use singledata(std::move(val1)) instead. Here the expression std::move(val1) has an r-value type, by the definition of what std::move does. An r-value reference inside the singledata constructor can thus bind to it.

Body:
Preamble

Before reading this, please be aware I am a C++ beginner. I have not learnt all the (basic) concepts yet (like templates for example), but I am attempting the understand some fundamentals fully before moving on to something else.

So please do not mention std::string or std:array, vectors, boost::arrays, and their superiority to C-style arrays. I am sure their are, but that is not the point here :)

I also now that it is sometimes preferred to assign elements in the ctor body than using its member initializer list.

My Question

Considering the following example.
When I reached the moment I had to define a copy constructor to initialize my character2 declared in main(), I noticed, in Visual Studio 2017, that IntelliSense displays 3 different overloads to initialize the class members from the initializer list. For example, with the 'name' variable, the available listed overloads are:

char [50](const char [50] &)

char [50](char [50] &&)

char [50]()

Subsidiary question 1: Why IntelliSense allows to display these overloads only when the variable is declared as class member ? (nothing is shown with CTRL+SHIFT+SPACE if declared in main())

The one that intrigues me most is the one with an rvalue reference in it :

char [50](char [50] &&) for the 'name' variable

int [10](int [10] &&) for the 'data' variable

int(int &&) for the 'singledata' variable

Now, if I use name() in an initializer list, overload #3 appears to be used. If I use name("aaa"), overload #1 appears to be used. This got me to investigate on other concepts: I now understand the concepts of lvalue, rvalue, and lvalue references (but not this, too much complicated for me right now), and I fail to completely understand the concept of rvalue reference and move semantics.

Considering my partial understanding, I tried to declare an rvalue reference in my "parameterized constructor 2" (which then becomes an lvalue of type "rvalue reference to int") and to initialize the 'singledata' variable with it, hoping to see the initializer overload #3 poping up in IntelliSense, but it does not. The one with the lvalue reference parameter (overload #2) appears to be used again in this case. That I can't explain.

So here I am, stuck, and this is my MAIN QUESTION 1: When does the initializer with an rvalue reference parameter happen to be used for a class member?

MAIN QUESTION 2: Why is it not possible to initialize a char array using another char array while it is possible using string literal expressions?
 because there are pure rvalues (prvalues) while a variable could only be converted to an xvalue expression at best?

I know this is absolutely not standard, but if I look at the dissassembly, the initialization of an array of chars is quite simple:

     2:     const char arrchar1[10]("hello");
01142771 A1 38 9B 14 01       mov         eax,dword ptr [string "hello" (01149B38h)]
01142776 89 45 D8             mov         dword ptr [arrchar1],eax
01142779 66 8B 0D 3C 9B 14 01 mov         cx,word ptr ds:[1149B3Ch]
01142780 66 89 4D DC          mov         word ptr [ebp-24h],cx
01142784 33 C0                xor         eax,eax
01142786 89 45 DE             mov         dword ptr [ebp-22h],eax

the stack-allocated space [arrchar1] (being [ebp-28h] in my case) in the current stack frame is simply filled by a MOV instruction set (2, really, in this case: 1 dword is moved for "hell", then 1 word is moved for the rest) with the contents of the static space containing the "hello" string literal.

Why is there no C++ way resulting in something similar once compiled, which would perform the same thing but 'moving' the contents of a stack-allocated space (another array variable), rather than 'moving' some static memory? I would expect something like this: char arrchar2[10](arrchar1)

Example:

#include <string.h> // for strcpy

class Character
{
public:
    //default constructor
    Character() {};

    //parameterized constructor 1
    Character(const char * pname) : // pointer to the string literal must be const (otherwise it is Undefined Behaviour)
        name(), data{ 1, 2, 3 } // mem-initializer-list:
                                // - name is initialized with value-initialization (empty expression-list in a pair of parentheses following identifier)
                                // - (C++11) data is initialized using list-initialization which becomes aggregate-initialization since it is an aggregate (array)
    {
        strcpy_s(name, pname);
    };

    //parameterized constructor 2
    Character(const char * pname, int &&val1) :
        name(), data{ 1, 2, 3 }, singledata(val1)
    {
        strcpy_s(name, pname);
    };

    //copy constructor
    Character(const Character & tocopy)
        // member initializer list

        //:name(),  // >> IntelliSense shows 3 initializer overloads: char [50](const char [50] &) || char [50](char [50] &&) || char [50]()
                    // >> (visible only if the array is declared in a class, no pop up in main...)

        : name("aaa"),

        //data()    // >> IntelliSense shows 3 initializer overloads: int [10](const int [10] &) || int [10](int [10] &&) || int [10]()
                    // >> (visible only if the array is declared in a class, no pop up in main...)

        data{ 1, 2, 3 }
    {
        // ctor body definition
    };
private:
    char name[50];
    int data[10];
    int singledata;
};

void main()
{

    Character character1("characterOne"); // the string literal has static storage duration (static memory), passed pointer allocated on stack memory
    Character character2(character1);
    Character character3("characterThree", 3);
}


问:
Networkx Statistical Inference
I have a directed weighted graph which I created successfully using networkx.

I'm trying to generate some statistical inferences on this network, but I'm having trouble. Here they are:

(i) The Average degree of the network. (The only one I could find was average_degree_connectivity, which returns a dictionary and not a single float with the average degree of the whole network)

(ii) The Average weighted degree of the network. (same as above)

(iii) The Average clustering coefficient of the network. (I know that I have to use nx.average_clustering(g), however how do I take the fact that it is weighted directed graph into consideration? I keep getting the error:
NetworkXError: ('Clustering algorithms are not defined ', 'for directed graphs.') )

Thank you!

答:
Regarding point (i): Average degree of a network, for directed graphs,
Networkx internally computes it as follows:

```<code>nnodes = G.number_of_nodes()
deg = sum(d for n, d in G.in_degree()) / float(nnodes)
info += "Average in degree: %8.4f\n" % deg
deg = sum(d for n, d in G.out_degree()) / float(nnodes)
info += "Average out degree: %8.4f" % deg
</code>```

You can check it on github.

Title: Networkx Statistical Inference

Body:
Regarding point (i): Average degree of a network, for directed graphs,
Networkx internally computes it as follows:

nnodes = G.number_of_nodes()
deg = sum(d for n, d in G.in_degree()) / float(nnodes)
info += "Average in degree: %8.4f\n" % deg
deg = sum(d for n, d in G.out_degree()) / float(nnodes)
info += "Average out degree: %8.4f" % deg

You can check it on github.


问:
Only one .idx and .pack files using git gc
Jenkins jobs are running every 5 min. and each forced push creates .idx and .pack files
as you can see at the below;

```<code>pack-8eca24ab5048f727d323cd7f9fc8ed323f384c40.idx
pack-8eca24ab5048f727d323cd7f9fc8ed323f384c40.pack
.
.
.
</code>```

In consequence these files are huge and I used the command;

```<code>git gc --aggressive
</code>```

This is worked for me but its manual. The point is; I want to automatically do that.

```<code>git gc --aggressive --auto
</code>```

This command doesn't work, I just need one .idx and .pack files in my all .git project.

Any suggestion ?

答:
While it's clear that you think you have a good use case for this, I very much doubt it.  That said, unlike others who've tried to point this out in comments, I don't need to agree with you to answer a simple technical question.

I'm not sure what you expected --auto to do.  This is a flag used when gc is run automatically; it is used by gc to know the difference between when you tell gc to run, vs. when other git commands tell gc to run.

If you want to persistently change how the automatic gc runs work, then you need to alter the configuration.

You may find the gc.autoPackLimit value to be particularly useful here.  By default it lets the pack count reach 50, but if you literally will only tolerate one then you could say

```<code>git config gc.autoPackLimit 1
</code>```

Body:
Jenkins jobs are running every 5 min. and each forced push creates .idx and .pack files
as you can see at the below;

pack-8eca24ab5048f727d323cd7f9fc8ed323f384c40.idx
pack-8eca24ab5048f727d323cd7f9fc8ed323f384c40.pack
.
.
.

In consequence these files are huge and I used the command;

git gc --aggressive

This is worked for me but its manual. The point is; I want to automatically do that.

git gc --aggressive --auto

This command doesn't work, I just need one .idx and .pack files in my all .git project.

Any suggestion ?

Body:
While it's clear that you think you have a good use case for this, I very much doubt it.  That said, unlike others who've tried to point this out in comments, I don't need to agree with you to answer a simple technical question.

I'm not sure what you expected --auto to do.  This is a flag used when gc is run automatically; it is used by gc to know the difference between when you tell gc to run, vs. when other git commands tell gc to run.

If you want to persistently change how the automatic gc runs work, then you need to alter the configuration.

You may find the gc.autoPackLimit value to be particularly useful here.  By default it lets the pack count reach 50, but if you literally will only tolerate one then you could say

git config gc.autoPackLimit 1


问:
How to implement a REST API Server?
I am a university student with an intermediate level of C++ programming experience. I would like to implement a simple REST based API for my application as quickly as possible.

I have looked at Casablanca and libWebSockets but the examples posted on their respective sites are a bit over my head. Is there any library that has more beginner oriented tutorials on creating a RESTFUL API Server in C++ ?

Note: I am aware that this question has been asked a few times in C# but the answers are over a year or two old and mostly not aimed at beginners. I hope that a new post will yield some fresh answers!

答: http://pistache.io/ looks a good and modern to me. The hello world is just 9 lines long.</p>

Title: How to implement a REST API Server?


问:
Multithreading in c++
I want to run one function with different parameters on different threads:

```<code>int threads = 3;
int par1[] = {1, 2, 3};
int par2[] = {4, 5, 6};
for (int i=0; i<threads; i++){
  //new_thread function(par1[i], par2[i]);
}
</code>```

I know nothing about threads. I tried to do something the windows API (can't use other libraries), but it doesn't work. How should I implement this? And it is possible to start an unknown number of threads of the time of programming (dynamically creating threads)?

答:
May i suggest the use of boost::thread_group ?</p>

```<code>boost::thread_group g;
int threads = 3;
int par1[] = {1, 2, 3};
int par2[] = {4, 5, 6};
for (int i=0; i<threads; i++){
  g.create_thread(/*function*/);
  //new_thread function(par1[i], par2[i]);
}
g.join_all();
</code>```

Title: Multithreading in c++

Body:
I want to run one function with different parameters on different threads:

int threads = 3;
int par1[] = {1, 2, 3};
int par2[] = {4, 5, 6};
for (int i=0; i<threads; i++){
  //new_thread function(par1[i], par2[i]);
}

I know nothing about threads. I tried to do something the windows API (can't use other libraries), but it doesn't work. How should I implement this? And it is possible to start an unknown number of threads of the time of programming (dynamically creating threads)?

Body:
May i suggest the use of boost::thread_group ?

boost::thread_group g;
int threads = 3;
int par1[] = {1, 2, 3};
int par2[] = {4, 5, 6};
for (int i=0; i<threads; i++){
  g.create_thread(/*function*/);
  //new_thread function(par1[i], par2[i]);
}
g.join_all();

ContentLicense: CC BY-SA 2.5


问:
Unload and load in actionscript 3
There is a button in a sprite. I want to click that button and load menu.swf and unload the current swf. But only that sprite is removed, not the entire swf. What can I do?</p>

```<code>go.addEventListener(MouseEvent.CLICK, fl_ClickToLoadUnloadSWF);

import fl.display.ProLoader;
var fl_ProLoader: ProLoader;

//This variable keeps track of whether you want to load or unload the SWF
var fl_ToLoad: Boolean = true;

function fl_ClickToLoadUnloadSWF(event: MouseEvent): void {
    if (fl_ToLoad) {

        var x: Number = this.numChildren;
        while (x--) {
            this.removeChildAt(x);
        }

        fl_ProLoader = new ProLoader();
        fl_ProLoader.load(new URLRequest("menu.swf"));
        addChild(fl_ProLoader);
        fl_ProLoader.graphics.clear();
        fl_ProLoader.x = -245;
        fl_ProLoader.y = -140;
        fl_ProLoader.width = 600;
        fl_ProLoader.height = 850;
        fl_ProLoader.scaleX = 1
        fl_ProLoader.scaleY = 1
    } else {
        fl_ProLoader.unload();
        removeChild(fl_ProLoader);
        fl_ProLoader = null;

        for (var i: int = fl_ProLoader.numChildren - 1; i >= 0; i--) {
            fl_ProLoader.removeChildAt(i);

        }

    }
    // Toggle whether you want to load or unload the SWF
    fl_ToLoad = !fl_ToLoad;
}
</code>```

答:
```<code>var rootContainer:DisplayObjectContainer = DisplayObjectContainer (root);
</code>```

This gives you a reference to root cast to DisplayObjectContainer. You can now replace this with rootContainer

Title: Unload and load in actionscript 3

Body:
There is a button in a sprite. I want to click that button and load menu.swf and unload the current swf. But only that sprite is removed, not the entire swf. What can I do?

go.addEventListener(MouseEvent.CLICK, fl_ClickToLoadUnloadSWF);

import fl.display.ProLoader;
var fl_ProLoader: ProLoader;

//This variable keeps track of whether you want to load or unload the SWF
var fl_ToLoad: Boolean = true;

function fl_ClickToLoadUnloadSWF(event: MouseEvent): void {
    if (fl_ToLoad) {

        var x: Number = this.numChildren;
        while (x--) {
            this.removeChildAt(x);
        }

        fl_ProLoader = new ProLoader();
        fl_ProLoader.load(new URLRequest("menu.swf"));
        addChild(fl_ProLoader);
        fl_ProLoader.graphics.clear();
        fl_ProLoader.x = -245;
        fl_ProLoader.y = -140;
        fl_ProLoader.width = 600;
        fl_ProLoader.height = 850;
        fl_ProLoader.scaleX = 1
        fl_ProLoader.scaleY = 1
    } else {
        fl_ProLoader.unload();
        removeChild(fl_ProLoader);
        fl_ProLoader = null;

        for (var i: int = fl_ProLoader.numChildren - 1; i >= 0; i--) {
            fl_ProLoader.removeChildAt(i);

        }

    }
    // Toggle whether you want to load or unload the SWF
    fl_ToLoad = !fl_ToLoad;
}

Body:
var rootContainer:DisplayObjectContainer = DisplayObjectContainer (root);

This gives you a reference to root cast to DisplayObjectContainer. You can now replace this with rootContainer


问:
How to know browser idle time?
How can I track the browser idle time? I am using IE8.

I am not using any session management and don't want to handle it on server side.

答:
I needed a similar thing and created this :https://github.com/harunurhan/idlejs

It simple, configurable and powerful in a way, without any dependencies. Here's an example.

```<code>import { Idle } from 'idlejs/dist';

// with predefined events on `document`
const idle = new Idle()
  .whenNotInteractive()
  .within(60)
  .do(() => console.log('IDLE'))
  .start();
</code>```

You can also use custom event targets and events

```<code>const idle = new Idle()
  .whenNot([{
    events: ['click', 'hover'],
    target: buttonEl,
  },
  {
    events: ['click', 'input'],
    target: inputEl,
  },
  ])
  .within(10)
  .do(() => called = true)
  .start();
</code>```

(Written in typescript and compiled to es5)

Title: How to know browser idle time?

Body:
I needed a similar thing and created this :https://github.com/harunurhan/idlejs

It simple, configurable and powerful in a way, without any dependencies. Here's an example.

import { Idle } from 'idlejs/dist';

// with predefined events on `document`
const idle = new Idle()
  .whenNotInteractive()
  .within(60)
  .do(() => console.log('IDLE'))
  .start();

You can also use custom event targets and events

const idle = new Idle()
  .whenNot([{
    events: ['click', 'hover'],
    target: buttonEl,
  },
  {
    events: ['click', 'input'],
    target: inputEl,
  },
  ])
  .within(10)
  .do(() => called = true)
  .start();

(Written in typescript and compiled to es5)


问:
How to use fancybox to show specific class of webpage?
https://jsfiddle.net/054j0fj7/

As you can see when you click on show catlinks you get the wikipedia page, How ever I would like to show the catlinks at the end of page.This area is defined in HTML as following:

```<code><div id="catlinks" class="catlinks" data-mw="interface">
</code>```

and this is the fancybox

```<code><div> <a href="https://de.wikipedia.org/wiki/British_Broadcasting_Corporation" class="fancybox"  data-fancybox-type="iframe"> Show Catlink</a>  </div>
</code>```

答:
Just change target URL to correct one with anchor #catlinks.

```<code><div>
    <a href="https://de.wikipedia.org/wiki/British_Broadcasting_Corporation#catlinks" class="fancybox"  data-fancybox-type="iframe"> Show Catlink</a>
</div>
</code>```

Body:
https://jsfiddle.net/054j0fj7/

As you can see when you click on show catlinks you get the wikipedia page, How ever I would like to show the catlinks at the end of page.This area is defined in HTML as following:

and this is the fancybox

  Show Catlink

Body:
Just change target URL to correct one with anchor #catlinks.

<div>
    <a href="https://de.wikipedia.org/wiki/British_Broadcasting_Corporation#catlinks" class="fancybox"  data-fancybox-type="iframe"> Show Catlink</a>
</div>


问:
Switching between browsers in protractor
I m doing automation Testing of an angular 4 chat application using protractor in that i m doing login of two diffrent users in chrome and firefox browser respectively. Now after login they there is a button of chat. On click on chat button one new window of each browser will open. Now for chat i have to do continuous switching between these 2 window. How can i do that? I provided chrome as a browser in protractor configuration file and to open firefox browser i am using following snippet.

let driver_fx;
driver_fx = new webdriver.Builder().forBrowser('firefox').build();

答:
I would suggest using 2 configuration files and run them one after another.
For example I run conf1.js (run on chrome) to run test1.js and then run conf2.js (run on firefox) to run test2.js and validate received message. </p>


问:
Importing sqldump into docker-container
I am trying to import a sqldump into a running MySQL Docker-Container with this command:

```<code> sudo docker exec -i a2bdd4db352a /usr/bin/mysql -u username -ppassword --max_allowed_packet=1500M --default-character-set=utf8 database < /srv/Dump.sql
</code>```

After a while getting these error:

```<code>ERROR 2006 (HY000) at line 979: MySQL server has gone away
read unix @->/var/run/docker.sock: read: connection reset by peer
</code>```

Logs:

```<code>2017-12-07T09:44:21.099302Z 3 [Note] Aborted connection 3 to db: 'database' user: 'database' host: 'localhost' (Got a packet bigger than 'max_allowed_packet' bytes)
</code>```

Tried to increase the max_allowed_package variable in my MySQL-Conf ---> Nothing changed - still the same error.

My Dump has a size of 16 GB.

Has anybody a idea - how to fix this?

答:
Error says the particular row data has size more than 1500M, so try increasing  max_allowed_packet to higher value

For detailed info refer below link
http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_max_allowed_packet

Title: Importing sqldump into docker-container

Body:
I am trying to import a sqldump into a running MySQL Docker-Container with this command:

 sudo docker exec -i a2bdd4db352a /usr/bin/mysql -u username -ppassword --max_allowed_packet=1500M --default-character-set=utf8 database < /srv/Dump.sql

After a while getting these error:

ERROR 2006 (HY000) at line 979: MySQL server has gone away
read unix @->/var/run/docker.sock: read: connection reset by peer

Logs:

2017-12-07T09:44:21.099302Z 3 [Note] Aborted connection 3 to db: 'database' user: 'database' host: 'localhost' (Got a packet bigger than 'max_allowed_packet' bytes)

Tried to increase the max_allowed_package variable in my MySQL-Conf ---> Nothing changed - still the same error.

My Dump has a size of 16 GB.

Has anybody a idea - how to fix this?


问:
Dapper UpdateAsync ignore column
I am trying to update with Dapper.Contrib this table:

```<code>public class MyTable
{
    public int ID { get; set; }
    public int SomeColumn1 { get; set; }
    public int SomeColumn2 { get; set; }
    public int CreateUserID { get; set; }
    public int UpdateUserID { get; set; }
}
</code>```

I don't want to update the CreateUserID column because it is an update method so that I want to ignore this column while calling the Dapper - Update.Async(entity) method.

I tried using [NotMapped] and [UpdateIgnore] attributes but no help.

Note: I still want this column to be passed on insert operations, therefore, [Computed] and [Write(false)] is not appropriate.

Can someone help me figure out how to ignore this column when updating the table in the database?

答:
I suggest using the [Computed] attribute.

[Computed] - this property is computed and should not be part of updates

But, It appears that the documentation for Dapper.Contrib is worded in a confusing manner. The [Computed] attribute appears to be ignored on inserts as well - this may or may not work for your use case.

ContentLicense: CC BY-SA 4.0

Title: Dapper UpdateAsync ignore column

Body:
I am trying to update with Dapper.Contrib this table:

public class MyTable
{
    public int ID { get; set; }
    public int SomeColumn1 { get; set; }
    public int SomeColumn2 { get; set; }
    public int CreateUserID { get; set; }
    public int UpdateUserID { get; set; }
}

I don't want to update the CreateUserID column because it is an update method so that I want to ignore this column while calling the Dapper - Update.Async(entity) method.

I tried using [NotMapped] and [UpdateIgnore] attributes but no help.

Note: I still want this column to be passed on insert operations, therefore, [Computed] and [Write(false)] is not appropriate.

Can someone help me figure out how to ignore this column when updating the table in the database?


问:
Django - importing dynamically
I'm trying to do a dynamic import of a python module in django.  I have two different apps that I want to import from, and I want to replace these import statements:

```<code>from app1.forms import App1ProfileForm
from app2.forms import App2ProfileForm
</code>```

I am dynamically able to create the strings App1ProfileForm and App2ProfileForm and then instantiate them like so:

```<code>globals()[form]()
</code>```

I tried following some of the instructions in this post: Dynamically import class by name for static access

and so I tried doing this:

```<code>theModule = __import__("app1.forms.App1ProfileForm")
</code>```

but I'm getting an error that says No module named App1ProfileForm

EDIT:::
Ok I tried this code:

```<code> theModule = __import__("app1")
    print theModule
    theClass = getattr(theModule,'forms')
    print theClass
    theForm = getattr(theClass,'App1ProfileForm')
    print theForm
    theForm.initialize()
</code>```

but I get an error that type object 'App1ProfileForm' has no attribute 'initialize'

答: Aren't you trying to import a class, and not a module ? I'm not an expert, but I think you must import the module using __import__, then select it's App1ProfileForm class with something like yourmodule.App1ProfileForm</p>

Title: Django - importing dynamically

Body:
I'm trying to do a dynamic import of a python module in django.  I have two different apps that I want to import from, and I want to replace these import statements:

from app1.forms import App1ProfileForm
from app2.forms import App2ProfileForm

I am dynamically able to create the strings App1ProfileForm and App2ProfileForm and then instantiate them like so:

globals()[form]()

I tried following some of the instructions in this post: Dynamically import class by name for static access

and so I tried doing this:

theModule = __import__("app1.forms.App1ProfileForm")

but I'm getting an error that says No module named App1ProfileForm

EDIT:::
Ok I tried this code:

 theModule = __import__("app1")
    print theModule
    theClass = getattr(theModule,'forms')
    print theClass
    theForm = getattr(theClass,'App1ProfileForm')
    print theForm
    theForm.initialize()

but I get an error that type object 'App1ProfileForm' has no attribute 'initialize'


问:
vuejs/js object changes but doesn't reflect it in the DOM
I am trying to loop through and array of objects printing list items. I have a click listener which add a custom property the object and a class binding is dependent on that property value.
Here is my code please have a look.

Html

```<code><div class="row wi ony-bor-ans" v-if="q.ans" v-for="(ans,i) in q.ans" :key="i">
<div class="col-auto que-ans-main-ul">
    <ul>
        <li @click="voteOnAns(1,i)" :class="{voted:ans.ansVotedUp}">
            <i class="fa fa-chevron-up"></i>
        </li>
        <li><span>{{i}}</span></li>
        <li @click="voteOnAns(-1,i)" :class="{voted:ans.ansVotedDown}">
            <i class="fa fa-chevron-down"></i>
        </li>
    </ul>
</div>
</code>```

My vue method voteOnAns looks like this

```<code>voteOnAns(ansVoteType,i){
if(ansVoteType>0){
    this.q.ans[i].ansVotedUp=true;
    this.q.ans[i].ansVotedDown=false;
}else{
    this.q.ans[i].ansVotedDown=true;
    this.q.ans[i].ansVotedUp=false;
}
console.log(this.q.ans);
</code>```

}

Here this.q.ans prints the specific object correctly.

Another interesting thing is, I am using vue chrome extension and there I see some time this new property added and sometime is they are not there in object. But console.log shows the object correctly.

Any help or explanation is highly appreciated.
Thank you.

答:
Due to limitations of Javascript, Vue can not detect property additions so those new properties are not reactive.

You have to use Vue.set to add reactive properties dynamically:

```<code>Vue.set(this.q.ans[i], 'ansVotedUp', true);
</code>```

Body:
I am trying to loop through and array of objects printing list items. I have a click listener which add a custom property the object and a class binding is dependent on that property value.
Here is my code please have a look.

Html

{{i}}

My vue method voteOnAns looks like this

voteOnAns(ansVoteType,i){
if(ansVoteType>0){
    this.q.ans[i].ansVotedUp=true;
    this.q.ans[i].ansVotedDown=false;
}else{
    this.q.ans[i].ansVotedDown=true;
    this.q.ans[i].ansVotedUp=false;
}
console.log(this.q.ans);

}

Here this.q.ans prints the specific object correctly.

Another interesting thing is, I am using vue chrome extension and there I see some time this new property added and sometime is they are not there in object. But console.log shows the object correctly.

Any help or explanation is highly appreciated.
Thank you.

Body:
Due to limitations of Javascript, Vue can not detect property additions so those new properties are not reactive.

You have to use Vue.set to add reactive properties dynamically:

Vue.set(this.q.ans[i], 'ansVotedUp', true);


问:
Searching for an item within a ListBox using a TextBox and a Button
I am creating a system that includes a ListBox of integers inserted by the user. I have contained a search button and a search TextBox for the user to input the integer they want to search for within the ListBox. Once the user has inputted the integer, I want a message box to be displayed either informing the user that there is e.g. 1 integer of value '3' in the list box, or an error message box informing the user that the integer does not exist within the list box.

```<code>private void buttonSearch_Click(object sender, EventArgs e)
{
    listBoxAddedIntegers.SelectedItems.Clear();
    for (int i = listBoxAddedIntegers.Items.Count - 1;i>=0; i--) ;
    {
        if (listBoxAddedIntegers.Items[i].ToString().ToLower().Contains(textBoxSearch.Text.ToLower())) ;
        {
            listBoxAddedIntegers.SetSelected(i, true);
        }
    }

    // ...
}
</code>```

I am not really sure on the code that I am meant to include here, and the code that I have already inserted suggests that 'i' does not exist in the current content.

Can anyone help please?

答:
You have to do this:</p>

```<code>int count=0;

for(int i=0;i<listBoxAddedIntegers.Items.Count;i++)
{
    if(listBoxAddedIntegers.Items[i].Items[i].ToString().ToLower().Contains(textBoxSearch.Text.ToLower())
    {
         count+=1;
    }
}

if(count>0)
{
     //display your message here after the loop with the count
}
else
{
     //display your message with error
}
</code>```

Body:
I am creating a system that includes a ListBox of integers inserted by the user. I have contained a search button and a search TextBox for the user to input the integer they want to search for within the ListBox. Once the user has inputted the integer, I want a message box to be displayed either informing the user that there is e.g. 1 integer of value '3' in the list box, or an error message box informing the user that the integer does not exist within the list box.

private void buttonSearch_Click(object sender, EventArgs e)
{
    listBoxAddedIntegers.SelectedItems.Clear();
    for (int i = listBoxAddedIntegers.Items.Count - 1;i>=0; i--) ;
    {
        if (listBoxAddedIntegers.Items[i].ToString().ToLower().Contains(textBoxSearch.Text.ToLower())) ;
        {
            listBoxAddedIntegers.SetSelected(i, true);
        }
    }

    // ...
}

I am not really sure on the code that I am meant to include here, and the code that I have already inserted suggests that 'i' does not exist in the current content.

Can anyone help please?

Body:
You have to do this:

int count=0;

for(int i=0;i<listBoxAddedIntegers.Items.Count;i++)
{
    if(listBoxAddedIntegers.Items[i].Items[i].ToString().ToLower().Contains(textBoxSearch.Text.ToLower())
    {
         count+=1;
    }
}

if(count>0)
{
     //display your message here after the loop with the count
}
else
{
     //display your message with error
}


问:
Creating .dll subproject in Visual Studio Code editor
I am going to create a .dll and an .exe using this .dll with C# and .NET.

How to create a .dll subproject in Visual Studio Code editor?

I develop on Debian Linux.

答:
Create folders for both the main .exe project and for the .dll subproject. .dll subproject folder should not be inside the main project folder.

Then in the main project folder run

```<code>dotnet add . reference ../xyz/xyz.csproj
</code>```

where xyz is the name of the .dll subproject.

After this building the main project automatically builds the subproject too. Exactly what I need.

Body:
Create folders for both the main .exe project and for the .dll subproject. .dll subproject folder should not be inside the main project folder.

Then in the main project folder run

dotnet add . reference ../xyz/xyz.csproj

where xyz is the name of the .dll subproject.

After this building the main project automatically builds the subproject too. Exactly what I need.


问:
Java: Curious ImmutableList add
I don't understand this method implementation. It's

```<code>public static <T> List<T> add(List<T> list, T element) {
    final int size = list.size();
    if (size == 0) {
        return ImmutableList.of(element);
    } else if (list instanceof ImmutableList) {
        if (size == 1) {
            final T val = list.get(0);
            list = Lists.newArrayList();
            list.add(val);
        } else {
            list = Lists.newArrayList(list);
        }
    }
    list.add(element);
    return list;
}
</code>```

Why not a straightforward list.add(element)?

答:
The reason that this method is not "a straightforward list.add(element)" is because this method is designed to be able to add elements to ImmutableLists. Those are, quite obviously, immutable (if you look, their native add method throws an UnsupportedOperationException) and so the only way to "add" to them is to create a new list.

The fact that the newly returned list is now mutable is a strange design decision and only a wider context or input from the code's author would help solve that one.

The special case where an empty input list will return an immutable list is another strange design decision. The function would work fine without that conditional branch.

Because this method returns a copy of the list, you should be careful to assign the result to something, probably the original variable:

```<code>myList = TheClass.add(myList, newElement);
</code>```

and note that the following usage will effectively do nothing:

```<code>TheClass.add(myList, newElement);
</code>```

Title: Java: Curious ImmutableList add

Body:
I don't understand this method implementation. It's

public static <T> List<T> add(List<T> list, T element) {
    final int size = list.size();
    if (size == 0) {
        return ImmutableList.of(element);
    } else if (list instanceof ImmutableList) {
        if (size == 1) {
            final T val = list.get(0);
            list = Lists.newArrayList();
            list.add(val);
        } else {
            list = Lists.newArrayList(list);
        }
    }
    list.add(element);
    return list;
}

Why not a straightforward list.add(element)?

Body:
The reason that this method is not "a straightforward list.add(element)" is because this method is designed to be able to add elements to ImmutableLists. Those are, quite obviously, immutable (if you look, their native add method throws an UnsupportedOperationException) and so the only way to "add" to them is to create a new list.

The fact that the newly returned list is now mutable is a strange design decision and only a wider context or input from the code's author would help solve that one.

The special case where an empty input list will return an immutable list is another strange design decision. The function would work fine without that conditional branch.

Because this method returns a copy of the list, you should be careful to assign the result to something, probably the original variable:

myList = TheClass.add(myList, newElement);

and note that the following usage will effectively do nothing:

TheClass.add(myList, newElement);


问:
How to implement key value observing of objects in an NSMutableArray
I need some help trying to understand KVO on a complex hierarchy of objects. Let me set the scenario. The MyClass object has a mutable array property that contains MyPerson objects. I want to observe changes in the myPeople property of MyClass. Furthermore I would like to observe all the properties contained in the MyPerson object as well. Here are the class definitions.

```<code>@interface MyClass:NSObject
{
   NSMutableArray *myPeople;
}

@property(nonatomic, retain)NSMutableArray *myArray;

@end
</code>```

Here is the MyPerson object,

```<code>@interface MyPerson:NSObject
{
   NSString *myName;
   NSString *myLastName;
}

@property(nonatomic, retain)NSString *myName;
@property(nonatomic, retain)NSString *myLastName;

@end
</code>```

Is it correct to observe the properties that I'm interested in the following manner?

```<code>MyClass *myClass = [[MyClass alloc] init]; //myPeople is filled with myPerson objects

MySchool *mySchool = [[MySchool alloc] init];

[myClass addObserver:mySchool
      forKeyPath:@"myPeople"
             options:NSKeyValueObservingOptionNew
         context:NULL];

[myClass addObserver:mySchool
      forKeyPath:@"myPeople.myName"
             options:NSKeyValueObservingOptionNew
         context:NULL]; //I am unsure about this one

[myClass addObserver:mySchool
      forKeyPath:@"myPeople.myLastName"
             options:NSKeyValueObservingOptionNew
         context:NULL]; //I am unsure about this one
</code>```

答: No, it's not correct. You would have to observe the properties for any object you add to the array separately. So whenever an object is added to or removed from the array, you would have to add/remove your observer to/from the added/removed object(s).</p>

Body:
I need some help trying to understand KVO on a complex hierarchy of objects. Let me set the scenario. The MyClass object has a mutable array property that contains MyPerson objects. I want to observe changes in the myPeople property of MyClass. Furthermore I would like to observe all the properties contained in the MyPerson object as well. Here are the class definitions.

@interface MyClass:NSObject
{
   NSMutableArray *myPeople;
}

@property(nonatomic, retain)NSMutableArray *myArray;

@end

Here is the MyPerson object,

@interface MyPerson:NSObject
{
   NSString *myName;
   NSString *myLastName;
}

@property(nonatomic, retain)NSString *myName;
@property(nonatomic, retain)NSString *myLastName;

@end

Is it correct to observe the properties that I'm interested in the following manner?

MyClass *myClass = [[MyClass alloc] init]; //myPeople is filled with myPerson objects

MySchool *mySchool = [[MySchool alloc] init];

[myClass addObserver:mySchool
      forKeyPath:@"myPeople"
             options:NSKeyValueObservingOptionNew
         context:NULL];

[myClass addObserver:mySchool
      forKeyPath:@"myPeople.myName"
             options:NSKeyValueObservingOptionNew
         context:NULL]; //I am unsure about this one

[myClass addObserver:mySchool
      forKeyPath:@"myPeople.myLastName"
             options:NSKeyValueObservingOptionNew
         context:NULL]; //I am unsure about this one


问:
Payara5 - payaradomain on Java 9
Im looking for some help running Payara 5 Alpha on Java 9. The blog post "Payara Server 5 Alpha 2 release is here!" says it runs the payara domain on Java 9, but Im still getting the java.lang.NullPointerException on AbstractModulesRegistryImpl.initializeServiceLocator -

```<code>C:\payara-5.0.0.Alpha4-20171117.004238-21\payara5\bin>java -version
java version "9.0.1"
Java(TM) SE Runtime Environment (build 9.0.1+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.1+11, mixed mode)

C:\payara-5.0.0.Alpha4-20171117.004238-21\payara5\bin>asadmin.bat start-domain payaradomain
Exception in thread "main" java.lang.NullPointerException
        at com.sun.enterprise.module.common_impl.AbstractModulesRegistryImpl.initializeServiceLocator(AbstractModulesRegistryImpl.java:152)
        at com.sun.enterprise.module.common_impl.AbstractModulesRegistryImpl.newServiceLocator(AbstractModulesRegistryImpl.java:144)
        at com.sun.enterprise.module.common_impl.AbstractModulesRegistryImpl.createServiceLocator(AbstractModulesRegistryImpl.java:218)
        at com.sun.enterprise.module.common_impl.AbstractModulesRegistryImpl.createServiceLocator(AbstractModulesRegistryImpl.java:224)
        at com.sun.enterprise.module.single.StaticModulesRegistry.createServiceLocator(StaticModulesRegistry.java:88)
        at com.sun.enterprise.admin.cli.CLIContainer.getServiceLocator(CLIContainer.java:216)
        at com.sun.enterprise.admin.cli.CLIContainer.getLocalCommand(CLIContainer.java:254)
        at com.sun.enterprise.admin.cli.CLICommand.getCommand(CLICommand.java:231)
        at com.sun.enterprise.admin.cli.AdminMain.executeCommand(AdminMain.java:370)
        at com.sun.enterprise.admin.cli.AdminMain.doMain(AdminMain.java:305)
        at org.glassfish.admin.cli.AsadminMain.main(AsadminMain.java:56)
</code>```

Is there more to the configuration? I've checked github for the Alpha2 and Alpha3 release but cant see more information relating to this

Thanks

答: Payara support for JDK 9 is still in the early stages and is not reliable. It is currently being worked on, but it will be complete by the time 5.181 is released. You can use GitHub (https://github.com/payara/Payara/issues) to report problems. You can also download the latest snapshot of Payara 5 from https://www.payara.fish/upstream_builds by scrolling down.</p>

Title: Payara5 - payaradomain on Java 9

Body:
Im looking for some help running Payara 5 Alpha on Java 9. The blog post "Payara Server 5 Alpha 2 release is here!" says it runs the payara domain on Java 9, but Im still getting the java.lang.NullPointerException on AbstractModulesRegistryImpl.initializeServiceLocator -

C:\payara-5.0.0.Alpha4-20171117.004238-21\payara5\bin>java -version
java version "9.0.1"
Java(TM) SE Runtime Environment (build 9.0.1+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.1+11, mixed mode)

C:\payara-5.0.0.Alpha4-20171117.004238-21\payara5\bin>asadmin.bat start-domain payaradomain
Exception in thread "main" java.lang.NullPointerException
        at com.sun.enterprise.module.common_impl.AbstractModulesRegistryImpl.initializeServiceLocator(AbstractModulesRegistryImpl.java:152)
        at com.sun.enterprise.module.common_impl.AbstractModulesRegistryImpl.newServiceLocator(AbstractModulesRegistryImpl.java:144)
        at com.sun.enterprise.module.common_impl.AbstractModulesRegistryImpl.createServiceLocator(AbstractModulesRegistryImpl.java:218)
        at com.sun.enterprise.module.common_impl.AbstractModulesRegistryImpl.createServiceLocator(AbstractModulesRegistryImpl.java:224)
        at com.sun.enterprise.module.single.StaticModulesRegistry.createServiceLocator(StaticModulesRegistry.java:88)
        at com.sun.enterprise.admin.cli.CLIContainer.getServiceLocator(CLIContainer.java:216)
        at com.sun.enterprise.admin.cli.CLIContainer.getLocalCommand(CLIContainer.java:254)
        at com.sun.enterprise.admin.cli.CLICommand.getCommand(CLICommand.java:231)
        at com.sun.enterprise.admin.cli.AdminMain.executeCommand(AdminMain.java:370)
        at com.sun.enterprise.admin.cli.AdminMain.doMain(AdminMain.java:305)
        at org.glassfish.admin.cli.AsadminMain.main(AsadminMain.java:56)

Is there more to the configuration? I've checked github for the Alpha2 and Alpha3 release but cant see more information relating to this

Thanks


问:
disable all form elements inside div
is there a way to disable all fields (textarea/textfield/option/input/checkbox/submit etc) in a form by telling only the parent div name in jquery/javascript?</p>

答:
Use the CSS Class to prevent from Editing the Div Elements

CSS:

.divoverlay
{
position:absolute;
width:100%;
height:100%;
background-color:transparent;
z-index:1;
top:0;
}
```

<p><strong>JS:</strong></p>

<pre class="lang-js prettyprint-override"><code>$('#divName').append('<div class=divoverlay></div>');
</code>```

Or add the class name in HTML Tag.
It will prevent from editing the Div Elements.

Title: disable all form elements inside div

Body:
Use the CSS Class to prevent from Editing the Div Elements

CSS:

.divoverlay
{
position:absolute;
width:100%;
height:100%;
background-color:transparent;
z-index:1;
top:0;
}

JS:

$('#divName').append('<div class=divoverlay></div>');

Or add the class name in HTML Tag.
It will prevent from editing the Div Elements.


答:
You cannot change the array value directly when use with Vue. What you need to do is to use Vue.set to update the value. Because Vue cannot detect the value changed when update the value with array. You may check the list rendering caveat on vue official site.

```<code>voteOnAns(ansVoteType,i){
    if(ansVoteType>0){
        Vue.set(this.q.ans[i], 'ansVotedUp', true);
        Vue.set(this.q.ans[i], 'ansVotedDown', false);
    }else{
        Vue.set(this.q.ans[i], 'ansVotedDown', true);
        Vue.set(this.q.ans[i], 'ansVotedUp', false);
    }
}
</code>```

Title: vuejs/js object changes but doesn't reflect it in the DOM

Body:
You cannot change the array value directly when use with Vue. What you need to do is to use Vue.set to update the value. Because Vue cannot detect the value changed when update the value with array. You may check the list rendering caveat on vue official site.

voteOnAns(ansVoteType,i){
    if(ansVoteType>0){
        Vue.set(this.q.ans[i], 'ansVotedUp', true);
        Vue.set(this.q.ans[i], 'ansVotedDown', false);
    }else{
        Vue.set(this.q.ans[i], 'ansVotedDown', true);
        Vue.set(this.q.ans[i], 'ansVotedUp', false);
    }
}