问:
Ifand statements using hours/minutes in Excel
Need a formula for the following 4 situations

If you work less than 9 hours and your break is less than 30:59
minutes, I want a 0.

If you work less than 9 hours and your break is
more than 31 minutes, I want a 1

If you work more than 9 hours and
your break is less than 45:59 minutes, I want a 0

If you work more
than 9 hours and your break is more than 46 minutes, I want a 1

Here is what I have so far.  Most of it works but not all the statements.

For example:

C2 = staffed time listed as 9:55:21

G2 = break time listed as :40:46

```<code>=IF(AND(C2<"9:00:00",G2<":30:59"),0,
   IF(AND(C2>"9:00:01",G2<":45:59"),0,
      IF(AND(C2<"9:00:00",G2>":31:00"),1,
        IF(AND(C2>"9:00:01",G2>":46:00"),1,"FALSE"))))
</code>```

I can get some of the situations to work but I can't get all 4 of them to work.  I'm thinking it may be a formatting issue with the time

答:
OP commented that both staffed-time and and break-time can be ill-formatted. So first we'd better format these data into proper date-type. When string-typed U2 is 9:55:21 or :51:13 or 51:13, below formulae will format it properly.

V2: =FIND(":", U2)

W2: =IFERROR(FIND(":", U2, V2+1), 0)

X2: =IF(W2=0, TIME(0,LEFT(U2,V2-1),MID(U2,V2+1,2)),
IF(V2>1,TIME(LEFT(U2,V2-1),MID(U2,V2+1,2),MID(U2,W2+1,2)),TIME(0,MID(U2,V2+1,2),MID(U2,W2+1,2))))

So if you get the proper date-typed for both staffed-time(X2) and break-time(say AC2), then you can get 0 or 1 based on your four conditions in order. (this formula can be shortened, but I didn't do for clarity.)

```<code>=IF(AND(HOUR(X2)<9,  HOUR(AC2)*60 + MINUTE(AC2)<31), 0,
 IF(AND(HOUR(X2)<9,  HOUR(AC2)*60 + MINUTE(AC2)>=31), 1,
 IF(AND(HOUR(X2)>=9, HOUR(AC2)*60 + MINUTE(AC2)<46), 0,
 IF(AND(HOUR(X2)>=9, HOUR(AC2)*60 + MINUTE(AC2)>=46), 1))))
</code>```

And I used >= instead of > because you didn't specify about equal conditions in plain text. Sample Excel file is here. Sample file handles well some ill-formatted input as well.

Body:
Need a formula for the following 4 situations

If you work less than 9 hours and your break is less than 30:59
minutes, I want a 0.

If you work less than 9 hours and your break is
more than 31 minutes, I want a 1

If you work more than 9 hours and
your break is less than 45:59 minutes, I want a 0

If you work more
than 9 hours and your break is more than 46 minutes, I want a 1

Here is what I have so far.  Most of it works but not all the statements.

For example:

C2 = staffed time listed as 9:55:21

G2 = break time listed as :40:46

=IF(AND(C2<"9:00:00",G2<":30:59"),0,
   IF(AND(C2>"9:00:01",G2<":45:59"),0,
      IF(AND(C2<"9:00:00",G2>":31:00"),1,
        IF(AND(C2>"9:00:01",G2>":46:00"),1,"FALSE"))))

I can get some of the situations to work but I can't get all 4 of them to work.  I'm thinking it may be a formatting issue with the time

Body:
OP commented that both staffed-time and and break-time can be ill-formatted. So first we'd better format these data into proper date-type. When string-typed U2 is 9:55:21 or :51:13 or 51:13, below formulae will format it properly.

V2: =FIND(":", U2)

W2: =IFERROR(FIND(":", U2, V2+1), 0)

X2: =IF(W2=0, TIME(0,LEFT(U2,V2-1),MID(U2,V2+1,2)),
IF(V2>1,TIME(LEFT(U2,V2-1),MID(U2,V2+1,2),MID(U2,W2+1,2)),TIME(0,MID(U2,V2+1,2),MID(U2,W2+1,2))))

So if you get the proper date-typed for both staffed-time(X2) and break-time(say AC2), then you can get 0 or 1 based on your four conditions in order. (this formula can be shortened, but I didn't do for clarity.)

=IF(AND(HOUR(X2)<9,  HOUR(AC2)*60 + MINUTE(AC2)<31), 0,
 IF(AND(HOUR(X2)<9,  HOUR(AC2)*60 + MINUTE(AC2)>=31), 1,
 IF(AND(HOUR(X2)>=9, HOUR(AC2)*60 + MINUTE(AC2)<46), 0,
 IF(AND(HOUR(X2)>=9, HOUR(AC2)*60 + MINUTE(AC2)>=46), 1))))

And I used >= instead of > because you didn't specify about equal conditions in plain text. Sample Excel file is here. Sample file handles well some ill-formatted input as well.


来源: stackexchange

问:
How to store file object to mysql database using php
I tried to store file to database:
I tried this:

```<code> <input type="hidden" name="MAX_FILE_SIZE" value="2000000">
    <div class="col-sm-3">
        <input name="userfile" type="file" id="userfile" >
    </div>

 <input type="button" class="btn btn-success col-sm-2 col-sm-offset-1"
            style="width: 10%" value="Submit" id=ctl_submit title="Submit">
</code>```

I get file object by doing this:

```<code> $('#userfile')[0].files[0]
</code>```

but how to process this object in php to store into DB. My DB contains these fields : filename, filecontent, filesize, filetype.
Can anyone please tell me?

答: After submit a form you must have a $_FILES object. Which contains all the file related information like size type etc. So you can use that. </p>

ContentLicense: CC BY-SA 3.0

Body:
I tried to store file to database:
I tried this:

 <input type="hidden" name="MAX_FILE_SIZE" value="2000000">

        <input name="userfile" type="file" id="userfile" >

 <input type="button" class="btn btn-success col-sm-2 col-sm-offset-1"
            style="width: 10%" value="Submit" id=ctl_submit title="Submit">

I get file object by doing this:

 $('#userfile')[0].files[0]

but how to process this object in php to store into DB. My DB contains these fields : filename, filecontent, filesize, filetype.
Can anyone please tell me?


问:
how to check If checkbox is checked or not laravel 5.4
I want to show a button if checkbox gets checked and if not checked button will not appear in laravel 5.4. How can I do this. </p>

答:
you can do this by using jquery </p>

```<code>$('#checkbox').change(function(){
        if($('#checkbox').is(':checked')){
    console.log("asdad");
        $('#button').css('display','inline');
    }else{
        $('#button').css('display','none');
    }
})
</code>```

Body:
you can do this by using jquery

$('#checkbox').change(function(){
        if($('#checkbox').is(':checked')){
    console.log("asdad");
        $('#button').css('display','inline');
    }else{
        $('#button').css('display','none');
    }
})


问:
Yocto Error: "non debug package contains .debug directory" with yocto recipe
I am trying to build a custom yocto recipe, which involves compiling a small C program. During the build -

```<code>$ bitbake -f interface-configuration
...
ERROR: QA Issue: non debug package contains .debug directory: interface-configuration path /work/cortexa9hf-vfp-poky-linux-gnueabi/interface-configuration/0.1-r0/packages-split/interface-configuration/etc/interfaces/bin/.debug/set
ERROR: QA run found fatal errors. Please consider fixing them.
ERROR: Function failed: do_package_qa
ERROR: Logfile of failure stored in: /home/git/poky/build-atmel/tmp/work/cortexa9hf-vfp-poky-linux-gnueabi/interface-configuration/0.1-r0/temp/log.do_package.28986
ERROR: Task 10 (/home/git/poky/meta-atmel/recipes-intelli/interface-configuration/interface-configuration_0.1.bb, do_package) failed with exit code '1'
</code>```

I was wondering if anyone on here know how to either disable debug info or remove the QA check. Google search for the error has proven fruitless so far.

Cheers

Update with interface-configuration.bb

```<code>DESCRIPTION = "Interface configuration files and tools"
SECTION = "examples"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://LICENSE;md5=3f40d7994397109285ec7b81fdeb3b58"
SRC_URI = "file://interface-configuration-0.1.tar.gz"

do_compile() {
    install -vd ${D}/
    ${CC} -g0 set.c -o set
    # CC is arm-poky-linux-gnueabi-gcc -march=armv7-a -marm -mthumb-interwork -mfloat-abi=hard -mtune=cortex-a9 --sysroot=/home/git/poky/build-atmel/tmp/sysroots/sama5d3xek
}

do_install() {
    cp -r ${S}/etc ${D}/etc
    install -vd ${D}/etc/interfaces/bin
    install -vm 0755 set ${D}/etc/interfaces/bin/
}

do_install_append() {
    # I added this to try to remove the error - it doesn't work
    rm -rf ${D}/etc/interfaces/bin/.debug
}

FILES_${PN} += "/etc/interfaces/MANIFEST \
    /etc/interfaces/conf/A \
    /etc/interfaces/conf/B \
    /etc/interfaces/conf/C \
    /etc/interfaces/conf/D \
    /etc/interfaces/template/A \
    /etc/interfaces/template/B \
    /etc/interfaces/template/C \
    /etc/interfaces/template/D \
    /set.c"
</code>```

答:
if you want to skip all of your recipe package
you can add the below line to skip QA issue in your " .bb " file

for installed -vs-shiped  issue:

```<code>INSANE_SKIP_${PN} = "installed-vs-shipped"
</code>```

for striping package issue :

```<code>INHIBIT_PACKAGE_STRIP = "1"
INHIBIT_PACKAGE_DEBUG_SPLIT = "1"
</code>```

hope this will work for you.

Body:
I am trying to build a custom yocto recipe, which involves compiling a small C program. During the build -

$ bitbake -f interface-configuration
...
ERROR: QA Issue: non debug package contains .debug directory: interface-configuration path /work/cortexa9hf-vfp-poky-linux-gnueabi/interface-configuration/0.1-r0/packages-split/interface-configuration/etc/interfaces/bin/.debug/set
ERROR: QA run found fatal errors. Please consider fixing them.
ERROR: Function failed: do_package_qa
ERROR: Logfile of failure stored in: /home/git/poky/build-atmel/tmp/work/cortexa9hf-vfp-poky-linux-gnueabi/interface-configuration/0.1-r0/temp/log.do_package.28986
ERROR: Task 10 (/home/git/poky/meta-atmel/recipes-intelli/interface-configuration/interface-configuration_0.1.bb, do_package) failed with exit code '1'

I was wondering if anyone on here know how to either disable debug info or remove the QA check. Google search for the error has proven fruitless so far.

Cheers

Update with interface-configuration.bb

DESCRIPTION = "Interface configuration files and tools"
SECTION = "examples"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://LICENSE;md5=3f40d7994397109285ec7b81fdeb3b58"
SRC_URI = "file://interface-configuration-0.1.tar.gz"

do_compile() {
    install -vd ${D}/
    ${CC} -g0 set.c -o set
    # CC is arm-poky-linux-gnueabi-gcc -march=armv7-a -marm -mthumb-interwork -mfloat-abi=hard -mtune=cortex-a9 --sysroot=/home/git/poky/build-atmel/tmp/sysroots/sama5d3xek
}

do_install() {
    cp -r ${S}/etc ${D}/etc
    install -vd ${D}/etc/interfaces/bin
    install -vm 0755 set ${D}/etc/interfaces/bin/
}

do_install_append() {
    # I added this to try to remove the error - it doesn't work
    rm -rf ${D}/etc/interfaces/bin/.debug
}

FILES_${PN} += "/etc/interfaces/MANIFEST \
    /etc/interfaces/conf/A \
    /etc/interfaces/conf/B \
    /etc/interfaces/conf/C \
    /etc/interfaces/conf/D \
    /etc/interfaces/template/A \
    /etc/interfaces/template/B \
    /etc/interfaces/template/C \
    /etc/interfaces/template/D \
    /set.c"

Body:
if you want to skip all of your recipe package
you can add the below line to skip QA issue in your " .bb " file

for installed -vs-shiped  issue:

INSANE_SKIP_${PN} = "installed-vs-shipped"

for striping package issue :

INHIBIT_PACKAGE_STRIP = "1"
INHIBIT_PACKAGE_DEBUG_SPLIT = "1"

hope this will work for you.


问:
Best practices of handling HTTP response with scala
I have ServerA which exposes an API method for a client, which looks like this:

```<code>def methodExposed()= Action.async(json) { req =>

    val reqAsModel = request.body.extractOpt[ClientRequestModel]

    reqAsModel match {
      case Some(clientRequest) =>
        myApiService
          .doSomething(clientRequest.someList)
          .map(res => ???)
      case None =>
        Future.successful(BadRequest("could not extract request"))
    }
  }
</code>```

So, I have a case class for the client request and if I cannot extract it from the request body, then I return a BadRequest with the message and otherwise I call an internal apiService to perform some action with this request.

doSomething performs an API call to ServerB that can return 3 possible responses:

200 status

400 status with body that I need to extract to a case class

500 status

doSomething looks like this:

```<code>def doSomething(list: List[String]) = {
    wSClient.url(url).withHeaders(("Content-Type", "application/json")).post(write(list)).map { response =>
      response.status match {
        case Status.BAD_REQUEST =>
          parse(response.body).extract[ServiceBResponse]
        case Status.INTERNAL_SERVER_ERROR =>
          val ex = new RuntimeException(s"ServiceB Failed with status: ${response.status} body: ${response.body}")
          throw ex
      }
    }
  }
</code>```

Now I have two issues:

Since the 200 returns with no body and 400 has a body, I don't know what should be the return type of doSomething

How should I handle this in the controller and return the response to the client properly in methodExposed?

答:
I would do something like this:

```<code>case class ServiceBResponse(status: Int, body: Option[String] = None)
</code>```

And then, doSomething would be like:

```<code>def doSomething(list: List[String]) = {
  wSClient.url(url).withHeaders(("Content-Type", "application/json")).post(write(list)).map { response =>
    response.status match {
      case Status.OK =>
        ServiceBResponse(response.status)
      case Status.BAD_REQUEST =>
        ServiceBResponse(response.status, Option(response.body))
      case Status.INTERNAL_SERVER_ERROR =>
        val message = s"ServiceB Failed with status: ${response.status} body: ${response.body}"
        ServiceBResponse(response.status, Option(message))
    }
  }
}
</code>```

Finally, inside the controller:

```<code>def methodExposed() = Action.async(json) { req =>

  val reqAsModel = request.body.extractOpt[ClientRequestModel]

  reqAsModel match {
    case Some(clientRequest) =>
      myApiService
        .doSomething(clientRequest.someList)
        .map(serviceBResponse => Status(serviceBResponse.status)(serviceBResponse.getOrElse("")))
    case None =>
      Future.successful(BadRequest("could not extract request"))
  }
}
</code>```

Another alternative is directly use WSResponse:

```<code>def doSomething(list: List[String]) = {
    wSClient
        .url(url)
        .withHeaders(("Content-Type", "application/json"))
        .post(write(list))
}
</code>```

And the controller:

```<code>def methodExposed() = Action.async(json) { req =>

  val reqAsModel = request.body.extractOpt[ClientRequestModel]

  reqAsModel match {
    case Some(clientRequest) =>
      myApiService
        .doSomething(clientRequest.someList)
        .map(wsResponse => Status(wsResponse.status)(wsResponse.body))
    case None =>
      Future.successful(BadRequest("could not extract request"))
  }
}
</code>```

Body:
I have ServerA which exposes an API method for a client, which looks like this:

def methodExposed()= Action.async(json) { req =>

    val reqAsModel = request.body.extractOpt[ClientRequestModel]

    reqAsModel match {
      case Some(clientRequest) =>
        myApiService
          .doSomething(clientRequest.someList)
          .map(res => ???)
      case None =>
        Future.successful(BadRequest("could not extract request"))
    }
  }

So, I have a case class for the client request and if I cannot extract it from the request body, then I return a BadRequest with the message and otherwise I call an internal apiService to perform some action with this request.

doSomething performs an API call to ServerB that can return 3 possible responses:

200 status

400 status with body that I need to extract to a case class

500 status

doSomething looks like this:

def doSomething(list: List[String]) = {
    wSClient.url(url).withHeaders(("Content-Type", "application/json")).post(write(list)).map { response =>
      response.status match {
        case Status.BAD_REQUEST =>
          parse(response.body).extract[ServiceBResponse]
        case Status.INTERNAL_SERVER_ERROR =>
          val ex = new RuntimeException(s"ServiceB Failed with status: ${response.status} body: ${response.body}")
          throw ex
      }
    }
  }

Now I have two issues:

Since the 200 returns with no body and 400 has a body, I don't know what should be the return type of doSomething

How should I handle this in the controller and return the response to the client properly in methodExposed?

Body:
I would do something like this:

case class ServiceBResponse(status: Int, body: Option[String] = None)

And then, doSomething would be like:

def doSomething(list: List[String]) = {
  wSClient.url(url).withHeaders(("Content-Type", "application/json")).post(write(list)).map { response =>
    response.status match {
      case Status.OK =>
        ServiceBResponse(response.status)
      case Status.BAD_REQUEST =>
        ServiceBResponse(response.status, Option(response.body))
      case Status.INTERNAL_SERVER_ERROR =>
        val message = s"ServiceB Failed with status: ${response.status} body: ${response.body}"
        ServiceBResponse(response.status, Option(message))
    }
  }
}

Finally, inside the controller:

def methodExposed() = Action.async(json) { req =>

  val reqAsModel = request.body.extractOpt[ClientRequestModel]

  reqAsModel match {
    case Some(clientRequest) =>
      myApiService
        .doSomething(clientRequest.someList)
        .map(serviceBResponse => Status(serviceBResponse.status)(serviceBResponse.getOrElse("")))
    case None =>
      Future.successful(BadRequest("could not extract request"))
  }
}

Another alternative is directly use WSResponse:

def doSomething(list: List[String]) = {
    wSClient
        .url(url)
        .withHeaders(("Content-Type", "application/json"))
        .post(write(list))
}

And the controller:

def methodExposed() = Action.async(json) { req =>

  val reqAsModel = request.body.extractOpt[ClientRequestModel]

  reqAsModel match {
    case Some(clientRequest) =>
      myApiService
        .doSomething(clientRequest.someList)
        .map(wsResponse => Status(wsResponse.status)(wsResponse.body))
    case None =>
      Future.successful(BadRequest("could not extract request"))
  }
}


问:
I'm getting NoSuchElement exception error
I have shared the below code please let me know the correction

```<code>import org.openqa.selenium.By;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class MyClass {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        /*System.setProperty("webdriver.ie.driver","D:\\Backup\\Documents\\Automation\\drivers\\IEDriverServer.exe");
        InternetExplorerDriver driver = new InternetExplorerDriver();
        driver.get("https://www.google.com");

        WebDriverWait driverWait = new WebDriverWait(driver,50);

        driverWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='lst-ib']"))).click();
        driver.findElementByXPath("//*[@id='lst-ib']").sendKeys("Make My Trip");
        driver.findElementById("_fZl").click();
        driverWait.until(ExpectedConditions.elementToBeClickable(By.linkText("MakeMyTrip, India's No 1 Travel Site | Book Hotels, Flights, Holiday ..."))).click();
        Screenshot S1 = new Screenshot();
        S1.Takescreen();*/
        String username = null;
        String password = null;
        MyClass C1 = new MyClass();
        C1.URLs(username, password);
    }

    public void URLs  (String username, String password) throws InterruptedException
    {

        System.setProperty("webdriver.ie.driver","D:\\Backup\\Documents\\Automation\\drivers\\IEDriverServer.exe");
        InternetExplorerDriver driver = new InternetExplorerDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://google.com");
        driver.findElement(By.className("lst lst-tbb sbibps")).sendKeys("irctc");
        driver.findElement(By.id("_fZl")).click();
        Thread.sleep(10000);
        driver.findElement(By.linkText("IRCTC Next Generation eTicketing System")).click();
        username = driver.findElement(By.id("usernameId")).getTagName();
        password = driver.findElement(By.className("loginPassword")).getTagName();
        System.out.println(username);
        System.out.println(password);
    }
}
</code>```

Error :

Exception in thread "main" org.openqa.selenium.NoSuchElementException:
  Unable to find element with class name == lst lst-tbb sbibps (WARNING:
  The server did not provide any stacktrace information) Command
  duration or timeout: 10.45 seconds

答:
Try this below code.

```<code>driver.get("http://google.com");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

driver.findElement(By.id("lst-ib")).sendKeys("irctc");

WebDriverWait wait = new WebDriverWait(driver, 5);   //use explicit wait method for 5 seconds until element not found.
wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.xpath("//a[text()='IRCTC Next Generation eTicketing System']"))));
driver.findElement(By.xpath("//a[text()='IRCTC Next Generation eTicketing System']")).click();

WebDriverWait homepage = new WebDriverWait(driver, 5);   //use explicit wait method for 5 seconds until element not found. Because when click on link button page is getting loading so wait for few seconds.
homepage.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.id("usernameId"))));

driver.findElement(By.id("usernameId")).sendKeys("Username");
driver.findElement(By.xpath("//input[@class='loginPassword'][@type='password']")).sendKeys("XXXXX");
</code>```

Note:- Instead of using Thread.sleep(), use Explicit wait method.

Body:
I have shared the below code please let me know the correction

import org.openqa.selenium.By;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class MyClass {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        /*System.setProperty("webdriver.ie.driver","D:\\Backup\\Documents\\Automation\\drivers\\IEDriverServer.exe");
        InternetExplorerDriver driver = new InternetExplorerDriver();
        driver.get("https://www.google.com");

        WebDriverWait driverWait = new WebDriverWait(driver,50);

        driverWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='lst-ib']"))).click();
        driver.findElementByXPath("//*[@id='lst-ib']").sendKeys("Make My Trip");
        driver.findElementById("_fZl").click();
        driverWait.until(ExpectedConditions.elementToBeClickable(By.linkText("MakeMyTrip, India's No 1 Travel Site | Book Hotels, Flights, Holiday ..."))).click();
        Screenshot S1 = new Screenshot();
        S1.Takescreen();*/
        String username = null;
        String password = null;
        MyClass C1 = new MyClass();
        C1.URLs(username, password);
    }

    public void URLs  (String username, String password) throws InterruptedException
    {

        System.setProperty("webdriver.ie.driver","D:\\Backup\\Documents\\Automation\\drivers\\IEDriverServer.exe");
        InternetExplorerDriver driver = new InternetExplorerDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://google.com");
        driver.findElement(By.className("lst lst-tbb sbibps")).sendKeys("irctc");
        driver.findElement(By.id("_fZl")).click();
        Thread.sleep(10000);
        driver.findElement(By.linkText("IRCTC Next Generation eTicketing System")).click();
        username = driver.findElement(By.id("usernameId")).getTagName();
        password = driver.findElement(By.className("loginPassword")).getTagName();
        System.out.println(username);
        System.out.println(password);
    }
}

Error :

Exception in thread "main" org.openqa.selenium.NoSuchElementException:
  Unable to find element with class name == lst lst-tbb sbibps (WARNING:
  The server did not provide any stacktrace information) Command
  duration or timeout: 10.45 seconds

Body:
Try this below code.

driver.get("http://google.com");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

driver.findElement(By.id("lst-ib")).sendKeys("irctc");

WebDriverWait wait = new WebDriverWait(driver, 5);   //use explicit wait method for 5 seconds until element not found.
wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.xpath("//a[text()='IRCTC Next Generation eTicketing System']"))));
driver.findElement(By.xpath("//a[text()='IRCTC Next Generation eTicketing System']")).click();

WebDriverWait homepage = new WebDriverWait(driver, 5);   //use explicit wait method for 5 seconds until element not found. Because when click on link button page is getting loading so wait for few seconds.
homepage.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.id("usernameId"))));

driver.findElement(By.id("usernameId")).sendKeys("Username");
driver.findElement(By.xpath("//input[@class='loginPassword'][@type='password']")).sendKeys("XXXXX");

Note:- Instead of using Thread.sleep(), use Explicit wait method.


问:
RxSwift - How to retry when an observable changes but emit only last value?
I'm trying to make chat services chain with RxSwift.
Basically it should do:

Check if chat has id, if yes go to next, if no flatMap to createChat Service

Check if sockect connection is Enabled

Send Chat Message

Basically function below works, but it is not checking socket connection status for now.
It should check before second flatMap if sockets are connected, if yes it should go to flatMap with messageUpload if not it should wait until connection returns true.
I have Variable with is telling me about current connection status(Bool)

```<code>chatSocketService.isSubscribedToChannel.asObservable()
</code>```

but I can't figure out how to put them together.
I tried with third flatMap(before current last one) it doesn't work.
Next problem is that user can try to send few messages before connection is back so each time he hits sendButton this method is executed, so it should send only last message when connection is back.
Any idea how I can handle that with Rx?

```<code>func sendMessage(withBody body: String) {
    guard !body.isEmpty else { return }

    Observable.just(chatModel.value)
        .filter({ $0.product != nil })
        .flatMap({ [unowned self] chatModel -> Observable<ChatModel> in
            if chatModel.id != nil {
                return Observable.just(chatModel)
            } else {
                return self.createChat(withProductModel: chatModel.product!)
            }
        })
        .flatMap({ [unowned self] chatModel -> Observable<ChatMessageModel> in
            return self.chatService.uploadChatMessage(forChat: chatModel, withBody: body)
                    .trackActivity(self.progressHelper.activityIndicator)
        })
        .subscribe(onNext: { [unowned self] chatMessageModel in
            self.finishedSendingMessage.onNext(())
        })
        .addDisposableTo(disposeBag)
}
</code>```

答:
```<code>.flatMap({ [unowned self] chatModel -> Observable<ChatMessageModel> in
    let successfulConnect = chatSocketService.isSubscribedToChannel.asObservable()
       .skipWhile { $0 == false }
       .map { _ -> Void in }
       .take(1)

    return successfulConnect.flatMap { self.chatService.uploadChatMessage(forChat: chatModel, withBody: body) }
        .trackActivity(self.progressHelper.activityIndicator)
})
</code>```

The above code should have the behavior described in the question for managing the connection. successfulConnect is an observable that will emit a value and complete when the connection status is true.

skipWhile will ignore false values, map transforms our observable from Observable<Bool> to Observable<Void> and take(1) makes sure the observable completes after the first value. flatMap then performs uploadChatMessage when sucessfulConnect sends a value.

The second behavior you describe implies cancelling the previous upload if user sends another message before the previous one has been uploaded. This can be handled by disposing of the subscription on entering sendMessage

```<code>var disposable: Disposable?

func sendMessage(withBody body: String) {
   disposable?.dispose()
   disposable = Observable.just(chatModel.value)
      // ...
      .subscribe(onNext: { /* ... */ })
}
</code>```

Body:
I'm trying to make chat services chain with RxSwift.
Basically it should do:

Check if chat has id, if yes go to next, if no flatMap to createChat Service

Check if sockect connection is Enabled

Send Chat Message

Basically function below works, but it is not checking socket connection status for now.
It should check before second flatMap if sockets are connected, if yes it should go to flatMap with messageUpload if not it should wait until connection returns true.
I have Variable with is telling me about current connection status(Bool)

chatSocketService.isSubscribedToChannel.asObservable()

but I can't figure out how to put them together.
I tried with third flatMap(before current last one) it doesn't work.
Next problem is that user can try to send few messages before connection is back so each time he hits sendButton this method is executed, so it should send only last message when connection is back.
Any idea how I can handle that with Rx?

func sendMessage(withBody body: String) {
    guard !body.isEmpty else { return }

    Observable.just(chatModel.value)
        .filter({ $0.product != nil })
        .flatMap({ [unowned self] chatModel -> Observable<ChatModel> in
            if chatModel.id != nil {
                return Observable.just(chatModel)
            } else {
                return self.createChat(withProductModel: chatModel.product!)
            }
        })
        .flatMap({ [unowned self] chatModel -> Observable<ChatMessageModel> in
            return self.chatService.uploadChatMessage(forChat: chatModel, withBody: body)
                    .trackActivity(self.progressHelper.activityIndicator)
        })
        .subscribe(onNext: { [unowned self] chatMessageModel in
            self.finishedSendingMessage.onNext(())
        })
        .addDisposableTo(disposeBag)
}

Body:
.flatMap({ [unowned self] chatModel -> Observable<ChatMessageModel> in
    let successfulConnect = chatSocketService.isSubscribedToChannel.asObservable()
       .skipWhile { $0 == false }
       .map { _ -> Void in }
       .take(1)

    return successfulConnect.flatMap { self.chatService.uploadChatMessage(forChat: chatModel, withBody: body) }
        .trackActivity(self.progressHelper.activityIndicator)
})

The above code should have the behavior described in the question for managing the connection. successfulConnect is an observable that will emit a value and complete when the connection status is true.

skipWhile will ignore false values, map transforms our observable from Observable<Bool> to Observable<Void> and take(1) makes sure the observable completes after the first value. flatMap then performs uploadChatMessage when sucessfulConnect sends a value.

The second behavior you describe implies cancelling the previous upload if user sends another message before the previous one has been uploaded. This can be handled by disposing of the subscription on entering sendMessage

var disposable: Disposable?

func sendMessage(withBody body: String) {
   disposable?.dispose()
   disposable = Observable.just(chatModel.value)
      // ...
      .subscribe(onNext: { /* ... */ })
}


问:
How to remove character from last array element
I need to remove the last element comma in Javascript array

```<code>var arr =  ["AAA,","BBB,"];
</code>```

I need the result below

```<code>var arr =  ["AAA,","BBB"];
</code>```

Any help is appreciated...

答:
One of the other way is this:

var arr =  ["AAA,",",BBB,"];
arr.push(arr.pop().replace(/,$/, ''));
console.log(arr);```

Body:
I need to remove the last element comma in Javascript array

var arr =  ["AAA,","BBB,"];

I need the result below

var arr =  ["AAA,","BBB"];

Any help is appreciated...


问:
Joomla 3 and Image gallery - sigplus
My page is http://www.budrysl2.ayz.pl/portal_new/praca-szkoly/wydarzenia/komunikaty/aktualnosci-uczniowskie

I try to use sig but I doesn't work.
In my article there is code {gallery}2016-17/pr_pow_ch{/gallery} but to gallery is shown.

答:
You need to check the requirements for this plugin to work.

Whether the Content - Image gallery - sigplus plugin is enabled.

Check if the folder name and path is correct.

Title: Joomla 3 and Image gallery - sigplus


问:
UISplitView with UINavigaionController detailView
I see there is UINavigationController as masterView in UISplitView.And the detailView has a UIToolBar at most but isn't base on UINavigationController.
So I would like to make the detailview base on UINavigaionController then I can pushViewController to show other controllers.
Can somebody show me how to implement?</p>

答: You can add a UINavigaionController in your detail view class. Then, create the view by UINavigaionController and add to your detial view class.</p>

ContentLicense: CC BY-SA 2.5


问:
File is not getting copied in Java using input and output stream reader
I am working in Java platform. I need to copy a file from the package to some folders in desktop. I am using input stream and output stream classes to do it, it is doing the job pretty well inside NetBeans.

The problem is, it's not copying the file while I am running the JAR file to test the application, and it is saying NULL.

```<code>       File source = new File("src/jrepo/css/bs.css");

       File dest = new File(ResultPath + "/css/bs.css");

        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(source);
            os = new FileOutputStream(dest);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
        } finally {
            is.close();
            os.close();
        }
</code>```

答: I found the way since I am using JavaFX, there is a problem which stops the file copying of CSS files. In order to resolve that issue just change the run time settings of the project in Netbeans. Right click the title of the project→go to Properties→Build→Packaging→uncheck the Binary Encode JavaFX CSS files checkbox and then save the project and rebuild it.</p>

Body:
I am working in Java platform. I need to copy a file from the package to some folders in desktop. I am using input stream and output stream classes to do it, it is doing the job pretty well inside NetBeans.

The problem is, it's not copying the file while I am running the JAR file to test the application, and it is saying NULL.

       File source = new File("src/jrepo/css/bs.css");

       File dest = new File(ResultPath + "/css/bs.css");

        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(source);
            os = new FileOutputStream(dest);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
        } finally {
            is.close();
            os.close();
        }


问:
Send messages while waiting for messages
Im using the mqtt protocol to send messages of sensor data to a mosquitto broker .What I want to do is send the sensor data every t seconds but if I receive a message proccess it in parallel.I was thiking of using time.sleep() but I think that will delay the "on_message" function too .Im using paho-mqtt and python 2.7 . Any ideas on how I could accomplish such a thing ?

Client No1.(Sends the sensor data)

```<code>from mysignals import mysignals
import paho.mqtt.client as mqtt
import time

def on_connect(client, userdata, rc):
    mqttc.subscribe(topic='/+/mysignals/status', qos=0)
    mqttc.subscribe(topic='/+/mysignals/add_sensor',qos=0)
    mqttc.subscribe(topic='/+/mysignals/remove_sensor',qos=0)

def on_message(client,userdata,message):
    print 'received data'
    base_topic = '/mysignals'
    member_id = message.topic.split('/')[1]
    status_topic = '/mysignals/status'
    add_sensor_topic = '/mysignals/add_sensor'
    remove_sensor_topic = '/mysignals/remove_sensor'
    log_topic = '/log'
    if status_topic in message.topic:
        action = mysignals_test.change_status(int(member_id),int(message.payload))
        mqttc.publish(topic='/'+member_id+status_topic+log_topic+'/',payload=action,qos=0)
    elif add_sensor_topic in message.topic:
        action = mysignals_test.add_sensor(message.playload,int(member_id))
        mqttc.publish(topic='/'+member_id+add_sensor_topic+log_topic+'/',payload=action,qos=0)
    elif remove_sensor_topic in message.topic:
        action = mysignals_test.remove_sensor(message.payload,int(member_id))
        mqttc.publish(topic='/'+member_id+remove_sensor_topic+log_topic+'/',payload=action,qos=0)
    else:
        mqttc.publish(topic='/'+member_id+base_topic+log_topic+'/',payload='Wrong Action.',qos=0)

mysignals_test = mysignals(email='blablabla',password='blabla')
mysignals_test.add_sensor('temp',150)
mysignals_test.change_status(150,1)
mqttc = mqtt.Client(client_id='mysignals')
mqttc.on_connect = on_connect
mqttc.on_message = on_message
mqttc.connect('broker ip')
mqttc.loop_start()

while True:
    for member in mysignals_test.members:
        if member.status == 1:
            live_data = mysignals_test.live(member.member_id)
            for data in live_data:
                topic = '/'+str(data.member_id)+'/mysignals/'+str(data.sensor_id)+'/'
                qos = 0
                retain = False
                if 'raw' in data.sensor_id:
                    payload = data.values
                else:
                    payload = data.value
                mqttc.publish(topic=topic,payload=payload,qos=qos,retain=retain)
    print 'sent data'
    time.sleep(55)
</code>```

Client No2(Receives data from client 1.Only subscriber.Also sends a test message to client1.only subscriber too.)

```<code>import paho.mqtt.client as mqtt

def on_connect(client, userdata, rc):
    mqttc.subscribe(topic='/+/mysignals/+/', qos=0)
    mqttc.subscribe(topic='/+/mysignals/status/+/', qos=0)
def on_disconnect(client,userdata,rc):
    pass
def on_message(client, userdata, message):
    if str(message.payload) == '':
        print 'empty message'
    else:
        print 'Received message :' + str(message.payload) + ', on topic: '+ message.topic + ', with QoS: ' + str(message.qos)
        mqttc.publish(topic='/154/mysignals/status',payload=0,qos=0)

mqttc = mqtt.Client(client_id='P1')
mqttc.on_connect = on_connect
mqttc.on_disconnect = on_disconnect
mqttc.on_message = on_message
mqttc.connect('broker ip')
mqttc.loop_start()
</code>```

Just for the record "mysignals" object is made by me its not something that exists out there.The problem with code above is that ,when Client 2 receives the sensor data it hangs and sends the test message back to the broker indefinetely.The test message that client 2 sends when it receives the sensor data should be read by client 1 and the client1 should manipulate the "mysignals" object accordingly .

Client 2 Output:

```<code>Received message :25.4, on topic: /150/mysignals/temp/, with QoS: 0
Received message :Success, on topic: /154/mysignals/status/log/, with QoS: 0
Received message :Success, on topic: /154/mysignals/status/log/, with QoS: 0
Received message :Success, on topic: /154/mysignals/status/log/, with QoS: 0
Received message :Success, on topic: /154/mysignals/status/log/, with QoS: 0
Received message :Success, on topic: /154/mysignals/status/log/, with QoS: 0
Received message :Success, on topic: /154/mysignals/status/log/, with QoS: 0
Received message :Success, on topic: /154/mysignals/status/log/, with QoS: 0
Received message :Success, on topic: /154/mysignals/status/log/, with QoS: 0
Received message :Success, on topic: /154/mysignals/status/log/, with QoS: 0
Received message :Success, on topic: /154/mysignals/status/log/, with QoS: 0
Received message :Success, on topic: /154/mysignals/status/log/, with QoS: 0
Received message :Success, on topic: /154/mysignals/status/log/, with QoS: 0
Received message :Success, on topic: /154/mysignals/status/log/, with
</code>```

Client 1 Output:

```<code>Login Successfull.
sent data
sent data
received data
received data
received data
received data
received data
received data
received data
received data
</code>```

PS:Im not including "mysignals.py" because is about 200 lines.

答:
My understanding of the way that the callbacks function in the Paho MQTT library is that the background loop (started by loop_start) will interrupt the main thread so I wouldn't worry about delays from using time.sleep(). So if your main concern is in not delaying the on_message callback, it shouldn't be a problem. I regularly have used sleep in Python scripts with MQTT callbacks.

Of course the callback may slightly delay the sensor sending data, but do you actually need the data to be sent with absolutely precise timing? Most databases-for example RRD-can easily adapt to a slightly off update time. Alternatively if your on_message callback takes an unacceptably long time to process, consider passing the payload of the MQTT message out of the callback function and process it elsewhere in your script.

If you really do need split-second precision on the sensor updates consider separating the functions into two scripts (or threads) which each serve only one purpose (sending or receiving).

Body:
Im using the mqtt protocol to send messages of sensor data to a mosquitto broker .What I want to do is send the sensor data every t seconds but if I receive a message proccess it in parallel.I was thiking of using time.sleep() but I think that will delay the "on_message" function too .Im using paho-mqtt and python 2.7 . Any ideas on how I could accomplish such a thing ?

Client No1.(Sends the sensor data)

from mysignals import mysignals
import paho.mqtt.client as mqtt
import time

def on_connect(client, userdata, rc):
    mqttc.subscribe(topic='/+/mysignals/status', qos=0)
    mqttc.subscribe(topic='/+/mysignals/add_sensor',qos=0)
    mqttc.subscribe(topic='/+/mysignals/remove_sensor',qos=0)

def on_message(client,userdata,message):
    print 'received data'
    base_topic = '/mysignals'
    member_id = message.topic.split('/')[1]
    status_topic = '/mysignals/status'
    add_sensor_topic = '/mysignals/add_sensor'
    remove_sensor_topic = '/mysignals/remove_sensor'
    log_topic = '/log'
    if status_topic in message.topic:
        action = mysignals_test.change_status(int(member_id),int(message.payload))
        mqttc.publish(topic='/'+member_id+status_topic+log_topic+'/',payload=action,qos=0)
    elif add_sensor_topic in message.topic:
        action = mysignals_test.add_sensor(message.playload,int(member_id))
        mqttc.publish(topic='/'+member_id+add_sensor_topic+log_topic+'/',payload=action,qos=0)
    elif remove_sensor_topic in message.topic:
        action = mysignals_test.remove_sensor(message.payload,int(member_id))
        mqttc.publish(topic='/'+member_id+remove_sensor_topic+log_topic+'/',payload=action,qos=0)
    else:
        mqttc.publish(topic='/'+member_id+base_topic+log_topic+'/',payload='Wrong Action.',qos=0)

mysignals_test = mysignals(email='blablabla',password='blabla')
mysignals_test.add_sensor('temp',150)
mysignals_test.change_status(150,1)
mqttc = mqtt.Client(client_id='mysignals')
mqttc.on_connect = on_connect
mqttc.on_message = on_message
mqttc.connect('broker ip')
mqttc.loop_start()

while True:
    for member in mysignals_test.members:
        if member.status == 1:
            live_data = mysignals_test.live(member.member_id)
            for data in live_data:
                topic = '/'+str(data.member_id)+'/mysignals/'+str(data.sensor_id)+'/'
                qos = 0
                retain = False
                if 'raw' in data.sensor_id:
                    payload = data.values
                else:
                    payload = data.value
                mqttc.publish(topic=topic,payload=payload,qos=qos,retain=retain)
    print 'sent data'
    time.sleep(55)

Client No2(Receives data from client 1.Only subscriber.Also sends a test message to client1.only subscriber too.)

import paho.mqtt.client as mqtt

def on_connect(client, userdata, rc):
    mqttc.subscribe(topic='/+/mysignals/+/', qos=0)
    mqttc.subscribe(topic='/+/mysignals/status/+/', qos=0)
def on_disconnect(client,userdata,rc):
    pass
def on_message(client, userdata, message):
    if str(message.payload) == '':
        print 'empty message'
    else:
        print 'Received message :' + str(message.payload) + ', on topic: '+ message.topic + ', with QoS: ' + str(message.qos)
        mqttc.publish(topic='/154/mysignals/status',payload=0,qos=0)

mqttc = mqtt.Client(client_id='P1')
mqttc.on_connect = on_connect
mqttc.on_disconnect = on_disconnect
mqttc.on_message = on_message
mqttc.connect('broker ip')
mqttc.loop_start()

Just for the record "mysignals" object is made by me its not something that exists out there.The problem with code above is that ,when Client 2 receives the sensor data it hangs and sends the test message back to the broker indefinetely.The test message that client 2 sends when it receives the sensor data should be read by client 1 and the client1 should manipulate the "mysignals" object accordingly .

Client 2 Output:

Received message :25.4, on topic: /150/mysignals/temp/, with QoS: 0
Received message :Success, on topic: /154/mysignals/status/log/, with QoS: 0
Received message :Success, on topic: /154/mysignals/status/log/, with QoS: 0
Received message :Success, on topic: /154/mysignals/status/log/, with QoS: 0
Received message :Success, on topic: /154/mysignals/status/log/, with QoS: 0
Received message :Success, on topic: /154/mysignals/status/log/, with QoS: 0
Received message :Success, on topic: /154/mysignals/status/log/, with QoS: 0
Received message :Success, on topic: /154/mysignals/status/log/, with QoS: 0
Received message :Success, on topic: /154/mysignals/status/log/, with QoS: 0
Received message :Success, on topic: /154/mysignals/status/log/, with QoS: 0
Received message :Success, on topic: /154/mysignals/status/log/, with QoS: 0
Received message :Success, on topic: /154/mysignals/status/log/, with QoS: 0
Received message :Success, on topic: /154/mysignals/status/log/, with QoS: 0
Received message :Success, on topic: /154/mysignals/status/log/, with

Client 1 Output:

Login Successfull.
sent data
sent data
received data
received data
received data
received data
received data
received data
received data
received data

PS:Im not including "mysignals.py" because is about 200 lines.


问:
sql split and replace string in table
I have data in table as below and trying to use Replace to do it, but I am ending up with either double semicolon ';;; or semicolon at end after using replace. Can I use split and replace to achieve this or any other ways??

```<code>    Test attempts;My attempts using operation;Additions, deletions, and modifications
    Test attempts;My attempts using operation
    Test attempts;access to information;attempts using nex;Additions, deletions, and modifications
    Test attempts;Changes to programs
</code>```

Replace 'My attempts using operation' with emptystring AND
    Replace 'attempts using nex' with 'attempts using imex' in above data column

```<code>    Result should be:

    Test attempts;Additions, deletions, and modifications
    Test attempts-- No semicolon should be there if it ends up at end with that after replace
    Test attempts;access to information;attempts using imex;Additions, deletions, and modifications

Test attempts;Changes to programs
</code>```

答:
First the sample data

```<code>IF OBJECT_ID('tempdb..#t') IS NOT NULL DROP TABLE #t;
CREATE TABLE #t(OriginalString varchar(1000));
INSERT #t
VALUES
('Test attempts;My attempts using operation;Additions, deletions, and modifications'),
('Test attempts;My attempts using operation'),
('Test attempts;access to information;attempts using nex;Additions, deletions, and modifications'),
('Test attempts;Changes to programs');
</code>```

How about this:

```<code>WITH prep(NewString) AS
(
  SELECT
    REPLACE(REPLACE(REPLACE(
      OriginalString, 'attempts using nex', 'attempts using imex'
    ), 'My attempts using operation', ''), ';;', ';')
  FROM #t
)
SELECT
  NewString =
    CASE
      WHEN NewString LIKE '%;'
      THEN SUBSTRING(NewString, 1, LEN(NewString)-1)
      ELSE NewString
    END
FROM prep;
</code>```

Title: sql split and replace string in table

Body:
I have data in table as below and trying to use Replace to do it, but I am ending up with either double semicolon ';;; or semicolon at end after using replace. Can I use split and replace to achieve this or any other ways??

    Test attempts;My attempts using operation;Additions, deletions, and modifications
    Test attempts;My attempts using operation
    Test attempts;access to information;attempts using nex;Additions, deletions, and modifications
    Test attempts;Changes to programs

Replace 'My attempts using operation' with emptystring AND
    Replace 'attempts using nex' with 'attempts using imex' in above data column

    Result should be:

    Test attempts;Additions, deletions, and modifications
    Test attempts-- No semicolon should be there if it ends up at end with that after replace
    Test attempts;access to information;attempts using imex;Additions, deletions, and modifications

Test attempts;Changes to programs

Body:
First the sample data

IF OBJECT_ID('tempdb..#t') IS NOT NULL DROP TABLE #t;
CREATE TABLE #t(OriginalString varchar(1000));
INSERT #t
VALUES
('Test attempts;My attempts using operation;Additions, deletions, and modifications'),
('Test attempts;My attempts using operation'),
('Test attempts;access to information;attempts using nex;Additions, deletions, and modifications'),
('Test attempts;Changes to programs');

How about this:

WITH prep(NewString) AS
(
  SELECT
    REPLACE(REPLACE(REPLACE(
      OriginalString, 'attempts using nex', 'attempts using imex'
    ), 'My attempts using operation', ''), ';;', ';')
  FROM #t
)
SELECT
  NewString =
    CASE
      WHEN NewString LIKE '%;'
      THEN SUBSTRING(NewString, 1, LEN(NewString)-1)
      ELSE NewString
    END
FROM prep;


问:
Nginx connection refused while connecting to Node.js upstream inside a Docker container
I have the following setup:

Docker container which has supervisord as the entry point,
supervisord runs a Node.js process and Nginx proxy.
the Nginx port is exposed outside.

on the host machine, another Nginx is used for SSL termination and vhost routing / load balancing, its used as a proxy for the Docker containers.

I'm experiencing some strange issues, where sometimes the Nginx server inside the Docker containers is reporting errors with connecting to the upstream Node.js servers. seems like the HTTP requests are 200 so maybe it auto retries even if there's only one upstream?!

also, no sign of errors or crashes in the Node.js process stdout/stderr..

This are the errors that I see:

```<code>2014/07/31 12:48:54 [error] 15#0: *10 connect() failed (111: Connection refused) while connecting to upstream, client: 172.17.42.1, server: f074d2f4389f, request: "GET /users/me HTTP/1.1", upstream: "http://[::1]:3000/users/me", host: "xxx.xxx.com", referrer: "https://xxx.xxx.com/"
</code>```

what can be the problem?

This is the supervisord config files:

```<code>[supervisord]
nodaemon=true
logfile=/var/log/supervisor/supervisord.log    ; supervisord log file
logfile_maxbytes=50MB                           ; maximum size of logfile before rotation
logfile_backups=10                              ; number of backed up logfiles
loglevel=info                                  ; info, debug, warn, trace
pidfile=/var/run/supervisord.pid                ; pidfile location
childlogdir=/var/log/supervisor/               ; where child log files will live"
</code>```

and this file is included in other files:

```<code>[include]
files = /etc/supervisor/conf.d/supervisord.conf

[program:api]
command=node api-cluster.js
directory=/src
autorestart=true
startretries=100000000
stdout_logfile=/var/log/supervisor/api_stdout.log
stderr_logfile=/var/log/supervisor/api_stderr.log

[program:nginx]
command=/usr/sbin/nginx
autorestart=true
startretries=100000000
stdout_logfile=/var/log/supervisor/nginx_stdout.log
stderr_logfile=/var/log/supervisor/nginx_stderr.log"
</code>```

and this is the Nginx conf file inside the Docker container:

```<code># -------------------------------------------------------------------
#                         Nginx configuraiton
# -------------------------------------------------------------------

worker_processes 4;
daemon off;

error_log   stderr  info;
pid         /var/run/nginx.pid;

events {
    #use epoll;
    worker_connections 768;
}

http {
    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;

    include     /etc/nginx/mime.types;
    default_type application/octet-stream;

    log_format main 'ip=\$http_x_real_ip [\$time_local] '
    '"\$request" \$status \$body_bytes_sent "\$http_referer" '
    '"\$http_user_agent"' ;

    ##
    # Gzip Settings
    ##

    gzip on;
    gzip_disable "msie6";

    upstream app_proxy {
        server localhost:3000;      # nodejs server
    }

    server {
        listen          80 deferred;
        server_name     \$hostname;
        access_log      /dev/stdout main;

        location ~ ^/(images/|img/|javascript/|js/|css/|stylesheets/|flash/|media/|static/|scripts/|views/|styles/|bower_components/|robots.txt|humans.txt|favicon.ico|home/|html|xml) {
            root /src/web/public;
            access_log off;
            expires max;
        }

        location / {
            proxy_redirect off;
            #proxy_set_header X-Real-IP \$remote_addr;
            #proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto \$scheme;
            proxy_set_header Host \$http_host;
            proxy_set_header X-NginX-Proxy true;
            proxy_intercept_errors off;
            proxy_pass       http://app_proxy/;
        }
    }
}
</code>```

答:
Nginx connects to nodejs on the IPv6 loopback [::1]. nodejs is probably just listening on IPv4.

Try setting

```<code>upstream api {
    server 127.0.0.1:5000;
}
</code>```

Body:
I have the following setup:

Docker container which has supervisord as the entry point,
supervisord runs a Node.js process and Nginx proxy.
the Nginx port is exposed outside.

on the host machine, another Nginx is used for SSL termination and vhost routing / load balancing, its used as a proxy for the Docker containers.

I'm experiencing some strange issues, where sometimes the Nginx server inside the Docker containers is reporting errors with connecting to the upstream Node.js servers. seems like the HTTP requests are 200 so maybe it auto retries even if there's only one upstream?!

also, no sign of errors or crashes in the Node.js process stdout/stderr..

This are the errors that I see:

2014/07/31 12:48:54 [error] 15#0: *10 connect() failed (111: Connection refused) while connecting to upstream, client: 172.17.42.1, server: f074d2f4389f, request: "GET /users/me HTTP/1.1", upstream: "http://[::1]:3000/users/me", host: "xxx.xxx.com", referrer: "https://xxx.xxx.com/"

what can be the problem?

This is the supervisord config files:

[supervisord]
nodaemon=true
logfile=/var/log/supervisor/supervisord.log    ; supervisord log file
logfile_maxbytes=50MB                           ; maximum size of logfile before rotation
logfile_backups=10                              ; number of backed up logfiles
loglevel=info                                  ; info, debug, warn, trace
pidfile=/var/run/supervisord.pid                ; pidfile location
childlogdir=/var/log/supervisor/               ; where child log files will live"

and this file is included in other files:

[include]
files = /etc/supervisor/conf.d/supervisord.conf

[program:api]
command=node api-cluster.js
directory=/src
autorestart=true
startretries=100000000
stdout_logfile=/var/log/supervisor/api_stdout.log
stderr_logfile=/var/log/supervisor/api_stderr.log

[program:nginx]
command=/usr/sbin/nginx
autorestart=true
startretries=100000000
stdout_logfile=/var/log/supervisor/nginx_stdout.log
stderr_logfile=/var/log/supervisor/nginx_stderr.log"

and this is the Nginx conf file inside the Docker container:

# -------------------------------------------------------------------
#                         Nginx configuraiton
# -------------------------------------------------------------------

worker_processes 4;
daemon off;

error_log   stderr  info;
pid         /var/run/nginx.pid;

events {
    #use epoll;
    worker_connections 768;
}

http {
    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;

    include     /etc/nginx/mime.types;
    default_type application/octet-stream;

    log_format main 'ip=\$http_x_real_ip [\$time_local] '
    '"\$request" \$status \$body_bytes_sent "\$http_referer" '
    '"\$http_user_agent"' ;

    ##
    # Gzip Settings
    ##

    gzip on;
    gzip_disable "msie6";

    upstream app_proxy {
        server localhost:3000;      # nodejs server
    }

    server {
        listen          80 deferred;
        server_name     \$hostname;
        access_log      /dev/stdout main;

        location ~ ^/(images/|img/|javascript/|js/|css/|stylesheets/|flash/|media/|static/|scripts/|views/|styles/|bower_components/|robots.txt|humans.txt|favicon.ico|home/|html|xml) {
            root /src/web/public;
            access_log off;
            expires max;
        }

        location / {
            proxy_redirect off;
            #proxy_set_header X-Real-IP \$remote_addr;
            #proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto \$scheme;
            proxy_set_header Host \$http_host;
            proxy_set_header X-NginX-Proxy true;
            proxy_intercept_errors off;
            proxy_pass       http://app_proxy/;
        }
    }
}

Body:
Nginx connects to nodejs on the IPv6 loopback [::1]. nodejs is probably just listening on IPv4.

Try setting

upstream api {
    server 127.0.0.1:5000;
}


问:
How to convert a html table obtained as a parameter on success of a Jquery $.get method
I have a Jquery $.get function which calls a controller which in turn returns a View containing a html table.

```<code> $.get("/VM/VmProcesses?pr=" + processes, function (process)
 {
        oTable.fnOpen(nTr, process, 'table');
 }
</code>```

This works fine and displays the table as intended. But i cant get this returned table to convert to a datatable using Jquery datatable() method as shown below.

```<code> $.get("/VM/VmProcesses?pr=" + processes, function (process)
 {
        oTable.fnOpen(nTr, process, 'table');
        $('#mytable').datatable();
 }
</code>```

I get an error Uncaught TypeError: $(...).datatable is not a function
Any way to get this working ? Also, i tried converting the table in the view itself and that didnt work either.

答:
Should it be:</p>

```<code> $('#mytable').DataTable();
</code>```

Body:
I have a Jquery $.get function which calls a controller which in turn returns a View containing a html table.

 $.get("/VM/VmProcesses?pr=" + processes, function (process)
 {
        oTable.fnOpen(nTr, process, 'table');
 }

This works fine and displays the table as intended. But i cant get this returned table to convert to a datatable using Jquery datatable() method as shown below.

 $.get("/VM/VmProcesses?pr=" + processes, function (process)
 {
        oTable.fnOpen(nTr, process, 'table');
        $('#mytable').datatable();
 }

I get an error Uncaught TypeError: $(...).datatable is not a function
Any way to get this working ? Also, i tried converting the table in the view itself and that didnt work either.

Body:
Should it be:

 $('#mytable').DataTable();


问:
How to create base class for all my symfony controllers
I want to create a base controller class for all my controllers in Symfony, I am very new to Symfony, so don't be angry with dumb question. I am asking this question because I can't do something like this

```<code>    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    class AbstractController extends Controller
    {
        public function __construct()
        {
            //...... check access level
            $user = $this->getUser(); //This is not working, I don't have access to the Controller(the base class) properties
        }
    }
</code>```

Now one of my controllers

```<code>    class UserController extends AbstractController
    {
        public deleteUserAction(Request $request)
        {
          var_dump($this);// this will dump an empty class that is not instance of Symfony\Bundle\FrameworkBundle\Controller\Controller
          //.... delete user
        }
    }
</code>```

What is the best way to do this? please...
EDIT....
What I really want to do is to check whether a user privilege level is enough to access a particular action(e.g. deleteUserAction()) in a particular controller(e.g. UserController), I have a class that attach privilege level to all actions in all controllers. The check will be very efficient if it happens in a parent controller (e.g. BaseController's constructor) which is executed before UserController->deleteUserAction() but in the base controller I don't have access to $this.
I have tried voter and ACL none help my situation.
Thanks in advance.

答:
I think second one is the best way to create your own class and use common function in it.

If you want to add some common functions of controller then it is not the proper way to add it into the Symfony default controller, Instead you can create BaseController and extend your all the controller with BaseController and your BaseController should extends Controller.

By this way the default controller of the symfony stay untouched.

Body:
I want to create a base controller class for all my controllers in Symfony, I am very new to Symfony, so don't be angry with dumb question. I am asking this question because I can't do something like this

    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    class AbstractController extends Controller
    {
        public function __construct()
        {
            //...... check access level
            $user = $this->getUser(); //This is not working, I don't have access to the Controller(the base class) properties
        }
    }

Now one of my controllers

    class UserController extends AbstractController
    {
        public deleteUserAction(Request $request)
        {
          var_dump($this);// this will dump an empty class that is not instance of Symfony\Bundle\FrameworkBundle\Controller\Controller
          //.... delete user
        }
    }

What is the best way to do this? please...
EDIT....
What I really want to do is to check whether a user privilege level is enough to access a particular action(e.g. deleteUserAction()) in a particular controller(e.g. UserController), I have a class that attach privilege level to all actions in all controllers. The check will be very efficient if it happens in a parent controller (e.g. BaseController's constructor) which is executed before UserController->deleteUserAction() but in the base controller I don't have access to $this.
I have tried voter and ACL none help my situation.
Thanks in advance.


问:
How to search for subarrays with a specific ids and generate a new array from their elements?
I've been trying to organize data into a multidimensional array from a foreach loop but the data is all over the place.

This is what I coded:

```<code>$productIDs = array(
    '0' => array(
        'product_id' => '10',
        'product_name' => 'Test',
        'product_file' => 'file10',
        'product_image' => 'https://i.imgur.com/dXb6.png',
    ),
    '1' => array(
        'product_id' => '20',
        'product_name' => 'Test1',
        'product_file' => 'file20',
        'product_image' => 'https://i.imgur.com/MuP8.png',
    ),
    '2' => array(
        'product_id' => '30',
        'product_name' => 'No product',
        'product_file' => 'file30',
        'product_image' => 'https://i.imgur.com/kWP3.png',
    )
);

$urlIDs  = array(10,20);

function getFiles($productIDs, $urlIDs)
{
    foreach($productIDs as $ids)
    {
        foreach($urlIDs as $products)
        {
            if(in_array($products, $ids)){
                $data1[] = $ids['product_id'];
                $data2[] = $ids['product_file'];
                $data3[] = $ids['product_image'];
            }
        }
    }
    return array($data1, $data2, $data3);
}
$getFiles = getFiles($productIDs, $urlIDs);
</code>```

And the output for the following is:

```<code>Array
(
    [0] => Array
        (
            [0] => 10
            [1] => 20
        )

    [1] => Array
        (
            [0] => file10
            [1] => file20
        )

    [2] => Array
        (
            [0] => https://i.imgur.com/dXb6.png
            [1] => https://i.imgur.com/MuP8.png
        )

)
</code>```

Although what I'm trying to accomplish is:

```<code>Array
(
    [0] => Array
        (
            [id] => 10
            [file] => file10
            [image] => https://i.imgur.com/dXb6.png
        )

    [1] => Array
        (
            [id] => 20
            [file] => file20
            [image] => https://i.imgur.com/MuP8.png
        )

)
</code>```

I tried the following:

```<code>function getFiles($productIDs, $urlIDs)
{
    foreach($productIDs as $ids)
    {
        foreach($urlIDs as $products)
        {
            if(in_array($products, $ids)){
                $data['id'] = $ids['product_id'];
                $data['file'] = $ids['product_file'];
                $data['image'] = $ids['product_image'];
            }
        }
    }
    return array($data);
}
</code>```

Which returns the following without looping through all id's, it should return both arrays since both id's are matching.

```<code>Array
(
    [0] => Array
        (
            [id] => 20
            [file] => file20
            [image] => https://i.imgur.com/MuP8.png
        )

)
</code>```

You could say the first batch of code without the specific key names isn't what I want, but I just wanted to show what I had tried. The last batch works (with key names), but doesn't loop through all of the $urlIDs, and for some reason that I can't understand, the code isn't even returning id = 10, it's returning id = 20, though it's second in the array. If someone could explain why this is happening I'd appreciate it.

In case it's useful: https://eval.in/764083

答:
Try this version

```<code>    <?php
    /**
     * Created by PhpStorm.
     * User: lenovo
     * Date: 3/30/2017
     * Time: 5:53 AM
     */
    $productIDs = array(
        '0' => array(
            'product_id' => '10',
            'product_name' => 'Test',
            'product_file' => 'file10',
            'product_image' => 'https://i.imgur.com/dXb6.png',
        ),
        '1' => array(
            'product_id' => '20',
            'product_name' => 'Test1',
            'product_file' => 'file20',
            'product_image' => 'https://i.imgur.com/MuP8.png',
        ),
        '2' => array(
            'product_id' => '30',
            'product_name' => 'No product',
            'product_file' => 'file30',
            'product_image' => 'https://i.imgur.com/kWP3.png',
        )
    );

    $urlIDs  = array(10,20);

    $ouput = [];

    foreach($productIDs as $product){

        if(in_array($product['product_id'],$urlIDs)){
           $ouput[] = array("id"=>$product["product_id"], "file"=>$product["product_file"], "image"=>$product["product_image"]);
        }
    }

   echo "```";
     print_r($ouput);
    echo "```";
</code>```

Check the

Good Luck

Body:
I've been trying to organize data into a multidimensional array from a foreach loop but the data is all over the place.

This is what I coded:

$productIDs = array(
    '0' => array(
        'product_id' => '10',
        'product_name' => 'Test',
        'product_file' => 'file10',
        'product_image' => 'https://i.imgur.com/dXb6.png',
    ),
    '1' => array(
        'product_id' => '20',
        'product_name' => 'Test1',
        'product_file' => 'file20',
        'product_image' => 'https://i.imgur.com/MuP8.png',
    ),
    '2' => array(
        'product_id' => '30',
        'product_name' => 'No product',
        'product_file' => 'file30',
        'product_image' => 'https://i.imgur.com/kWP3.png',
    )
);

$urlIDs  = array(10,20);

function getFiles($productIDs, $urlIDs)
{
    foreach($productIDs as $ids)
    {
        foreach($urlIDs as $products)
        {
            if(in_array($products, $ids)){
                $data1[] = $ids['product_id'];
                $data2[] = $ids['product_file'];
                $data3[] = $ids['product_image'];
            }
        }
    }
    return array($data1, $data2, $data3);
}
$getFiles = getFiles($productIDs, $urlIDs);

And the output for the following is:

Array
(
    [0] => Array
        (
            [0] => 10
            [1] => 20
        )

    [1] => Array
        (
            [0] => file10
            [1] => file20
        )

    [2] => Array
        (
            [0] => https://i.imgur.com/dXb6.png
            [1] => https://i.imgur.com/MuP8.png
        )

)

Although what I'm trying to accomplish is:

Array
(
    [0] => Array
        (
            [id] => 10
            [file] => file10
            [image] => https://i.imgur.com/dXb6.png
        )

    [1] => Array
        (
            [id] => 20
            [file] => file20
            [image] => https://i.imgur.com/MuP8.png
        )

)

I tried the following:

function getFiles($productIDs, $urlIDs)
{
    foreach($productIDs as $ids)
    {
        foreach($urlIDs as $products)
        {
            if(in_array($products, $ids)){
                $data['id'] = $ids['product_id'];
                $data['file'] = $ids['product_file'];
                $data['image'] = $ids['product_image'];
            }
        }
    }
    return array($data);
}

Which returns the following without looping through all id's, it should return both arrays since both id's are matching.

Array
(
    [0] => Array
        (
            [id] => 20
            [file] => file20
            [image] => https://i.imgur.com/MuP8.png
        )

)

You could say the first batch of code without the specific key names isn't what I want, but I just wanted to show what I had tried. The last batch works (with key names), but doesn't loop through all of the $urlIDs, and for some reason that I can't understand, the code isn't even returning id = 10, it's returning id = 20, though it's second in the array. If someone could explain why this is happening I'd appreciate it.

In case it's useful: https://eval.in/764083

Body:
Try this version

    <?php
    /**
     * Created by PhpStorm.
     * User: lenovo
     * Date: 3/30/2017
     * Time: 5:53 AM
     */
    $productIDs = array(
        '0' => array(
            'product_id' => '10',
            'product_name' => 'Test',
            'product_file' => 'file10',
            'product_image' => 'https://i.imgur.com/dXb6.png',
        ),
        '1' => array(
            'product_id' => '20',
            'product_name' => 'Test1',
            'product_file' => 'file20',
            'product_image' => 'https://i.imgur.com/MuP8.png',
        ),
        '2' => array(
            'product_id' => '30',
            'product_name' => 'No product',
            'product_file' => 'file30',
            'product_image' => 'https://i.imgur.com/kWP3.png',
        )
    );

    $urlIDs  = array(10,20);

    $ouput = [];

    foreach($productIDs as $product){

        if(in_array($product['product_id'],$urlIDs)){
           $ouput[] = array("id"=>$product["product_id"], "file"=>$product["product_file"], "image"=>$product["product_image"]);
        }
    }

   echo "<pre>";
     print_r($ouput);
    echo "</pre>";

Check the

Good Luck


问:
Handle multiple request Alamofire while Search
I'm having SearchContoller and whenever user starts searching I have to display the result. But continuous API calls over here sometimes old result remains even if there is no data received from API.
How to queue them so that there won't be any misplaced data viewed.</p>

```<code>    fileprivate func getData(searchString: String){
        getFriendList = false
        guard let currentUser = AppController.shared.currentUser else { return }
//        self.friendsList.removeAll()
        APIHandler.shared.doAPIGetCallForUrl(Constants.kcFindFriends + "?UserId=" + String(currentUser.userId) + "&seachString=" + searchString + "&PageNumber=" + String(pageNumber) , callback: { [weak self](success, jsonData, error) in
            guard let weakSelf = self else { return }
            guard success == true else {
//                weakSelf.findFriendsTableView.reloadData()
                return
            }
            guard let json = jsonData else { return }
            guard let findFriendList: [FriendList] = json.value() else { return }
            weakSelf.friendsList.append(contentsOf: findFriendList)
            weakSelf.findFriendsTableView.reloadData()
        })
    }

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    searchString = searchText
    pageNumber = 1
    getData(searchString: searchString)
}
</code>```

答:
@BhavinRamani Reply</p>

```<code> func searchBar(searchBar: UISearchBar!, textDidChange searchText: String!) {
    NSObject.cancelPreviousPerformRequestsWithTarget(withTarget: self, selector: #selector(YourView.getData(searchString:)), object: searchBar)

     if !searchBar.text.isEmpty {
        dispatch_after_delay(0.25) {
           searchString = searchText
           pageNumber = 1
          getData(searchString: searchString)
        }
    } else {

         }

}
</code>```

Body:
I'm having SearchContoller and whenever user starts searching I have to display the result. But continuous API calls over here sometimes old result remains even if there is no data received from API.
How to queue them so that there won't be any misplaced data viewed.

    fileprivate func getData(searchString: String){
        getFriendList = false
        guard let currentUser = AppController.shared.currentUser else { return }
//        self.friendsList.removeAll()
        APIHandler.shared.doAPIGetCallForUrl(Constants.kcFindFriends + "?UserId=" + String(currentUser.userId) + "&seachString=" + searchString + "&PageNumber=" + String(pageNumber) , callback: { [weak self](success, jsonData, error) in
            guard let weakSelf = self else { return }
            guard success == true else {
//                weakSelf.findFriendsTableView.reloadData()
                return
            }
            guard let json = jsonData else { return }
            guard let findFriendList: [FriendList] = json.value() else { return }
            weakSelf.friendsList.append(contentsOf: findFriendList)
            weakSelf.findFriendsTableView.reloadData()
        })
    }

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    searchString = searchText
    pageNumber = 1
    getData(searchString: searchString)
}

Body:
@BhavinRamani Reply

 func searchBar(searchBar: UISearchBar!, textDidChange searchText: String!) {
    NSObject.cancelPreviousPerformRequestsWithTarget(withTarget: self, selector: #selector(YourView.getData(searchString:)), object: searchBar)

     if !searchBar.text.isEmpty {
        dispatch_after_delay(0.25) {
           searchString = searchText
           pageNumber = 1
          getData(searchString: searchString)
        }
    } else {

         }

}


问:
SQL Query question
No particular DBMS in mind, how would I do the following:

```<code># There are many tables per one restaurant, many napkins per one table
# Pseudo SQL

SELECT RESTAURANT WHERE ID = X;
SELECT ALL TABLES WHERE RESTAURANT_ID = RESTAURANT.ID;
SELECT ALL NAPKINS WHERE TABLE_ID = TABLE.ID;
</code>```

But, all in one query? I've used a JOIN to get all the tables in the same query as restaurant, but is it possible to get all napkins for each table as well, in the same query?

答:
You would definitely end up in repeating Tables and restaurant information on the rows, like:

Restaurant1 Table1 Napkin1

Restaurant1 Table1 Napkin2

Restaurant1 Table1 Napkin3

Restaurant1 Table2 Napkin4

Restaurant2 Table1 Napkin5

Title: SQL Query question

Body:
No particular DBMS in mind, how would I do the following:

# There are many tables per one restaurant, many napkins per one table
# Pseudo SQL

SELECT RESTAURANT WHERE ID = X;
SELECT ALL TABLES WHERE RESTAURANT_ID = RESTAURANT.ID;
SELECT ALL NAPKINS WHERE TABLE_ID = TABLE.ID;

But, all in one query? I've used a JOIN to get all the tables in the same query as restaurant, but is it possible to get all napkins for each table as well, in the same query?


问:
Dynamically add cells to table rows and dynamically create table rows with reactjs
I'm building a tbody dynamically in reactjs. I have a function that creates seed data from a loop with this:

```<code>accounts.push(
  <tr key={i}>
  <td>{obj.type}</td>
  <td>{obj.name}</td>
  <td>{obj.balance}</td>
  <td>{obj.id}</td>
</tr>);
</code>```

It works and i can populate rows in react with
{accounts}
. Now I'm trying to dynamically add . I tried the following but it creates a string and ReactJS throws error Warning: validateDOMNesting(...): Text nodes cannot appear as a child of
:

```<code>let fields = ['type', 'name', 'balance', 'id'];

data.forEach( function(element, index) {
  let fieldsLabel = `<tr key=${++i}>`;
  fields.forEach( function(key, index) {
    fieldsLabel = fieldsLabel.concat(`<td>${element[key]}</td>`);
  });
  fieldsLabel = fieldsLabel.concat(`</tr>`);
  accounts.push(Array.from(fieldsLabel));
});
</code>```

I'd like to do something simple like the following but it won't work because of the open
 tag:

```<code>    data.forEach( function(element, index) {
      let row = []
      row.push(<tr key={++i}>)
      fields.forEach( function(key, index) {
        row.push(<td>{element[key]}</td>)
      });
      row.push(</tr>)
      accounts.push(row.join(''));
    });
</code>```

How do you dynamically push  into an array so it can be used in reactjs like {accounts}?

答:
How do you dynamically push  into an array so it can be used in reactjs like {accounts}?

You have the right idea but you're storing a string into fieldsLabel instead of a JSX element. Don't wrap your elements in backticks.

Don't use strings to create elements. Remember that JSX transpiles to React.createElement calls. If you create an element using strings then babel won't transpile that. Refer to the reactjs documentation to learn more about how JSX works.

Body:
I'm building a tbody dynamically in reactjs. I have a function that creates seed data from a loop with this:

accounts.push(

  {obj.type}
  {obj.name}
  {obj.balance}
  {obj.id}

);

It works and i can populate rows in react with
{accounts}
. Now I'm trying to dynamically add . I tried the following but it creates a string and ReactJS throws error Warning: validateDOMNesting(...): Text nodes cannot appear as a child of
:

let fields = ['type', 'name', 'balance', 'id'];

data.forEach( function(element, index) {
  let fieldsLabel = `<tr key=${++i}>`;
  fields.forEach( function(key, index) {
    fieldsLabel = fieldsLabel.concat(`<td>${element[key]}</td>`);
  });
  fieldsLabel = fieldsLabel.concat(`</tr>`);
  accounts.push(Array.from(fieldsLabel));
});

I'd like to do something simple like the following but it won't work because of the open
 tag:

    data.forEach( function(element, index) {
      let row = []
      row.push(
)
      fields.forEach( function(key, index) {
        row.push({element[key]}	)
      });
      row.push(
)
      accounts.push(row.join(''));
    });

How do you dynamically push  into an array so it can be used in reactjs like {accounts}?


答:
try this</p>

```<code>data.map((item,i) => {
  return(
    <tr key={++i}>
      {fields.length > 0 && fields.map((field,j) => {
         return(
            <td>{item[field]}</td>
         )
      })
    </tr>
  );
});
</code>```

Title: Dynamically add cells to table rows and dynamically create table rows with reactjs

Body:
try this

data.map((item,i) => {
  return(
    <tr key={++i}>
      {fields.length > 0 && fields.map((field,j) => {
         return(
            <td>{item[field]}</td>
         )
      })
    </tr>
  );
});


问:
Pattern within a pattern?
I want to capture Alta, Utah, USA from asd Alta, Utah, USA qwe. Basically I'm trying to capture places from a text. It won't be a perfect method, but the places must start with a capital and use a comma, followed by another word with a capital.

So far, I have wrote:

```<code>\s[A-Z][a-z]+[,]?
</code>```

I want to do multiple words, not just the first word, Alta. This is my attempt to use square brackets inside other square brackets.

```<code>[\s[A-Z][a-z]+[,]?]+
</code>```

But that doesn't work, so it must be syntactically incorrect.

答:
Updated as per OP's comment:

```<code>(?:\s*[A-Z][A-Za-z]+[,\s])+
</code>```

Demo

Original Answer:

```<code>\b([A-Z][a-zA-Z]+),?
</code>```

Original Demo

And you will get the names of the country in group 1 for each match

Title: Pattern within a pattern?

Body:
I want to capture Alta, Utah, USA from asd Alta, Utah, USA qwe. Basically I'm trying to capture places from a text. It won't be a perfect method, but the places must start with a capital and use a comma, followed by another word with a capital.

So far, I have wrote:

\s[A-Z][a-z]+[,]?

I want to do multiple words, not just the first word, Alta. This is my attempt to use square brackets inside other square brackets.

[\s[A-Z][a-z]+[,]?]+

But that doesn't work, so it must be syntactically incorrect.

Body:
Updated as per OP's comment:

(?:\s*[A-Z][A-Za-z]+[,\s])+

Demo

Original Answer:

\b([A-Z][a-zA-Z]+),?

Original Demo

And you will get the names of the country in group 1 for each match


问:
Copying audio file, issue with pointers
I was wondering if someone could help me with a problem that I'm having. I'm fairly sure that it's a pointer issue (read: I'm VERY much a C beginner), but I've been struggling with it for a fair while and have been unable to fix the issue (despite reading reference pages).

My code is meant to copy a .WAV file using two functions (the function prototypes are fixed). First it reads the file, then it writes a new file using the data samples from the old file. The header is defined in "R_WAV.h" as a typedef struct. The code is run from this:

```<code>#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <malloc.h>
#include "R_WAV.h"

//Function Declarations
int read_WAV(header_type *header, char **data, char *filename);
int write_WAV(header_type *header, char *data, char *filename);

int main()
{
    //Run read_WAV
    {
        header_type *header;
        char *filename[] = {//Various files};
        char **data;
        read_WAV(header, data, *filename);
    }
    //Run write_WAV
    {
        header_type *header;
        char *filename[] = {//Various files};
        char *data;
        write_WAV(header, data, *filename);
    }

    //Run read_WAV again on new files to ensure header info is valid
    {
    header_type *header;
    char *filename[] = {//output files from write};
    char *data;
    read_WAV(header, data, *filename);
    }

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

The read_WAV function I've written (abbreviated slightly) is:

```<code>int read_WAV(header_type *header, char **data, char *filename)
{

    unsigned char   buffer4[4];
    unsigned char   buffer2[2];

    FILE    *fp = fopen(filename, "rb");    //Open file

    //Code here that checks if file successfully opened

    //If file valid, find length of file
    fseek(fp, 0L, SEEK_END);    //Place position at EoF
    int size = ftell(fp);       //Read the current value
    rewind(fp);                 //Reset position

    //Code here that checks if file size < min. header size, if true exits

    header = (void*)malloc(size);

    //Reading RIFF string
    fread(header->ChunkID, sizeof(header->ChunkID), 1, fp);
    printf("\nChunkID: %s \n", (header->ChunkID));
</code>```

And so on, until it comes time to read the data:

```<code>//Read DATA samples
char *buffer_data = (char*)malloc(header->Subchunk2Size);
fread(buffer_data,1,(header->Subchunk2Size),fp);

//Error checking code here for if buffer==NULL

*data = buffer_data;

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

The write_WAV function is:

```<code>int write_WAV(header_type *header, char *data, char *filename)
{
    char n_file[50];                            //Init. for new filename
    int data_size = header->Subchunk2Size;      //Hold size of data chunk

    //CODE TO ALTER FILENAME (working properly)

    //Open new file (COPY_of_filename)
    FILE * fp_w = fopen(n_file, "wb");

    //Check to see if file was successfully created
    if (fp_w==NULL)
    {
        printf("\nUnable to create file.");
        return(-1);
    }

    //Write header to new file (first 44 bytes)
    fwrite(header, 1, 44, fp_w);

    //Write data to new file
    fwrite(data, 1, data_size, fp_w);
fclose(fp_w);
return (1);

}
</code>```

I'm running into two main issues:

1) I can only get the header info (first 44 bytes) to write properly in write_WAV() if I open one of the .WAV files in that function, then use fread and a buffer to store it. Does it have to be done this way? Is there another way to use the *header that will result in this data being accessible from read_WAV() without needing to reopen the old file in write_WAV()?

2) I can't get the data samples to copy over properly. Even when I read in the header as above (and check that the header info is all correct), all I get is corrupt noise upon opening the new file. I've been trying to research this, but I've gotten nowhere. Could someone help explain/point to the mistakes in what I've done, and what I need to do in order to resolve them?

I know this is really simple stuff, and I wish that my brain was working enough to figure it out by myself. Like I said, I've read reference pages, but I'm still not getting anywhere. Not really firing on all cylinders right now.

Thank you for any (much needed) assistance!

答:
Your problem is the block scoping of data in main in a few places.

That is, when you read in the file, because of variable scoping, you lose the pointer to the data. That is, when you do the write, the pointer it uses points to random memory.

I think you also have the same problem for the header pointer [although I didn't address that issue below, the fix would be similar]. Also, note that in the two read blocks, the type used for header is inconsistent even though they do the same thing.

Here's a version annotated with the bugs:

```<code>int main()
{
    //Run read_WAV
    {
        header_type *header;
        char *filename[] = {//Various files};
// NOTE/BUG: this is scoped to _this_ block, so the write section below won't
// see it
// NOTE/BUG: this should be char *data and the function call should use &data
        char **data;
        read_pcm_wavefile(header, data, *filename);
    }
    //Run write_WAV
    {
        pcm_wavefile_header_type *header;
        char *filename[] = {//Various files};
// NOTE/BUG: this scoped 'data' declaration has none of the data in the read
// sectioon above
        char *data;
        write_pcm_wavefile(header, data, *filename);
    }

    //Run read_WAV again on new files to ensure header info is valid
    {
    pcm_wavefile_header_type *header;
    char *filename[] = {//output files from write};
    char *data;
    read_pcm_wavefile(header, data, *filename);
    }

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

Here's a fixed version:

```<code>int main()
{
    char *data;

    //Run read_WAV
    {
        header_type *header;
        char *filename[] = {//Various files};
        read_pcm_wavefile(header, &data, *filename);
    }

    //Run write_WAV
    {
        pcm_wavefile_header_type *header;
        char *filename[] = {//Various files};
        write_pcm_wavefile(header, data, filename[0]);
    }

    free(data);

    //Run read_WAV again on new files to ensure header info is valid
    {
        pcm_wavefile_header_type *header;
        char *filename[] = {//output files from write};
        read_pcm_wavefile(header, &data, filename[0]);
    }

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

UPDATE:

I've fixed that up. Still unable to get a proper output, which I'm thinking is in the passing of the data/pointer from each function?

As I mentioned you need to do the same for header because main needs the pointer to be filled in by your read function. As it is, after the read call, the value of header in main is unchanged (i.e. not updated by read_WAV as you'd like).

Change:

```<code>int read_WAV(header_type *header, char **data, char *filename)
</code>```

Into:

```<code>int read_WAV(header_type **header, char **data, char *filename)
</code>```

And, make all corresponding adjustments in main and read_WAV

Also, apply the same scoping fix in main for header that was done for data (i.e. header should not be block scoped, but, rather function scoped).

Because, even with the prototype change to read_WAV, main would lose the header value that read_WAV tried to pass back and write_WAV would get a garbage header pointer.

After you get this working, think about the temporal duration of the block scoped variables vs function scoped variables. In other words, if you set a variable, when does the value "go out of scope" [and become invalid].

For comparison, here's a version that does not use block scoped variables:

```<code>int
main(void)
{
    char *data;
    header_type *header;
    char *infiles[FILECOUNT] = {//Various files};
    char *outfiles[FILECOUNT] = {//Various files};

    for (int fidx = 0;  fidx < FILECOUNT;  ++fidx) {
        //Run read_WAV
        read_pcm_wavefile(&header, &data, infiles[fidx]);

        //Run write_WAV
        write_pcm_wavefile(header, data, outfiles[fidx]);

        free(header);
        free(data);

        //Run read_WAV again on new files to ensure header info is valid
        read_pcm_wavefile(&header, &data, outfiles[fidx]);

        free(header);
        free(data);
    }

    return 0;
}
</code>```

Title: Copying audio file, issue with pointers

Body:
I was wondering if someone could help me with a problem that I'm having. I'm fairly sure that it's a pointer issue (read: I'm VERY much a C beginner), but I've been struggling with it for a fair while and have been unable to fix the issue (despite reading reference pages).

My code is meant to copy a .WAV file using two functions (the function prototypes are fixed). First it reads the file, then it writes a new file using the data samples from the old file. The header is defined in "R_WAV.h" as a typedef struct. The code is run from this:

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <malloc.h>
#include "R_WAV.h"

//Function Declarations
int read_WAV(header_type *header, char **data, char *filename);
int write_WAV(header_type *header, char *data, char *filename);

int main()
{
    //Run read_WAV
    {
        header_type *header;
        char *filename[] = {//Various files};
        char **data;
        read_WAV(header, data, *filename);
    }
    //Run write_WAV
    {
        header_type *header;
        char *filename[] = {//Various files};
        char *data;
        write_WAV(header, data, *filename);
    }

    //Run read_WAV again on new files to ensure header info is valid
    {
    header_type *header;
    char *filename[] = {//output files from write};
    char *data;
    read_WAV(header, data, *filename);
    }

    return(0);
}

The read_WAV function I've written (abbreviated slightly) is:

int read_WAV(header_type *header, char **data, char *filename)
{

    unsigned char   buffer4[4];
    unsigned char   buffer2[2];

    FILE    *fp = fopen(filename, "rb");    //Open file

    //Code here that checks if file successfully opened

    //If file valid, find length of file
    fseek(fp, 0L, SEEK_END);    //Place position at EoF
    int size = ftell(fp);       //Read the current value
    rewind(fp);                 //Reset position

    //Code here that checks if file size < min. header size, if true exits

    header = (void*)malloc(size);

    //Reading RIFF string
    fread(header->ChunkID, sizeof(header->ChunkID), 1, fp);
    printf("\nChunkID: %s \n", (header->ChunkID));

And so on, until it comes time to read the data:

//Read DATA samples
char *buffer_data = (char*)malloc(header->Subchunk2Size);
fread(buffer_data,1,(header->Subchunk2Size),fp);

//Error checking code here for if buffer==NULL

*data = buffer_data;

fclose(fp);
return(1);
}

The write_WAV function is:

int write_WAV(header_type *header, char *data, char *filename)
{
    char n_file[50];                            //Init. for new filename
    int data_size = header->Subchunk2Size;      //Hold size of data chunk

    //CODE TO ALTER FILENAME (working properly)

    //Open new file (COPY_of_filename)
    FILE * fp_w = fopen(n_file, "wb");

    //Check to see if file was successfully created
    if (fp_w==NULL)
    {
        printf("\nUnable to create file.");
        return(-1);
    }

    //Write header to new file (first 44 bytes)
    fwrite(header, 1, 44, fp_w);

    //Write data to new file
    fwrite(data, 1, data_size, fp_w);
fclose(fp_w);
return (1);

}

I'm running into two main issues:

1) I can only get the header info (first 44 bytes) to write properly in write_WAV() if I open one of the .WAV files in that function, then use fread and a buffer to store it. Does it have to be done this way? Is there another way to use the *header that will result in this data being accessible from read_WAV() without needing to reopen the old file in write_WAV()?

2) I can't get the data samples to copy over properly. Even when I read in the header as above (and check that the header info is all correct), all I get is corrupt noise upon opening the new file. I've been trying to research this, but I've gotten nowhere. Could someone help explain/point to the mistakes in what I've done, and what I need to do in order to resolve them?

I know this is really simple stuff, and I wish that my brain was working enough to figure it out by myself. Like I said, I've read reference pages, but I'm still not getting anywhere. Not really firing on all cylinders right now.

Thank you for any (much needed) assistance!

Body:
Your problem is the block scoping of data in main in a few places.

That is, when you read in the file, because of variable scoping, you lose the pointer to the data. That is, when you do the write, the pointer it uses points to random memory.

I think you also have the same problem for the header pointer [although I didn't address that issue below, the fix would be similar]. Also, note that in the two read blocks, the type used for header is inconsistent even though they do the same thing.

Here's a version annotated with the bugs:

int main()
{
    //Run read_WAV
    {
        header_type *header;
        char *filename[] = {//Various files};
// NOTE/BUG: this is scoped to _this_ block, so the write section below won't
// see it
// NOTE/BUG: this should be char *data and the function call should use &data
        char **data;
        read_pcm_wavefile(header, data, *filename);
    }
    //Run write_WAV
    {
        pcm_wavefile_header_type *header;
        char *filename[] = {//Various files};
// NOTE/BUG: this scoped 'data' declaration has none of the data in the read
// sectioon above
        char *data;
        write_pcm_wavefile(header, data, *filename);
    }

    //Run read_WAV again on new files to ensure header info is valid
    {
    pcm_wavefile_header_type *header;
    char *filename[] = {//output files from write};
    char *data;
    read_pcm_wavefile(header, data, *filename);
    }

    return(0);
}

Here's a fixed version:

int main()
{
    char *data;

    //Run read_WAV
    {
        header_type *header;
        char *filename[] = {//Various files};
        read_pcm_wavefile(header, &data, *filename);
    }

    //Run write_WAV
    {
        pcm_wavefile_header_type *header;
        char *filename[] = {//Various files};
        write_pcm_wavefile(header, data, filename[0]);
    }

    free(data);

    //Run read_WAV again on new files to ensure header info is valid
    {
        pcm_wavefile_header_type *header;
        char *filename[] = {//output files from write};
        read_pcm_wavefile(header, &data, filename[0]);
    }

    return(0);
}

UPDATE:

I've fixed that up. Still unable to get a proper output, which I'm thinking is in the passing of the data/pointer from each function?

As I mentioned you need to do the same for header because main needs the pointer to be filled in by your read function. As it is, after the read call, the value of header in main is unchanged (i.e. not updated by read_WAV as you'd like).

Change:

int read_WAV(header_type *header, char **data, char *filename)

Into:

int read_WAV(header_type **header, char **data, char *filename)

And, make all corresponding adjustments in main and read_WAV

Also, apply the same scoping fix in main for header that was done for data (i.e. header should not be block scoped, but, rather function scoped).

Because, even with the prototype change to read_WAV, main would lose the header value that read_WAV tried to pass back and write_WAV would get a garbage header pointer.

After you get this working, think about the temporal duration of the block scoped variables vs function scoped variables. In other words, if you set a variable, when does the value "go out of scope" [and become invalid].

For comparison, here's a version that does not use block scoped variables:

int
main(void)
{
    char *data;
    header_type *header;
    char *infiles[FILECOUNT] = {//Various files};
    char *outfiles[FILECOUNT] = {//Various files};

    for (int fidx = 0;  fidx < FILECOUNT;  ++fidx) {
        //Run read_WAV
        read_pcm_wavefile(&header, &data, infiles[fidx]);

        //Run write_WAV
        write_pcm_wavefile(header, data, outfiles[fidx]);

        free(header);
        free(data);

        //Run read_WAV again on new files to ensure header info is valid
        read_pcm_wavefile(&header, &data, outfiles[fidx]);

        free(header);
        free(data);
    }

    return 0;
}


问:
JSP: Show search conditions and search results on a page
I'm a newbie JSP.

I want to built a page which contain a textbox and a Search button.
After I click Search button I want to remain search condition and show results below(not redirect to another page).

How do I built it?

Please give me an example.

答:
Hint:

In your search.jsp, write javascript function which gets triggered when button is clicked. Within this function call your search action(server side, may be a servlet) using AJAX, it will return you a promise aka callback function. In callback JS function, write logic to render your search results.