问:
Where is a singleton instance stored in ninject?
The title has it all.  When I do this:

```<code>var kernel = new StandardKernel();
kernel.Bind<IMyClass>().To<MyClass>().InSingletonScope();
var myClass = kernel.Get<IMyClass>();
</code>```

Where is the instance of MyClass stored?  Is it stored in a static dictionary somewhere globally?  Or is it stored in the kernel instance?

For example if I do this:

```<code>var kernel1 = new StandardKernel();
var kernel2 = new StandardKernel();
kernel1.Bind<IMyClass>().To<MyClass>().InSingletonScope();
kernel2.Bind<IMyClass>().To<MyClass>().InSingletonScope();
var myClass1 = kernel1.Get<IMyClass>();
var myClass2 = kernel2.Get<IMyClass>();
</code>```

Will myClass1 be the same instance as myClass2 or will they be different instances.

To kind of jump on an inevitable question "Why do you need to do that?":  It doesn't matter.  That is not the point of the question.  I have my reasons and just want to know how this piece works.

答:
So Ninject stores them here:

```<code>  /// <summary>Tracks instances for re-use in certain scopes.</summary>
  public class Cache : NinjectComponent, ICache, INinjectComponent, IDisposable, IPruneable
  {
    /// <summary>
    /// Contains all cached instances.
    /// This is a dictionary of scopes to a multimap for bindings to cache entries.
    /// </summary>
    private readonly IDictionary<object, Multimap<IBindingConfiguration, Cache.CacheEntry>> entries = (IDictionary<object, Multimap<IBindingConfiguration, Cache.CacheEntry>>) new Dictionary<object, Multimap<IBindingConfiguration, Cache.CacheEntry>>((IEqualityComparer<object>) new WeakReferenceEqualityComparer());
...
</code>```

and Cache is scoped to instance of a kernel.

Will myClass1 be the same instance as myClass2 or will they be
  different instances.

Different. Cache is not static.

Body:
The title has it all.  When I do this:

var kernel = new StandardKernel();
kernel.Bind<IMyClass>().To<MyClass>().InSingletonScope();
var myClass = kernel.Get<IMyClass>();

Where is the instance of MyClass stored?  Is it stored in a static dictionary somewhere globally?  Or is it stored in the kernel instance?

For example if I do this:

var kernel1 = new StandardKernel();
var kernel2 = new StandardKernel();
kernel1.Bind<IMyClass>().To<MyClass>().InSingletonScope();
kernel2.Bind<IMyClass>().To<MyClass>().InSingletonScope();
var myClass1 = kernel1.Get<IMyClass>();
var myClass2 = kernel2.Get<IMyClass>();

Will myClass1 be the same instance as myClass2 or will they be different instances.

To kind of jump on an inevitable question "Why do you need to do that?":  It doesn't matter.  That is not the point of the question.  I have my reasons and just want to know how this piece works.

Body:
So Ninject stores them here:

  /// <summary>Tracks instances for re-use in certain scopes.</summary>
  public class Cache : NinjectComponent, ICache, INinjectComponent, IDisposable, IPruneable
  {
    /// <summary>
    /// Contains all cached instances.
    /// This is a dictionary of scopes to a multimap for bindings to cache entries.
    /// </summary>
    private readonly IDictionary<object, Multimap<IBindingConfiguration, Cache.CacheEntry>> entries = (IDictionary<object, Multimap<IBindingConfiguration, Cache.CacheEntry>>) new Dictionary<object, Multimap<IBindingConfiguration, Cache.CacheEntry>>((IEqualityComparer<object>) new WeakReferenceEqualityComparer());
...

and Cache is scoped to instance of a kernel.

Will myClass1 be the same instance as myClass2 or will they be
  different instances.

Different. Cache is not static.


来源: stackexchange

问:
R: using param_get
I am new to R, migrating from SAS :) I have the following df:

```<code>id      scd     cat     qs
700689  1       di      NS=Ev12&id=1048&id2=1048&id3=ZX&HId=xl
</code>```

The qs is a url decoded query string and I am trying to get the following output

```<code>id      scd  cat    qs                               NS   id  id2  id3 HId
700689  1    di     NS=Ev12&id=1&id2=10&id3=Z&HId=x  Ev12  1   10  Z    X
</code>```

I am using the following code and the output seems to add a"q." to every column. I am unable to use any function on the added columns.

raw2$q <- param_get(raw2$qs, c("NS","id","id2","id3",HId"))

e.g. test <- na.omit(raw2$NS) does not work.

Any suggestion and help will be appreciated

答:
You can also do the following with tidyverse:

```<code>library(dplyr)
library(tidyr)
library(stringr)

df %>%
  extract(qs, str_extract_all(df$qs, "(?<=^|&).+?(?==|$)")[[1]],
          "^.+?=(.+)&.+?=(.+)&.+?=(.+)&.+?=(.+)&.+?=(.+)$", remove = FALSE)
</code>```

or:

```<code>str_extract_all(df$qs, "(?<==).+?(?=&|$)") %>%
  lapply(setNames, str_extract_all(df$qs, "(?<=^|&).+?(?==|$)")[[1]]) %>%
  do.call(rbind, .) %>%
  cbind(df, .)
</code>```

Result:

```<code>      id scd cat                                     qs   NS   id  id2 id3 HId
1 700689   1  di NS=Ev12&id=1048&id2=1048&id3=ZX&HId=xl Ev12 1048 1048  ZX  xl
</code>```

ContentLicense: CC BY-SA 3.0

Title: R: using param_get

Body:
I am new to R, migrating from SAS :) I have the following df:

id      scd     cat     qs
700689  1       di      NS=Ev12&id=1048&id2=1048&id3=ZX&HId=xl

The qs is a url decoded query string and I am trying to get the following output

id      scd  cat    qs                               NS   id  id2  id3 HId
700689  1    di     NS=Ev12&id=1&id2=10&id3=Z&HId=x  Ev12  1   10  Z    X

I am using the following code and the output seems to add a"q." to every column. I am unable to use any function on the added columns.

raw2$q <- param_get(raw2$qs, c("NS","id","id2","id3",HId"))

e.g. test <- na.omit(raw2$NS) does not work.

Any suggestion and help will be appreciated

Body:
You can also do the following with tidyverse:

library(dplyr)
library(tidyr)
library(stringr)

df %>%
  extract(qs, str_extract_all(df$qs, "(?<=^|&).+?(?==|$)")[[1]],
          "^.+?=(.+)&.+?=(.+)&.+?=(.+)&.+?=(.+)&.+?=(.+)$", remove = FALSE)

or:

str_extract_all(df$qs, "(?<==).+?(?=&|$)") %>%
  lapply(setNames, str_extract_all(df$qs, "(?<=^|&).+?(?==|$)")[[1]]) %>%
  do.call(rbind, .) %>%
  cbind(df, .)

Result:

      id scd cat                                     qs   NS   id  id2 id3 HId
1 700689   1  di NS=Ev12&id=1048&id2=1048&id3=ZX&HId=xl Ev12 1048 1048  ZX  xl


问:
AVCaptureDevice on macOS
Is it possible to display a camera feed in a macOS app? I'm basically trying to capture images frame by frame from a camera feed. I know how to do this in iOS, but for some reasons, on macOS, I can't seem to find any AVCaptureDevice for video.

```<code>let x = AVCaptureDevice.devices()
</code>```

// When I print x, I only see the Microphone as the only capture device. No reference to video/camera whatsoever

```<code>guard let device = AVCaptureDevice.default(for: .video) else{ return }
</code>```

答:
To find available capture devices use AVCaptureDevice.DiscoverySession as documented here

Then use the default(_:for:position:) method to return a default device for the specified media type as documented here

Title: AVCaptureDevice on macOS

Body:
Is it possible to display a camera feed in a macOS app? I'm basically trying to capture images frame by frame from a camera feed. I know how to do this in iOS, but for some reasons, on macOS, I can't seem to find any AVCaptureDevice for video.

let x = AVCaptureDevice.devices()

// When I print x, I only see the Microphone as the only capture device. No reference to video/camera whatsoever

guard let device = AVCaptureDevice.default(for: .video) else{ return }


问:
github, how to search issues I posted or commented
github only list top several issues I posted or commented, so I'm wondering how to search for the rest of them myself, of all issues that I myself participated.

答:
I achieved this by putting is:issue involves:my-username in GitHub search.

This chapter from official docs can be really helpful GitHub Help: Searching issues and pull requests.


问:
Find folder of specific file
I am trying to find the folder location of a specific file, for this example libgfortran.so.

What I've tried so far is:

```<code>find 2>/dev/null / -name libgfortran.so
</code>```

... which will output something like the following to stdout (redirecting stderr to /dev/null):

```<code>/usr/lib/gcc/x86_64-linux-gnu/4.8/libgfortran.so
</code>```

From this I want to extract just the folder (without a trailing /):

```<code>/usr/lib/gcc/x86_64-linux-gnu/4.8
</code>```

I've got as far as trying something like:

```<code>find 2>/dev/null / -name libgfortran.so | sed 's/\(\/.*\/\)/\1/'
</code>```

... which I was hoping would capture what is between the first and last / (I would then need to remove the last /), but the output I get is still:

```<code>/usr/lib/gcc/x86_64-linux-gnu/4.8/libgfortran.so
</code>```

How do I achieve what I want?

答:
Something like:

```<code>dirname `find 2>/dev/null / -name libgfortran.so`
</code>```

should work.

Title: Find folder of specific file

Body:
I am trying to find the folder location of a specific file, for this example libgfortran.so.

What I've tried so far is:

find 2>/dev/null / -name libgfortran.so

... which will output something like the following to stdout (redirecting stderr to /dev/null):

/usr/lib/gcc/x86_64-linux-gnu/4.8/libgfortran.so

From this I want to extract just the folder (without a trailing /):

/usr/lib/gcc/x86_64-linux-gnu/4.8

I've got as far as trying something like:

find 2>/dev/null / -name libgfortran.so | sed 's/\(\/.*\/\)/\1/'

... which I was hoping would capture what is between the first and last / (I would then need to remove the last /), but the output I get is still:

/usr/lib/gcc/x86_64-linux-gnu/4.8/libgfortran.so

How do I achieve what I want?

Body:
Something like:

dirname `find 2>/dev/null / -name libgfortran.so`

should work.


问:
How to check if link redirects to another URI when I open it from mobile phone
I want to check if link redirects to another URI when I open it from mobile phone (Android). I know that site, which I tested, changes its link from "www.site.com" to "www.m.site.com", when I open it from mobile phone.

I tried this code, but it doesn't work:

```<code>HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("User-Agent", "Mozilla/5.0 (Linux; Android 7.0; SAMSUNG SM-G930F Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/6.2 Chrome/56.0.2924.87 Mobile Safari/537.36");

HttpClient httpClient = HttpClients.createDefault();
HttpClientContext context = HttpClientContext.create();
httpClient.execute(httpGet, context);
List<URI> redirectURIs = context.getRedirectLocations();
if (redirectURIs != null && !redirectURIs.isEmpty()) {
    for (URI redirectURI : redirectURIs) {
        System.out.println("Redirect URI: " + redirectURI);
    }
    URI mobileURI = redirectURIs.get(redirectURIs.size() - 1);
    return mobileURI.toString();
}
</code>```

I always receive null in mobileURI. I would appreciate any help.

答:
To test if the page will redirect after it is loaded you need to emulate target (in your case mobile) browser. You can do this with SeleniumHQ (org.seleniumhq.selenium:selenium-server:3.4.0) and Chrome Driver. For example:</p>

```<code>@Test
public void testSeleniumChromeDriver() throws IOException {
    // Create a new instance of the Chrome driver
    System.setProperty("webdriver.chrome.driver", "/usr/bin/chromedriver");
    Map<String, Object> deviceMetrics = new HashMap<>();
    deviceMetrics.put("width", 360);
    deviceMetrics.put("height", 640);
    deviceMetrics.put("pixelRatio", 3.0);

    Map<String, Object> mobileEmulation = new HashMap<>();
    mobileEmulation.put("deviceMetrics", deviceMetrics);
    mobileEmulation.put("userAgent", "Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19");

    ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.setExperimentalOption("mobileEmulation", mobileEmulation);
    WebDriver driver = new ChromeDriver(chromeOptions);

    // GET the page
    driver.get("http://www.fishki.net");

    try {
        assertThat(driver.getCurrentUrl(), is("http://m.fishki.net/"));
    } finally {
        //Close the browser
        driver.quit();
    }
}
</code>```

Body:
I want to check if link redirects to another URI when I open it from mobile phone (Android). I know that site, which I tested, changes its link from "www.site.com" to "www.m.site.com", when I open it from mobile phone.

I tried this code, but it doesn't work:

HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("User-Agent", "Mozilla/5.0 (Linux; Android 7.0; SAMSUNG SM-G930F Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/6.2 Chrome/56.0.2924.87 Mobile Safari/537.36");

HttpClient httpClient = HttpClients.createDefault();
HttpClientContext context = HttpClientContext.create();
httpClient.execute(httpGet, context);
List<URI> redirectURIs = context.getRedirectLocations();
if (redirectURIs != null && !redirectURIs.isEmpty()) {
    for (URI redirectURI : redirectURIs) {
        System.out.println("Redirect URI: " + redirectURI);
    }
    URI mobileURI = redirectURIs.get(redirectURIs.size() - 1);
    return mobileURI.toString();
}

I always receive null in mobileURI. I would appreciate any help.

Body:
To test if the page will redirect after it is loaded you need to emulate target (in your case mobile) browser. You can do this with SeleniumHQ (org.seleniumhq.selenium:selenium-server:3.4.0) and Chrome Driver. For example:

@Test
public void testSeleniumChromeDriver() throws IOException {
    // Create a new instance of the Chrome driver
    System.setProperty("webdriver.chrome.driver", "/usr/bin/chromedriver");
    Map<String, Object> deviceMetrics = new HashMap<>();
    deviceMetrics.put("width", 360);
    deviceMetrics.put("height", 640);
    deviceMetrics.put("pixelRatio", 3.0);

    Map<String, Object> mobileEmulation = new HashMap<>();
    mobileEmulation.put("deviceMetrics", deviceMetrics);
    mobileEmulation.put("userAgent", "Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19");

    ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.setExperimentalOption("mobileEmulation", mobileEmulation);
    WebDriver driver = new ChromeDriver(chromeOptions);

    // GET the page
    driver.get("http://www.fishki.net");

    try {
        assertThat(driver.getCurrentUrl(), is("http://m.fishki.net/"));
    } finally {
        //Close the browser
        driver.quit();
    }
}


问:
Adding a subelement to a subelement lxml
I am using lxml in an attempt to to output the following xml code:

```<code><annotation>
    <folder>images</folder>
    <filename>IMG_8111.JPG</filename>
    <size>
        <width>400</width>
        <height>400</height>
    </size>
    <segmented>0</segmented>
    <object>
        <name>Bottle</name>
        <bndbox>
            <xmin>16</xmin>
            <ymin>71</ymin>
            <xmax>390</xmax>
            <ymax>323</ymax>
        </bndbox>
    </object>
</annotation>
</code>```

Im using this tutorial to learn how to implement lxml for my needs. The issue I am facing is that my desired output has subelements to subelements. For instance - <annotation> is my main element, and then <folder>, <filename> and <size> are subelements, but then, <height> and <width>' are subelements to the` subelements. How do I make this happen with lxml. I have the following so far:

```<code>from lxml import etree
import xml.etree.cElementTree as ET

root = etree.Element("annotation")
etree.SubElement(root, "folder").text = "Child 1"
etree.SubElement(root, "filename").text = "Child 2"
size = etree.SubElement(root, "size").text = "Child 3"
etree.SubElement(size, "width").text = "Child 4"

with open ('xmltree.xml', 'wb') as f:
    f.write(etree.tostring(root, pretty_print = True))
</code>```

But it throws the following error:

```<code> etree.SubElement(size, "width").text = "Child 4"
TypeError: Argument '_parent' has incorrect type (expected lxml.etree._Element, got str)
</code>```

Please help me out on what I am doing wrong and how to proceed.

答:
Your variable size has type string because it has "child 3" value. You should do: </p>

```<code>size = etree.SubElement(root,"size")
size.text = "child 3"
etree.SubElement(size, "width").text="child 4"
</code>```

Body:
I am using lxml in an attempt to to output the following xml code:

<annotation>
    <folder>images</folder>
    <filename>IMG_8111.JPG</filename>
    <size>
        <width>400</width>
        <height>400</height>
    </size>
    <segmented>0</segmented>
    <object>
        <name>Bottle</name>
        <bndbox>
            <xmin>16</xmin>
            <ymin>71</ymin>
            <xmax>390</xmax>
            <ymax>323</ymax>
        </bndbox>
    </object>
</annotation>

Im using this tutorial to learn how to implement lxml for my needs. The issue I am facing is that my desired output has subelements to subelements. For instance - <annotation> is my main element, and then <folder>, <filename> and <size> are subelements, but then, <height> and <width>' are subelements to the` subelements. How do I make this happen with lxml. I have the following so far:

from lxml import etree
import xml.etree.cElementTree as ET

root = etree.Element("annotation")
etree.SubElement(root, "folder").text = "Child 1"
etree.SubElement(root, "filename").text = "Child 2"
size = etree.SubElement(root, "size").text = "Child 3"
etree.SubElement(size, "width").text = "Child 4"

with open ('xmltree.xml', 'wb') as f:
    f.write(etree.tostring(root, pretty_print = True))

But it throws the following error:

 etree.SubElement(size, "width").text = "Child 4"
TypeError: Argument '_parent' has incorrect type (expected lxml.etree._Element, got str)

Please help me out on what I am doing wrong and how to proceed.

Body:
Your variable size has type string because it has "child 3" value. You should do:

size = etree.SubElement(root,"size")
size.text = "child 3"
etree.SubElement(size, "width").text="child 4"


问:
Watch Service java.lang.IllegalStateException
I have created a watch service to monitor a folder.  I amgetting an error once i create or update file from that folder. I have shared my code and error log below. Please let me know how to handle this issue.

//Code.

```<code>@Override
public void runTask() {

    log.info("Task Running in Lithium **********************************************************");
    log.info("Path *** "+path);
        try {
           WatchService watchService = path.getFileSystem().newWatchService();
           path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE);
           while (true) {
               final WatchKey wk = watchService.take();
                for (WatchEvent<?> event : wk.pollEvents()) {
                    final Path changed = (Path) event.context();
                    log.info("before File changed");
                    log.info("Path Changed "+path);

                    if (changed.endsWith("LithiumRole.xlsx") || changed.endsWith("LithiumRole.xls")) {
                        log.info("Inside File changed");
                        log.info(filePath+fileName);

                        lithiumRoleService.doProcess(ExcelUtil.getWorkbook(new FileInputStream(new File(filePath+fileName))));
             }
            else
                log.info("changed event path does not ends with LithiumRole.xlsx");

                }
        // reset the key
        boolean valid = wk.reset();
        if (!valid) {
            log.info("watch Key has been unregistered");
          }
     }

  } catch (final ApplicationException applicationEx) {
      log.error("Exception occured!", applicationEx);
  } catch (IOException e) {
    // TODO Auto-generated catch block
      e.printStackTrace();
  } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

    }
</code>```

//Error Log.

INFO: Illegal access: this web application instance has been stopped
  already.  Could not load
  com.sun.org.apache.xerces.internal.parsers.SAXParser.  The eventual
  following stack trace is caused by an error thrown for debugging
  purposes as well as to attempt to terminate the thread which caused
  the illegal access, and has no functional impact.
  java.lang.IllegalStateException   at
  org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1612)
    at
  org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
    at
  org.apache.tomee.catalina.LazyStopWebappClassLoader.loadClass(LazyStopWebappClassLoader.java:129)
    at org.xml.sax.helpers.NewInstance.newInstance(NewInstance.java:82)
    at
  org.xml.sax.helpers.XMLReaderFactory.loadClass(XMLReaderFactory.java:228)
    at
  org.xml.sax.helpers.XMLReaderFactory.createXMLReader(XMLReaderFactory.java:191)
    at org.dom4j.io.SAXHelper.createXMLReader(SAXHelper.java:83)    at
  org.dom4j.io.SAXReader.createXMLReader(SAXReader.java:894)    at
  org.dom4j.io.SAXReader.getXMLReader(SAXReader.java:715)   at
  org.dom4j.io.SAXReader.read(SAXReader.java:435)   at
  org.dom4j.io.SAXReader.read(SAXReader.java:343)   at
  org.apache.poi.openxml4j.opc.PackageRelationshipCollection.parseRelationshipsPart(PackageRelationshipCollection.java:305)
    at
  org.apache.poi.openxml4j.opc.PackageRelationshipCollection.(PackageRelationshipCollection.java:156)
    at
  org.apache.poi.openxml4j.opc.PackageRelationshipCollection.(PackageRelationshipCollection.java:124)
    at
  org.apache.poi.openxml4j.opc.PackagePart.loadRelationships(PackagePart.java:527)
    at
  org.apache.poi.openxml4j.opc.PackagePart.(PackagePart.java:112)
    at
  org.apache.poi.openxml4j.opc.PackagePart.(PackagePart.java:83)
    at
  org.apache.poi.openxml4j.opc.PackagePart.(PackagePart.java:128)
    at
  org.apache.poi.openxml4j.opc.ZipPackagePart.(ZipPackagePart.java:78)
    at
  org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:187)
    at
  org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:585)
    at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:222)
    at
  org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:63)
    at com.test.am.utils.excel.ExcelUtil.getWorkbook(ExcelUtil.java:311)
    at
  com.test.maxup.lithium.task.LithiumRoleTask.runTask(LithiumRoleTask.java:56)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)     at
  org.springframework.util.MethodInvoker.invoke(MethodInvoker.java:273)
    at
  org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean$MethodInvokingJob.executeInternal(MethodInvokingJobDetailFactoryBean.java:264)
    at
  org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:86)
    at org.quartz.core.JobRunShell.run(JobRunShell.java:199)    at
  org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:546)

答:
One of the packages that throw java.lang.IllegalStateException is java.nio.file which is what you use in your case.

Pay attention to your exception:

com.test.am.utils.excel.ExcelUtil.getWorkbook(ExcelUtil.java:311) at
  com.test.maxup.lithium.task.LithiumRoleTask.runTask(LithiumRoleTask.java:56)

I can't tell the line number, but I'm pretty sure it's this spot:

```<code>lithiumRoleService.doProcess(ExcelUtil.getWorkbook(new FileInputStream(new File(filePath+fileName))));
</code>```

Make sure to create the file before (untested code below):

```<code>    Path path = Paths.get(filePath+fileName);
    if (!Files.exists(path)) {
        try {
            Files.createDirectories(path);
        } catch (FileAlreadyExistsException x) {
            // log exceptiopn
        } catch (IOException x) {
            // log exception
        }
    }
lithiumRoleService.doProcess(ExcelUtil.getWorkbook(new FileInputStream(path.toString())));
</code>```

Also is this while(true) a wanted behavior? This loop is never stopping, unless an exception is thrown.

Body:
I have created a watch service to monitor a folder.  I amgetting an error once i create or update file from that folder. I have shared my code and error log below. Please let me know how to handle this issue.

//Code.

@Override
public void runTask() {

    log.info("Task Running in Lithium **********************************************************");
    log.info("Path *** "+path);
        try {
           WatchService watchService = path.getFileSystem().newWatchService();
           path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE);
           while (true) {
               final WatchKey wk = watchService.take();
                for (WatchEvent<?> event : wk.pollEvents()) {
                    final Path changed = (Path) event.context();
                    log.info("before File changed");
                    log.info("Path Changed "+path);

                    if (changed.endsWith("LithiumRole.xlsx") || changed.endsWith("LithiumRole.xls")) {
                        log.info("Inside File changed");
                        log.info(filePath+fileName);

                        lithiumRoleService.doProcess(ExcelUtil.getWorkbook(new FileInputStream(new File(filePath+fileName))));
             }
            else
                log.info("changed event path does not ends with LithiumRole.xlsx");

                }
        // reset the key
        boolean valid = wk.reset();
        if (!valid) {
            log.info("watch Key has been unregistered");
          }
     }

  } catch (final ApplicationException applicationEx) {
      log.error("Exception occured!", applicationEx);
  } catch (IOException e) {
    // TODO Auto-generated catch block
      e.printStackTrace();
  } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

    }

//Error Log.

INFO: Illegal access: this web application instance has been stopped
  already.  Could not load
  com.sun.org.apache.xerces.internal.parsers.SAXParser.  The eventual
  following stack trace is caused by an error thrown for debugging
  purposes as well as to attempt to terminate the thread which caused
  the illegal access, and has no functional impact.
  java.lang.IllegalStateException   at
  org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1612)
    at
  org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
    at
  org.apache.tomee.catalina.LazyStopWebappClassLoader.loadClass(LazyStopWebappClassLoader.java:129)
    at org.xml.sax.helpers.NewInstance.newInstance(NewInstance.java:82)
    at
  org.xml.sax.helpers.XMLReaderFactory.loadClass(XMLReaderFactory.java:228)
    at
  org.xml.sax.helpers.XMLReaderFactory.createXMLReader(XMLReaderFactory.java:191)
    at org.dom4j.io.SAXHelper.createXMLReader(SAXHelper.java:83)    at
  org.dom4j.io.SAXReader.createXMLReader(SAXReader.java:894)    at
  org.dom4j.io.SAXReader.getXMLReader(SAXReader.java:715)   at
  org.dom4j.io.SAXReader.read(SAXReader.java:435)   at
  org.dom4j.io.SAXReader.read(SAXReader.java:343)   at
  org.apache.poi.openxml4j.opc.PackageRelationshipCollection.parseRelationshipsPart(PackageRelationshipCollection.java:305)
    at
  org.apache.poi.openxml4j.opc.PackageRelationshipCollection.(PackageRelationshipCollection.java:156)
    at
  org.apache.poi.openxml4j.opc.PackageRelationshipCollection.(PackageRelationshipCollection.java:124)
    at
  org.apache.poi.openxml4j.opc.PackagePart.loadRelationships(PackagePart.java:527)
    at
  org.apache.poi.openxml4j.opc.PackagePart.(PackagePart.java:112)
    at
  org.apache.poi.openxml4j.opc.PackagePart.(PackagePart.java:83)
    at
  org.apache.poi.openxml4j.opc.PackagePart.(PackagePart.java:128)
    at
  org.apache.poi.openxml4j.opc.ZipPackagePart.(ZipPackagePart.java:78)
    at
  org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:187)
    at
  org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:585)
    at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:222)
    at
  org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:63)
    at com.test.am.utils.excel.ExcelUtil.getWorkbook(ExcelUtil.java:311)
    at
  com.test.maxup.lithium.task.LithiumRoleTask.runTask(LithiumRoleTask.java:56)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)     at
  org.springframework.util.MethodInvoker.invoke(MethodInvoker.java:273)
    at
  org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean$MethodInvokingJob.executeInternal(MethodInvokingJobDetailFactoryBean.java:264)
    at
  org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:86)
    at org.quartz.core.JobRunShell.run(JobRunShell.java:199)    at
  org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:546)

Body:
One of the packages that throw java.lang.IllegalStateException is java.nio.file which is what you use in your case.

Pay attention to your exception:

com.test.am.utils.excel.ExcelUtil.getWorkbook(ExcelUtil.java:311) at
  com.test.maxup.lithium.task.LithiumRoleTask.runTask(LithiumRoleTask.java:56)

I can't tell the line number, but I'm pretty sure it's this spot:

lithiumRoleService.doProcess(ExcelUtil.getWorkbook(new FileInputStream(new File(filePath+fileName))));

Make sure to create the file before (untested code below):

    Path path = Paths.get(filePath+fileName);
    if (!Files.exists(path)) {
        try {
            Files.createDirectories(path);
        } catch (FileAlreadyExistsException x) {
            // log exceptiopn
        } catch (IOException x) {
            // log exception
        }
    }
lithiumRoleService.doProcess(ExcelUtil.getWorkbook(new FileInputStream(path.toString())));

Also is this while(true) a wanted behavior? This loop is never stopping, unless an exception is thrown.


问:
FirebaseAuthUI IOS - how to add login screen background image?
I want to add an image behind the login buttons of the login screen. I currently get the following error message :

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle <...> with name ...

Here is my code :

In AppDelegate :

```<code>class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var authHandle: AuthStateDidChangeListenerHandle?
    var userInfo:User!

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        FirebaseApp.configure()

        //checkLoggedIn
        authHandle = Auth.auth().addStateDidChangeListener { auth, user in
            if let user = user {
                self.userInfo = user
            } else {
                // No user is signed in.
                self.login()
            }
        }

        return true
    }

func login() {
        let authUI = FUIAuth.defaultAuthUI()
        authUI?.delegate = self as? FUIAuthDelegate

        let providers: [FUIAuthProvider] = [
            FUIFacebookAuth()
        ]
        authUI?.providers = providers

        // Present the auth view controller and then implement the sign in callback.
        let authViewController = CustomAuthViewController(authUI: authUI!)
        self.window?.rootViewController?.present(authViewController, animated: false, completion: nil)
    }

    func authPickerViewController(for authUI: FUIAuth) -> FUIAuthPickerViewController {
        return CustomAuthViewController(nibName: "CustomAuthViewController",
                                        bundle: Bundle.main,
                                        authUI: authUI)
    }
}
</code>```

In CustomAuthViewController :

```<code>class CustomAuthViewController: FUIAuthPickerViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        let width = UIScreen.main.bounds.size.width
        let height = UIScreen.main.bounds.size.height

        let imageViewBackground = UIImageView(frame: CGRect(x: 0, y: 0, width: width, height: height))
        imageViewBackground.image = UIImage(named: "myimage")

        // you can change the content mode:
        imageViewBackground.contentMode = UIViewContentMode.scaleToFill

        view.insertSubview(imageViewBackground, at: 0)
    }
</code>```

Do you see what is wrong ? I am not sure that  the authPickerViewController function should be in my AppDelegate, can you confirm it's ok?

I found this post and this one but I cannot make it work.
I use Firebase-UI 4.1.1, my login flow works without background image (so without CustomPickerViewController).

Thank you,

Alex

答:
This is what my customized override looks like:

```<code>import UIKit
import FirebaseAuthUI

class BizzyAuthViewController: FUIAuthPickerViewController {

    override init(nibName: String?, bundle: Bundle?, authUI: FUIAuth) {
        super.init(nibName: "FUIAuthPickerViewController", bundle: bundle, authUI: authUI)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        let width = UIScreen.main.bounds.size.width
        let height = UIScreen.main.bounds.size.height

        let imageViewBackground = UIImageView(frame: CGRect(x: 0, y: 0, width: width, height: height))
        imageViewBackground.image = UIImage(named: "lavenderWithBees")

        // you can change the content mode:
        imageViewBackground.contentMode = UIViewContentMode.scaleAspectFill

        view.insertSubview(imageViewBackground, at: 0)

    }

}
</code>```

And this is what my login function (inside "ViewController.swift") looks like:

```<code>func login() {

    //FirebaseApp.configure()
    let authUI = FUIAuth.defaultAuthUI()
    let providers: [FUIAuthProvider] = [FUIGoogleAuth(), FUIFacebookAuth()]
    authUI?.providers = providers
    authUI?.delegate = self as FUIAuthDelegate

    let authViewController = BizzyAuthViewController(authUI: authUI!)
    let navc = UINavigationController(rootViewController: authViewController)
    self.present(navc, animated: true, completion: nil)

}
</code>```

Body:
I want to add an image behind the login buttons of the login screen. I currently get the following error message :

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle <...> with name ...

Here is my code :

In AppDelegate :

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var authHandle: AuthStateDidChangeListenerHandle?
    var userInfo:User!

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        FirebaseApp.configure()

        //checkLoggedIn
        authHandle = Auth.auth().addStateDidChangeListener { auth, user in
            if let user = user {
                self.userInfo = user
            } else {
                // No user is signed in.
                self.login()
            }
        }

        return true
    }

func login() {
        let authUI = FUIAuth.defaultAuthUI()
        authUI?.delegate = self as? FUIAuthDelegate

        let providers: [FUIAuthProvider] = [
            FUIFacebookAuth()
        ]
        authUI?.providers = providers

        // Present the auth view controller and then implement the sign in callback.
        let authViewController = CustomAuthViewController(authUI: authUI!)
        self.window?.rootViewController?.present(authViewController, animated: false, completion: nil)
    }

    func authPickerViewController(for authUI: FUIAuth) -> FUIAuthPickerViewController {
        return CustomAuthViewController(nibName: "CustomAuthViewController",
                                        bundle: Bundle.main,
                                        authUI: authUI)
    }
}

In CustomAuthViewController :

class CustomAuthViewController: FUIAuthPickerViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        let width = UIScreen.main.bounds.size.width
        let height = UIScreen.main.bounds.size.height

        let imageViewBackground = UIImageView(frame: CGRect(x: 0, y: 0, width: width, height: height))
        imageViewBackground.image = UIImage(named: "myimage")

        // you can change the content mode:
        imageViewBackground.contentMode = UIViewContentMode.scaleToFill

        view.insertSubview(imageViewBackground, at: 0)
    }

Do you see what is wrong ? I am not sure that  the authPickerViewController function should be in my AppDelegate, can you confirm it's ok?

I found this post and this one but I cannot make it work.
I use Firebase-UI 4.1.1, my login flow works without background image (so without CustomPickerViewController).

Thank you,

Alex

Body:
This is what my customized override looks like:

import UIKit
import FirebaseAuthUI

class BizzyAuthViewController: FUIAuthPickerViewController {

    override init(nibName: String?, bundle: Bundle?, authUI: FUIAuth) {
        super.init(nibName: "FUIAuthPickerViewController", bundle: bundle, authUI: authUI)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        let width = UIScreen.main.bounds.size.width
        let height = UIScreen.main.bounds.size.height

        let imageViewBackground = UIImageView(frame: CGRect(x: 0, y: 0, width: width, height: height))
        imageViewBackground.image = UIImage(named: "lavenderWithBees")

        // you can change the content mode:
        imageViewBackground.contentMode = UIViewContentMode.scaleAspectFill

        view.insertSubview(imageViewBackground, at: 0)

    }

}

And this is what my login function (inside "ViewController.swift") looks like:

func login() {

    //FirebaseApp.configure()
    let authUI = FUIAuth.defaultAuthUI()
    let providers: [FUIAuthProvider] = [FUIGoogleAuth(), FUIFacebookAuth()]
    authUI?.providers = providers
    authUI?.delegate = self as FUIAuthDelegate

    let authViewController = BizzyAuthViewController(authUI: authUI!)
    let navc = UINavigationController(rootViewController: authViewController)
    self.present(navc, animated: true, completion: nil)

}


问:
launch cocos2dx project with Android
I'm using Cocos2dx 3.0 RC1, and in the installation i typed : ./setup.py

I entered my NDK root, and my SDK root, but didn't put anything on my ANT root as explained in this tutorial : here
. But know when i use : cocos run -s ~/MyCompany/MyGame -p android, it says that my ANT_ROOT is not defined. I've installed it using Macport, but when i type ant, it says Build is missing.

I just want to create a game in Android using Cocos2dx.

答:
For macOS:

Install Homebrew. Run brew install ant. Add the export (with correct location) to your .bash_profile file:

export ANT_ROOT=/usr/local/bin

Title: launch cocos2dx project with Android


问:
Set cluster name of elasticsearch with environmental variable
I am running elasticsearch service with docker-compose. I need to specify custom cluster name.
As I found in this github ticket, I can pass a custom cluster name in es.cluster.name property. This approach is working for me.

Question:

Is possible to set cluster name with env variables, even with version 2.4 and this docker image Docker hub?

In docker documentation for 5.3 version, I see I could also specify it in environmental variables but in elasticsearch:2.4 this is not working. I have to use version 2.4 because of spring data compatibility.

I didn't manage to get to end of this with version 2.4, or was this enabled only in latest versions?

Part of docker compose file:

```<code>elastic:
    image: "elasticsearch:2.4-alpine"
    # Setting property value works
    command: "elasticsearch -Des.cluster.name=custom-cluster-name"

    # Setting env properties is not working, but I would prefer it this way
    #environment:
    # - es.cluster.name=custom-cluster-name
</code>```

答:
This worked for me (I was on ES 1.5.2):</p>

```<code>    command: elasticsearch -Des.cluster.name=<cluster_name>
</code>```

Body:
I am running elasticsearch service with docker-compose. I need to specify custom cluster name.
As I found in this github ticket, I can pass a custom cluster name in es.cluster.name property. This approach is working for me.

Question:

Is possible to set cluster name with env variables, even with version 2.4 and this docker image Docker hub?

In docker documentation for 5.3 version, I see I could also specify it in environmental variables but in elasticsearch:2.4 this is not working. I have to use version 2.4 because of spring data compatibility.

I didn't manage to get to end of this with version 2.4, or was this enabled only in latest versions?

Part of docker compose file:

elastic:
    image: "elasticsearch:2.4-alpine"
    # Setting property value works
    command: "elasticsearch -Des.cluster.name=custom-cluster-name"

    # Setting env properties is not working, but I would prefer it this way
    #environment:
    # - es.cluster.name=custom-cluster-name

Body:
This worked for me (I was on ES 1.5.2):

    command: elasticsearch -Des.cluster.name=<cluster_name>


问:
Printing a list after having removed adjacent duplicate elements
```<code>new_list = []

i = 0

def remove_adjacent(nums):
    global i
    while i < len(nums) - 1:
        if nums[i] != nums[i+1]:
            new_list.append(nums[i])
        else:
            i += 1
            remove_adjacent(nums[i:])
            return
    i += 1

l = [1, 2, 3, 5, 4, 4, 5, 5, 6, 7, 7, 7, 8, 8, 9, 8, 8]

remove_adjacent(l)

print new_list
</code>```

Question: Given a list of numbers, return a list where all adjacent == elements have been reduced to a single element, so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or modify the passed in list.

Issue: The final list printed consists of [1, 2, 3, 5] instead of [1, 2, 3, 5, 4, 5, 6, 7, 8, 9, 8]

答:
This is perfect for a generator.  I'm not altering the original list.  Instead, I'm returning a new list with no adjacent values equal to one another.

```<code>def removerator(l):
    last = None
    for x in l:
        if x != last:
            last = x
            yield x

list(removerator(l))

[1, 2, 3, 5, 4, 5, 6, 7, 8, 9, 8]
</code>```

Setup

```<code>l = [1, 2, 3, 5, 4, 4, 5, 5, 6, 7, 7, 7, 8, 8, 9, 8, 8]
</code>```

Body:
new_list = []

i = 0

def remove_adjacent(nums):
    global i
    while i < len(nums) - 1:
        if nums[i] != nums[i+1]:
            new_list.append(nums[i])
        else:
            i += 1
            remove_adjacent(nums[i:])
            return
    i += 1

l = [1, 2, 3, 5, 4, 4, 5, 5, 6, 7, 7, 7, 8, 8, 9, 8, 8]

remove_adjacent(l)

print new_list

Question: Given a list of numbers, return a list where all adjacent == elements have been reduced to a single element, so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or modify the passed in list.

Issue: The final list printed consists of [1, 2, 3, 5] instead of [1, 2, 3, 5, 4, 5, 6, 7, 8, 9, 8]

Body:
This is perfect for a generator.  I'm not altering the original list.  Instead, I'm returning a new list with no adjacent values equal to one another.

def removerator(l):
    last = None
    for x in l:
        if x != last:
            last = x
            yield x

list(removerator(l))

[1, 2, 3, 5, 4, 5, 6, 7, 8, 9, 8]

Setup

l = [1, 2, 3, 5, 4, 4, 5, 5, 6, 7, 7, 7, 8, 8, 9, 8, 8]


问:
What is the most ridiculous pessimization you've seen?
We all know that premature optimization is the root of all evil because it leads to unreadable/unmaintainable code.  Even worse is pessimization, when someone implements an "optimization" because they think it will be faster, but it ends up being slower, as well as being buggy, unmaintainable, etc.  What is the most ridiculous example of this that you've seen?

答:
Someone in my department once wrote a string class.  An interface like CString, but without the Windows dependence.

One "optimization" they did was to not allocate any more memory than necessary.  Apparently not realizing that the reason classes like std::string do allocate excess memory is so that a sequence of += operations can run in O(n) time.

Instead, every single += call forced a reallocation, which turned repeated appends into an O(n²) Schlemiel the Painter's algorithm.

OwnerDisplayName: dsimcha

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: IainMH


问:
Return Empty column if column does not exist in dataframe
I created a dataframe df as below:

```<code>Type = ['A', 'B', 'C', 'D']
Size = [72,23,66,12]
df = pd.DataFrame({'Type': Type, 'Size': Size})
</code>```

I can extract any existing column using:

```<code>df_count = df['Size']
</code>```

However, if a data frame is too big, and I don't know if the column exist in df or not. In such if I call a column e.g. df['Shape'] as below:

```<code>df_null = df['Shape']
</code>```

It raises a KeyError. However I want that df_null should get an empty column with name "Shape".

答:
IIUC, try this

```<code>col = 'Shape'
df_null = pd.Series() if col not in df.columns else df[col]
</code>```

Output:

```<code>Series([], dtype: float64)
</code>```

OR

```<code>col = 'Size'
df_null = pd.Series() if col not in df.columns else df[col]
</code>```

Output:

```<code>0    72
1    23
2    66
3    12
Name: Size, dtype: int64
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I created a dataframe df as below:

Type = ['A', 'B', 'C', 'D']
Size = [72,23,66,12]
df = pd.DataFrame({'Type': Type, 'Size': Size})

I can extract any existing column using:

df_count = df['Size']

However, if a data frame is too big, and I don't know if the column exist in df or not. In such if I call a column e.g. df['Shape'] as below:

df_null = df['Shape']

It raises a KeyError. However I want that df_null should get an empty column with name "Shape".

Body:
IIUC, try this

col = 'Shape'
df_null = pd.Series() if col not in df.columns else df[col]

Output:

Series([], dtype: float64)

OR

col = 'Size'
df_null = pd.Series() if col not in df.columns else df[col]

Output:

0    72
1    23
2    66
3    12
Name: Size, dtype: int64


问:
Odd sublime text 3 graphic glitch - red and green lines
I have already tried uninstalling Sublime Text (version: Build 3143), restarting my computer, and downloading a fresh version, however I am still getting this weird graphic glitch.  I also try switching new themes, but weird red and green lines graphic is still there.  This does not happen to other programs, just Sublime Text 3. In the meantime, I am reverting back to Sublime Text 2 and the program works fine with no graphic glitches. I am using Mac OS Sierra 10.12.6.

答:
Per the FAQ on Build 3143:

```<code>Q: My tabs, buttons or other UI elements look funny, broken, or red and
yellow!

This indicates the currently loaded theme is referencing images that
could not be loaded. Most likely you are either:

- using a custom theme that is referencing images that are no longer
  part of the Theme - Default package (it was redesigned)

- you have overridden the Theme - Default package – look for a file
  named Packages/Theme - Default/Default.sublime-theme and move it
  to a safe place for backup

- you have customized the Default theme, most likely via a file
  named Packages/User/Default.sublime-theme – move it to a safe
  place for backup
</code>```

In particular, this problem is caused by the theme engine being told to display graphics that it was unable to load. In those cases it uses this image in order to immediately draw attention to the fact that required theme assets are missing.

Along with theme engine enhancements, the Default theme was also overhauled. Many old themes (and likely all ST2 themes) are not directly compatible with this build because many of them reference graphical assets in the Default theme that are no longer there.

The Default and Adaptive themes that ship with Sublime Text 3 should work just fine out of the box; if they display this graphical problem, it's for the reasons noted above. Principally there are override modifications to the Theme that are making assumptions about assets.

Body:
Per the FAQ on Build 3143:

Q: My tabs, buttons or other UI elements look funny, broken, or red and
yellow!

This indicates the currently loaded theme is referencing images that
could not be loaded. Most likely you are either:

- using a custom theme that is referencing images that are no longer
  part of the Theme - Default package (it was redesigned)

- you have overridden the Theme - Default package – look for a file
  named Packages/Theme - Default/Default.sublime-theme and move it
  to a safe place for backup

- you have customized the Default theme, most likely via a file
  named Packages/User/Default.sublime-theme – move it to a safe
  place for backup

In particular, this problem is caused by the theme engine being told to display graphics that it was unable to load. In those cases it uses this image in order to immediately draw attention to the fact that required theme assets are missing.

Along with theme engine enhancements, the Default theme was also overhauled. Many old themes (and likely all ST2 themes) are not directly compatible with this build because many of them reference graphical assets in the Default theme that are no longer there.

The Default and Adaptive themes that ship with Sublime Text 3 should work just fine out of the box; if they display this graphical problem, it's for the reasons noted above. Principally there are override modifications to the Theme that are making assumptions about assets.


问:
How to make TinyMce wysiwyg noneditable for the users?
I got a TinyMCE WYSIWYG editor which I send to my SQL and bring back to the same page. A solution is to make another page where you retrieve the information but I thought why built more pages if it's posible to create the wanted context on the same page. Saves a bit of space and makes it more compact.

On the site of TinyMCE I saw that in the ajax formula there was a function called: Noneditable. Which I tried but without success. Somehow that didn't work. After that, I tried to make a div inside the editor content with Noneditable which worked. Well solved you would say. Problem is that there is a bit of space between my textarea where the TinyMCE is called to and the div inside of the area. That space is still editable what makes the noneditable div useless.

After that, I tried to make jQuery magic happen. But I can't make a connection to the class or id of the content were the textarea is. Also tried to make the content hide which isn't a solution at all but even that doesn't work.

TinyCME Javascript

```<code>$(document).ready(function() {
   tinymce.init ({
      selector: '.add_body_structure',
      height: 1000,
      menubar: true,
      branding: false,
      toolbar: 'undo redo | styleselect bold italic forecolor backcolor fontselect
      fontsizeselect | link | alignleft aligncenter alignright alignjustify
      | outdent indent bullist numlist | removeformat | insert',
      plugins: 'print preview searchreplace autolink directionality visualblocks
      visualchars fullscreen image link media mediaembed template  table
      charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist
      lists textcolor wordcount imagetools contextmenu colorpicker
      textpattern help autoresize noneditable',
      advlist_bullet_styles: 'square',
      advlist_number_styles: 'lower-alpha,lower-roman,upper-alpha,upper-roman',
      statusbar: false,
      browser_spellcheck: true,
      image_title: true,
      automatic_uploads: true,
      media_live_embeds: true,
      noneditable_noneditable_class: "noEdit",
      contextmenu: true,
      relative_urls: false,
      remove_script_host: false,
      encoding: 'xml',
      invalid_elements: 'script, input, textarea, textfield, col, colgroup,
      caption, dir, meta, object, select, option, source, title',
      fontsize_formats: '8pt 10pt 12pt 14pt 16pt 18pt 20pt 22pt 24pt 26pt
      28pt 30pt 32pt 34pt 36pt 38pt 40pt', }); });
</code>```

PHP page

```<code><?php foreach($viewmodel as $item) : ?>
<form method="post">
<div>
    <br><br><br><br>
    <textarea id="wysiwyg_frontpage" name="body" class="noEdit <?php if (isset($_SESSION['is_logged_in'])) : ?> add_body_structure <?php endif;?>" accept="video/mp4,video/x-m4v,video/*">
        <div class="noEdit">
        <?php echo html_entity_decode($item['body']);?>
        </div>
    </textarea>
    <input name="image" type="file" id="upload" class="hidden" onchange="">
</div>
    <?php if (isset($_SESSION['is_logged_in'])) : ?> <input class="btn btn-primary" name="edit" value="Post" type="submit"></input><?php endif;?>
        </form>
<?php endforeach; ?>
</code>```

Body details of the current page

```<code><body id="tinymce" class="mce-content-body " data-id="wysiwyg_frontpage" contenteditable="true" style="overflow-y: hidden; padding-left: 1px; padding-right: 1px; padding-bottom: 50px;" data-mce-style="overflow-y: auto; padding-left: 1px; padding-right: 1px; padding-bottom: 50px;">
<div class="noEdit" contenteditable="false"><div class="noEdit" contenteditable="false"></div>
</code>```

As you can see in the html above you see 2 noEdit classes and that's because of the div inside of the textarea. It will send an extra div with it when posted. Also body contenteditable is true which is set by the TinyMCE which I can't change or am not able to.

Conclusion
How do I make editable or not editable when I set as such. Try to hide behind a session but first I want to tackle this issue.

If more information is needed then ask for it. These 3 are the main sources.

答:
TinyMCE includes a readonly mode:

```<code>editor.setMode('readonly');
</code>```

Here is a TinyMCE Fiddle that shows this in action:  http://fiddle.tinymce.com/Hegaab

Body:
I got a TinyMCE WYSIWYG editor which I send to my SQL and bring back to the same page. A solution is to make another page where you retrieve the information but I thought why built more pages if it's posible to create the wanted context on the same page. Saves a bit of space and makes it more compact.

On the site of TinyMCE I saw that in the ajax formula there was a function called: Noneditable. Which I tried but without success. Somehow that didn't work. After that, I tried to make a div inside the editor content with Noneditable which worked. Well solved you would say. Problem is that there is a bit of space between my textarea where the TinyMCE is called to and the div inside of the area. That space is still editable what makes the noneditable div useless.

After that, I tried to make jQuery magic happen. But I can't make a connection to the class or id of the content were the textarea is. Also tried to make the content hide which isn't a solution at all but even that doesn't work.

TinyCME Javascript

$(document).ready(function() {
   tinymce.init ({
      selector: '.add_body_structure',
      height: 1000,
      menubar: true,
      branding: false,
      toolbar: 'undo redo | styleselect bold italic forecolor backcolor fontselect
      fontsizeselect | link | alignleft aligncenter alignright alignjustify
      | outdent indent bullist numlist | removeformat | insert',
      plugins: 'print preview searchreplace autolink directionality visualblocks
      visualchars fullscreen image link media mediaembed template  table
      charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist
      lists textcolor wordcount imagetools contextmenu colorpicker
      textpattern help autoresize noneditable',
      advlist_bullet_styles: 'square',
      advlist_number_styles: 'lower-alpha,lower-roman,upper-alpha,upper-roman',
      statusbar: false,
      browser_spellcheck: true,
      image_title: true,
      automatic_uploads: true,
      media_live_embeds: true,
      noneditable_noneditable_class: "noEdit",
      contextmenu: true,
      relative_urls: false,
      remove_script_host: false,
      encoding: 'xml',
      invalid_elements: 'script, input, textarea, textfield, col, colgroup,
      caption, dir, meta, object, select, option, source, title',
      fontsize_formats: '8pt 10pt 12pt 14pt 16pt 18pt 20pt 22pt 24pt 26pt
      28pt 30pt 32pt 34pt 36pt 38pt 40pt', }); });

PHP page

<?php foreach($viewmodel as $item) : ?>
<form method="post">

    <textarea id="wysiwyg_frontpage" name="body" class="noEdit <?php if (isset($_SESSION['is_logged_in'])) : ?> add_body_structure <?php endif;?>" accept="video/mp4,video/x-m4v,video/*">

        <?php echo html_entity_decode($item['body']);?>

    </textarea>
    <input name="image" type="file" id="upload" class="hidden" onchange="">

    <?php if (isset($_SESSION['is_logged_in'])) : ?> <input class="btn btn-primary" name="edit" value="Post" type="submit"></input><?php endif;?>
        </form>
<?php endforeach; ?>

Body details of the current page

As you can see in the html above you see 2 noEdit classes and that's because of the div inside of the textarea. It will send an extra div with it when posted. Also body contenteditable is true which is set by the TinyMCE which I can't change or am not able to.

Conclusion
How do I make editable or not editable when I set as such. Try to hide behind a session but first I want to tackle this issue.

If more information is needed then ask for it. These 3 are the main sources.

Body:
TinyMCE includes a readonly mode:

editor.setMode('readonly');

Here is a TinyMCE Fiddle that shows this in action:  http://fiddle.tinymce.com/Hegaab


问:
Adding rendered item position to an array of items?
I'd like to add the positional coordinates of each object as it's rendered so that I can then designate it as a drop zone.

I can get one piece of data into the objLocation, but obviously, it keeps overwriting as each SubComponent is rendered. What is the correct way to built that array of object locations?

```<code>const data = [
  { id: 1 },
  { id: 2 },
  { id: 3 },
]

export default class Viewport extends Component {
    this.state = {
      objLocation = [],
    }

    render() {
      return (
        {data.map( d => {
          return(
            <SubComponent onLayout={this.getLayout} id={d.id} />
          )
        })}
      )
    }

    getLayout = (e) => (
      const obj = {
        width: e.nativeEvent.layout.width,
        height: e.nativeEvent.layout.height,
        x: e.nativeEvent.layout.x,
        y: e.nativeEvent.layout.y,
      }
      this.setState({
        objLocation: obj
      });
    }
}
</code>```

答:
Found the answer here.</p>

```<code>this.setState({
  arrayvar: this.state.arrayvar.concat([newelement])
})

ES6 With Spread operator.
this.setState({
  arrayvar: [...this.state.arrayvar, newelement]
})
</code>```

Body:
I'd like to add the positional coordinates of each object as it's rendered so that I can then designate it as a drop zone.

I can get one piece of data into the objLocation, but obviously, it keeps overwriting as each SubComponent is rendered. What is the correct way to built that array of object locations?

const data = [
  { id: 1 },
  { id: 2 },
  { id: 3 },
]

export default class Viewport extends Component {
    this.state = {
      objLocation = [],
    }

    render() {
      return (
        {data.map( d => {
          return(
            <SubComponent onLayout={this.getLayout} id={d.id} />
          )
        })}
      )
    }

    getLayout = (e) => (
      const obj = {
        width: e.nativeEvent.layout.width,
        height: e.nativeEvent.layout.height,
        x: e.nativeEvent.layout.x,
        y: e.nativeEvent.layout.y,
      }
      this.setState({
        objLocation: obj
      });
    }
}

Body:
Found the answer here.

this.setState({
  arrayvar: this.state.arrayvar.concat([newelement])
})

ES6 With Spread operator.
this.setState({
  arrayvar: [...this.state.arrayvar, newelement]
})


问:
Matlab integration and abs
In MATLAB (R2017b, online version) I found an issue during symbolic integration: try to calculate integral of f(t) = abs(sin(t)) . Due to the fact that f(t) is always positive, I expect that the integral in [a, b] is lower equal than the integral in [a, b'] if b < b'. But:

```<code>int( abs(sin(t)), t, 0, pi )   -> 2 % OK
int( abs(sin(t)), t, 0, 2*pi ) -> 2 % NO (should be 4)
</code>```

In fact, if we plot the function that represent the integral from 0 to x, which should be monotonic, we found something different:

```<code>% for each value x(i) of x we will calculate integral from 0 to x(i)
x = 0 : pi/8 : 4*pi;
% actual computation
Z = zeros(length(x), 1);                            % create array
syms t;                                             % create symbolic variable t
calculate_int = @(n) int(abs(sin(t)), t, 0, n);     % integral function
for i = 1 : length(Z)
    Z(i) = calculate_int(x(i));
end
% plot result
figure;
plot(x, Z);
</code>```

results in this obviously non monotonic function:

Non symbolic integration gives no problem:

```<code>x = 0 : 0.01 : pi;
f = abs(sin(x));
value = sum(f * 0.01) % 2

x = 0 : 0.01 : 2 * pi;
f = abs(sin(x));
value = sum(f * 0.01) % 4
</code>```

答: It is a bug in Matlab R2017b. See @horchler comments for details. </p>

Title: Matlab integration and abs

Body:
In MATLAB (R2017b, online version) I found an issue during symbolic integration: try to calculate integral of f(t) = abs(sin(t)) . Due to the fact that f(t) is always positive, I expect that the integral in [a, b] is lower equal than the integral in [a, b'] if b < b'. But:

int( abs(sin(t)), t, 0, pi )   -> 2 % OK
int( abs(sin(t)), t, 0, 2*pi ) -> 2 % NO (should be 4)

In fact, if we plot the function that represent the integral from 0 to x, which should be monotonic, we found something different:

% for each value x(i) of x we will calculate integral from 0 to x(i)
x = 0 : pi/8 : 4*pi;
% actual computation
Z = zeros(length(x), 1);                            % create array
syms t;                                             % create symbolic variable t
calculate_int = @(n) int(abs(sin(t)), t, 0, n);     % integral function
for i = 1 : length(Z)
    Z(i) = calculate_int(x(i));
end
% plot result
figure;
plot(x, Z);

results in this obviously non monotonic function:

Non symbolic integration gives no problem:

x = 0 : 0.01 : pi;
f = abs(sin(x));
value = sum(f * 0.01) % 2

x = 0 : 0.01 : 2 * pi;
f = abs(sin(x));
value = sum(f * 0.01) % 4


问:
getopt always returning -1 / getopt not doing anything
I am trying to parse command line arguments using getopt(). Below is my code. getopt() is always returning -1 no matter what arguments I pass when running the program.

For example:

```<code>$ gcc -o test test.c
$ ./test f
</code>```

Can anybody see what I am doing wrong? Thank you.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>

void usage (char * progname)
{
    fprintf(stderr, "Usage Instructions Here ...\n");
    exit(-1);
}

int main (int argc, char *argv[])
{
    int opt;

    while((opt = getopt(argc, argv, "?hf:")) != -1) {
        switch(opt) {
            case '?':
            case 'h':
                usage(argv[0]);
                break;
            case 'f':
                {
                    FILE *fp;
                    char *filename = strdup(optarg);

                    if((fp = fopen(filename, "r")) == NULL) {
                        usage(argv[0]);
                    }
                }
                break;
            default:
                fprintf(stderr, "Error - No such opt, '%c'\n", opt);
                usage(argv[0]);
        }
    }

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

答:
You're not actually passing an option here:

```<code>$ ./test f
</code>```

Options are expected to start with a - character.  f does not, so it is not considered an option.  If you call it like this:

```<code>$ ./test -f
</code>```

You'll get this:

```<code>./test: option requires an argument -- 'f'
Usage Instructions Here ...
</code>```

Also, the ? character has special meaning to getopt.  It is returned when an unknown option is found, with a copy of the invalid option stored in optopt.  So you probably don't want to use ? in your option string.

Body:
I am trying to parse command line arguments using getopt(). Below is my code. getopt() is always returning -1 no matter what arguments I pass when running the program.

For example:

$ gcc -o test test.c
$ ./test f

Can anybody see what I am doing wrong? Thank you.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>

void usage (char * progname)
{
    fprintf(stderr, "Usage Instructions Here ...\n");
    exit(-1);
}

int main (int argc, char *argv[])
{
    int opt;

    while((opt = getopt(argc, argv, "?hf:")) != -1) {
        switch(opt) {
            case '?':
            case 'h':
                usage(argv[0]);
                break;
            case 'f':
                {
                    FILE *fp;
                    char *filename = strdup(optarg);

                    if((fp = fopen(filename, "r")) == NULL) {
                        usage(argv[0]);
                    }
                }
                break;
            default:
                fprintf(stderr, "Error - No such opt, '%c'\n", opt);
                usage(argv[0]);
        }
    }

    return(0);
}

Body:
You're not actually passing an option here:

$ ./test f

Options are expected to start with a - character.  f does not, so it is not considered an option.  If you call it like this:

$ ./test -f

You'll get this:

./test: option requires an argument -- 'f'
Usage Instructions Here ...

Also, the ? character has special meaning to getopt.  It is returned when an unknown option is found, with a copy of the invalid option stored in optopt.  So you probably don't want to use ? in your option string.


问:
git-svn branching without copying every subdirectory
Our project's trunk looks something like:

```<code>trunk/foo
trunk/bar
trunk/baz
</code>```

The subdirectories foo, bar, and baz are actually unrelated to each other, and bar and baz are actually quite huge. How do I create a branch with just foo, such that my branches would look something like:

```<code>branches/branch1/foo
branches/branch2/foo
</code>```

Right now, what I'm doing is branching the whole trunk, then deleting bar and baz, but I think that would be problematic during the merge since it would try to delete bar and baz. What I'd like is for it to be intelligent enough to know that I just want to work with foo and not do anything with bar or baz.

Secondary question, not as important, what if I want a branch with foo and bar, like:

```<code>branches/branch1/foo
branches/branch1/bar
</code>```

Would the process for branching these two folders without branching the others be harder?

Edit:
It's been pointed out to me that I can use svn cp. This works, but I was hoping to work from a git svn repo, and as far as I can tell, the closest analogue git-svn has to svn cp is git svn branch, which automatically handles the copying. Unfortunately, I can't find any option in there that lets me branch just a specific subdirectory.

答:
Branching in Subversion is basically just making copies of files (but they aren't really copies since they don't take up any space). So:

```<code>svn cp svn://server/repo/trunk/foo svn://server/repo/branches/branch1/foo
</code>```

You don't need to copy the bar and baz directories if you don't want to. Alternately, you can copy everything (since copy is essentially free) and check out only what you need:

```<code>svn cp svn://server/repo/trunk svn://server/repo/branches/branch1
svn co svn://server/repo/branches/branch1/foo
</code>```

Body:
Our project's trunk looks something like:

trunk/foo
trunk/bar
trunk/baz

The subdirectories foo, bar, and baz are actually unrelated to each other, and bar and baz are actually quite huge. How do I create a branch with just foo, such that my branches would look something like:

branches/branch1/foo
branches/branch2/foo

Right now, what I'm doing is branching the whole trunk, then deleting bar and baz, but I think that would be problematic during the merge since it would try to delete bar and baz. What I'd like is for it to be intelligent enough to know that I just want to work with foo and not do anything with bar or baz.

Secondary question, not as important, what if I want a branch with foo and bar, like:

branches/branch1/foo
branches/branch1/bar

Would the process for branching these two folders without branching the others be harder?

Edit:
It's been pointed out to me that I can use svn cp. This works, but I was hoping to work from a git svn repo, and as far as I can tell, the closest analogue git-svn has to svn cp is git svn branch, which automatically handles the copying. Unfortunately, I can't find any option in there that lets me branch just a specific subdirectory.

Body:
Branching in Subversion is basically just making copies of files (but they aren't really copies since they don't take up any space). So:

svn cp svn://server/repo/trunk/foo svn://server/repo/branches/branch1/foo

You don't need to copy the bar and baz directories if you don't want to. Alternately, you can copy everything (since copy is essentially free) and check out only what you need:

svn cp svn://server/repo/trunk svn://server/repo/branches/branch1
svn co svn://server/repo/branches/branch1/foo


问:
Finding duplicate values only for 2 highest values in a dict
Code:

```<code>candidates_and_fp_votes = {'a': 25, 'b': 0, 'c': 17, 'd': 23, 'e': 0}

print(candidates_and_fp_votes)
final_vals = [a for a, b in candidates_and_fp_votes.items() if
              list(candidates_and_fp_votes.values()).count(b) > 1]
print("Duplicates are: ")
for i in final_vals:
    print(i)
print(final_vals)

if not final_vals:
    print("No tiebreaker sys required")
else:
    print("Tie-breaker required")
</code>```

Currently, this outputs "Tie-breaker required" as 'b' and 'e' have a value of 0.
I would like this so it only finds duplicates that affect the highest or second highest value.
Eg:

Right now, it should print "No tiebreaker sys required because even if there is a duplicate with 'b' and 'e' it is not
a duplicate with the second and highest values '25' and '23'

if the dict to be = {'a': 25, 'b': 0, 'c': 23, 'd': 23, 'e': 0}
it would print out "Tie-breaker required as it is affecting the 2nd highest value - 23.

Also, I just had a little change in mind, if the highest score is duplicating with a number but this number does not duplicate with the second highest, it would just output "No tiebreaker sys required"

How can I do this?

Thanks in advance.

答:
As I understand it, you are looking to determine a winner based on the highest number of votes and whether a tie breaker is necessary. You could do that like this:

```<code>import operator
candidates_and_fp_votes = {'a': 25, 'b': 0, 'c': 17, 'd': 23, 'e': 0}
sorted_candidates = sorted(candidates_and_fp_votes.items(), key=operator.itemgetter(1), reverse=True)
</code>```

The output of sorted_candidates will look like:

```<code>[('a', 25), ('d', 23), ('c', 17), ('b', 0), ('e', 0)]
</code>```

You can then iterate over this:

```<code>tie = False
for idx, _ in enumerate(sorted_candidates):
     candidate, votes = sorted_candidates[idx]
     next_candidate, next_votes = sorted_candidates[idx+1]

     if votes > next_votes:
         if tie is True:
             print("Tie Breaker needed!")
         else:
             print(f"Candidate {candidate} is the Winner!")
         break

     elif votes == next_votes:
         print("Tie!")
         tie = True
</code>```

Just one of many ways to get there. I hope that helps.

Reference:

Python 3.6

Googled: python sort dict on value

Result: How to sort a dictionary by value?

Edit:

You are asking to determine if the is a tie. My approach would be to reverse the dict. Making the votes the key and creating a list of candidates that have an equal number of votes. Something like this:

```<code>from collections import defaultdict
reversed_dict = defaultdict(list)
for key,value in candidates_and_fp_votes.items():
    reversed_dict[value].append(key)
</code>```

Outputting:

```<code>defaultdict(list, {0: ['b', 'e'], 17: ['c'], 23: ['d'], 25: ['a']})
</code>```

Any key that has a candidate value-list of len > 1 needs a tie breaker.

Body:
Code:

candidates_and_fp_votes = {'a': 25, 'b': 0, 'c': 17, 'd': 23, 'e': 0}

print(candidates_and_fp_votes)
final_vals = [a for a, b in candidates_and_fp_votes.items() if
              list(candidates_and_fp_votes.values()).count(b) > 1]
print("Duplicates are: ")
for i in final_vals:
    print(i)
print(final_vals)

if not final_vals:
    print("No tiebreaker sys required")
else:
    print("Tie-breaker required")

Currently, this outputs "Tie-breaker required" as 'b' and 'e' have a value of 0.
I would like this so it only finds duplicates that affect the highest or second highest value.
Eg:

Right now, it should print "No tiebreaker sys required because even if there is a duplicate with 'b' and 'e' it is not
a duplicate with the second and highest values '25' and '23'

if the dict to be = {'a': 25, 'b': 0, 'c': 23, 'd': 23, 'e': 0}
it would print out "Tie-breaker required as it is affecting the 2nd highest value - 23.

Also, I just had a little change in mind, if the highest score is duplicating with a number but this number does not duplicate with the second highest, it would just output "No tiebreaker sys required"

How can I do this?

Thanks in advance.

Body:
As I understand it, you are looking to determine a winner based on the highest number of votes and whether a tie breaker is necessary. You could do that like this:

import operator
candidates_and_fp_votes = {'a': 25, 'b': 0, 'c': 17, 'd': 23, 'e': 0}
sorted_candidates = sorted(candidates_and_fp_votes.items(), key=operator.itemgetter(1), reverse=True)

The output of sorted_candidates will look like:

[('a', 25), ('d', 23), ('c', 17), ('b', 0), ('e', 0)]

You can then iterate over this:

tie = False
for idx, _ in enumerate(sorted_candidates):
     candidate, votes = sorted_candidates[idx]
     next_candidate, next_votes = sorted_candidates[idx+1]

     if votes > next_votes:
         if tie is True:
             print("Tie Breaker needed!")
         else:
             print(f"Candidate {candidate} is the Winner!")
         break

     elif votes == next_votes:
         print("Tie!")
         tie = True

Just one of many ways to get there. I hope that helps.

Reference:

Python 3.6

Googled: python sort dict on value

Result: How to sort a dictionary by value?

Edit:

You are asking to determine if the is a tie. My approach would be to reverse the dict. Making the votes the key and creating a list of candidates that have an equal number of votes. Something like this:

from collections import defaultdict
reversed_dict = defaultdict(list)
for key,value in candidates_and_fp_votes.items():
    reversed_dict[value].append(key)

Outputting:

defaultdict(list, {0: ['b', 'e'], 17: ['c'], 23: ['d'], 25: ['a']})

Any key that has a candidate value-list of len > 1 needs a tie breaker.


问:
How to import nwjs in ES6/typescript?
In ES6, I want to use this sample code in angular 1.6 code.

```<code>var win = nw.Window.get();

win.on('new-win-policy', function(frame, url, policy){
    policy.forceNewWindow();
});
</code>```

These are the steps I did,(updated package.json)

```<code>npm install nwjs
</code>```

in code,

```<code>import nw from 'nwjs'; //I guess this is not correct
</code>```

please help what am I doing wrong.

答:
did you try ?

```<code>import nw = require('nwjs');
</code>```

not sure if this works in angular project but this is how i use it in Node + Typescript.

Title: How to import nwjs in ES6/typescript?

Body:
In ES6, I want to use this sample code in angular 1.6 code.

var win = nw.Window.get();

win.on('new-win-policy', function(frame, url, policy){
    policy.forceNewWindow();
});

These are the steps I did,(updated package.json)

npm install nwjs

in code,

import nw from 'nwjs'; //I guess this is not correct

please help what am I doing wrong.

Body:
did you try ?

import nw = require('nwjs');

not sure if this works in angular project but this is how i use it in Node + Typescript.


问:
Selenium 3.7.1 gson dependency throwing a ClassNotFoundException
OS:

Windows 10

Selenium Version:
3.7.1 (JAVA)

Browser:

Chrome 62.0.3 (64bit)
Chrome driver 2.33.0

After upgrading to Selenium 3.7.1 and chrome driver 2.33.0 my tests are failing due to a Class not found exception on the gson jar. I can see the jar in my maven dependencies. I can get around this issue from inside my eclipse environment by adding the gson as an external jar but this limits me to only running from the IDE.

Has anyone else seen this issue or can anyone see where I'm gone wrong? As gson is included as a dependency of selenium I presume I shouldn't have to add the dependency to my pom. Any help would be great, thanks in advance

Regards
Donagh

Console output

```<code>org.testng.TestNGException:
Cannot instantiate class Reg_Editor.EditFunctionality
    at org.testng.internal.ObjectFactoryImpl.newInstance(ObjectFactoryImpl.java:31)
    at org.testng.internal.ClassHelper.createInstance1(ClassHelper.java:410)
    at org.testng.internal.ClassHelper.createInstance(ClassHelper.java:323)
    at org.testng.internal.ClassImpl.getDefaultInstance(ClassImpl.java:126)
    at org.testng.internal.ClassImpl.getInstances(ClassImpl.java:191)
    at org.testng.TestClass.getInstances(TestClass.java:99)
    at org.testng.TestClass.initTestClassesAndInstances(TestClass.java:85)
    at org.testng.TestClass.init(TestClass.java:77)
    at org.testng.TestClass.<init>(TestClass.java:42)
    at org.testng.TestRunner.initMethods(TestRunner.java:423)
    at org.testng.TestRunner.init(TestRunner.java:250)
    at org.testng.TestRunner.init(TestRunner.java:220)
    at org.testng.TestRunner.<init>(TestRunner.java:169)
    at org.testng.remote.support.RemoteTestNG6_10$1.newTestRunner(RemoteTestNG6_10.java:28)
    at org.testng.remote.support.RemoteTestNG6_10$DelegatingTestRunnerFactory.newTestRunner(RemoteTestNG6_10.java:61)
    at org.testng.SuiteRunner$ProxyTestRunnerFactory.newTestRunner(SuiteRunner.java:616)
    at org.testng.SuiteRunner.init(SuiteRunner.java:185)
    at org.testng.SuiteRunner.<init>(SuiteRunner.java:131)
    at org.testng.TestNG.createSuiteRunner(TestNG.java:1383)
    at org.testng.TestNG.createSuiteRunners(TestNG.java:1363)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1217)
    at org.testng.TestNG.runSuites(TestNG.java:1144)
    at org.testng.TestNG.run(TestNG.java:1115)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.testng.internal.ObjectFactoryImpl.newInstance(ObjectFactoryImpl.java:23)
    ... 25 more
Caused by: java.lang.NoClassDefFoundError: com/google/gson/JsonParseException
    at org.openqa.selenium.logging.profiler.HttpProfilerLogEntry.constructMessage(HttpProfilerLogEntry.java:37)
    at org.openqa.selenium.logging.profiler.HttpProfilerLogEntry.<init>(HttpProfilerLogEntry.java:29)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:141)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:600)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:219)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:142)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:161)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:107)
    at Util.EMDriverSingleton.setLocalDriver(EMDriverSingleton.java:81)
    at Util.EMDriverSingleton.getDriver(EMDriverSingleton.java:46)
    at Util.Supertest.<init>(Supertest.java:82)
    at Reg_Editor.EditFunctionality.<init>(EditFunctionality.java:16)
    ... 30 more
Caused by: java.lang.ClassNotFoundException: com.google.gson.JsonParseException
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 43 more
</code>```

POM

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ExpertModels</groupId>
    <artifactId>Expert_Models</artifactId>
    <version>0.1-SNAPSHOT</version>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.19.1</version>

                <configuration>
                    <browser>${browser}</browser>
                    <deployment>${deployment}</deployment>
                    <seleniumGrid>${seleniumGrid}</seleniumGrid>
                    <threadCount>0</threadCount>
                    <suiteXmlFiles>
                        <suiteXmlFile>testNG XML Files\${suiteXmlFile}</suiteXmlFile>
                    </suiteXmlFiles>
                </configuration>
            </plugin>

        </plugins>
    </build>
    <packaging>jar</packaging>

    <name>Expert_Models</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <!--Surefire Reporting POM Dependency -->

    <reporting>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-report-plugin</artifactId>
                <version>2.19.1</version>
                <configuration>
                    <showSuccess>true</showSuccess>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jxr-plugin</artifactId>
                <version>2.5</version>
            </plugin>
            <plugin>
                <artifactId>maven-project-info-reports-plugin</artifactId>
                <version>2.7</version>
            </plugin>
        </plugins>
    </reporting>

    <!--Selenium Dependency -->

    <dependencies>

        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>3.0.3</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.7.1</version>
        </dependency>

        <!--EXTENT REPORTS DEPENDENCY -->
        <dependency>
            <groupId>com.relevantcodes</groupId>
            <artifactId>extentreports</artifactId>
            <version>2.41.2</version>
        </dependency>

        <!-- http://mvnrepository.com/artifact/javax.servlet/jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.9.0</version>
        </dependency>

        <!--JUNIT DEPENDENCY -->

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <!--TESTNG DEPENDENCY -->
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.11</version>
        </dependency>

        <!--JXL DEPENDENCY -->
        <dependency>
            <groupId>net.sourceforge.jexcelapi</groupId>
            <artifactId>jxl</artifactId>
            <version>2.6</version>
        </dependency>

        <!--Chrome Driver for Maven -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-chrome-driver</artifactId>
            <version>2.33.0</version>
        </dependency>

        <!--IE Edge Driver for Maven -->
        <!-- <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-edge-driver</artifactId>
            <version>2.53.0</version> <scope>test</scope> </dependency> -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-edge-driver</artifactId>
            <version>2.47.1</version>
        </dependency>

        <!-- IE Driver for Maven -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-ie-driver</artifactId>
            <version>2.53.1</version>
        </dependency>
    </dependencies>

</project>
</code>```

答:
Remove the following from POM.xml

```<code>  <!--Chrome Driver for Maven -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-chrome-driver</artifactId>
        <version>2.33.0</version>
    </dependency>

    <!--IE Edge Driver for Maven -->
    <!-- <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-edge-driver</artifactId>
        <version>2.53.0</version> <scope>test</scope> </dependency> -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-edge-driver</artifactId>
        <version>2.47.1</version>
    </dependency>

    <!-- IE Driver for Maven -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-ie-driver</artifactId>
        <version>2.53.1</version>
    </dependency>
</code>```

These drivers are transitive dependencies of selenium-java, so there are automatically resolved by Maven and there is no need to declare them in pom.xml.

If you declare them in th POM.XML, this causes versions conflict of these libraries. Mavens pick a version declared in the POM and ignores the nevest version.

If you are using eclipse, you can observe this on dependency hierarch tab, it looks like this

Body:
OS:

Windows 10

Selenium Version:
3.7.1 (JAVA)

Browser:

Chrome 62.0.3 (64bit)
Chrome driver 2.33.0

After upgrading to Selenium 3.7.1 and chrome driver 2.33.0 my tests are failing due to a Class not found exception on the gson jar. I can see the jar in my maven dependencies. I can get around this issue from inside my eclipse environment by adding the gson as an external jar but this limits me to only running from the IDE.

Has anyone else seen this issue or can anyone see where I'm gone wrong? As gson is included as a dependency of selenium I presume I shouldn't have to add the dependency to my pom. Any help would be great, thanks in advance

Regards
Donagh

Console output

org.testng.TestNGException:
Cannot instantiate class Reg_Editor.EditFunctionality
    at org.testng.internal.ObjectFactoryImpl.newInstance(ObjectFactoryImpl.java:31)
    at org.testng.internal.ClassHelper.createInstance1(ClassHelper.java:410)
    at org.testng.internal.ClassHelper.createInstance(ClassHelper.java:323)
    at org.testng.internal.ClassImpl.getDefaultInstance(ClassImpl.java:126)
    at org.testng.internal.ClassImpl.getInstances(ClassImpl.java:191)
    at org.testng.TestClass.getInstances(TestClass.java:99)
    at org.testng.TestClass.initTestClassesAndInstances(TestClass.java:85)
    at org.testng.TestClass.init(TestClass.java:77)
    at org.testng.TestClass.<init>(TestClass.java:42)
    at org.testng.TestRunner.initMethods(TestRunner.java:423)
    at org.testng.TestRunner.init(TestRunner.java:250)
    at org.testng.TestRunner.init(TestRunner.java:220)
    at org.testng.TestRunner.<init>(TestRunner.java:169)
    at org.testng.remote.support.RemoteTestNG6_10$1.newTestRunner(RemoteTestNG6_10.java:28)
    at org.testng.remote.support.RemoteTestNG6_10$DelegatingTestRunnerFactory.newTestRunner(RemoteTestNG6_10.java:61)
    at org.testng.SuiteRunner$ProxyTestRunnerFactory.newTestRunner(SuiteRunner.java:616)
    at org.testng.SuiteRunner.init(SuiteRunner.java:185)
    at org.testng.SuiteRunner.<init>(SuiteRunner.java:131)
    at org.testng.TestNG.createSuiteRunner(TestNG.java:1383)
    at org.testng.TestNG.createSuiteRunners(TestNG.java:1363)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1217)
    at org.testng.TestNG.runSuites(TestNG.java:1144)
    at org.testng.TestNG.run(TestNG.java:1115)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.testng.internal.ObjectFactoryImpl.newInstance(ObjectFactoryImpl.java:23)
    ... 25 more
Caused by: java.lang.NoClassDefFoundError: com/google/gson/JsonParseException
    at org.openqa.selenium.logging.profiler.HttpProfilerLogEntry.constructMessage(HttpProfilerLogEntry.java:37)
    at org.openqa.selenium.logging.profiler.HttpProfilerLogEntry.<init>(HttpProfilerLogEntry.java:29)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:141)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:600)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:219)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:142)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:161)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:107)
    at Util.EMDriverSingleton.setLocalDriver(EMDriverSingleton.java:81)
    at Util.EMDriverSingleton.getDriver(EMDriverSingleton.java:46)
    at Util.Supertest.<init>(Supertest.java:82)
    at Reg_Editor.EditFunctionality.<init>(EditFunctionality.java:16)
    ... 30 more
Caused by: java.lang.ClassNotFoundException: com.google.gson.JsonParseException
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 43 more

POM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ExpertModels</groupId>
    <artifactId>Expert_Models</artifactId>
    <version>0.1-SNAPSHOT</version>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.19.1</version>

                <configuration>
                    <browser>${browser}</browser>
                    <deployment>${deployment}</deployment>
                    <seleniumGrid>${seleniumGrid}</seleniumGrid>
                    <threadCount>0</threadCount>
                    <suiteXmlFiles>
                        <suiteXmlFile>testNG XML Files\${suiteXmlFile}</suiteXmlFile>
                    </suiteXmlFiles>
                </configuration>
            </plugin>

        </plugins>
    </build>
    <packaging>jar</packaging>

    <name>Expert_Models</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <reporting>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-report-plugin</artifactId>
                <version>2.19.1</version>
                <configuration>
                    <showSuccess>true</showSuccess>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jxr-plugin</artifactId>
                <version>2.5</version>
            </plugin>
            <plugin>
                <artifactId>maven-project-info-reports-plugin</artifactId>
                <version>2.7</version>
            </plugin>
        </plugins>
    </reporting>

    <dependencies>

        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>3.0.3</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.7.1</version>
        </dependency>

        <dependency>
            <groupId>com.relevantcodes</groupId>
            <artifactId>extentreports</artifactId>
            <version>2.41.2</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.9.0</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.11</version>
        </dependency>

        <dependency>
            <groupId>net.sourceforge.jexcelapi</groupId>
            <artifactId>jxl</artifactId>
            <version>2.6</version>
        </dependency>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-chrome-driver</artifactId>
            <version>2.33.0</version>
        </dependency>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-edge-driver</artifactId>
            <version>2.47.1</version>
        </dependency>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-ie-driver</artifactId>
            <version>2.53.1</version>
        </dependency>
    </dependencies>

</project>

Body:
Remove the following from POM.xml

  <!--Chrome Driver for Maven -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-chrome-driver</artifactId>
        <version>2.33.0</version>
    </dependency>

    <!--IE Edge Driver for Maven -->
    <!-- <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-edge-driver</artifactId>
        <version>2.53.0</version> <scope>test</scope> </dependency> -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-edge-driver</artifactId>
        <version>2.47.1</version>
    </dependency>

    <!-- IE Driver for Maven -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-ie-driver</artifactId>
        <version>2.53.1</version>
    </dependency>

These drivers are transitive dependencies of selenium-java, so there are automatically resolved by Maven and there is no need to declare them in pom.xml.

If you declare them in th POM.XML, this causes versions conflict of these libraries. Mavens pick a version declared in the POM and ignores the nevest version.

If you are using eclipse, you can observe this on dependency hierarch tab, it looks like this