问:
How to open .doc or .docx extension file using robot framework
I have to open downloaded .doc or .docx file using robot framework from my windows machine. If any of you have ever worked on opening external files using robot framework, I request your knowledge. </p>

答:
Using the keyword Run (or it's siblings) from the OperatingSystem Library should do the trick. In the below example I've put the test.docx file next to the robot script.  </p>

```<code>*** Settings ***
Library    OperatingSystem

*** Test Cases ***
Open Word
    Run    C:\\PROGRA~2\\MICROS~2\\Office14\\winword.exe ${EXECDIR}${/}test.docx
</code>```

Body:
Using the keyword Run (or it's siblings) from the OperatingSystem Library should do the trick. In the below example I've put the test.docx file next to the robot script.

*** Settings ***
Library    OperatingSystem

*** Test Cases ***
Open Word
    Run    C:\\PROGRA~2\\MICROS~2\\Office14\\winword.exe ${EXECDIR}${/}test.docx


来源: stackexchange

问:
Archiving Pages with Scrapy
I just started playing with Scrapy and my current goal is to build a webpage archiving tool.

So far I have this bit of code which saves a page to an .html file in the project folder.

```<code>import scrapy

class TestSpider(scrapy.Spider):
    name = "testbot"
    allowed_domain = ["URL"]
    start_urls = ["URL"]

def parse(self, response):
    filename = response.url.split("/")[-2] + '.html'
    with open(filename, 'wb') as f:
        f.write(response.body)
</code>```

The above code works great but now how do I download all the pages assets. Images, CSS, JS

Any help is appreciated. Thanks!

答:
For downloading assets, scrapy has the Files and Images pipelines. Or you can write you own custom pipeline for downloading the files (images, js, css). Next you need just extract the url addresses of the files from response and yield its to pipeline. For example like this:

```<code>def parse(self, response):

 links = response.selector.xpath("/html/head/link[@rel='stylesheet']")
 for style_link in links:
   yield {
       'type' : 'stylesheet',
       'url' : style_link.xpath('@href')
   }

 images = response.selector.xpath("//img")
 for img in images:
   yield {
       'type' : 'image',
       'url' : img.xpath('@src')
   }

 java_scripts = response.selector.xpath("//script[@type='text/javascript']")
 for js in java_scripts:
   yield {
       'type' : 'js',
       'url' : js.xpath('@src')
   }
</code>```

it's a basic example how you cant do it. The format of the item can be different depending on the which pipeline you use.

ContentLicense: CC BY-SA 3.0

Title: Archiving Pages with Scrapy

Body:
I just started playing with Scrapy and my current goal is to build a webpage archiving tool.

So far I have this bit of code which saves a page to an .html file in the project folder.

import scrapy

class TestSpider(scrapy.Spider):
    name = "testbot"
    allowed_domain = ["URL"]
    start_urls = ["URL"]

def parse(self, response):
    filename = response.url.split("/")[-2] + '.html'
    with open(filename, 'wb') as f:
        f.write(response.body)

The above code works great but now how do I download all the pages assets. Images, CSS, JS

Any help is appreciated. Thanks!

Body:
For downloading assets, scrapy has the Files and Images pipelines. Or you can write you own custom pipeline for downloading the files (images, js, css). Next you need just extract the url addresses of the files from response and yield its to pipeline. For example like this:

def parse(self, response):

 links = response.selector.xpath("/html/head/link[@rel='stylesheet']")
 for style_link in links:
   yield {
       'type' : 'stylesheet',
       'url' : style_link.xpath('@href')
   }

 images = response.selector.xpath("//img")
 for img in images:
   yield {
       'type' : 'image',
       'url' : img.xpath('@src')
   }

 java_scripts = response.selector.xpath("//script[@type='text/javascript']")
 for js in java_scripts:
   yield {
       'type' : 'js',
       'url' : js.xpath('@src')
   }

it's a basic example how you cant do it. The format of the item can be different depending on the which pipeline you use.


问:
How can I test raise exception in JUnit5?
I want to test whether exception works well or not using JUnit5.

For example, let say I test queue.

```<code>public class ArrayCircleQueue {
    .
    .
    .
    public void enQueue(char item) {
        if (isFull()) {
            throw new IndexOutOfBoundsException("Queue is full now!");
        } else {
            itemArray[rear++] = item;
        }
    }
}
</code>```

TestClass

```<code>class ArrayCircleQueueTest {
    .
    .
    .
    @org.junit.jupiter.api.Test
    void testEnQueueOverflow() {
        for (int i=0; i<100; i++) {
            queue.enQueue('c');  # test for 10-size queue. It should catch exception
        }
    }
}
</code>```

I search it in google, but there are only answer for JUnit4:
@Test(expected=NoPermissionException.class)

but it doesn't work on JUnit5.

How can I deal with it?

答:
In JUnit 5 you can do similar things with a custom extension of  TestExecutionExceptionHandler:

```<code>import org.junit.jupiter.api.extension.TestExecutionExceptionHandler;
import org.junit.jupiter.api.extension.TestExtensionContext;

public class HandleExtension implements TestExecutionExceptionHandler {

    @Override
    public void handleTestExecutionException(TestExtensionContext context,
            Throwable throwable) throws Throwable {
        // handle exception as you prefer
    }

}
</code>```

Then in your test, you need to declare that extension with ExtendWith:

```<code>import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

public class ExceptionTest {

    @ExtendWith(HandleExtension.class)
    @Test
    public void test() {
        // your test logic
    }

}
</code>```

Body:
I want to test whether exception works well or not using JUnit5.

For example, let say I test queue.

public class ArrayCircleQueue {
    .
    .
    .
    public void enQueue(char item) {
        if (isFull()) {
            throw new IndexOutOfBoundsException("Queue is full now!");
        } else {
            itemArray[rear++] = item;
        }
    }
}

TestClass

class ArrayCircleQueueTest {
    .
    .
    .
    @org.junit.jupiter.api.Test
    void testEnQueueOverflow() {
        for (int i=0; i<100; i++) {
            queue.enQueue('c');  # test for 10-size queue. It should catch exception
        }
    }
}

I search it in google, but there are only answer for JUnit4:
@Test(expected=NoPermissionException.class)

but it doesn't work on JUnit5.

How can I deal with it?

Body:
In JUnit 5 you can do similar things with a custom extension of  TestExecutionExceptionHandler:

import org.junit.jupiter.api.extension.TestExecutionExceptionHandler;
import org.junit.jupiter.api.extension.TestExtensionContext;

public class HandleExtension implements TestExecutionExceptionHandler {

    @Override
    public void handleTestExecutionException(TestExtensionContext context,
            Throwable throwable) throws Throwable {
        // handle exception as you prefer
    }

}

Then in your test, you need to declare that extension with ExtendWith:

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

public class ExceptionTest {

    @ExtendWith(HandleExtension.class)
    @Test
    public void test() {
        // your test logic
    }

}


问:
Pick random property and value from Javascript object
I've just started learning Javascript and need some help.

I wanted to build a random picker from an array which I accomplished

```<code>var movie = ["star wars", "lotr", "moonlight", "avengers"]

function newMovie() {
  var randomNumber = Math.floor(Math.random() * (movie.length));

  document.getElementById("display").innerHTML = "You should watch " + movie[randomNumber];
}
</code>```

Now I want to add more options for such as books, games.. so I've created an object for it:

```<code>var chooseOption = {
    watch: ["star wars", "lotr", "moonlight", "avengers"],
    read: ["scott pilgrim", "harry potter", "eragon"],
    play: ["starbound", "skyrim", "bioshock", "fallout"]
}
</code>```

I'm a bit lost on how to proceed - I want it to first pick out one of the properties and then one of the values of the said property, all by random.
And then print it out in a "You should" + [property] + [value]

How would I do that? Is the object a way to go, or any better options?

答:
use with object.keys() and Math.random()

first select the random key from object using Object.keys().length.

Then get the respected array of the key.

Then pick the random value from the array using array length

function newMovie() {
var types =Object.keys(chooseOption);
  var rn = Math.floor(Math.random() * (types.length));
var t = types[rn];
var val = chooseOption[types[rn]];
var vn = Math.floor(Math.random() * (val.length));
var v = val[vn]
 console.log("You should watch " +t +' '+v);
}

var chooseOption = {
  watch: ["star wars", "lotr", "moonlight", "avengers"],
  read: ["scott pilgrim", "harry potter", "eragon"],
  play: ["starbound", "skyrim", "bioshock", "fallout"]
}
newMovie()```

Body:
I've just started learning Javascript and need some help.

I wanted to build a random picker from an array which I accomplished

var movie = ["star wars", "lotr", "moonlight", "avengers"]

function newMovie() {
  var randomNumber = Math.floor(Math.random() * (movie.length));

  document.getElementById("display").innerHTML = "You should watch " + movie[randomNumber];
}

Now I want to add more options for such as books, games.. so I've created an object for it:

var chooseOption = {
    watch: ["star wars", "lotr", "moonlight", "avengers"],
    read: ["scott pilgrim", "harry potter", "eragon"],
    play: ["starbound", "skyrim", "bioshock", "fallout"]
}

I'm a bit lost on how to proceed - I want it to first pick out one of the properties and then one of the values of the said property, all by random.
And then print it out in a "You should" + [property] + [value]

How would I do that? Is the object a way to go, or any better options?


问:
Passing Datetime from JSON to WCF POST
i have a class like this:

```<code>public class BudgetTransactionRequest
    {
        [DataMember]
        public string transaction_code { get; set; }
        [DataMember]
        public double? amount { get; set; }

        public DateTime request_date { get; set; }

        [DataMember(Name = "request_date")]
        public string req_date { get; set; }

        [OnSerializing]
        void OnSerializing(StreamingContext context)
        {
            this.req_date = this.request_date.ToString("MM/dd/yyyy h:mm tt", CultureInfo.InvariantCulture);
        }

        [OnDeserialized]
        void OnDeserialized(StreamingContext context)
        {
            DateTime value;
            if (DateTime.TryParseExact(this.req_date, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out value))
            {
                this.request_date = value;
            }
        }
}
</code>```

Using fiddler, i tried to call this web service by sending JSON  like below:

```<code>{"transaction_code":"MCN34", "amount":2000.000,"request_date":"/Date(1235764800000)/"}
</code>```

But i got this following error:

```<code>{"ErrorDetails":"DateTime is less than minumum value supported by CrmDateTime. Actual value: 01\/01\/0001 00:00:00, Minimum value supported: 01\/01\/1753 00:00:00\"}
</code>```

What am i missing here ?

答:
Your code is slightly wrong.
You declared req_date as
 <code>[DataMember(Name = "request_date")]
        public string req_date { get; set; }
</code>
If you send request_date as "request_date":"/Date(1235764800000)/" means, the date value will stored in req_date variable.
Then, you try to assign request_date to req_date. By default, Null value in request_date  variable.
If you pass NULL value means, it will take default value as ' 01/01/0001 00:00:00'.</p>

Title: Passing Datetime from JSON to WCF POST

Body:
i have a class like this:

public class BudgetTransactionRequest
    {
        [DataMember]
        public string transaction_code { get; set; }
        [DataMember]
        public double? amount { get; set; }

        public DateTime request_date { get; set; }

        [DataMember(Name = "request_date")]
        public string req_date { get; set; }

        [OnSerializing]
        void OnSerializing(StreamingContext context)
        {
            this.req_date = this.request_date.ToString("MM/dd/yyyy h:mm tt", CultureInfo.InvariantCulture);
        }

        [OnDeserialized]
        void OnDeserialized(StreamingContext context)
        {
            DateTime value;
            if (DateTime.TryParseExact(this.req_date, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out value))
            {
                this.request_date = value;
            }
        }
}

Using fiddler, i tried to call this web service by sending JSON  like below:

{"transaction_code":"MCN34", "amount":2000.000,"request_date":"/Date(1235764800000)/"}

But i got this following error:

{"ErrorDetails":"DateTime is less than minumum value supported by CrmDateTime. Actual value: 01\/01\/0001 00:00:00, Minimum value supported: 01\/01\/1753 00:00:00\"}

What am i missing here ?

Body:
Your code is slightly wrong.
You declared req_date as
 [DataMember(Name = "request_date")]
        public string req_date { get; set; }

If you send request_date as "request_date":"/Date(1235764800000)/" means, the date value will stored in req_date variable.
Then, you try to assign request_date to req_date. By default, Null value in request_date  variable.
If you pass NULL value means, it will take default value as ' 01/01/0001 00:00:00'.


问:
How to set IP_MULTICAST_LOOP on multicast UDPConn in Golang
I need to set IP_MULTICAST_LOOP on a multicast UDP connection/socket so I can send/receive multicast packets on my local machine. This is the call that I've found which should work:

```<code>l, err := net.ListenMulticastUDP("udp4", nil, addr)
file, err := l.File()
fd := syscall.Handle(file.Fd())

err = syscall.SetsockoptInt(fd, syscall.IPPROTO_IP, syscall.IP_MULTICAST_LOOP, 1)
</code>```

However it fails with "not supported by windows". I'm pretty sure this is supported by sockets in windows, just not in the Go net package. Any idea on how I can set this flag on my connection? (I'm new to the Go language, I may have overlooked something obvious). This is on Windows, I haven't had a chance to test on Linux.

答:
As the doc says, net.ListenMulticastUDP is just for convenience of simple small applications. You can use golang.org/x/net/ipv4 for general purpose uses, this package offers you more options about multicast.. Actually, the source code of net.ListenMulticastUDP() sets IP_MULTICAST_LOOP to false:

```<code>func listenIPv4MulticastUDP(c *UDPConn, ifi *Interface, ip IP) error {
    if ifi != nil {
        if err := setIPv4MulticastInterface(c.fd, ifi); err != nil {
            return err
        }
    }
    if err := setIPv4MulticastLoopback(c.fd, false); err != nil {
        return err
    }
    if err := joinIPv4Group(c.fd, ifi, ip); err != nil {
        return err
    }
    return nil
}
</code>```

setIPv4MulticastLoopback() is implemented for different OSes, and it's not exported. For Windows, it's in sockoptip_windows.go:

```<code>func setIPv4MulticastLoopback(fd *netFD, v bool) error {
    if err := fd.incref(); err != nil {
        return err
    }
    defer fd.decref()
    return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(fd.sysfd, syscall.IPPROTO_IP, syscall.IP_MULTICAST_LOOP, boolint(v)))
}
</code>```

Below is an example with golang.org/x/net/ipv4, you can get/set MulticastLoopback

```<code>package main

import (
    "fmt"
    "net"
    "golang.org/x/net/ipv4"
)

func main() {
    ipv4Addr := &net.UDPAddr{IP: net.IPv4(224, 0, 0, 251), Port: 5352}
    conn, err := net.ListenUDP("udp4", ipv4Addr)
    if err != nil {
        fmt.Printf("ListenUDP error %v\n", err)
        return
    }

    pc := ipv4.NewPacketConn(conn)

    // assume your have a interface named wlan
    iface, err := net.InterfaceByName("wlan")
    if err != nil {
        fmt.Printf("can't find specified interface %v\n", err)
        return
    }
    if err := pc.JoinGroup(iface, &net.UDPAddr{IP: net.IPv4(224, 0, 0, 251)}); err != nil {
        return
    }

    // test
    if loop, err := pc.MulticastLoopback(); err == nil {
        fmt.Printf("MulticastLoopback status:%v\n", loop)
        if !loop {
            if err := pc.SetMulticastLoopback(true); err != nil {
            fmt.Printf("SetMulticastLoopback error:%v\n", err)
            }
        }
    }

    if _, err := conn.WriteTo([]byte("hello"), ipv4Addr); err != nil {
        fmt.Printf("Write failed, %v\n", err)
    }

    buf := make([]byte, 1024)
    for {
        if n, addr, err := conn.ReadFrom(buf); err != nil {
            fmt.Printf("error %v", err)
        } else {
            fmt.Printf("recv %s from %v\n", string(buf[:n]), addr)
        }
    }

    return
}
</code>```

Body:
I need to set IP_MULTICAST_LOOP on a multicast UDP connection/socket so I can send/receive multicast packets on my local machine. This is the call that I've found which should work:

l, err := net.ListenMulticastUDP("udp4", nil, addr)
file, err := l.File()
fd := syscall.Handle(file.Fd())

err = syscall.SetsockoptInt(fd, syscall.IPPROTO_IP, syscall.IP_MULTICAST_LOOP, 1)

However it fails with "not supported by windows". I'm pretty sure this is supported by sockets in windows, just not in the Go net package. Any idea on how I can set this flag on my connection? (I'm new to the Go language, I may have overlooked something obvious). This is on Windows, I haven't had a chance to test on Linux.

Body:
As the doc says, net.ListenMulticastUDP is just for convenience of simple small applications. You can use golang.org/x/net/ipv4 for general purpose uses, this package offers you more options about multicast.. Actually, the source code of net.ListenMulticastUDP() sets IP_MULTICAST_LOOP to false:

func listenIPv4MulticastUDP(c *UDPConn, ifi *Interface, ip IP) error {
    if ifi != nil {
        if err := setIPv4MulticastInterface(c.fd, ifi); err != nil {
            return err
        }
    }
    if err := setIPv4MulticastLoopback(c.fd, false); err != nil {
        return err
    }
    if err := joinIPv4Group(c.fd, ifi, ip); err != nil {
        return err
    }
    return nil
}

setIPv4MulticastLoopback() is implemented for different OSes, and it's not exported. For Windows, it's in sockoptip_windows.go:

func setIPv4MulticastLoopback(fd *netFD, v bool) error {
    if err := fd.incref(); err != nil {
        return err
    }
    defer fd.decref()
    return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(fd.sysfd, syscall.IPPROTO_IP, syscall.IP_MULTICAST_LOOP, boolint(v)))
}

Below is an example with golang.org/x/net/ipv4, you can get/set MulticastLoopback

package main

import (
    "fmt"
    "net"
    "golang.org/x/net/ipv4"
)

func main() {
    ipv4Addr := &net.UDPAddr{IP: net.IPv4(224, 0, 0, 251), Port: 5352}
    conn, err := net.ListenUDP("udp4", ipv4Addr)
    if err != nil {
        fmt.Printf("ListenUDP error %v\n", err)
        return
    }

    pc := ipv4.NewPacketConn(conn)

    // assume your have a interface named wlan
    iface, err := net.InterfaceByName("wlan")
    if err != nil {
        fmt.Printf("can't find specified interface %v\n", err)
        return
    }
    if err := pc.JoinGroup(iface, &net.UDPAddr{IP: net.IPv4(224, 0, 0, 251)}); err != nil {
        return
    }

    // test
    if loop, err := pc.MulticastLoopback(); err == nil {
        fmt.Printf("MulticastLoopback status:%v\n", loop)
        if !loop {
            if err := pc.SetMulticastLoopback(true); err != nil {
            fmt.Printf("SetMulticastLoopback error:%v\n", err)
            }
        }
    }

    if _, err := conn.WriteTo([]byte("hello"), ipv4Addr); err != nil {
        fmt.Printf("Write failed, %v\n", err)
    }

    buf := make([]byte, 1024)
    for {
        if n, addr, err := conn.ReadFrom(buf); err != nil {
            fmt.Printf("error %v", err)
        } else {
            fmt.Printf("recv %s from %v\n", string(buf[:n]), addr)
        }
    }

    return
}


问:
While accessing the same angular 2 app on 2 different system ,when i scroll on 1 system, it gets scroll dat same page on another system automatically
My question seems confusing, but pardon me , I am having this dilemma that,
I made an angular2 app, and am running the same app on two different system and while doing so, when I am accessing a page , scrolling it then that same page if opened on another system getting scrolled at the same time automatically.
I dont want my app to work like this.
I have provided a snapshot to support my question.

Scrolling bar happening at the same time on another system for the same page

P.S: I am beginner in Angular 2

答:
In your gulpfile.js which you given the link.

Change the default task which has browserSync call.

Add the ghostMode: false as a new key and value.

Then restart the server

Change your default gulp task.

```<code>   var browserSync = require('browser-sync');

    gulp.task('default', function () {

        browserSync(
        {
            server: './app',
            ghostMode: false
        }
        );

        gulp.watch('./app/scss/*.scss', ['sass']);
        gulp.watch('./app/*.html',      ['html-watch']);
    });
</code>```

Body:
In your gulpfile.js which you given the link.

Change the default task which has browserSync call.

Add the ghostMode: false as a new key and value.

Then restart the server

Change your default gulp task.

   var browserSync = require('browser-sync');

    gulp.task('default', function () {

        browserSync(
        {
            server: './app',
            ghostMode: false
        }
        );

        gulp.watch('./app/scss/*.scss', ['sass']);
        gulp.watch('./app/*.html',      ['html-watch']);
    });


问:
SVN remains in conflict?
How do I get this directory out of conflict? I don't care if it's resolved using "theirs" or "mine" or whatever... </p>

```<code>PS C:\Users\Mark\Desktop\myproject> svn ci -m "gr"
svn: Commit failed (details follow):
svn: Aborting commit: 'C:\Users\Mark\Desktop\myproject\addons' remains in conflict

PS C:\Users\Mark\Desktop\myproject> svn resolve --accept working C:\Users\Mark\Desktop\myproject\addons
Resolved conflicted state of 'C:\Users\Mark\Desktop\myproject\addons'

PS C:\Users\Mark\Desktop\myproject> svn ci -m "grr"
svn: Commit failed (details follow):
svn: Commit item 'addons' has copy flag but an invalid revision

PS C:\Users\Mark\Desktop\myproject> svn update
   C addons
svn: Can't move 'addons\debug_toolbar\templates\debug_toolbar\.svn\tmp\entries' to 'addons\debug_toolbar\templates\debug
_toolbar\.svn\entries': The file or directory is corrupted and unreadable.

PS C:\Users\Mark\Desktop\myproject> svn cleanup

PS C:\Users\Mark\Desktop\myproject> svn update
Skipped 'addons'
At revision 51.
Summary of conflicts:
  Skipped paths: 1

PS C:\Users\Mark\Desktop\myproject> svn ci -m "grrr"
svn: Commit failed (details follow):
svn: Aborting commit: 'C:\Users\Mark\Desktop\myproject\addons' remains in conflict
</code>```

答:
Instructions for Tortoise SVN

Navigate to the directory where you see this error.
If you do not have any changes perform the following

a. Right click and do a 'Revert'

b. Select all the files

c. Then update the directory again

ContentLicense: CC BY-SA 2.5

Title: SVN remains in conflict?

Body:
How do I get this directory out of conflict? I don't care if it's resolved using "theirs" or "mine" or whatever...

PS C:\Users\Mark\Desktop\myproject> svn ci -m "gr"
svn: Commit failed (details follow):
svn: Aborting commit: 'C:\Users\Mark\Desktop\myproject\addons' remains in conflict

PS C:\Users\Mark\Desktop\myproject> svn resolve --accept working C:\Users\Mark\Desktop\myproject\addons
Resolved conflicted state of 'C:\Users\Mark\Desktop\myproject\addons'

PS C:\Users\Mark\Desktop\myproject> svn ci -m "grr"
svn: Commit failed (details follow):
svn: Commit item 'addons' has copy flag but an invalid revision

PS C:\Users\Mark\Desktop\myproject> svn update
   C addons
svn: Can't move 'addons\debug_toolbar\templates\debug_toolbar\.svn\tmp\entries' to 'addons\debug_toolbar\templates\debug
_toolbar\.svn\entries': The file or directory is corrupted and unreadable.

PS C:\Users\Mark\Desktop\myproject> svn cleanup

PS C:\Users\Mark\Desktop\myproject> svn update
Skipped 'addons'
At revision 51.
Summary of conflicts:
  Skipped paths: 1

PS C:\Users\Mark\Desktop\myproject> svn ci -m "grrr"
svn: Commit failed (details follow):
svn: Aborting commit: 'C:\Users\Mark\Desktop\myproject\addons' remains in conflict


问:
Record Actions using Selenium
I have a semi-vague question to ask about Selenium. I've discovered a few different ways to perform actions using the FirefoxDriver. What I need to do is repeat actions that a user performs on a web page (clicking a link, checking a checkbox, etc.). Is there any method or combination of methods that allows me to "record" the user's actions? Here is what I have so far to perform actions (you'll notice I've tried using the WebDriverBackedSelenium and Actions  classes to perform actions)</p>

```<code>import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriverBackedSelenium;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.Action;

public class MyReplayer {
    public static void main(String[] args) throws Exception {
        // The Firefox driver supports javascript
        FirefoxDriver driver = new FirefoxDriver();

        driver.get("http://www.cs.umd.edu");

        List<WebElement> elements = driver.findElements(By.tagName("a"));
        //WebDriverBackedSelenium driverBacked = new WebDriverBackedSelenium(driver,        "http://www.cs.umd.edu");
        Actions builder = new Actions(driver);
        Action clickLink = builder.click(elements.get(100)).build();
        clickLink.perform();
        //driverBacked.click("document.getElementsByTagName('a')[100]");
     }
}
</code>```

答:
I am currently working on a project that does something like this: https://github.com/hristo-vrigazov/selenium-record-replay
It works by putting a proxy between the browser and the application, and injecting javascript which listens for actions that you have defined. See for example https://github.com/hristo-vrigazov/selenium-record-replay/blob/master/terminator-cli/src/main/java/browser/Main.java#L74

```<code>        RecordBrowserBase recordBrowserBase = new ChromeRecordBrowser(pathToChromedriver, pathToJSInjectionFile);
        try {
            recordBrowserBase.record(baseUrl);
            System.out.println("Press Enter when finished recording");
            System.in.read();
            recordBrowserBase.dumpActions(outputFile);
        } catch (IOException | InterruptedException | URISyntaxException e) {
            e.printStackTrace();
        }

        recordBrowserBase.cleanUp();

        System.exit(0);
</code>```

The project is still in a very early stage, but it can be used even now. Currently only Chrome is supported, but I will soon add other browsers as well.

Disclaimer: I am the creator and maintainer of the project

Title: Record Actions using Selenium

Body:
I have a semi-vague question to ask about Selenium. I've discovered a few different ways to perform actions using the FirefoxDriver. What I need to do is repeat actions that a user performs on a web page (clicking a link, checking a checkbox, etc.). Is there any method or combination of methods that allows me to "record" the user's actions? Here is what I have so far to perform actions (you'll notice I've tried using the WebDriverBackedSelenium and Actions  classes to perform actions)

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriverBackedSelenium;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.Action;

public class MyReplayer {
    public static void main(String[] args) throws Exception {
        // The Firefox driver supports javascript
        FirefoxDriver driver = new FirefoxDriver();

        driver.get("http://www.cs.umd.edu");

        List<WebElement> elements = driver.findElements(By.tagName("a"));
        //WebDriverBackedSelenium driverBacked = new WebDriverBackedSelenium(driver,        "http://www.cs.umd.edu");
        Actions builder = new Actions(driver);
        Action clickLink = builder.click(elements.get(100)).build();
        clickLink.perform();
        //driverBacked.click("document.getElementsByTagName('a')[100]");
     }
}

Body:
I am currently working on a project that does something like this: https://github.com/hristo-vrigazov/selenium-record-replay
It works by putting a proxy between the browser and the application, and injecting javascript which listens for actions that you have defined. See for example https://github.com/hristo-vrigazov/selenium-record-replay/blob/master/terminator-cli/src/main/java/browser/Main.java#L74

        RecordBrowserBase recordBrowserBase = new ChromeRecordBrowser(pathToChromedriver, pathToJSInjectionFile);
        try {
            recordBrowserBase.record(baseUrl);
            System.out.println("Press Enter when finished recording");
            System.in.read();
            recordBrowserBase.dumpActions(outputFile);
        } catch (IOException | InterruptedException | URISyntaxException e) {
            e.printStackTrace();
        }

        recordBrowserBase.cleanUp();

        System.exit(0);

The project is still in a very early stage, but it can be used even now. Currently only Chrome is supported, but I will soon add other browsers as well.

Disclaimer: I am the creator and maintainer of the project


问:
Check if one of the elements of array is within other array
I want to check to see if a voucher is valid for an event.
The voucher can be valid on certain days (mo-su) which is stored in an array:

```<code>$validOn = [1,3,4]; // Monday, Thursday
</code>```

An event can be happening on 1 or more days:

```<code>$event = [2,6]; // Tuesday, Saturday (unique)
</code>```

How can I check if the voucher is valid for the given event?

```<code>valid([2,6], $validOn); // false
valid([1,6], $validOn); // true
valid([1,4], $validOn); // true
valid([3], $validOn);   // true
etc etc
</code>```

答:
You can use array_intersect

```<code>function valid($a, $b) {
   return  count(array_intersect($a, $b)) > 0;
}
</code>```

Body:
I want to check to see if a voucher is valid for an event.
The voucher can be valid on certain days (mo-su) which is stored in an array:

$validOn = [1,3,4]; // Monday, Thursday

An event can be happening on 1 or more days:

$event = [2,6]; // Tuesday, Saturday (unique)

How can I check if the voucher is valid for the given event?

valid([2,6], $validOn); // false
valid([1,6], $validOn); // true
valid([1,4], $validOn); // true
valid([3], $validOn);   // true
etc etc

Body:
You can use array_intersect

function valid($a, $b) {
   return  count(array_intersect($a, $b)) > 0;
}


问:
label constraints not working
```<code>class videoCell:UICollectionViewCell
{
    override init(frame: CGRect) {
    super.init(frame: frame)
        setUpViews()

    }
   let titlelabel : UILabel =
        {
            var label = UILabel()
        label.backgroundColor = UIColor.brown
        label.translatesAutoresizingMaskIntoConstraints = false
            return label
        }()

    func setUpViews()
    {

        addSubview(titlelabel)

        addConstraint(NSLayoutConstraint(item: titlelabel, attribute:.top, relatedBy: .equal, toItem: thumbNailImageView, attribute: .bottom, multiplier: 1, constant: 8))
        addConstraint(NSLayoutConstraint(item: titlelabel, attribute:.left, relatedBy: .equal, toItem: thumbNailImageView, attribute: .right, multiplier: 1, constant: 8))
        addConstraint(NSLayoutConstraint(item: titlelabel, attribute: .right, relatedBy: .equal, toItem: thumbNailImageView, attribute: .right, multiplier: 1, constant: 0))

        addConstraintsWithFormat(format: "V:[v0(20)]", views:titlelabel)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension UIView
{

    func addConstraintsWithFormat(format:String,views:UIView...)
    {
        var allViews = [String:UIView]()
        for data in 0...views.count-1
        {
            let key = "v\(data)"
            allViews[key] = views[data]
        }
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: allViews))

    }

}
</code>```

My above function setUpViews() is not rendering my label on view.Can anyone help me out here. I am not getting any error it compiles fine but no output.

Is there any issue with addConstraints method.??

please help thanks.

It works if I add this constraint-:

```<code>addConstraintsWithFormat(format: "H:|[v0]|", views:titlelabel)
</code>```

And comment this line of code-:

```<code>addConstraint(NSLayoutConstraint(item: titlelabel, attribute:.left, relatedBy: .equal, toItem: thumbNailImageView, attribute: .right, multiplier: 1, constant: 8))
        addConstraint(NSLayoutConstraint(item: titlelabel, attribute: .right, relatedBy: .equal, toItem: thumbNailImageView, attribute: .right, multiplier: 1, constant: 0))
</code>```

But that doesn't pin my view where I need to and how I want it to work .

答: You have to call your setUpViews() function in the awakeFromNib() method.</p>

Title: label constraints not working

Body:
class videoCell:UICollectionViewCell
{
    override init(frame: CGRect) {
    super.init(frame: frame)
        setUpViews()

    }
   let titlelabel : UILabel =
        {
            var label = UILabel()
        label.backgroundColor = UIColor.brown
        label.translatesAutoresizingMaskIntoConstraints = false
            return label
        }()

    func setUpViews()
    {

        addSubview(titlelabel)

        addConstraint(NSLayoutConstraint(item: titlelabel, attribute:.top, relatedBy: .equal, toItem: thumbNailImageView, attribute: .bottom, multiplier: 1, constant: 8))
        addConstraint(NSLayoutConstraint(item: titlelabel, attribute:.left, relatedBy: .equal, toItem: thumbNailImageView, attribute: .right, multiplier: 1, constant: 8))
        addConstraint(NSLayoutConstraint(item: titlelabel, attribute: .right, relatedBy: .equal, toItem: thumbNailImageView, attribute: .right, multiplier: 1, constant: 0))

        addConstraintsWithFormat(format: "V:[v0(20)]", views:titlelabel)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension UIView
{

    func addConstraintsWithFormat(format:String,views:UIView...)
    {
        var allViews = [String:UIView]()
        for data in 0...views.count-1
        {
            let key = "v\(data)"
            allViews[key] = views[data]
        }
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: allViews))

    }

}

My above function setUpViews() is not rendering my label on view.Can anyone help me out here. I am not getting any error it compiles fine but no output.

Is there any issue with addConstraints method.??

please help thanks.

It works if I add this constraint-:

addConstraintsWithFormat(format: "H:|[v0]|", views:titlelabel)

And comment this line of code-:

addConstraint(NSLayoutConstraint(item: titlelabel, attribute:.left, relatedBy: .equal, toItem: thumbNailImageView, attribute: .right, multiplier: 1, constant: 8))
        addConstraint(NSLayoutConstraint(item: titlelabel, attribute: .right, relatedBy: .equal, toItem: thumbNailImageView, attribute: .right, multiplier: 1, constant: 0))

But that doesn't pin my view where I need to and how I want it to work .


问:
alfresco preview .ply files
I have an STL previewer which can preview the file with mime type "application/sla" in alfresco. So I want to render the file with the mime type "application/pla" as "application/sla". For this, I have created a rule on a folder with the following script

var renderingEngineName = 'reformat';
var renditionDefinitionName = 'cm:stl';
var renditionDef = renditionService.createRenditionDefinition(renditionDefinitionName, renderingEngineName);
renditionDef.parameters['mime-type'] = 'application/sla';
renditionService.render(document, renditionDef);

And I am also able to see rendition child in node browser of admin console

But still, I am not able to get a preview of the files with mime type "application/pla".

I also followed another approach by creating custom thumbnail by defining new spring bean in the following way

```<code><bean id="thumbnailDefinitionSTLpreview" class="org.alfresco.repo.thumbnail.ThumbnailDefinition">
    <property name="name" value="stl" />
    <property name="mimetype" value="application/sla" />
    <property name="transformationOptions">
        <!-- The thumbnail definition have transformationOptions mandatory -->
        <!-- But there are none for pdf, so use SWFTransformationsOptions as a dummy -->
        <bean class="org.alfresco.repo.content.transform.swf.SWFTransformationOptions">
            <property name="flashVersion" value="9" />
        </bean>
    </property>
 </bean>

  <bean id="baseThumbnailRegistry" abstract="true">
    <property name="contentService" ref="ContentService"/>
    <property name="renditionService" ref="renditionService" />
    <property name="transactionService" ref="TransactionService" />
    <property name="tenantAdminService" ref="tenantAdminService" />
    <property name="redeployStaticDefsOnStartup" value="${system.thumbnail.redeployStaticDefsOnStartup}" />
    <property name="thumbnailDefinitions">
        <list>
            <ref bean="thumbnailDefinitionMedium" />
            <ref bean="thumbnailDefinitionDoclib" />
            <ref bean="thumbnailDefinitionImgpreview" />
            <ref bean="thumbnailDefinitionAvatar" />
            <ref bean="thumbnailDefinitionAvatar32" />
            <ref bean="thumbnailDefinitionPDFpreview" />
            <ref bean="thumbnailDefinitionWebpreview" />
            <ref bean="thumbnailDefinitionSTLpreview" />
        </list>
    </property>
    <property name="thumbnailRenditionConvertor" ref="thumbnailRenditionConvertor" />
 </bean>
</code>```

and in "web-preview.get.config.xml" have also added following code to use created thumbnail for preview

```<code><condition mimeType="application/sla">
      <plugin src="webpreview" paging="true">STLViewer</plugin>
      <plugin srcMaxSize="500000">Image</plugin>
</condition>

<condition thumbnail="stl">
         <plugin src="stl" paging="true">STLViewer</plugin>
</condition>
</code>```

and in order to create a thumbnail, I am executing a script on a folder rule which is as follows

```<code>document.createThumbnail("stl", true);
document.save();
</code>```

At the end I am able to get STLViewer screen but object is not getting rendered.

I would be great if anyone can help me with this.

答:
have you created STLViewer plugin ?? like this and you need to add the js / css dependency files to share/WEB-INF/classes/alfresco/web-extension/site-webscripts/org/alfresco/components/preview/include/web-preview-css-dependencies.lib.ftl and web-preview-js-dependencies.lib.ftl file.

For more information refer this blog

Title: alfresco preview .ply files

Body:
I have an STL previewer which can preview the file with mime type "application/sla" in alfresco. So I want to render the file with the mime type "application/pla" as "application/sla". For this, I have created a rule on a folder with the following script

var renderingEngineName = 'reformat';
var renditionDefinitionName = 'cm:stl';
var renditionDef = renditionService.createRenditionDefinition(renditionDefinitionName, renderingEngineName);
renditionDef.parameters['mime-type'] = 'application/sla';
renditionService.render(document, renditionDef);

And I am also able to see rendition child in node browser of admin console

But still, I am not able to get a preview of the files with mime type "application/pla".

I also followed another approach by creating custom thumbnail by defining new spring bean in the following way

<bean id="thumbnailDefinitionSTLpreview" class="org.alfresco.repo.thumbnail.ThumbnailDefinition">
    <property name="name" value="stl" />
    <property name="mimetype" value="application/sla" />
    <property name="transformationOptions">

        <bean class="org.alfresco.repo.content.transform.swf.SWFTransformationOptions">
            <property name="flashVersion" value="9" />
        </bean>
    </property>
 </bean>

  <bean id="baseThumbnailRegistry" abstract="true">
    <property name="contentService" ref="ContentService"/>
    <property name="renditionService" ref="renditionService" />
    <property name="transactionService" ref="TransactionService" />
    <property name="tenantAdminService" ref="tenantAdminService" />
    <property name="redeployStaticDefsOnStartup" value="${system.thumbnail.redeployStaticDefsOnStartup}" />
    <property name="thumbnailDefinitions">
        <list>
            <ref bean="thumbnailDefinitionMedium" />
            <ref bean="thumbnailDefinitionDoclib" />
            <ref bean="thumbnailDefinitionImgpreview" />
            <ref bean="thumbnailDefinitionAvatar" />
            <ref bean="thumbnailDefinitionAvatar32" />
            <ref bean="thumbnailDefinitionPDFpreview" />
            <ref bean="thumbnailDefinitionWebpreview" />
            <ref bean="thumbnailDefinitionSTLpreview" />
        </list>
    </property>
    <property name="thumbnailRenditionConvertor" ref="thumbnailRenditionConvertor" />
 </bean>

and in "web-preview.get.config.xml" have also added following code to use created thumbnail for preview

<condition mimeType="application/sla">
      <plugin src="webpreview" paging="true">STLViewer</plugin>
      <plugin srcMaxSize="500000">Image</plugin>
</condition>

<condition thumbnail="stl">
         <plugin src="stl" paging="true">STLViewer</plugin>
</condition>

and in order to create a thumbnail, I am executing a script on a folder rule which is as follows

document.createThumbnail("stl", true);
document.save();

At the end I am able to get STLViewer screen but object is not getting rendered.

I would be great if anyone can help me with this.


问:
How to pass multiple uniforms efficiently and dynamically to GLSL
I want to pass an array of struct I have in my program, I know there are a few way's to do this but I want to do it efficiently, here is what I know I can do:

I can use simply create a struct with the things I want to pass to the shaders and create an array of how many can be passed:

```<code>struct Light
{
    vec3 Position;
    vec3 diffuse;
    float Intensity;
};

#define NUM_OF_LIGHTS 5
uniform Light lights[NUM_OF_LIGHTS];
</code>```

Pros: Really easy to do.

Cons: It is not dynamic, I need to choose a maximum amount of lights, which I want to avoid doing.

I can use Uniform Blocks Objects (UBO) which I read on opengl.org that I can use array for them from OpenGL 4.0 (Which is my target by the way, (considering 4.1)).

Pros: Cleaner(?) to do. might be faster(?)1

Cons: Still, not dynamic.

Shader Storage Blocks Objects (SSBO) is another option but I can't use them because they are core on version 4.3. bad for me because, as far as I read, they are dynamic and that is what I want.

I couldn't find anything else about how to pass things as I want to do.

If I can't do it, how can game engines create multiple lighting without knowing how much lights the user will enter (considering they using OpenGL and they target 3.X up to 4.0, which seem reasonable to me)?

Thanks in advance.

Footnotes:

I might be wrong here, so if I do let me know and I will delete those.

答:
How about your first solution with a little modification:

```<code>struct Light
{
    vec3 Position;
    vec3 diffuse;
    float Intensity;
};

#define MAX_NUM_OF_LIGHTS 50            //define max number of lights
uniform Light lights[MAX_NUM_OF_LIGHTS];
uniform int number_of_lights            //the actual number of lights, for loops
</code>```

Still not exactly what you want but it works well.

Body:
I want to pass an array of struct I have in my program, I know there are a few way's to do this but I want to do it efficiently, here is what I know I can do:

I can use simply create a struct with the things I want to pass to the shaders and create an array of how many can be passed:

struct Light
{
    vec3 Position;
    vec3 diffuse;
    float Intensity;
};

#define NUM_OF_LIGHTS 5
uniform Light lights[NUM_OF_LIGHTS];

Pros: Really easy to do.

Cons: It is not dynamic, I need to choose a maximum amount of lights, which I want to avoid doing.

I can use Uniform Blocks Objects (UBO) which I read on opengl.org that I can use array for them from OpenGL 4.0 (Which is my target by the way, (considering 4.1)).

Pros: Cleaner(?) to do. might be faster(?)1

Cons: Still, not dynamic.

Shader Storage Blocks Objects (SSBO) is another option but I can't use them because they are core on version 4.3. bad for me because, as far as I read, they are dynamic and that is what I want.

I couldn't find anything else about how to pass things as I want to do.

If I can't do it, how can game engines create multiple lighting without knowing how much lights the user will enter (considering they using OpenGL and they target 3.X up to 4.0, which seem reasonable to me)?

Thanks in advance.

Footnotes:

I might be wrong here, so if I do let me know and I will delete those.

Body:
How about your first solution with a little modification:

struct Light
{
    vec3 Position;
    vec3 diffuse;
    float Intensity;
};

#define MAX_NUM_OF_LIGHTS 50            //define max number of lights
uniform Light lights[MAX_NUM_OF_LIGHTS];
uniform int number_of_lights            //the actual number of lights, for loops

Still not exactly what you want but it works well.


问:
What could cause unzip command returning -1 in my scenario?
I run unzip via a system() call in my C++ code in below format:

```<code>/usr/bin/unzip -o -q /<my_path_to_zip_file>/cfg_T-KTMAKUCB.zip -d /<my_path_to_dest>/../
</code>```

This will almost 90% of times succeed. I cannot understand what could make it fail time to time with -1 return code. Any ideas?

答:
According my local man system,

The value returned is -1 on error (e.g.  fork(2) failed), and the return status of the command otherwise.

and the POSIX spec says,

If a child process cannot be created, or if the termination status for the command language interpreter cannot be obtained, system() shall return -1 and set errno to indicate the error

Finally, the manpage for unzip lists various return codes, but -1 isn't among them.

If the command itself can't return -1, the problem is probably with the initial fork/exec, due to something like a system-wide or per-user limit (memory exhausted; process table full; maximum processes, open files or VM size limit for the user etc. etc).

You should be checking errno when system fails anyway. Running the whole thing under strace -f will also show what happens.

Body:
I run unzip via a system() call in my C++ code in below format:

/usr/bin/unzip -o -q /<my_path_to_zip_file>/cfg_T-KTMAKUCB.zip -d /<my_path_to_dest>/../

This will almost 90% of times succeed. I cannot understand what could make it fail time to time with -1 return code. Any ideas?


答:
Try this

```<code>$result = array_intersect($validOn, $event);
if(count($result) > 0) {
  //we have a match
}
</code>```

See: http://php.net/manual/en/function.array-intersect.php for more information as well.

Title: Check if one of the elements of array is within other array

Body:
Try this

$result = array_intersect($validOn, $event);
if(count($result) > 0) {
  //we have a match
}

See: http://php.net/manual/en/function.array-intersect.php for more information as well.


问:
How to remove whitespaces in strings in Swift?
This works

```<code>let replaced = String(map(aString.generate()) {
    $0 == " " ? "-" : $0 })
</code>```

and this doesn't

```<code>let replaced = String(map(aString.generate()) {
    $0 == " " ? "" : $0 })
</code>```

Why?

答:
In Swift 3.0 DO as

```<code>func RemoveWhiteSpace(aString:String) -> String
    {
        let replaced = aString.trimmingCharacters(in: NSCharacterSet.whitespaces)
        return replaced
    }
</code>```

And use like this

```<code>let nonWhiteSpaceStr = self.RemoveWhiteSpace(aString: "I have white Space        ")
</code>```

Body:
This works

let replaced = String(map(aString.generate()) {
    $0 == " " ? "-" : $0 })

and this doesn't

let replaced = String(map(aString.generate()) {
    $0 == " " ? "" : $0 })

Why?

Body:
In Swift 3.0 DO as

func RemoveWhiteSpace(aString:String) -> String
    {
        let replaced = aString.trimmingCharacters(in: NSCharacterSet.whitespaces)
        return replaced
    }

And use like this

let nonWhiteSpaceStr = self.RemoveWhiteSpace(aString: "I have white Space        ")


问:
Regex for links in html text
I hope this question is not a RTFM one.
I am trying to write a Python script that extracts links from a standard HTML webpage (the <link href... tags).
I have searched the web for matching regexen and found many different patterns. Is there any agreed, standard regex to match links?

Adam

UPDATE:
I am actually looking for two different answers:

What's the library solution for parsing HTML links. Beautiful Soup seems to be a good solution (thanks, Igal Serban and cletus!)

Can a link be defined using a regex?

答:
Shoudln't a link be a well-defined regex? This is a rather theoretical question,

I second PEZ's answer:

I don't think HTML lends itself to "well defined" regular expressions since it's not a regular language.

As far as I know, any HTML tag may contain any number of nested tags. For example:

```<code><a href="http://stackoverflow.com">stackoverflow</a>
<a href="http://stackoverflow.com"><i>stackoverflow</i></a>
<a href="http://stackoverflow.com"><b><i>stackoverflow</i></b></a>
...
</code>```

Thus, in principle, to match a tag properly you must be able at least to match strings of the form:

```<code>BE
BBEE
BBBEEE
...
BBBBBBBBBBEEEEEEEEEE
...
</code>```

where B means the beginning of a tag and E means the end. That is, you must be able to match strings formed by any number of B's followed by the same number of E's. To do that, your matcher must be able to "count", and regular expressions (i.e. finite state automata) simply cannot do that (in order to count, an automaton needs at least a stack). Referring to PEZ's answer, HTML is a context-free grammar, not a regular language.

OwnerDisplayName: Udi Pasmon

Title: Regex for links in html text

LastEditorDisplayName: Udi Pasmon

Body:
Shoudln't a link be a well-defined regex? This is a rather theoretical question,

I second PEZ's answer:

I don't think HTML lends itself to "well defined" regular expressions since it's not a regular language.

As far as I know, any HTML tag may contain any number of nested tags. For example:

<a href="http://stackoverflow.com">stackoverflow</a>
<a href="http://stackoverflow.com"><i>stackoverflow</i></a>
<a href="http://stackoverflow.com"><b><i>stackoverflow</i></b></a>
...

Thus, in principle, to match a tag properly you must be able at least to match strings of the form:

BE
BBEE
BBBEEE
...
BBBBBBBBBBEEEEEEEEEE
...

where B means the beginning of a tag and E means the end. That is, you must be able to match strings formed by any number of B's followed by the same number of E's. To do that, your matcher must be able to "count", and regular expressions (i.e. finite state automata) simply cannot do that (in order to count, an automaton needs at least a stack). Referring to PEZ's answer, HTML is a context-free grammar, not a regular language.

OwnerDisplayName: Federico Ramponi


问:
Of these four libraries, which are you most likely to use?
I'm trying to pick out my next hackery project.  It'll likely be one of the following:

A sparse radix trie Implementation with extremely fast set operations

A really good soft heap implementation

A bloomier filter implementation

A  collection of small financial algorithms, such as deriving total returns given a set of dividends and minimal information about them.

But I can't choose.  So I thought I'd put my fate in the hands of my peers.  Which of those four would you find most useful?  Most interesting to work on?  Which do you think is the most needed?

答: I didn't know what a bloomier (maybe Bloom?) filter is until reading your question. Sounds cool and useful.</p>


问:
Javascript RegExp for matching different values with $ (dollar sign) as part of the string
I'm looking for a way to construct a RegExp object from a user input value that will match against some values which contains a dollar character $ (currency).

As I know this character must be escaped I have issues getting it to work correctly, especially in combination with other operators and characters.

I'm looking for to construct a RegExp that will work based on user input and hence it needs to be dynamic. Trying try to explain the scenario, something in this fashion:

User input: "$50" or "50"

```<code>"$50" // match
"$50 + $5" // match as it matches on "$50"
"$500 + $50" // match as it matches on "$50"
"$500" // should not match
"$5000" // should not match
"$5.50" // should not match
</code>```

user input: "$5000" or "5000"

```<code>"$5000" // match
"$5,000" // match as it resembles the same value
"$5000 + $500" // match
"$5.000" // should not match
"$5000.50" // should not match
</code>```

So basically it should only match the exact user input, with the exception of the dollar character ($), if there's a value that follows it but they are separated by a plus symbol (but still the same string), or if the value has a comma which is commonly used when writing larger numbers (for example 5,000).

Is this possible with a RegExp object?

答:
First, we have to prep the user input a bit — remove the $ if present, and add the beginnings of our regex to allow an optional comma in appropriate thousands places. I've broken out the individual steps, though of course they could be combined:

```<code>var userInput = "$5000";
var userInputWithoutDollar = userInput.replace(/^\$/, "");
var userInputWithOptionalCommas = userInputWithoutDollar.replace(/\B(?=(\d{3})+(?!\d))/g, ",?");
</code>```

That last bit is a variation on this answer for adding commas as thousands separators to a number.

Then, we build our regular expression, remembering that when we're building regular expressions with string literals, we have to double-escape (since backslashes are meaningful both in the string literal and at the regular expression level):

```<code>  var rex = new RegExp("(?:^|[^.,\\d])((?:\\$?)" + userInputWithOptionalCommas + ")(?=$|[^.,\\d])");
</code>```

That says:

Beginning of string or a character that isn't ., ,, or a digit

Find our number with optional commas

And ensure it isn't followed by a ., ,, or digit

The matched text is the first capture group.

Example w/tests:

runTests("$5000", [
    {result: true, value: "$5000"}, // match
    {result: true, value: "$5,000"}, // match as it resembles the same value
    {result: true, value: "$5000 + $500"}, // match
    {result: true, value: "$500 + $5000"}, // match
    {result: false, value: "$5.000"}, // should not match
    {result: false, value: "$5000.50"} // should not match
]);
runTests("500", [
    {result: true, value: "$500"},
    {result: true, value: "$500"},
    {result: false, value: "$1,500"},
    {result: false, value: "1,500"}
]);

function runTests(userInput, tests) {
  var userInputWithoutDollar = userInput.replace(/^\$/, "");
  var userInputWithOptionalCommas = userInputWithoutDollar.replace(/\B(?=(\d{3})+(?!\d))/g, ",?");
  var rex = new RegExp("(?:^|[^.,\\d])((?:\\$?)" + userInputWithOptionalCommas + ")(?=$|[^.,\\d])");
  tests.forEach(function(test) {
      var match = rex.exec(test.value);
      var result = !!match;
      console.log(
          (result == test.result ? "GOOD" : "ERROR") +
          " - Value '" + test.value + "' " +
          (result ? "Matches, got '" + match[1] + "'" : "Doesn't match")
      );
  });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {
  max-height: 100% !important;
}</code>```

Body:
I'm looking for a way to construct a RegExp object from a user input value that will match against some values which contains a dollar character $ (currency).

As I know this character must be escaped I have issues getting it to work correctly, especially in combination with other operators and characters.

I'm looking for to construct a RegExp that will work based on user input and hence it needs to be dynamic. Trying try to explain the scenario, something in this fashion:

User input: "$50" or "50"

"$50" // match
"$50 + $5" // match as it matches on "$50"
"$500 + $50" // match as it matches on "$50"
"$500" // should not match
"$5000" // should not match
"$5.50" // should not match

user input: "$5000" or "5000"

"$5000" // match
"$5,000" // match as it resembles the same value
"$5000 + $500" // match
"$5.000" // should not match
"$5000.50" // should not match

So basically it should only match the exact user input, with the exception of the dollar character ($), if there's a value that follows it but they are separated by a plus symbol (but still the same string), or if the value has a comma which is commonly used when writing larger numbers (for example 5,000).

Is this possible with a RegExp object?

Body:
First, we have to prep the user input a bit — remove the $ if present, and add the beginnings of our regex to allow an optional comma in appropriate thousands places. I've broken out the individual steps, though of course they could be combined:

var userInput = "$5000";
var userInputWithoutDollar = userInput.replace(/^\$/, "");
var userInputWithOptionalCommas = userInputWithoutDollar.replace(/\B(?=(\d{3})+(?!\d))/g, ",?");

That last bit is a variation on this answer for adding commas as thousands separators to a number.

Then, we build our regular expression, remembering that when we're building regular expressions with string literals, we have to double-escape (since backslashes are meaningful both in the string literal and at the regular expression level):

  var rex = new RegExp("(?:^|[^.,\\d])((?:\\$?)" + userInputWithOptionalCommas + ")(?=$|[^.,\\d])");

That says:

Beginning of string or a character that isn't ., ,, or a digit

Find our number with optional commas

And ensure it isn't followed by a ., ,, or digit

The matched text is the first capture group.

Example w/tests:

runTests("$5000", [
    {result: true, value: "$5000"}, // match
    {result: true, value: "$5,000"}, // match as it resembles the same value
    {result: true, value: "$5000 + $500"}, // match
    {result: true, value: "$500 + $5000"}, // match
    {result: false, value: "$5.000"}, // should not match
    {result: false, value: "$5000.50"} // should not match
]);
runTests("500", [
    {result: true, value: "$500"},
    {result: true, value: "$500"},
    {result: false, value: "$1,500"},
    {result: false, value: "1,500"}
]);

function runTests(userInput, tests) {
  var userInputWithoutDollar = userInput.replace(/^\$/, "");
  var userInputWithOptionalCommas = userInputWithoutDollar.replace(/\B(?=(\d{3})+(?!\d))/g, ",?");
  var rex = new RegExp("(?:^|[^.,\\d])((?:\\$?)" + userInputWithOptionalCommas + ")(?=$|[^.,\\d])");
  tests.forEach(function(test) {
      var match = rex.exec(test.value);
      var result = !!match;
      console.log(
          (result == test.result ? "GOOD" : "ERROR") +
          " - Value '" + test.value + "' " +
          (result ? "Matches, got '" + match[1] + "'" : "Doesn't match")
      );
  });
}

.as-console-wrapper {
  max-height: 100% !important;
}


问:
Is increment an atomic operation in JavaScript?
Is increment an atomic operation in JavaScript? If one thread is accessing
++i; and at the same time another one starts to access the operation will there be any problems?

答:
Javascript is single threaded, So you need to worry about deallocks or dirty read problems.
Why doesn't JavaScript support multithreading?</p>


问:
Kubernetes "no IP addresses available in network: podnet; Skipping pod"
I have a 2-host coreos powered k8s setup just like here: https://coreos.com/kubernetes/docs/latest/getting-started.html

It is was setup to work with jenkins kubernetes plugin and after a while I got it to work. It was scheduling containers on the master just fine. Then I left it over the weekend and after coming back to it found that containers are now trying to get scheduled on the other node (not master) but they fail to sync.

```<code>kubectl describe pod jenkinsminions-1582d1b3b52f79
</code>```

But I only have 8 docker containers running on the master and 4 on the slave. I shouldn't have been able to deplete all the IP address space there is. How would I proceed with troubleshooting from here? Should I try to change the pod network from 10.x.x.x to 172.x.x.x?

UPDATES

Both nodes in the cluster are responsive via kubectl and etcd.

```<code>etcdctl get /coreos.com/network/config
{"Network":"10.2.0.0/16","Backend":{"Type":"vxlan"}}

etcdctl ls /coreos.com/network/subnets
/coreos.com/network/subnets/10.2.44.0-24
/coreos.com/network/subnets/10.2.96.0-24
</code>```

Also I observe cni network interface to only be present on the minion node.

答:
I believe it is CNI config inconsistent, you could clean files in <code>/etc/cni/net.d/</code> and restart your cluster.
Also I found your issue report in kubernetes community, I post it here for anyone who meet the same issue.
https://github.com/kubernetes/kubernetes/issues/39557 </p>

Body:
I have a 2-host coreos powered k8s setup just like here: https://coreos.com/kubernetes/docs/latest/getting-started.html

It is was setup to work with jenkins kubernetes plugin and after a while I got it to work. It was scheduling containers on the master just fine. Then I left it over the weekend and after coming back to it found that containers are now trying to get scheduled on the other node (not master) but they fail to sync.

kubectl describe pod jenkinsminions-1582d1b3b52f79

But I only have 8 docker containers running on the master and 4 on the slave. I shouldn't have been able to deplete all the IP address space there is. How would I proceed with troubleshooting from here? Should I try to change the pod network from 10.x.x.x to 172.x.x.x?

UPDATES

Both nodes in the cluster are responsive via kubectl and etcd.

etcdctl get /coreos.com/network/config
{"Network":"10.2.0.0/16","Backend":{"Type":"vxlan"}}

etcdctl ls /coreos.com/network/subnets
/coreos.com/network/subnets/10.2.44.0-24
/coreos.com/network/subnets/10.2.96.0-24

Also I observe cni network interface to only be present on the minion node.

Body:
I believe it is CNI config inconsistent, you could clean files in /etc/cni/net.d/ and restart your cluster.
Also I found your issue report in kubernetes community, I post it here for anyone who meet the same issue.
https://github.com/kubernetes/kubernetes/issues/39557


问:
how to create a foreign key in Oracle
How to link the MgrId in ManagerProject to EmpId in the Employee table ?
This is wat I tried :

```<code>CREATE TABLE Employee(EmpId varchar2(5),
                       EmpName varchar2(25),
                       DeptId varchar2(3),
                       Salary Number(8),
Constraint PK_addn primary key (EmpId, DeptId),
Constraint fk_Department foreign key (DeptId) references Department (DeptId));
</code>```

But the second table failed to be created :

```<code>CREATE TABLE ManagerProject(ProjId varchar2(4),
                            MgrId varchar2(5),
                            StartDate Date,
                            EndDate Date,
Constraint fk_managerproject foreign key (MgrId) references Employee (EmpId),
Constraint PK_Managerproject Primary key(ProjId, MgrId, StartDate));
</code>```

It displays

ORA-02270: no matching unique or primary key for this column-list

答:
The error message says that you are trying to create a FK referencing a column on which there is no Unique or Primary Key constraint.

Assuming that you don't want to add the column DeptId to ManagerProject, you need to add a unique key on employee:

```<code>alter table Employee add constraint empId_UK unique ( empId)
</code>```

But this strongly depends on what your schema should be.

If you want to add the column DeptId to ManagerProject, you will need to edit your FK to both use EmpId and DeptId in referencing employee.

Title: how to create a foreign key in Oracle

Body:
How to link the MgrId in ManagerProject to EmpId in the Employee table ?
This is wat I tried :

CREATE TABLE Employee(EmpId varchar2(5),
                       EmpName varchar2(25),
                       DeptId varchar2(3),
                       Salary Number(8),
Constraint PK_addn primary key (EmpId, DeptId),
Constraint fk_Department foreign key (DeptId) references Department (DeptId));

But the second table failed to be created :

CREATE TABLE ManagerProject(ProjId varchar2(4),
                            MgrId varchar2(5),
                            StartDate Date,
                            EndDate Date,
Constraint fk_managerproject foreign key (MgrId) references Employee (EmpId),
Constraint PK_Managerproject Primary key(ProjId, MgrId, StartDate));

It displays

ORA-02270: no matching unique or primary key for this column-list

Body:
The error message says that you are trying to create a FK referencing a column on which there is no Unique or Primary Key constraint.

Assuming that you don't want to add the column DeptId to ManagerProject, you need to add a unique key on employee:

alter table Employee add constraint empId_UK unique ( empId)

But this strongly depends on what your schema should be.

If you want to add the column DeptId to ManagerProject, you will need to edit your FK to both use EmpId and DeptId in referencing employee.


问:
not submitted app for review
I wanted to submit my app for the App Store on iTunes Connect, but whatever I do I got this last message telling me there are still one or more errors on the page.

Things I completed till now:

Filled app information.

Filled contact information.

Uploaded screenshots for all supported sizes.

Uploaded binary / selected on iTunes connect.

Filled rating form.

Changes done for "Pricing".

Change app versions.

Screenshot of my error in iTunes connect:

Please help me to solve this error.

答:
Step - 1 Your application should now be tested and ready to roll. All you need to do is submit to Apple for approval. This is surprisingly easy considering what you’ve been through already.
Go to Xcode and choose Generic iOS Device in the scheme chooser:

Step - 2 choose Product\Archive:

Step - 3 Xcode should have already validated against most problems. So save yourself some time and click Upload to App Store…

Step - 4 Select your iOS Developer credentials and click Choose:

Step - 5 Next, you will be shown the app to upload. Click Upload:

Step - 6 Your app will start uploading to iTunes Connect. Various windows will update with messages as code is compiled, verified and code-signed. When the upload finishes, you should see the following message:

Step - 7 You now just have a couple of quick steps to submit the app. Switch back to iTunes Connect and scroll down to the Build area you skipped earlier and click Select a build before you submit your app:

Step - 8 Select the build Xcode just uploaded and click Done:

Step - 9 Click Submit for Review:

Title: not submitted app for review


问:
Looping Java switch statement
My system is a banking system and I want my program to loop after the user has interacted with one of the processes (withdraw, view balance etc).

After user get result I want to give a chance to continue with another process:

```<code>package smartcode.atm.h.w;

import java.util.Scanner;

public class SmartCodeATMHW {

    public static void main(String[] args) {
        int p;
        int y = 1234;
        int Amount = 500;
        int result;
        int info;
        int f;
        int g;

        Scanner in = new Scanner(System.in);

        for (int i = 0; i < 3; i++) {
            System.out.println("Please enter PIN Number ");
            p = in.nextInt();

            if (p == y) {
                System.out.println("You have entered correct PIN number \n\n*****************");

                profile pr = new profile();
                pr.setName("Prapashtica");
                System.out.println("Welcome mr." + pr.getName());

                //loop from here
                boolean end = false;
                do{
                    System.out.println("\nPress 1 to View Bank Account");
                    System.out.println("Press 2 to Deposit money");
                    System.out.println("Press 3 to Withdraw money");
                    System.out.println("Press 4 to Cancle the Process \n\n********************");
                    info = in.nextInt();

                    switch (info) {
                        case 1:
                            System.out.println("You have  " + Amount + "$ available");
                            return;

                        case 2:
                            System.out.println("You have  " + Amount + "$ available");
                            System.out.println("Please enter the amount you wish to deposit");
                            f = in.nextInt();

                            result = Amount + f;
                            System.out.println("You have  " + result + "$ available");
                            break;
                        case 3:
                            for (int l = 0; l < 3; l++) {
                                System.out.println("You have  " + Amount + "  $ available");
                                System.out.println("Please eter the amount you wish to withdraw");
                                g = in.nextInt();
                                if (g > 500) {
                                    System.out.println("You cannot withdraw more than your current amount");
                                } else {
                                    System.out.println("You have succesfully withdrawed  " + g + " $");
                                    result = Amount - g;

                                    System.out.println("You now have  " + result + "  $ available");
                                }
                            }
                            System.out.println("Your card is now blocked");
                            break;
                        case 4:
                            System.out.println("You have canceled the proccess");
                            break;
                        default:
                            System.out.println("Error \nInvalid number");
                            break;

                    }
                    return;
                }while (end == false);
            } else {
                System.out.println("You have entered incorrect PIN number  \nPlease try again  \n*******************************");
            }
        }
        System.out.println("Your card is now blocked");
    }
}
</code>```

答:
just put all cases into a infinite loop and when user select case 4 then system.exit(0); will terminate program otherwise it will loop.

import java.util.Scanner;

public class Test {

```<code>public static void main(String [] args){
    int p;
    int y = 1234;
    int Amount = 500;
    int result;
    int info;
    int f;
    int g;

    Scanner in = new Scanner(System.in);

    for (int i = 0; i < 3; i++) {
        System.out.println("Please enter PIN Number ");
        p = in.nextInt();

        if (p == y) {
            System.out.println("You have entered correct PIN number \n\n*****************");

            profile pr = new profile();
            pr.setName("Prapashtica");
            System.out.println("Welcome mr." + pr.getName());

            //loop from here
            boolean end = false;
            while(true){
                System.out.println("\nPress 1 to View Bank Account");
                System.out.println("Press 2 to Deposit money");
                System.out.println("Press 3 to Withdraw money");
                System.out.println("Press 4 to Cancle the Process \n\n********************");
                info = in.nextInt();

                switch (info) {
                    case 1:
                        System.out.println("You have  " + Amount + "$ available");
                        return;

                    case 2:
                        System.out.println("You have  " + Amount + "$ available");
                        System.out.println("Please enter the amount you wish to deposit");
                        f = in.nextInt();

                        result = Amount + f;
                        System.out.println("You have  " + result + "$ available");
                        break;
                    case 3:
                        for (int l = 0; l < 3; l++) {
                            System.out.println("You have  " + Amount + "  $ available");
                            System.out.println("Please eter the amount you wish to withdraw");
                            g = in.nextInt();
                            if (g > 500) {
                                System.out.println("You cannot withdraw more than your current amount");
                            } else {
                                System.out.println("You have succesfully withdrawed  " + g + " $");
                                result = Amount - g;

                                System.out.println("You now have  " + result + "  $ available");
                            }
                        }
                        System.out.println("Your card is now blocked");
                        break;
                    case 4:
                        System.out.println("You have canceled the proccess");
                        System.exit(0);
                        break;
                    default:
                        System.out.println("Error \nInvalid number");
                        break;

                }

            }
        } else {
            System.out.println("You have entered incorrect PIN number  \nPlease try again  \n*******************************");
        }
    }
    System.out.println("Your card is now blocked");

}
</code>```

}

Title: Looping Java switch statement

Body:
My system is a banking system and I want my program to loop after the user has interacted with one of the processes (withdraw, view balance etc).

After user get result I want to give a chance to continue with another process:

package smartcode.atm.h.w;

import java.util.Scanner;

public class SmartCodeATMHW {

    public static void main(String[] args) {
        int p;
        int y = 1234;
        int Amount = 500;
        int result;
        int info;
        int f;
        int g;

        Scanner in = new Scanner(System.in);

        for (int i = 0; i < 3; i++) {
            System.out.println("Please enter PIN Number ");
            p = in.nextInt();

            if (p == y) {
                System.out.println("You have entered correct PIN number \n\n*****************");

                profile pr = new profile();
                pr.setName("Prapashtica");
                System.out.println("Welcome mr." + pr.getName());

                //loop from here
                boolean end = false;
                do{
                    System.out.println("\nPress 1 to View Bank Account");
                    System.out.println("Press 2 to Deposit money");
                    System.out.println("Press 3 to Withdraw money");
                    System.out.println("Press 4 to Cancle the Process \n\n********************");
                    info = in.nextInt();

                    switch (info) {
                        case 1:
                            System.out.println("You have  " + Amount + "$ available");
                            return;

                        case 2:
                            System.out.println("You have  " + Amount + "$ available");
                            System.out.println("Please enter the amount you wish to deposit");
                            f = in.nextInt();

                            result = Amount + f;
                            System.out.println("You have  " + result + "$ available");
                            break;
                        case 3:
                            for (int l = 0; l < 3; l++) {
                                System.out.println("You have  " + Amount + "  $ available");
                                System.out.println("Please eter the amount you wish to withdraw");
                                g = in.nextInt();
                                if (g > 500) {
                                    System.out.println("You cannot withdraw more than your current amount");
                                } else {
                                    System.out.println("You have succesfully withdrawed  " + g + " $");
                                    result = Amount - g;

                                    System.out.println("You now have  " + result + "  $ available");
                                }
                            }
                            System.out.println("Your card is now blocked");
                            break;
                        case 4:
                            System.out.println("You have canceled the proccess");
                            break;
                        default:
                            System.out.println("Error \nInvalid number");
                            break;

                    }
                    return;
                }while (end == false);
            } else {
                System.out.println("You have entered incorrect PIN number  \nPlease try again  \n*******************************");
            }
        }
        System.out.println("Your card is now blocked");
    }
}

Body:
just put all cases into a infinite loop and when user select case 4 then system.exit(0); will terminate program otherwise it will loop.

import java.util.Scanner;

public class Test {

public static void main(String [] args){
    int p;
    int y = 1234;
    int Amount = 500;
    int result;
    int info;
    int f;
    int g;

    Scanner in = new Scanner(System.in);

    for (int i = 0; i < 3; i++) {
        System.out.println("Please enter PIN Number ");
        p = in.nextInt();

        if (p == y) {
            System.out.println("You have entered correct PIN number \n\n*****************");

            profile pr = new profile();
            pr.setName("Prapashtica");
            System.out.println("Welcome mr." + pr.getName());

            //loop from here
            boolean end = false;
            while(true){
                System.out.println("\nPress 1 to View Bank Account");
                System.out.println("Press 2 to Deposit money");
                System.out.println("Press 3 to Withdraw money");
                System.out.println("Press 4 to Cancle the Process \n\n********************");
                info = in.nextInt();

                switch (info) {
                    case 1:
                        System.out.println("You have  " + Amount + "$ available");
                        return;

                    case 2:
                        System.out.println("You have  " + Amount + "$ available");
                        System.out.println("Please enter the amount you wish to deposit");
                        f = in.nextInt();

                        result = Amount + f;
                        System.out.println("You have  " + result + "$ available");
                        break;
                    case 3:
                        for (int l = 0; l < 3; l++) {
                            System.out.println("You have  " + Amount + "  $ available");
                            System.out.println("Please eter the amount you wish to withdraw");
                            g = in.nextInt();
                            if (g > 500) {
                                System.out.println("You cannot withdraw more than your current amount");
                            } else {
                                System.out.println("You have succesfully withdrawed  " + g + " $");
                                result = Amount - g;

                                System.out.println("You now have  " + result + "  $ available");
                            }
                        }
                        System.out.println("Your card is now blocked");
                        break;
                    case 4:
                        System.out.println("You have canceled the proccess");
                        System.exit(0);
                        break;
                    default:
                        System.out.println("Error \nInvalid number");
                        break;

                }

            }
        } else {
            System.out.println("You have entered incorrect PIN number  \nPlease try again  \n*******************************");
        }
    }
    System.out.println("Your card is now blocked");

}

}


问:
How to pass Json string with variable in c#?
```<code>string a;

string b;

string jSonContent = @"{""fields"":{""summary"":""summary"" , ""description"": ""modified.""}}";
</code>```

I want a instead of summary and b instead of modified. It works if I replace summary but gives errors if I replace both.

The edited code is, string jSonContent = @"{""fields"":{""summary"":"+ "\""+ a+ "\"" +" , ""description"": "+ "\""+ b+ "\"" +"}}"; It's not giving any error, summary field is getting updated, but the description field is not.

Please revert. Thanks!

答:
I highly suggest you to use JSON library, for example Json.Net.

First of all, you'll be able to work with strongly typed objects, in addition you will avoid typos and similar bugs since the serializer will do the serialization for you.

```<code>public void Test()
{
    string a = ""; //content of 'a' variable
    string b = ""; //content of 'b' variable

    var obj = new RootObject();
    obj.Fields = new Fields();

    obj.Fields.Summary = a;
    obj.Fields.Description = b;

    var jsonOutput = Newtonsoft.Json.JsonSerializer.Serialize(obj, typeof(RootObject));
}

public class Fields
{
    [JsonProperty("summary")]
    public string Summary { get; set; }

    [JsonProperty("description")]
    public string Description { get; set; }
}

public class RootObject
{
    [JsonProperty("fields")]
    public Fields Fields { get; set; }
}
</code>```

Note: If you don't want to create unnecessary types, you can work directly with JObject, this is one of possible uses:

```<code>var jobj = Newtonsoft.Json.Linq.JObject.FromObject(new {
    fields = new {
        summary = a,
        description = b
    }
});
var jsonOutput = jobj.ToString();
</code>```

Body:
string a;

string b;

string jSonContent = @"{""fields"":{""summary"":""summary"" , ""description"": ""modified.""}}";

I want a instead of summary and b instead of modified. It works if I replace summary but gives errors if I replace both.

The edited code is, string jSonContent = @"{""fields"":{""summary"":"+ "\""+ a+ "\"" +" , ""description"": "+ "\""+ b+ "\"" +"}}"; It's not giving any error, summary field is getting updated, but the description field is not.

Please revert. Thanks!

Body:
I highly suggest you to use JSON library, for example Json.Net.

First of all, you'll be able to work with strongly typed objects, in addition you will avoid typos and similar bugs since the serializer will do the serialization for you.

public void Test()
{
    string a = ""; //content of 'a' variable
    string b = ""; //content of 'b' variable

    var obj = new RootObject();
    obj.Fields = new Fields();

    obj.Fields.Summary = a;
    obj.Fields.Description = b;

    var jsonOutput = Newtonsoft.Json.JsonSerializer.Serialize(obj, typeof(RootObject));
}

public class Fields
{
    [JsonProperty("summary")]
    public string Summary { get; set; }

    [JsonProperty("description")]
    public string Description { get; set; }
}

public class RootObject
{
    [JsonProperty("fields")]
    public Fields Fields { get; set; }
}

Note: If you don't want to create unnecessary types, you can work directly with JObject, this is one of possible uses:

var jobj = Newtonsoft.Json.Linq.JObject.FromObject(new {
    fields = new {
        summary = a,
        description = b
    }
});
var jsonOutput = jobj.ToString();


问:
Error F_SETLK when building bazel on CentOS 6.5
I am working on building and installing tensorflow on my institution's cluster computer, which is running CentOS 6.5.

Obviously, the first step is building and installing bazel. The build works just fine, but when I try to run the bazel binary, I get the following error:

Error: unexpected result from F_SETLK: Function not implemented

gcc version is 4.7.2

java version is jdk1.8.0_65

edit: I have also tried compiling gcc 4.9.4 and building with this version, and I have tried building both the latest dist of bazel, and the 0.3.1 from the git repo. All variants get the same error.

答:
This happens if the filesystem where Bazel tries to install itself (unpack its embedded tools) doesn't support locking.

Workaround (until the relevant issue is resolved) is to specify a path on a local, writable (and file-lockable) filesystem for --output_user_root, for example:

```<code>bazel --output_user_root=/usr/local/$USER/bazelout build <targets>
</code>```

Body:
This happens if the filesystem where Bazel tries to install itself (unpack its embedded tools) doesn't support locking.

Workaround (until the relevant issue is resolved) is to specify a path on a local, writable (and file-lockable) filesystem for --output_user_root, for example:

bazel --output_user_root=/usr/local/$USER/bazelout build <targets>


问:
Error starting MongoDB in windows 7 [32-bit]
I followed a blog(link) to install and configure MongoDB in my system[Windows 7 32 bit].

As per blogger said, I have download mongodb-win32-i386-2.6.5 and extract to D:/mongodb/ and followed the blog

Upto installation everything alright, but when I try to start service using following command,

```<code> D:\mongodb\bin>net start MongoDB
</code>```

I got error response as,

```<code>System error 2 has occurred.

The system cannot find the file specified.
</code>```

How to solve this ?

Update : Log File

2014-11-19T16:43:25.356+0530 [DataFileSync] flushing diag log

2014-11-19T16:43:25.403+0530 [initandlisten] MongoDB starting : pid=5128 port=27017 dbpath=D:\mongodb\data 32-bit host=AVVENIRE-JAVA

2014-11-19T16:43:25.403+0530 [initandlisten]

2014-11-19T16:43:25.403+0530 [initandlisten] ** NOTE: This is a 32 bit MongoDB binary.

2014-11-19T16:43:25.403+0530 [initandlisten] **       32 bit builds are limited to less than 2GB of data (or less with --journal).

2014-11-19T16:43:25.403+0530 [initandlisten] **       See http://dochub.mongodb.org/core/32bit

2014-11-19T16:43:25.404+0530 [initandlisten]

2014-11-19T16:43:25.404+0530 [initandlisten] targetMinOS: Windows XP SP3

2014-11-19T16:43:25.404+0530 [initandlisten] db version v2.6.1

2014-11-19T16:43:25.404+0530 [initandlisten] git version: 4b95b086d2374bdcfcdf2249272fb552c9c726e8

2014-11-19T16:43:25.404+0530 [initandlisten] build info: windows sys.getwindowsversion(major=6, minor=0, build=6002, platform=2, service_pack='Service Pack 2') BOOST_LIB_VERSION=1_49

2014-11-19T16:43:25.404+0530 [initandlisten] allocator: system
2014-11-19T16:43:25.404+0530 [initandlisten] options: { config: "d:\mongodb\mongo.config", diaglog: 3, net: { bindIp: "127.0.0.1", port: 27017 }, storage: { dbPath: "D:\mongodb\data", journal: { enabled: true } }, systemLog: { destination: "file", logAppend: true, path: "D:\mongodb\log\mongo.log", quiet: true } }

2014-11-19T16:43:25.483+0530 [initandlisten] journal dir=D:\mongodb\data\journal

2014-11-19T16:43:25.484+0530 [initandlisten] recover : no journal files present, no recovery needed

2014-11-19T16:43:25.770+0530 [initandlisten] waiting for connections on port 27017

2014-11-19T16:44:25.439+0530 [DataFileSync] flushing diag log

2014-11-19T16:45:25.361+0530 [DataFileSync] flushing diag log

2014-11-19T16:46:25.360+0530 [DataFileSync] flushing diag log

2014-11-19T16:46:31.869+0530 [conn1] terminating, shutdown command received

2014-11-19T16:46:31.869+0530 [conn1] dbexit: shutdown called

2014-11-19T16:46:31.869+0530 [conn1] shutdown: going to close listening sockets...

2014-11-19T16:46:31.869+0530 [conn1] closing listening socket: 540

2014-11-19T16:46:31.869+0530 [conn1] shutdown: going to flush diaglog...

2014-11-19T16:46:31.869+0530 [conn1] flushing diag log

2014-11-19T16:46:31.869+0530 [conn1] shutdown: going to close sockets...

2014-11-19T16:46:31.870+0530 [conn1] shutdown: waiting for fs preallocator...

2014-11-19T16:46:31.870+0530 [conn1] shutdown: lock for final commit...

2014-11-19T16:46:31.870+0530 [conn1] shutdown: final commit...

2014-11-19T16:46:31.873+0530 [conn1] shutdown: closing all files...

2014-11-19T16:46:31.873+0530 [conn1] closeAllFiles() finished

2014-11-19T16:46:31.873+0530 [conn1] journalCleanup...

2014-11-19T16:46:31.889+0530 [conn1] removeJournalFiles

2014-11-19T16:46:31.891+0530 [conn1] shutdown: removing fs lock...

2014-11-19T16:46:31.891+0530 [conn1] dbexit: really exiting now

2014-11-19T16:47:08.985+0530 ***** SERVER RESTARTED *****

2014-11-19T16:47:08.985+0530 Trying to install Windows service 'MongoDB'

2014-11-19T16:47:08.985+0530 There is already a service named 'MongoDB', aborting

Update 2(result of @disposer's suggestion):

答:
Download from this link @ http://downloads.mongodb.org/win32/mongodb-win32-i386-v3.2-latest-signed.msi?_ga=1.10304565.1436936475.1490595203

After installation in E: drive, run mongod command with options
 @ E:\Program Files\MongoDB\Server\3.2\bin>
mongod --storageEngine=mmapv1 --dbpath C:\data\db

Observe, two options are necessary to be installed without errors, specially for 32-bit, --storageEngine=mmapv1 and create a directory in OS drive(c:) only as --dbpath C:\data\db

Keep your server running at command prompt, install mongobooster from http://s3.mongobooster.com/download/3.5/mongobooster-3.5.3.exe for GUI to manage mongodb.
and connect to local database..try samples @ https://www.youtube.com/playlist?list=PL6gx4Cwl9DGDQ5DrbIl20Zu9hx1IjeVhO

Body:
I followed a blog(link) to install and configure MongoDB in my system[Windows 7 32 bit].

As per blogger said, I have download mongodb-win32-i386-2.6.5 and extract to D:/mongodb/ and followed the blog

Upto installation everything alright, but when I try to start service using following command,

 D:\mongodb\bin>net start MongoDB

I got error response as,

System error 2 has occurred.

The system cannot find the file specified.

How to solve this ?

Update : Log File

2014-11-19T16:43:25.356+0530 [DataFileSync] flushing diag log

2014-11-19T16:43:25.403+0530 [initandlisten] MongoDB starting : pid=5128 port=27017 dbpath=D:\mongodb\data 32-bit host=AVVENIRE-JAVA

2014-11-19T16:43:25.403+0530 [initandlisten]

2014-11-19T16:43:25.403+0530 [initandlisten] ** NOTE: This is a 32 bit MongoDB binary.

2014-11-19T16:43:25.403+0530 [initandlisten] **       32 bit builds are limited to less than 2GB of data (or less with --journal).

2014-11-19T16:43:25.403+0530 [initandlisten] **       See http://dochub.mongodb.org/core/32bit

2014-11-19T16:43:25.404+0530 [initandlisten]

2014-11-19T16:43:25.404+0530 [initandlisten] targetMinOS: Windows XP SP3

2014-11-19T16:43:25.404+0530 [initandlisten] db version v2.6.1

2014-11-19T16:43:25.404+0530 [initandlisten] git version: 4b95b086d2374bdcfcdf2249272fb552c9c726e8

2014-11-19T16:43:25.404+0530 [initandlisten] build info: windows sys.getwindowsversion(major=6, minor=0, build=6002, platform=2, service_pack='Service Pack 2') BOOST_LIB_VERSION=1_49

2014-11-19T16:43:25.404+0530 [initandlisten] allocator: system
2014-11-19T16:43:25.404+0530 [initandlisten] options: { config: "d:\mongodb\mongo.config", diaglog: 3, net: { bindIp: "127.0.0.1", port: 27017 }, storage: { dbPath: "D:\mongodb\data", journal: { enabled: true } }, systemLog: { destination: "file", logAppend: true, path: "D:\mongodb\log\mongo.log", quiet: true } }

2014-11-19T16:43:25.483+0530 [initandlisten] journal dir=D:\mongodb\data\journal

2014-11-19T16:43:25.484+0530 [initandlisten] recover : no journal files present, no recovery needed

2014-11-19T16:43:25.770+0530 [initandlisten] waiting for connections on port 27017

2014-11-19T16:44:25.439+0530 [DataFileSync] flushing diag log

2014-11-19T16:45:25.361+0530 [DataFileSync] flushing diag log

2014-11-19T16:46:25.360+0530 [DataFileSync] flushing diag log

2014-11-19T16:46:31.869+0530 [conn1] terminating, shutdown command received

2014-11-19T16:46:31.869+0530 [conn1] dbexit: shutdown called

2014-11-19T16:46:31.869+0530 [conn1] shutdown: going to close listening sockets...

2014-11-19T16:46:31.869+0530 [conn1] closing listening socket: 540

2014-11-19T16:46:31.869+0530 [conn1] shutdown: going to flush diaglog...

2014-11-19T16:46:31.869+0530 [conn1] flushing diag log

2014-11-19T16:46:31.869+0530 [conn1] shutdown: going to close sockets...

2014-11-19T16:46:31.870+0530 [conn1] shutdown: waiting for fs preallocator...

2014-11-19T16:46:31.870+0530 [conn1] shutdown: lock for final commit...

2014-11-19T16:46:31.870+0530 [conn1] shutdown: final commit...

2014-11-19T16:46:31.873+0530 [conn1] shutdown: closing all files...

2014-11-19T16:46:31.873+0530 [conn1] closeAllFiles() finished

2014-11-19T16:46:31.873+0530 [conn1] journalCleanup...

2014-11-19T16:46:31.889+0530 [conn1] removeJournalFiles

2014-11-19T16:46:31.891+0530 [conn1] shutdown: removing fs lock...

2014-11-19T16:46:31.891+0530 [conn1] dbexit: really exiting now

2014-11-19T16:47:08.985+0530 ***** SERVER RESTARTED *****

2014-11-19T16:47:08.985+0530 Trying to install Windows service 'MongoDB'

2014-11-19T16:47:08.985+0530 There is already a service named 'MongoDB', aborting

Update 2(result of @disposer's suggestion):


问:
How do I get my modal information to show, while trying to make it dynamic?
Trying to open a modal which should grab information from my database and present it onto the modal, after clicking on a specific image. The modal pops up, but it shows on the html inputs and none of the php inputs. How can i fix this?  rental_id is the primary in the database table.

```<code><?php
 require_once '../core/init.php';
$id = $_POST['rental_id'];
$id = (int)$id;
$sql = "SELECT * FROM rental WHERE rental_id = '$id'";
$result = $db->query($sql);
$rental = mysqli_fetch_assoc($result);

 ?>

 <!-- the div that represents the modal for the form -->
 <?php ob_start();?>
            <div class="modal fade" id="quote" tabindex="-1" role="dialog" aria-labelledby="quote" aria-hidden="true">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button class="close" type="button" data-dismiss='modal' aria-label="Close">
                                <span aria-hidden="true">×</span>
                            </button>
                            <h4 class="modal-title text-center">Quote</h4>
                        </div>
                        <div class="modal-body">
                            <div class="container-fluid">
                                <div class="row">
                                <div class="col-sm-6">
                                <div class="center-block">
                                    <img src="<?= $rental['img']; ?>" alt="<?= $rental['make']; ?>" class="w3-image img-responsive"/>
                                </div>...
</code>```

and...

```<code><script>
    function detailsmodal(rental_id){
        var data = {"rental_id" : rental_id};
        jQuery.ajax({
            url : <?php echo BASEURL;?> + 'includes/detailsmodal.php',
            method : "post",
            data : data,
            success: function(data){
                jQuery('body').append(data);
                jQuery('#quote').modal('show');
            },
            error: function(){
                alert("Something went wrong!");
            }
        });
    }
</script>
</code>```

答:
Have you checked $id = (int)$id; ? is it set, ok with a value ?
Any return error message ? (SO question )

```<code><?php
print_r($rental); /* seems ok when tested with ie: $id=3 */

$sql = " SELECT img, make FROM rental WHERE rental_id=? ";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $id);

$results = $stmt->execute();
$stmt->bind_result($img, $make);
$stmt->store_result();

while($stmt->fetch()){
echo"[ $img / $make ]";
}
?>
</code>```

does it make a difference ?

Body:
Trying to open a modal which should grab information from my database and present it onto the modal, after clicking on a specific image. The modal pops up, but it shows on the html inputs and none of the php inputs. How can i fix this?  rental_id is the primary in the database table.

<?php
 require_once '../core/init.php';
$id = $_POST['rental_id'];
$id = (int)$id;
$sql = "SELECT * FROM rental WHERE rental_id = '$id'";
$result = $db->query($sql);
$rental = mysqli_fetch_assoc($result);

 ?>

 <?php ob_start();?>

                            <button class="close" type="button" data-dismiss='modal' aria-label="Close">
                                ×
                            </button>

Quote

                                    <img src="<?= $rental['img']; ?>" alt="<?= $rental['make']; ?>" class="w3-image img-responsive"/>

...

and...

Body:
Have you checked $id = (int)$id; ? is it set, ok with a value ?
Any return error message ? (SO question )

<?php
print_r($rental); /* seems ok when tested with ie: $id=3 */

$sql = " SELECT img, make FROM rental WHERE rental_id=? ";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $id);

$results = $stmt->execute();
$stmt->bind_result($img, $make);
$stmt->store_result();

while($stmt->fetch()){
echo"[ $img / $make ]";
}
?>

does it make a difference ?