问:
Deleting a jar from another jar
I have two jar files, Foo.jar and Bar.jar. Inside Foo.jar I have a class Foo with a main method which looks like this:

```<code>public class Foo {
  public static void main(String[] args) {
    Bar bar = new Bar();
    bar.sayHello();
    new File("./Bar.jar").deleteOnExit();
  }
}
</code>```

The class Bar lives in Bar.jar and looks like this:

```<code>public class Bar {
  public void sayHello() {
    System.out.println("Hello! I'm Bar!");
  }
}
</code>```

The intention here is that Foo.jar will use a class in Bar.jar and afterwards it will delete Bar.jar. With the above implementation this is the output when executed:

```<code>$ java -jar Foo.jar
Hello! I'm Bar!
</code>```

but Bar.jar does not get deleted. Here I've tried both new File("./Bar.jar").deleteOnExit(); and new File("./Bar.jar").delete(); in class Foo.

If I change class Bar to close its ClassLoader like this:

```<code>public class Bar {
  public void sayHello() {
    System.out.println("Hello! I'm Bar!");

    URLClassLoader classLoader = (URLClassLoader) this.getClass().getClassLoader();
    try {
      classLoader.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
</code>```

and run Foo.jar again, this is the output:

```<code>$ java -jar Foo.jar
Hello! I'm Bar!
</code>```

the output is the same as in the previous example, but in this case Bar.jar is deleted, which is great, but the problem now is that if I do something like this in class Foo:

```<code>9   public class Foo {
10    public static void main(String[] args) {
11      Bar bar = new Bar();
12      bar.sayHello();
13
14      new File("./Bar.jar").deleteOnExit();
15
16      SimpleFileVisitor<Path> visitor = new SimpleFileVisitor<Path>() {
17      };
18    }
19  }
</code>```

this becomes the output of executing Foo.jar:

```<code>$ java -jar Foo.jar
Hello! I'm Bar!
Exception in thread "main" java.lang.NoClassDefFoundError: playground/modulae/Foo$1
        at playground.modulae.Foo.main(Foo.java:16)
Caused by: java.lang.ClassNotFoundException: playground.modulae.Foo$1
        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)
        ... 1 more
</code>```

In this case, Bar.jar still gets deleted, but when I try to create a new SimpleFileVisitor it crashes with a NoClassDefFoundError. It seems like closing the ClassLoader in Bar.jar causes things to get a bit messed up for Foo.jar as well, but I have not found any other way that lets me delete Bar.jar from Foo.jar.

The general structure of this example closely resembles what happens in the real application, which uses java.nio.file.SimpleFileVisitor later on. I've tried creating a few other classes instead of java.no.file.SimpleFileVisitor and none of them crash, but I guess it depends on whether or not they have been loaded by the ClassLoader before Foo calls Bar.

Update

After messing around with class loaders (which I still don't fully understand) I have something that seems to be sufficient. However, I fear that I'm doing something a bit dodgy and that there is a more 'correct' way of handling the class loader manipulation that I'm doing.

So the setup now is:

I have class Foo with a main method and a speak() method in Foo.jar.

A class Bar with a simple sayHello() method in Bar.jar.

In the main function I create an instance foo of Foo with a custom class loader and call foo.speak()

In foo.speak() I create a instance bar of Bar like this: Bar bar = new Bar() <- Notice that there is no reflection or anything fancy here. Then I call bar.sayHello()

In bar.sayHello() I callthis.getClass().getClassLoader().close()

Everything then returns to main which deletes Bar.jar

And then the code:

Foo.java (in Foo.jar)

```<code>public class Foo {
  public static void main(String[] args) throws MalformedURLException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
    System.out.println("Foo.main: Class path: " + System.getProperty("java.class.path"));

    URLClassLoader initialClassLoader = (URLClassLoader) Foo.class.getClassLoader();
    System.out.println("Foo.main: initialClassLoader = " + initialClassLoader);
    System.out.println("Foo.main: initialClassLoader.getURLs() = " + Arrays.toString(initialClassLoader.getURLs()));

    File fooJar = new File("./Foo.jar");
    File barJar = new File("./Bar.jar");

    CustomClassLoader customClassLoader = new CustomClassLoader(new URL[]{fooJar.toURI().toURL(), barJar.toURI().toURL()});
    System.out.println("Foo.main: customClassLoader = " + customClassLoader);
    System.out.println("Foo.main: customClassLoader.getURLs() = " + Arrays.toString(customClassLoader.getURLs()));
    Class<?> fooClass = customClassLoader.findClass("Foo");
    Object foo = fooClass.newInstance();
    Method speak = fooClass.getMethod("speak");
    speak.invoke(foo);

    barJar.deleteOnExit();

    SimpleFileVisitor<Path> visitor = new SimpleFileVisitor<Path>() {
    };
  }

  public void speak() {
    System.out.println("Foo.speak()");
    URLClassLoader classLoader = (URLClassLoader) this.getClass().getClassLoader();
    System.out.println("Foo.speak(): classLoader = " + classLoader);
    System.out.println("Foo.speak(): classLoader.getURLs() = " + Arrays.toString(classLoader.getURLs()));

    Bar bar = new Bar();
    bar.sayHello();
  }
}
</code>```

Bar.java (in Bar.jar)

```<code>public class Bar {
  public void sayHello() {
    System.out.println("Bar.sayHello()");
    URLClassLoader classLoader = (URLClassLoader) this.getClass().getClassLoader();
    System.out.println("Bar.sayHello(): classLoader = " + classLoader);
    System.out.println("Bar.sayHello(): classLoader.getURLs() = " + Arrays.toString(classLoader.getURLs()));

    try {
      classLoader.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
</code>```

CustomClassLoader (in Foo.jar)

```<code>public class CustomClassLoader extends URLClassLoader {
  public CustomClassLoader(URL[] urls) {
    super(urls);
  }

  @Override
  public Class<?> findClass(String name) throws ClassNotFoundException {
    return super.findClass(name);
  }
}
</code>```

Output

```<code>$ java -jar Foo.jar
Foo.main: Class path: Foo.jar
Foo.main: initialClassLoader = sun.misc.Launcher$AppClassLoader@1f96302
Foo.main: initialClassLoader.getURLs() = [file:/Foo.jar]
Foo.main: customClassLoader = CustomClassLoader@a298b7
Foo.main: customClassLoader.getURLs() = [file:/Foo.jar, file:/Bar.jar]
Foo.speak()
Foo.speak(): classLoader = CustomClassLoader@a298b7
Foo.speak(): classLoader.getURLs() = [file:/Foo.jar, file:/Bar.jar]
Bar.sayHello()
Bar.sayHello(): classLoader = CustomClassLoader@a298b7
Bar.sayHello(): classLoader.getURLs() = [file:/Foo.jar, file:/Bar.jar]
</code>```

and Bar.jar is deleted.

Thoughts

As we see, Bar can be referenced from within Foo.jar without any reflection, it has been loaded with the correct CustomClassLoader and Bar.jar can successfully be deleted from Foo after having called bar.sayHello().

Now, this solves my problem. However, I'm not confident that I have solved the CustomClassLoader correctly. In fact, the only thing that CustomClassLoader effectively does is make findClass() public. I tried a whole bunch of different ways of implementing loadClass(), but could never get it to work and just by accident I tried findClass() instead and it worked.

Does anyone have any opinions on how CustomClassLoader is used?

答:
OK, so here what I would do:

I would define an interface to use by Foo, and implement by Bar:

```<code>public interface BarIntf {
    public void sayHello();
}
</code>```

The interface must be in Foo.jar.

The Bar class would implement BarIntf:

```<code>public class Bar implements BarIntf {
    @Override
    public void sayHello() {
        System.out.println("Hello! I'm Bar!");
    }
}
</code>```

Now, instead of putting both Foo.jar and Bar.jar in the classpath, I would put only Foo.jar, and create a class loader in program Foo just to load the Bar class.

It looks like this:

```<code>public class Foo {
    public static void main(String[] args) {
        File jar = new File("./Bar.jar");
        try (URLClassLoader cl = new URLClassLoader(
                new URL[] {jar.toURI().toURL()})) {
            Class<?> clazz = cl.loadClass("bar.Bar");
            BarIntf bar = (BarIntf)clazz.newInstance();
            bar.sayHello();
            // ...a lot of very useful things
        } catch (IOException | ClassNotFoundException
                | InstantiationException | IllegalAccessException ex) {
            Logger.getLogger(Foo.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            jar.delete();
        }
    }
}
</code>```

UPDATE:

With reflection (no interface required):

```<code>public class Foo {
    public static void main(String[] args) {
        File jar = new File("./Bar.jar");
        try (URLClassLoader cl = new URLClassLoader(
                new URL[] {jar.toURI().toURL()})) {
            Class<?> clazz = cl.loadClass("bar.Bar");
            Method method = clazz.getDeclaredMethod("sayHello");
            Object bar = clazz.newInstance();
            method.invoke(bar);
            // ...a lot of very useful things
        } catch (IOException | ClassNotFoundException
                | InstantiationException | IllegalAccessException
                | NoSuchMethodException | SecurityException
                | InvocationTargetException ex) {
            Logger.getLogger(Foo.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            jar.delete();
        }
    }
}
</code>```

Title: Deleting a jar from another jar

Body:
I have two jar files, Foo.jar and Bar.jar. Inside Foo.jar I have a class Foo with a main method which looks like this:

public class Foo {
  public static void main(String[] args) {
    Bar bar = new Bar();
    bar.sayHello();
    new File("./Bar.jar").deleteOnExit();
  }
}

The class Bar lives in Bar.jar and looks like this:

public class Bar {
  public void sayHello() {
    System.out.println("Hello! I'm Bar!");
  }
}

The intention here is that Foo.jar will use a class in Bar.jar and afterwards it will delete Bar.jar. With the above implementation this is the output when executed:

$ java -jar Foo.jar
Hello! I'm Bar!

but Bar.jar does not get deleted. Here I've tried both new File("./Bar.jar").deleteOnExit(); and new File("./Bar.jar").delete(); in class Foo.

If I change class Bar to close its ClassLoader like this:

public class Bar {
  public void sayHello() {
    System.out.println("Hello! I'm Bar!");

    URLClassLoader classLoader = (URLClassLoader) this.getClass().getClassLoader();
    try {
      classLoader.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

and run Foo.jar again, this is the output:

$ java -jar Foo.jar
Hello! I'm Bar!

the output is the same as in the previous example, but in this case Bar.jar is deleted, which is great, but the problem now is that if I do something like this in class Foo:

9   public class Foo {
10    public static void main(String[] args) {
11      Bar bar = new Bar();
12      bar.sayHello();
13
14      new File("./Bar.jar").deleteOnExit();
15
16      SimpleFileVisitor<Path> visitor = new SimpleFileVisitor<Path>() {
17      };
18    }
19  }

this becomes the output of executing Foo.jar:

$ java -jar Foo.jar
Hello! I'm Bar!
Exception in thread "main" java.lang.NoClassDefFoundError: playground/modulae/Foo$1
        at playground.modulae.Foo.main(Foo.java:16)
Caused by: java.lang.ClassNotFoundException: playground.modulae.Foo$1
        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)
        ... 1 more

In this case, Bar.jar still gets deleted, but when I try to create a new SimpleFileVisitor it crashes with a NoClassDefFoundError. It seems like closing the ClassLoader in Bar.jar causes things to get a bit messed up for Foo.jar as well, but I have not found any other way that lets me delete Bar.jar from Foo.jar.

The general structure of this example closely resembles what happens in the real application, which uses java.nio.file.SimpleFileVisitor later on. I've tried creating a few other classes instead of java.no.file.SimpleFileVisitor and none of them crash, but I guess it depends on whether or not they have been loaded by the ClassLoader before Foo calls Bar.

Update

After messing around with class loaders (which I still don't fully understand) I have something that seems to be sufficient. However, I fear that I'm doing something a bit dodgy and that there is a more 'correct' way of handling the class loader manipulation that I'm doing.

So the setup now is:

I have class Foo with a main method and a speak() method in Foo.jar.

A class Bar with a simple sayHello() method in Bar.jar.

In the main function I create an instance foo of Foo with a custom class loader and call foo.speak()

In foo.speak() I create a instance bar of Bar like this: Bar bar = new Bar() <- Notice that there is no reflection or anything fancy here. Then I call bar.sayHello()

In bar.sayHello() I callthis.getClass().getClassLoader().close()

Everything then returns to main which deletes Bar.jar

And then the code:

Foo.java (in Foo.jar)

public class Foo {
  public static void main(String[] args) throws MalformedURLException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
    System.out.println("Foo.main: Class path: " + System.getProperty("java.class.path"));

    URLClassLoader initialClassLoader = (URLClassLoader) Foo.class.getClassLoader();
    System.out.println("Foo.main: initialClassLoader = " + initialClassLoader);
    System.out.println("Foo.main: initialClassLoader.getURLs() = " + Arrays.toString(initialClassLoader.getURLs()));

    File fooJar = new File("./Foo.jar");
    File barJar = new File("./Bar.jar");

    CustomClassLoader customClassLoader = new CustomClassLoader(new URL[]{fooJar.toURI().toURL(), barJar.toURI().toURL()});
    System.out.println("Foo.main: customClassLoader = " + customClassLoader);
    System.out.println("Foo.main: customClassLoader.getURLs() = " + Arrays.toString(customClassLoader.getURLs()));
    Class<?> fooClass = customClassLoader.findClass("Foo");
    Object foo = fooClass.newInstance();
    Method speak = fooClass.getMethod("speak");
    speak.invoke(foo);

    barJar.deleteOnExit();

    SimpleFileVisitor<Path> visitor = new SimpleFileVisitor<Path>() {
    };
  }

  public void speak() {
    System.out.println("Foo.speak()");
    URLClassLoader classLoader = (URLClassLoader) this.getClass().getClassLoader();
    System.out.println("Foo.speak(): classLoader = " + classLoader);
    System.out.println("Foo.speak(): classLoader.getURLs() = " + Arrays.toString(classLoader.getURLs()));

    Bar bar = new Bar();
    bar.sayHello();
  }
}

Bar.java (in Bar.jar)

public class Bar {
  public void sayHello() {
    System.out.println("Bar.sayHello()");
    URLClassLoader classLoader = (URLClassLoader) this.getClass().getClassLoader();
    System.out.println("Bar.sayHello(): classLoader = " + classLoader);
    System.out.println("Bar.sayHello(): classLoader.getURLs() = " + Arrays.toString(classLoader.getURLs()));

    try {
      classLoader.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

CustomClassLoader (in Foo.jar)

public class CustomClassLoader extends URLClassLoader {
  public CustomClassLoader(URL[] urls) {
    super(urls);
  }

  @Override
  public Class<?> findClass(String name) throws ClassNotFoundException {
    return super.findClass(name);
  }
}

Output

$ java -jar Foo.jar
Foo.main: Class path: Foo.jar
Foo.main: initialClassLoader = sun.misc.Launcher$AppClassLoader@1f96302
Foo.main: initialClassLoader.getURLs() = [file:/Foo.jar]
Foo.main: customClassLoader = CustomClassLoader@a298b7
Foo.main: customClassLoader.getURLs() = [file:/Foo.jar, file:/Bar.jar]
Foo.speak()
Foo.speak(): classLoader = CustomClassLoader@a298b7
Foo.speak(): classLoader.getURLs() = [file:/Foo.jar, file:/Bar.jar]
Bar.sayHello()
Bar.sayHello(): classLoader = CustomClassLoader@a298b7
Bar.sayHello(): classLoader.getURLs() = [file:/Foo.jar, file:/Bar.jar]

and Bar.jar is deleted.

Thoughts

As we see, Bar can be referenced from within Foo.jar without any reflection, it has been loaded with the correct CustomClassLoader and Bar.jar can successfully be deleted from Foo after having called bar.sayHello().

Now, this solves my problem. However, I'm not confident that I have solved the CustomClassLoader correctly. In fact, the only thing that CustomClassLoader effectively does is make findClass() public. I tried a whole bunch of different ways of implementing loadClass(), but could never get it to work and just by accident I tried findClass() instead and it worked.

Does anyone have any opinions on how CustomClassLoader is used?

Body:
OK, so here what I would do:

I would define an interface to use by Foo, and implement by Bar:

public interface BarIntf {
    public void sayHello();
}

The interface must be in Foo.jar.

The Bar class would implement BarIntf:

public class Bar implements BarIntf {
    @Override
    public void sayHello() {
        System.out.println("Hello! I'm Bar!");
    }
}

Now, instead of putting both Foo.jar and Bar.jar in the classpath, I would put only Foo.jar, and create a class loader in program Foo just to load the Bar class.

It looks like this:

public class Foo {
    public static void main(String[] args) {
        File jar = new File("./Bar.jar");
        try (URLClassLoader cl = new URLClassLoader(
                new URL[] {jar.toURI().toURL()})) {
            Class<?> clazz = cl.loadClass("bar.Bar");
            BarIntf bar = (BarIntf)clazz.newInstance();
            bar.sayHello();
            // ...a lot of very useful things
        } catch (IOException | ClassNotFoundException
                | InstantiationException | IllegalAccessException ex) {
            Logger.getLogger(Foo.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            jar.delete();
        }
    }
}

UPDATE:

With reflection (no interface required):

public class Foo {
    public static void main(String[] args) {
        File jar = new File("./Bar.jar");
        try (URLClassLoader cl = new URLClassLoader(
                new URL[] {jar.toURI().toURL()})) {
            Class<?> clazz = cl.loadClass("bar.Bar");
            Method method = clazz.getDeclaredMethod("sayHello");
            Object bar = clazz.newInstance();
            method.invoke(bar);
            // ...a lot of very useful things
        } catch (IOException | ClassNotFoundException
                | InstantiationException | IllegalAccessException
                | NoSuchMethodException | SecurityException
                | InvocationTargetException ex) {
            Logger.getLogger(Foo.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            jar.delete();
        }
    }
}


来源: stackexchange

问:
Unlimited keepalive in MQTT
Currently developing something like "smart home" and I have few different devices in my home. All of them connected to OpenHab via MQTT. I'm using Paho MQTT library (Python) for my purposes.

Generally, MQTT has "keepalive" property. This property describes how much time my client will be connected (AFAIK it sends the ping to the server) to MQTT server when there are no updates on the subscribed topic.

But here I have a huge problem. Needed topic could be updated once per hour or even once per few days/months. Let's say that this is indoor alarm.
How can I avoid that keepalive timeout or ignore that field? Could it be unlimited?

答:
You have miss understood what the keepalive value represents.

MQTT clients can stay connected indefinitely even if they do not publish or receive any messages. But the broker needs to keep track of which clients are still connected so it knows when to send the Last Will and Testament (LWT) message for the client. In order to do this it uses the keepalive time.

Every time a message is sent or received by the client, the broker resets a timer, if this timer exceeds 1.5 times the value of the keepalive time then the broker marks the client as disconnected and processes the LWT. To prevent clients with very low messages rates from being disconnected, such a client can send a PINGREQ packet at any time (most likely on timeout of the keepalive value) to the server/broker. The server receives the PINGREQ, answers with a PINGRESP packet and it will reset the keepalive timer to zero and leave the client in the connected state.

See Keep Alive section of the MQTT standard: (http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc385349238)

The Client can send PINGREQ at any time, irrespective of the Keep Alive value, and use the PINGRESP to determine that the network and the Server are working. If the Keep Alive value is non-zero and the Server does not receive a Control Packet from the Client within one and a half times the Keep Alive time period, it MUST disconnect the Network Connection to the Client as if the network had failed

ContentLicense: CC BY-SA 3.0

Title: Unlimited keepalive in MQTT

ContentLicense: CC BY-SA 4.0


问:
React - do I need Flux/Redux at this point? (communication between components)
I'm at a point in my app that has me a bit stumped, and I'm not totally sure what to do.

Basically, I have a component structure like this:

```<code>Layout
  FilePage
    FileDrop
  BackgroundActivity
    UploadQueue
      FileUpload
</code>```

So on every single page, the BackgroundActivity component is there, which will show files currently being uploaded. Each FileUpload is basically a progress meter and a filename.

The issue here is, when a user drops a file on FileDrop, I need that to somehow send file info to UploadQueue to create a new FileUpload, e.g.:

```<code>UploadQueue = React.createClass({
  propTypes: {
    fileList: React.PropTypes.any.isRequired
  },

  statusChange(status) {
    debugMode && console.info('[UploadQueue] Status change! %o', status);
  },

  render() {
    let files = [];

    // Convert to a true array
    for (let i = 0; i < this.props.fileList.length; ++i) {
      files = files.concat(this.props.fileList[i]);
    }

    return (
      <div>
        {files.map(file => {
          return <FileUpload key={file.name}
                             name={file.name}
                             statusChange={this.statusChange} />
        })}
      </div>
    )
  }
});
</code>```

It seems that I'd have to pass a callback from Layout down to FilePage, down to FileDrop, so that FileDrop can pass file information back upwards to Layout which would then send it down to BackgroundActivity to pass to UploadQueue. This seems like a messy way to connect grandchildren.

Am I at a point where I need Flux or Redux? I know that those frameworks claim to reduce complexity, but looking at Redux examples, it seems to just add more complexity. Or is passing functions down several levels just the way things are done in React?

答:
As far as React is concerned, both of the following approaches are just fine, ie. :

Some people pass functions and props down to children

Some others use a flux(y) architecture (redux, flux, mobx ...)

Answering your questions:

Am I at a point where I need flux ?

Flux is not required as such to build an application, however most developers just include it because the state of any significant application will sooner or later go out of control.

I know that those frameworks claim to reduce complexity, but looking at Redux examples, it seems to just add more complexity.

At first, it is a little overwhelming, but once you've built a significant sized application without redux and you shift, you'd most probably love to work with redux. It just feels a little complex but makes much sense and is very easy once it enters your muscle memory.

Also, the javascript community is fatigued with new packages and its followers everyday. Redux+React has acquired a strong fanbase, so much so that it has become the almost defacto standard of building react applications. But this does not mean that it is absolutely required.

If this is a project where you can afford to go slow, then you can simply go ahead with passing down props. There is nothing technically wrong in that approach. In fact that is how react was built. Later you can try implementing redux when you face problems like sharing state between components, having a single source of truth etc.

This article by Dan Abramov(The author of redux might be of help too) : You might not need redux

Body:
I'm at a point in my app that has me a bit stumped, and I'm not totally sure what to do.

Basically, I have a component structure like this:

Layout
  FilePage
    FileDrop
  BackgroundActivity
    UploadQueue
      FileUpload

So on every single page, the BackgroundActivity component is there, which will show files currently being uploaded. Each FileUpload is basically a progress meter and a filename.

The issue here is, when a user drops a file on FileDrop, I need that to somehow send file info to UploadQueue to create a new FileUpload, e.g.:

UploadQueue = React.createClass({
  propTypes: {
    fileList: React.PropTypes.any.isRequired
  },

  statusChange(status) {
    debugMode && console.info('[UploadQueue] Status change! %o', status);
  },

  render() {
    let files = [];

    // Convert to a true array
    for (let i = 0; i < this.props.fileList.length; ++i) {
      files = files.concat(this.props.fileList[i]);
    }

    return (

        {files.map(file => {
          return <FileUpload key={file.name}
                             name={file.name}
                             statusChange={this.statusChange} />
        })}

    )
  }
});

It seems that I'd have to pass a callback from Layout down to FilePage, down to FileDrop, so that FileDrop can pass file information back upwards to Layout which would then send it down to BackgroundActivity to pass to UploadQueue. This seems like a messy way to connect grandchildren.

Am I at a point where I need Flux or Redux? I know that those frameworks claim to reduce complexity, but looking at Redux examples, it seems to just add more complexity. Or is passing functions down several levels just the way things are done in React?


问:
c# doing a custom sort on a datatable
i have data in a datatable that needs to be sorted on the first column this way:

```<code>A02 BLANK0010
D02 BLANK0007
B04 BLANK0011
G05 BLANK0012
C06 BLANK0014
E08 BLANK0013
F10 BLANK0016
H12 BLANK0015
B02 G112486
C02 G125259
E02 G125257
F02 G112492
G02 G125095
H02 G112489
A03 G125090
B03 G112499
C03 G125256
D03 G002007
E03 G112494
F03 G002005
G03 G112495
H03 G002008
A04 G115717
</code>```

if i do a regular sort, it will just sort like this: A02, A03, A04. but i need A02, B02, C02... etc

how can i do this>? here my code so far:

DataView view = dt.DefaultView;
        view.Sort = "position";

答: As possible way: add additional column that will first letter of first column and then sort by that column and first column.</p>

ContentLicense: CC BY-SA 2.5

Title: c# doing a custom sort on a datatable

Body:
i have data in a datatable that needs to be sorted on the first column this way:

A02 BLANK0010
D02 BLANK0007
B04 BLANK0011
G05 BLANK0012
C06 BLANK0014
E08 BLANK0013
F10 BLANK0016
H12 BLANK0015
B02 G112486
C02 G125259
E02 G125257
F02 G112492
G02 G125095
H02 G112489
A03 G125090
B03 G112499
C03 G125256
D03 G002007
E03 G112494
F03 G002005
G03 G112495
H03 G002008
A04 G115717

if i do a regular sort, it will just sort like this: A02, A03, A04. but i need A02, B02, C02... etc

how can i do this>? here my code so far:

DataView view = dt.DefaultView;
        view.Sort = "position";


问:
how to increase the Rest service timeout time in spring STS
I am using a spring STS to develop the project which  has the embedded tc server.  I don't know what causes this  issue, but my rest service always gets timeout of 60 seconds, even though I tried to keep timeout=100 in @Transactional and I tried putting the value in jpa.xml file too. Can anybody tell me how to increase the timeout?

答:
Hello Dhari,

Please double click on the embedded tomcat server .You can modify the time out seconds as per your wish. Please look at the screen shot provided.

```<code>More over your question is not related to increase the service timeout instead it should be server timeout which was pretty fishy to understand.Kindly update your question as suggested.
</code>```

Body:
Hello Dhari,

Please double click on the embedded tomcat server .You can modify the time out seconds as per your wish. Please look at the screen shot provided.

More over your question is not related to increase the service timeout instead it should be server timeout which was pretty fishy to understand.Kindly update your question as suggested.


问:
Generate a UNIQUE string made out of numeric / ALPHABET

My Problem

I don't know any VBA

Need to generate a string of 12 chars (ALPHA +  numbers , 0-9 , A-Z) IN VBA...

Sample output :

```<code>"ADF3V3224K1WQ"
</code>```

(12 characters long , Higher caps Alphabetical letters , and Numeric values aswell).

Story

I'm having a hard time figuring out how to create a string generator (didn't say it has to be random, but it 100% has to be unique, meaning it has to check for duplications or store existing values), I have no experience with VBA. I already found a similar post here, but it is different then mine, as it does not specifically ask for the string to be 100% unique. (I don't need a very low chance, I need 100% across the board).

Syntax-wise I'm pretty confused, I managed to find where the code behind events are, ie Button presses, so I know where I need to write it, but I have no idea how to check for duplications. (even relying on a time seed that can ensure it will be 100% unique is great).

Link to the similar post: MS Access Visual Basic - generate random string in text field

答:
There are multiple solutions to this problem, but I like this one:

```<code>Public Function newguidx() As String
    With CreateObject("Scriptlet.TypeLib")
        newguidx = Left(.Guid, 38)
    End With
End Function
</code>```

It creates a GUID. These aren't unique per se, but you can read on the Wikipedia page that they might as well be. You can use Replace to remove the {}- signs if you want to.

Also, since the format is standardized, it will be clear to most programmers what it is.

Obviously, you can trim characters out to get your desired length, and it will increase your chance of finding a duplicate.

Edit:

Unfortunately, access to Scriptlet.TypeLib is currently blocked by default because of security reasons. See MS Access VBA Error: Run time error '70' Permission Denied for information on that, and How can I generate GUIDs in Excel? for a nice overview of multiple methods to generate a GUID.

My personal preference:

```<code>Public Function CreateGUID() As String
    Do While Len(CreateGUID) < 32
        If Len(CreateGUID) = 16 Then
            '17th character holds version information
            CreateGUID = CreateGUID & Hex$(8 + CInt(Rnd * 3))
        End If
        CreateGUID = CreateGUID & Hex$(CInt(Rnd * 15))
    Loop
    CreateGUID = "{" & Mid(CreateGUID, 1, 8) & "-" & Mid(CreateGUID, 9, 4) & "-" & Mid(CreateGUID, 13, 4) & "-" & Mid(CreateGUID, 17, 4) & "-" & Mid(CreateGUID, 21, 12) & "}"
End Function
</code>```

Body:
My Problem

I don't know any VBA

Need to generate a string of 12 chars (ALPHA +  numbers , 0-9 , A-Z) IN VBA...

Sample output :

"ADF3V3224K1WQ"

(12 characters long , Higher caps Alphabetical letters , and Numeric values aswell).

Story

I'm having a hard time figuring out how to create a string generator (didn't say it has to be random, but it 100% has to be unique, meaning it has to check for duplications or store existing values), I have no experience with VBA. I already found a similar post here, but it is different then mine, as it does not specifically ask for the string to be 100% unique. (I don't need a very low chance, I need 100% across the board).

Syntax-wise I'm pretty confused, I managed to find where the code behind events are, ie Button presses, so I know where I need to write it, but I have no idea how to check for duplications. (even relying on a time seed that can ensure it will be 100% unique is great).

Link to the similar post: MS Access Visual Basic - generate random string in text field

Body:
There are multiple solutions to this problem, but I like this one:

Public Function newguidx() As String
    With CreateObject("Scriptlet.TypeLib")
        newguidx = Left(.Guid, 38)
    End With
End Function

It creates a GUID. These aren't unique per se, but you can read on the Wikipedia page that they might as well be. You can use Replace to remove the {}- signs if you want to.

Also, since the format is standardized, it will be clear to most programmers what it is.

Obviously, you can trim characters out to get your desired length, and it will increase your chance of finding a duplicate.

Edit:

Unfortunately, access to Scriptlet.TypeLib is currently blocked by default because of security reasons. See MS Access VBA Error: Run time error '70' Permission Denied for information on that, and How can I generate GUIDs in Excel? for a nice overview of multiple methods to generate a GUID.

My personal preference:

Public Function CreateGUID() As String
    Do While Len(CreateGUID) < 32
        If Len(CreateGUID) = 16 Then
            '17th character holds version information
            CreateGUID = CreateGUID & Hex$(8 + CInt(Rnd * 3))
        End If
        CreateGUID = CreateGUID & Hex$(CInt(Rnd * 15))
    Loop
    CreateGUID = "{" & Mid(CreateGUID, 1, 8) & "-" & Mid(CreateGUID, 9, 4) & "-" & Mid(CreateGUID, 13, 4) & "-" & Mid(CreateGUID, 17, 4) & "-" & Mid(CreateGUID, 21, 12) & "}"
End Function


问:
Get-WinEvent via Powershell remoting
I have a non-admin access to a server. I'm allowed to connect via RDP, and to use PowerShell remoting. When I invoke the following PowerShell command from an RDP session:

```<code>Get-WinEvent -MaxEvents 100 -Provider Microsoft-Windows-TaskScheduler
</code>```

I get 100 records, as expected.

When I do the same via PowerShell remoting, by invoking the following from my local machine:

```<code>invoke-command -ComputerName myserver {Get-WinEvent -MaxEvents 100 -Provider Microsoft-Windows-TaskScheduler }
</code>```

I get an error:

No events were found that match the specified selection criteria.

CategoryInfo          : ObjectNotFound: (:) [Get-WinEvent], Exception

FullyQualifiedErrorId : NoMatchingEventsFound,Microsoft.PowerShell.Commands.GetWinEventCommand

Any idea why? The remote PowerShell session should be running under identical credentials, right?

EDIT: whoami does show a difference in the security context between RDP logon and PowerShell remoting - the group set is different. In the RDP logon session, there are the following groups in the token:

BUILTIN\Remote Desktop Users

NT AUTHORITY\REMOTE INTERACTIVE LOGON

while in the remoted one, there's

CONSOLE LOGON

That could account for the discrepancy in rights...

EDIT: from the registry, it looks like the task scheduler log somehow is a part of the System log. According to MS KB article Q323076, the security descriptor for the System log can be found under HKLM\SYSTEM\CurrentControlSet\Services\EventLog\System, value CustomSD. I can't check the server in question, but on another server where I'm an admin, there's no CustomSD under that key. Under HKLM\SYSTEM\CurrentControlSet\Services\EventLog\System\Microsoft-Windows-TaskScheduler, neither. Only the Security log gets a CustomSD. The next question is, where's the default SD?

Permissions on the actual log file at C:\Windows\System32\winevt\LogsMicrosoft-Windows-TaskScheduler%4Operational.evtx are irrelevant, the access is being mediated by the EventLog service anyway.

答:
You need local admin rights to open a powershell session.

But there is a workaround/alterative here:

https://4sysops.com/archives/powershell-remoting-without-administrator-rights/

Title: Get-WinEvent via Powershell remoting

Body:
I have a non-admin access to a server. I'm allowed to connect via RDP, and to use PowerShell remoting. When I invoke the following PowerShell command from an RDP session:

Get-WinEvent -MaxEvents 100 -Provider Microsoft-Windows-TaskScheduler

I get 100 records, as expected.

When I do the same via PowerShell remoting, by invoking the following from my local machine:

invoke-command -ComputerName myserver {Get-WinEvent -MaxEvents 100 -Provider Microsoft-Windows-TaskScheduler }

I get an error:

No events were found that match the specified selection criteria.

CategoryInfo          : ObjectNotFound: (:) [Get-WinEvent], Exception

FullyQualifiedErrorId : NoMatchingEventsFound,Microsoft.PowerShell.Commands.GetWinEventCommand

Any idea why? The remote PowerShell session should be running under identical credentials, right?

EDIT: whoami does show a difference in the security context between RDP logon and PowerShell remoting - the group set is different. In the RDP logon session, there are the following groups in the token:

BUILTIN\Remote Desktop Users

NT AUTHORITY\REMOTE INTERACTIVE LOGON

while in the remoted one, there's

CONSOLE LOGON

That could account for the discrepancy in rights...

EDIT: from the registry, it looks like the task scheduler log somehow is a part of the System log. According to MS KB article Q323076, the security descriptor for the System log can be found under HKLM\SYSTEM\CurrentControlSet\Services\EventLog\System, value CustomSD. I can't check the server in question, but on another server where I'm an admin, there's no CustomSD under that key. Under HKLM\SYSTEM\CurrentControlSet\Services\EventLog\System\Microsoft-Windows-TaskScheduler, neither. Only the Security log gets a CustomSD. The next question is, where's the default SD?

Permissions on the actual log file at C:\Windows\System32\winevt\LogsMicrosoft-Windows-TaskScheduler%4Operational.evtx are irrelevant, the access is being mediated by the EventLog service anyway.


问:
Issue in reading and processing text file using VBA
I'm an amid new user to VBA and trying to read a text file of big in size. Sometimes text file of some MB's of size too.

The data consists of printed results against some number at different time stamps.

The time stamp where I need to store the values is as follows:

STEP TIME COMPLETED        1.00    ,  TOTAL TIME COMPLETED         1.00

Then the printed data is as follows:

```<code>90000354   1        -3.9630E-02 -3.5410E-02 -0.2695      0.4523       2.424      0.5630
</code>```

Now, I want to look for the number 90000354 and need to copy and paste these numbers -3.9630E-02, -3.5410E-02 & -0.2695 in to the excel sheet. Right now, I'm using the follow code, but it is giving issues. Please help to fix this issue.

Many thanks in advance.

```<code>Option Explicit

Private Sub CommandButton1_Click()

Dim text As String, MyData As String, strData() As String, myFile As String, textLine As String

Dim v As Variant

Dim numIde As Long, i As Long

myFile = Application.GetOpenFilename("Dat Files (*.dat), *.dat")

Open myFile For Input As #1

MyData = Space$(LOF(1))

Do Until EOF(1)

    Line Input #1, textLine

    MyData = MyData & textLine & vbCrLf

Loop

Close #1

strData() = Split(MyData, vbCrLf)

numIde = 90000354

For i = LBound(strData) To UBound(strData)

    If InStr(1, strData(i), numIde, vbTextCompare) Then

        Cells(2, 2).Value = Mid(numIde, numIde + 20, 11)

        Cells(2, 3).Value = Mid(numIde, numIde + 32, 11)

        Cells(2, 4).Value = Mid(numIde, numIde + 44, 11)

        Exit For
    End If
Next i
</code>```

End Sub

Running the code is ended up with an error as follows:

"Run-time error '54': Bad file mode"

While trying to debug, it is stopping at this code line "Get #1, , MyData"

答:
Get is for reading binary data, and you want to read text.  Use Line Input

Edit:  Updated - this should work better.  Read in each line, then check it.  Saves having to bother with the split function that may or may not recognize the vbCRLF, depending on OS etc.

Do something like this:

Private Sub CommandButton1_Click()

```<code>Dim text As String, MyData As String, strData() As String, myFile As String
Dim numIde As Integer
Dim i As Long

numIde = 90000354
myFile = Application.GetOpenFilename("Dat Files (*.dat), *.dat")

Open myFile For Input As #1

Do Until EOF(1)
    Line Input #1, textline
    If InStr(1, textline, numIde, vbTextCompare) Then
        Cells(2, 2).Value = Mid(textline, numIde + 20, 11)
        Cells(2, 3).Value = Mid(textline, numIde + 32, 11)
        Cells(2, 4).Value = Mid(textline, numIde + 44, 11)
    End If
Loop
Close #1
</code>```

If you prefer the way it was being done, then there was a slightly problem with the code I had previously posted.  It was that it was appending each line of text to a single string, not adding it as a new line, so the Split() function wouldn't work.  The updated code here should work.

```<code>Do Until EOF(1)
Line Input #1, text
    MyData = MyData & text & vbCrLf  '<-need to append the vbCRLF
Loop
Close #1
strData = Split(MyData, vbCrLf)
</code>```

Body:
I'm an amid new user to VBA and trying to read a text file of big in size. Sometimes text file of some MB's of size too.

The data consists of printed results against some number at different time stamps.

The time stamp where I need to store the values is as follows:

STEP TIME COMPLETED        1.00    ,  TOTAL TIME COMPLETED         1.00

Then the printed data is as follows:

90000354   1        -3.9630E-02 -3.5410E-02 -0.2695      0.4523       2.424      0.5630

Now, I want to look for the number 90000354 and need to copy and paste these numbers -3.9630E-02, -3.5410E-02 & -0.2695 in to the excel sheet. Right now, I'm using the follow code, but it is giving issues. Please help to fix this issue.

Many thanks in advance.

Option Explicit

Private Sub CommandButton1_Click()

Dim text As String, MyData As String, strData() As String, myFile As String, textLine As String

Dim v As Variant

Dim numIde As Long, i As Long

myFile = Application.GetOpenFilename("Dat Files (*.dat), *.dat")

Open myFile For Input As #1

MyData = Space$(LOF(1))

Do Until EOF(1)

    Line Input #1, textLine

    MyData = MyData & textLine & vbCrLf

Loop

Close #1

strData() = Split(MyData, vbCrLf)

numIde = 90000354

For i = LBound(strData) To UBound(strData)

    If InStr(1, strData(i), numIde, vbTextCompare) Then

        Cells(2, 2).Value = Mid(numIde, numIde + 20, 11)

        Cells(2, 3).Value = Mid(numIde, numIde + 32, 11)

        Cells(2, 4).Value = Mid(numIde, numIde + 44, 11)

        Exit For
    End If
Next i

End Sub

Running the code is ended up with an error as follows:

"Run-time error '54': Bad file mode"

While trying to debug, it is stopping at this code line "Get #1, , MyData"

Body:
Get is for reading binary data, and you want to read text.  Use Line Input

Edit:  Updated - this should work better.  Read in each line, then check it.  Saves having to bother with the split function that may or may not recognize the vbCRLF, depending on OS etc.

Do something like this:

Private Sub CommandButton1_Click()

Dim text As String, MyData As String, strData() As String, myFile As String
Dim numIde As Integer
Dim i As Long

numIde = 90000354
myFile = Application.GetOpenFilename("Dat Files (*.dat), *.dat")

Open myFile For Input As #1

Do Until EOF(1)
    Line Input #1, textline
    If InStr(1, textline, numIde, vbTextCompare) Then
        Cells(2, 2).Value = Mid(textline, numIde + 20, 11)
        Cells(2, 3).Value = Mid(textline, numIde + 32, 11)
        Cells(2, 4).Value = Mid(textline, numIde + 44, 11)
    End If
Loop
Close #1

If you prefer the way it was being done, then there was a slightly problem with the code I had previously posted.  It was that it was appending each line of text to a single string, not adding it as a new line, so the Split() function wouldn't work.  The updated code here should work.

Do Until EOF(1)
Line Input #1, text
    MyData = MyData & text & vbCrLf  '<-need to append the vbCRLF
Loop
Close #1
strData = Split(MyData, vbCrLf)


问:
How to join on more three tables in Rails 3
I would like to join more than three tables in Rails 3.

My code is

```<code>class offer < ActiveRecord::Base

  belongs_to :user
  has_many :usercomments, :dependent => :destroy
  has_many :comments, :through => :usercomments, :dependent => :destroy

end

class User < ActiveRecord::Base

  has_many :usercomments, :dependent =>:destroy
  has_many :comments,:through => :usercomments, :dependent => :destroy
  has_many :offers, :dependent => :destroy

end

class Usercomment < ActiveRecord::Base

  belongs_to :user
  belongs_to :comment
  belongs_to :offer

end

class Comment < ActiveRecord::Base

  has_one :usercomment, :dependent => :destroy
  has_one :offer, :through => :usercomments
  has_one :user, :through => :usercomments

end
</code>```

My schema is:

```<code>create_table "offers", :force => true do |t|
  t.integer  "step_id"
  t.integer  "user_id"
  t.date     "offerdate"
end

create_table "users", :force => true do |t|
  t.string   "firstname",            :limit => 100, :default => ""
  t.string   "lastname",             :limit => 100, :default => ""
  t.string   "email",                :limit => 100
end

create_table "usercomments", :force => true do |t|
  t.integer  "user_id"
  t.integer  "airoffer_id"
  t.integer  "comment_id"
  t.boolean  "shared"
end

create_table "comments", :force => true do |t|
  t.string   "comment"
  t.datetime "created_at"
  t.datetime "updated_at"
end
</code>```

and index.html.erb is:

```<code> <% airoffers.each do |airoffer| %>

???

 <% end %>
</code>```

In my html.erb page I would like to find a comment for an offer (offer_id) and an user (user_id).

答:
I would use it this way:

```<code>Comment.find(
  :all,
  :conditions => {
    :user_id  => 123,
    :offer_id => 456
  },
  :join => :usercomment
)
</code>```

OR:

```<code>Comment.find(
  :all,
  :conditions => [
    "usercomments.user_id = ? AND usercomments.offer_id = ?",
    123,
    456
  ],
  :join => :usercomment
)
</code>```

Rails have a lot of beautiful ways to write queries.

Body:
I would like to join more than three tables in Rails 3.

My code is

class offer < ActiveRecord::Base

  belongs_to :user
  has_many :usercomments, :dependent => :destroy
  has_many :comments, :through => :usercomments, :dependent => :destroy

end

class User < ActiveRecord::Base

  has_many :usercomments, :dependent =>:destroy
  has_many :comments,:through => :usercomments, :dependent => :destroy
  has_many :offers, :dependent => :destroy

end

class Usercomment < ActiveRecord::Base

  belongs_to :user
  belongs_to :comment
  belongs_to :offer

end

class Comment < ActiveRecord::Base

  has_one :usercomment, :dependent => :destroy
  has_one :offer, :through => :usercomments
  has_one :user, :through => :usercomments

end

My schema is:

create_table "offers", :force => true do |t|
  t.integer  "step_id"
  t.integer  "user_id"
  t.date     "offerdate"
end

create_table "users", :force => true do |t|
  t.string   "firstname",            :limit => 100, :default => ""
  t.string   "lastname",             :limit => 100, :default => ""
  t.string   "email",                :limit => 100
end

create_table "usercomments", :force => true do |t|
  t.integer  "user_id"
  t.integer  "airoffer_id"
  t.integer  "comment_id"
  t.boolean  "shared"
end

create_table "comments", :force => true do |t|
  t.string   "comment"
  t.datetime "created_at"
  t.datetime "updated_at"
end

and index.html.erb is:

 <% airoffers.each do |airoffer| %>

???

 <% end %>

In my html.erb page I would like to find a comment for an offer (offer_id) and an user (user_id).

Body:
I would use it this way:

Comment.find(
  :all,
  :conditions => {
    :user_id  => 123,
    :offer_id => 456
  },
  :join => :usercomment
)

OR:

Comment.find(
  :all,
  :conditions => [
    "usercomments.user_id = ? AND usercomments.offer_id = ?",
    123,
    456
  ],
  :join => :usercomment
)

Rails have a lot of beautiful ways to write queries.


问:
Will performFetchWithCompletionHandler be called if the app has been terminated
It's surprisingly difficult to find a definitive answer to this; couldn't find it mentioned in the Apple documentation and couldn't find a definite yes/no after searching past questions.

The question is simple - if the app requests a background fetch to be performed after N time, then the user terminates the app. Will the OS still launch the app into the background to perform the background fetch?

答:
Okay, once again background modes cause confusion. No offense to the other people trying to help, but this is more complicated than it seems.

First of all:
This is out of date, as Sausage guessed in the comments. I know this for a fact, because the section about VoIP apps is still explaining the "old way" to do this, with a handler that gets called periodically. I investigated this a bit for this answer, so I suggest you go and read that. The important lesson for this case here is that iOS makes a distinction between an app being terminated by the user or by the system, plus it also plays a role whether the phone was rebooted or not.

So to sum this (and your question) up you basically want to know whether this part of the above, outdated documentation is still correct word for word:

In most cases, the system does not relaunch apps after they are force quit by the user. One exception is location apps, which in iOS 8 and later are relaunched after being force quit by the user. In other cases, though, the user must launch the app explicitly or reboot the device before the app can be launched automatically into the background by the system. When password protection is enabled on the device, the system does not launch an app in the background before the user first unlocks the device.

 Apple: Understanding When Your App Gets Launched into the Background

I thoroughly investigated the rest of the docs, but did not find any definite answer, so it unfortunately boils down to what dan already suggested: Test it. My gut feeling is that the documentation is still correct in that regard, though (as said what's not is the VoIP stuff). I say that because the UI in the Settings app calls the feature "Background App Refresh", so users are probably supposed to understand that an app having this permission won't refresh when they "push" them out of background (i.e. home button -> swipe it out). For regular users, apps are either quit (not in the task manager at all), in the foreground (using them) or in background (they're in the task manager and another app is in foreground and/or the phone is locked).

To really test this you'd have to write an app and actually carry it around a bit (I assume at least two days) in each condition. First while it is in background (the OS should periodically let it fetch, as you probably know this can also be triggered in Xcode) and then while it is force-quit. The problem is to verify that it fetched stuff. I'd go with a logfile that can be shared via iTunes. I have typed up some code for this:

```<code>-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    NSLog(@"We're awake! Booyah!");

    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config
                                                          delegate:nil
                                                     delegateQueue:[NSOperationQueue mainQueue]];
    NSMutableURLRequest *request = [NSMutableURLRequest new];
    request.HTTPMethod = @"GET";
    request.URL = [NSURL URLWithString:@"https://www.google.com"];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                            completionHandler:^(NSData * _Nullable data,
                                                                NSURLResponse * _Nullable response,
                                                                NSError * _Nullable error) {
                                                NSDate *now = [NSDate date];
                                                NSString *toLog = [NSString stringWithFormat:@"%@ - fetched\n",
                                                                   [now description]];
                                                [self updateTestDocumentWithString:toLog];
                                                NSLog(@"Yay, done!");
                                                completionHandler(UIBackgroundFetchResultNewData);
                                            }];
    [task resume];
}

- (void)updateTestDocumentWithString:(NSString *)toAppend {
    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *filePath = [[docDir stringByAppendingPathComponent:@"logfile.txt"] copy];
    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        if (![[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil]) {
            NSLog(@"We're effed...");
            return;
        }
    }
    NSFileHandle *file = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
    if (!file) {
        NSLog(@"We're effed again...");
        return;
    }
    [file seekToEndOfFile];
    // ensure this is never nil
    [file writeData:[toAppend dataUsingEncoding:NSUTF8StringEncoding]];
    [file closeFile];
}
</code>```

This would go into the app delegate, and don't forget to add the Application supports iTunes file sharing boolean setting in your app's plist. I will leave this running on my development device for a bit and check the logfile, eventually reporting back here. Feel free to test it yourself, too.

Body:
Okay, once again background modes cause confusion. No offense to the other people trying to help, but this is more complicated than it seems.

First of all:
This is out of date, as Sausage guessed in the comments. I know this for a fact, because the section about VoIP apps is still explaining the "old way" to do this, with a handler that gets called periodically. I investigated this a bit for this answer, so I suggest you go and read that. The important lesson for this case here is that iOS makes a distinction between an app being terminated by the user or by the system, plus it also plays a role whether the phone was rebooted or not.

So to sum this (and your question) up you basically want to know whether this part of the above, outdated documentation is still correct word for word:

In most cases, the system does not relaunch apps after they are force quit by the user. One exception is location apps, which in iOS 8 and later are relaunched after being force quit by the user. In other cases, though, the user must launch the app explicitly or reboot the device before the app can be launched automatically into the background by the system. When password protection is enabled on the device, the system does not launch an app in the background before the user first unlocks the device.

 Apple: Understanding When Your App Gets Launched into the Background

I thoroughly investigated the rest of the docs, but did not find any definite answer, so it unfortunately boils down to what dan already suggested: Test it. My gut feeling is that the documentation is still correct in that regard, though (as said what's not is the VoIP stuff). I say that because the UI in the Settings app calls the feature "Background App Refresh", so users are probably supposed to understand that an app having this permission won't refresh when they "push" them out of background (i.e. home button -> swipe it out). For regular users, apps are either quit (not in the task manager at all), in the foreground (using them) or in background (they're in the task manager and another app is in foreground and/or the phone is locked).

To really test this you'd have to write an app and actually carry it around a bit (I assume at least two days) in each condition. First while it is in background (the OS should periodically let it fetch, as you probably know this can also be triggered in Xcode) and then while it is force-quit. The problem is to verify that it fetched stuff. I'd go with a logfile that can be shared via iTunes. I have typed up some code for this:

-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    NSLog(@"We're awake! Booyah!");

    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config
                                                          delegate:nil
                                                     delegateQueue:[NSOperationQueue mainQueue]];
    NSMutableURLRequest *request = [NSMutableURLRequest new];
    request.HTTPMethod = @"GET";
    request.URL = [NSURL URLWithString:@"https://www.google.com"];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                            completionHandler:^(NSData * _Nullable data,
                                                                NSURLResponse * _Nullable response,
                                                                NSError * _Nullable error) {
                                                NSDate *now = [NSDate date];
                                                NSString *toLog = [NSString stringWithFormat:@"%@ - fetched\n",
                                                                   [now description]];
                                                [self updateTestDocumentWithString:toLog];
                                                NSLog(@"Yay, done!");
                                                completionHandler(UIBackgroundFetchResultNewData);
                                            }];
    [task resume];
}

- (void)updateTestDocumentWithString:(NSString *)toAppend {
    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *filePath = [[docDir stringByAppendingPathComponent:@"logfile.txt"] copy];
    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        if (![[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil]) {
            NSLog(@"We're effed...");
            return;
        }
    }
    NSFileHandle *file = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
    if (!file) {
        NSLog(@"We're effed again...");
        return;
    }
    [file seekToEndOfFile];
    // ensure this is never nil
    [file writeData:[toAppend dataUsingEncoding:NSUTF8StringEncoding]];
    [file closeFile];
}

This would go into the app delegate, and don't forget to add the Application supports iTunes file sharing boolean setting in your app's plist. I will leave this running on my development device for a bit and check the logfile, eventually reporting back here. Feel free to test it yourself, too.


问:
How to implement a binary search tree in Python?
This is what I've got so far but it is not working:</p>

```<code>class Node:
    rChild,lChild,data = None,None,None

    def __init__(self,key):
        self.rChild = None
        self.lChild = None
        self.data = key

class Tree:
    root,size = None,0
    def __init__(self):
        self.root = None
        self.size = 0

    def insert(self,node,someNumber):
        if node is None:
            node = Node(someNumber)
        else:
            if node.data > someNumber:
                self.insert(node.rchild,someNumber)
            else:
                self.insert(node.rchild, someNumber)
        return

def main():
    t = Tree()
    t.root = Node(4)
    t.root.rchild = Node(5)
    print t.root.data #this works
    print t.root.rchild.data #this works too
    t = Tree()
    t.insert(t.root,4)
    t.insert(t.root,5)
    print t.root.data #this fails
    print t.root.rchild.data #this fails too

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

答:
its easy to implement a BST using two classes, 1. Node and 2. Tree
Tree class will be just for user interface, and actual methods will be implemented in Node class.

```<code>class Node():

    def __init__(self,val):
        self.value = val
        self.left = None
        self.right = None

    def _insert(self,data):
        if data == self.value:
            return False
        elif data < self.value:
            if self.left:
                return self.left._insert(data)
            else:
                self.left = Node(data)
                return True
        else:
            if self.right:
                return self.right._insert(data)
            else:
                self.right = Node(data)
                return True

    def _inorder(self):
        if self:
            if self.left:
                self.left._inorder()
            print(self.value)
            if self.right:
                self.right._inorder()

class Tree():

    def __init__(self):
        self.root = None

    def insert(self,data):
        if self.root:
            return self.root._insert(data)
        else:
            self.root = Node(data)
            return True
    def inorder(self):
        if self.root is not None:
            return self.root._inorder()
        else:
            return False

if __name__=="__main__":
    a = Tree()
    a.insert(16)
    a.insert(8)
    a.insert(24)
    a.insert(6)
    a.insert(12)
    a.insert(19)
    a.insert(29)
    a.inorder()
</code>```

Inorder function for checking whether BST is properly implemented.

Body:
This is what I've got so far but it is not working:

class Node:
    rChild,lChild,data = None,None,None

    def __init__(self,key):
        self.rChild = None
        self.lChild = None
        self.data = key

class Tree:
    root,size = None,0
    def __init__(self):
        self.root = None
        self.size = 0

    def insert(self,node,someNumber):
        if node is None:
            node = Node(someNumber)
        else:
            if node.data > someNumber:
                self.insert(node.rchild,someNumber)
            else:
                self.insert(node.rchild, someNumber)
        return

def main():
    t = Tree()
    t.root = Node(4)
    t.root.rchild = Node(5)
    print t.root.data #this works
    print t.root.rchild.data #this works too
    t = Tree()
    t.insert(t.root,4)
    t.insert(t.root,5)
    print t.root.data #this fails
    print t.root.rchild.data #this fails too

if __name__ == '__main__':
     main()

Body:
its easy to implement a BST using two classes, 1. Node and 2. Tree
Tree class will be just for user interface, and actual methods will be implemented in Node class.

class Node():

    def __init__(self,val):
        self.value = val
        self.left = None
        self.right = None

    def _insert(self,data):
        if data == self.value:
            return False
        elif data < self.value:
            if self.left:
                return self.left._insert(data)
            else:
                self.left = Node(data)
                return True
        else:
            if self.right:
                return self.right._insert(data)
            else:
                self.right = Node(data)
                return True

    def _inorder(self):
        if self:
            if self.left:
                self.left._inorder()
            print(self.value)
            if self.right:
                self.right._inorder()

class Tree():

    def __init__(self):
        self.root = None

    def insert(self,data):
        if self.root:
            return self.root._insert(data)
        else:
            self.root = Node(data)
            return True
    def inorder(self):
        if self.root is not None:
            return self.root._inorder()
        else:
            return False

if __name__=="__main__":
    a = Tree()
    a.insert(16)
    a.insert(8)
    a.insert(24)
    a.insert(6)
    a.insert(12)
    a.insert(19)
    a.insert(29)
    a.inorder()

Inorder function for checking whether BST is properly implemented.


问:
The SQL query contains a malformed ending
I got the following error when the server tried to execute the SQL request.

Please, I'd like to know what is incorrect.

```<code>Exception Description: Syntax error parsing [SELECT t FROM Trackings t GROUP BY t.dateTrackings WHERE EXISTS (SELECT DISTINCT tr.dateTrackings from Trackings tr )].
</code>```

答:
You need to mention the column in the SELECT clause.

You cant just mention the table alias t

and

WHERE should come before GROUP BY.

Any condition to apply upon GROUP BY.. You need to use HAVING clause

Something like :

SELECT t.dateTrackings, count(*)
 FROM   Trackings t
 WHERE EXISTS (SELECT *
               FROM Trackings tr
               WHERE tr.dateTrackings = t.dateTrackings)
 GROUP BY t.dateTrackings

Body:
I got the following error when the server tried to execute the SQL request.

Please, I'd like to know what is incorrect.

Exception Description: Syntax error parsing [SELECT t FROM Trackings t GROUP BY t.dateTrackings WHERE EXISTS (SELECT DISTINCT tr.dateTrackings from Trackings tr )].


问:
MYSQL How to update child table value with foreign key while insert data based on parent table
I have 2 table, a parent table and child table. Child table has foreign key to parent table. I have successfully create the foreign key. But how to auto update field 'nama' based on parent table while I only insert 'id_parent' ?
I only tried :

```<code>INSERT INTO child (id_parent) values (1)
</code>```

but field 'name' value is still NULL

Here my tables :

```<code>CREATE TABLE `child` (
  `id` int(6) NOT NULL AUTO_INCREMENT,
  `id_parent` int(6) DEFAULT NULL,
  `nama` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `aa` (`nama`,`id_parent`),
  CONSTRAINT `aa` FOREIGN KEY (`nama`, `id_parent`) REFERENCES `parent` (`nama`, `id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=armscii8;

-- ----------------------------
-- Table structure for parent
-- ----------------------------
CREATE TABLE `parent` (
  `id` int(5) NOT NULL AUTO_INCREMENT,
  `nama` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `nama` (`nama`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=armscii8;
</code>```

the parent table has data like this

```<code>INSERT INTO `parent` VALUES ('4', 'asa');
INSERT INTO `parent` VALUES ('1', 'batman');
INSERT INTO `parent` VALUES ('3', 'goku');
INSERT INTO `parent` VALUES ('2', 'robin');
INSERT INTO `parent` VALUES ('5', 'usu');
</code>```

答:
Check this line:

```<code>KEY `aa` (`nama`,`id_parent`),
  CONSTRAINT `aa` FOREIGN KEY (`nama`, `id_parent`) REFERENCES `parent` (`nama`, `id`)
</code>```

here you have created a foreign key relationship on two column i.e. parent (nama, id). In that case you can only insert those combination values in child table that are already in parent table. Remember, here foreign key is implemented by combining two columns, not on a single column.

Body:
I have 2 table, a parent table and child table. Child table has foreign key to parent table. I have successfully create the foreign key. But how to auto update field 'nama' based on parent table while I only insert 'id_parent' ?
I only tried :

INSERT INTO child (id_parent) values (1)

but field 'name' value is still NULL

Here my tables :

CREATE TABLE `child` (
  `id` int(6) NOT NULL AUTO_INCREMENT,
  `id_parent` int(6) DEFAULT NULL,
  `nama` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `aa` (`nama`,`id_parent`),
  CONSTRAINT `aa` FOREIGN KEY (`nama`, `id_parent`) REFERENCES `parent` (`nama`, `id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=armscii8;

-- ----------------------------
-- Table structure for parent
-- ----------------------------
CREATE TABLE `parent` (
  `id` int(5) NOT NULL AUTO_INCREMENT,
  `nama` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `nama` (`nama`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=armscii8;

the parent table has data like this

INSERT INTO `parent` VALUES ('4', 'asa');
INSERT INTO `parent` VALUES ('1', 'batman');
INSERT INTO `parent` VALUES ('3', 'goku');
INSERT INTO `parent` VALUES ('2', 'robin');
INSERT INTO `parent` VALUES ('5', 'usu');

Body:
Check this line:

KEY `aa` (`nama`,`id_parent`),
  CONSTRAINT `aa` FOREIGN KEY (`nama`, `id_parent`) REFERENCES `parent` (`nama`, `id`)

here you have created a foreign key relationship on two column i.e. parent (nama, id). In that case you can only insert those combination values in child table that are already in parent table. Remember, here foreign key is implemented by combining two columns, not on a single column.


问:
XPATH: exclude elements which which has a specific child
```<code><ul>
  <li><a></li>
  <li><a></li>
  <li>
    <div>
      <a>
    </div>
  </li>
</ul>
</code>```

How can I select only first 2 li items and exclude li that contains div inside?

Considering ul is set as parent, I've tried

```<code>./li[not(contains(descendant::div]
</code>```

But obviously that didn't work

答:
Remove the contains and use // instead of ./

```<code>//li[not(descendant::div)]
</code>```

Body:
How can I select only first 2 li items and exclude li that contains div inside?

Considering ul is set as parent, I've tried

./li[not(contains(descendant::div]

But obviously that didn't work

Body:
Remove the contains and use // instead of ./

//li[not(descendant::div)]


问:
How does c++ handle 0*(large expression)
Concerning speed, if I need to calculate a large expression, say:

```<code>switch1*(large expression 1)+switch2*(large expression 2)
</code>```

Depending on my input, switch1 can be 0 or 1, as can switch2 be. What would be the quickest for c++ to do, making an if statement or write it down as above?

答:
switch1 can be 0 or 1, as can switch2 be

If switch1 and switch2 can really only have values of 0 or 1 then it would be better for them to be booleans rather than integers.

With boolean switches, your statement becomes:

```<code>result = (switch1 ? (large expression 1) : 0)
       + (switch2 ? (large expression 2) : 0)
</code>```

It is the case that in this form, the expressions will be computed even if their result won't be used. A simple and clear way to avoid wasted computation is the obvious one:

```<code>result = 0;
if(switch1) {
    result += large expression 1;
}
if(switch2) {
    result += large expression 2;
}
</code>```

You could tidy this up by extracting methods, into which you pass the switches:

```<code>result = guardedLargeExpression1(switch1, otherparams1)
       + guardedLargeExpression2(switch2, otherparams2);
</code>```

... with ...

```<code>int guardedLargeExpression1(bool switch, foo params) {
    if(switch) {
        return 0;
    }
    return large expression(...);
}
</code>```

You could also do clever stuff with pointers to functions:

```<code>int guardedFunctionCall(bool switch, int *functionptr(foo), foo arg) {
    if(switch) {
        return 0;
    }
    return (*functionptr)(arg);
}
</code>```

... which is approaching the kind of thing you'd do in Java when you lazily evaluate code using a Supplier.

Or, since you're in C++ not C, you can do something more OO and actually use the C++ equivalent of Supplier: What is the C++ equivalent of a java.util.function.Supplier?

Body:
Concerning speed, if I need to calculate a large expression, say:

switch1*(large expression 1)+switch2*(large expression 2)

Depending on my input, switch1 can be 0 or 1, as can switch2 be. What would be the quickest for c++ to do, making an if statement or write it down as above?

Body:
switch1 can be 0 or 1, as can switch2 be

If switch1 and switch2 can really only have values of 0 or 1 then it would be better for them to be booleans rather than integers.

With boolean switches, your statement becomes:

result = (switch1 ? (large expression 1) : 0)
       + (switch2 ? (large expression 2) : 0)

It is the case that in this form, the expressions will be computed even if their result won't be used. A simple and clear way to avoid wasted computation is the obvious one:

result = 0;
if(switch1) {
    result += large expression 1;
}
if(switch2) {
    result += large expression 2;
}

You could tidy this up by extracting methods, into which you pass the switches:

result = guardedLargeExpression1(switch1, otherparams1)
       + guardedLargeExpression2(switch2, otherparams2);

... with ...

int guardedLargeExpression1(bool switch, foo params) {
    if(switch) {
        return 0;
    }
    return large expression(...);
}

You could also do clever stuff with pointers to functions:

int guardedFunctionCall(bool switch, int *functionptr(foo), foo arg) {
    if(switch) {
        return 0;
    }
    return (*functionptr)(arg);
}

... which is approaching the kind of thing you'd do in Java when you lazily evaluate code using a Supplier.

Or, since you're in C++ not C, you can do something more OO and actually use the C++ equivalent of Supplier: What is the C++ equivalent of a java.util.function.Supplier?


问:
save results in an array in Angular 4 after http.get()
I retrieve from an api with http.get() an array of objects. Each of item has only one property inside it: "number". I want that property to be stored in an array in my app.component. I will then use that array as data for a chart using chart.js, which for now works fine. It's more than a day that I am trying but can't figure out how to do it. Can you tell me please?

app.component.ts

```<code>import { Component } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/Rx';

import * as moment from 'moment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';

  nrs: any;
  count: any;
  public listNrs: Array<number> = [];

  private apiAllUrl: string = 'http://localhost:3000/api/all';
  private apiCountUrl: string = 'http://localhost:3000/api/count';
  //private apiBothUrl: string = 'http://localhost:3000/api/both';

  constructor(private http:Http) {
    let now = moment.locale("it");
  }

  ngOnInit() {
    this.getAllNrs();
    this.getCountNrs();
    this.getDataNumbers();
    //this.getCount();
    //this.loadData();
  }

  getAllNrs() {
    this.http.get(this.apiAllUrl)
      .map((res:Response) => res.json())
      .subscribe(
        data => { this.nrs = data},
        err => console.error(err),
        () => console.log(this.nrs)
      );
  }

  getCountNrs(){
    this.http.get(this.apiCountUrl)
      .map((res:Response) => res.json())
      .subscribe(
        data => { this.count = data},
        err => console.error(err),
        () => console.log(this.count)
      );
  }

  getDataNumbers(){

  }

  //tried using jsonp
  /*loadData() {
    this.jsonp.get(this.apiAllUrl)
        .map(res => res.json())
        .subscribe(data => console.log(data));
  }*/

  /*getCount(){
    this.getAllNrs();
    for(let nr of this.nrs){
      console.log(this.nrs.nr[1]);
    }
  }*/

  newDate(days) {
    return moment().add(days, 'days');
  }

  public lineChartData:Array<any> = [
    {data: [4, 5, 56, -23, 4,], label: 'Indexer meta served links'},
  ];

  public lineChartData1:Array<any> = [
    {data: [-23, 4, 4, 5, 56], label: 'Indexer served links'},
  ];

  public lineChartData2:Array<any> = [
    {data: [4, 5, 4, 56, -23], label: 'Real-Time served links'},
  ];

  public lineChartLabels:Array<any> = ['1 Lug 2017', '2 Lug 2017', '3 Lug 2017', '4 Lug 2017', '5 Lug 2017'];

  public lineChartOptions:any = {
    responsive: true,
    /*
    scales: {
      xAxes: [{
        type: 'time',
        time: {
          displayFormats: {
            'millisecond': 'DD MMM',
            'second': 'DD MMM',
            'minute': 'DD MMM',
            'hour': 'DD MMM',
            'day': 'DD MMM',
            'week': 'DD MMM',
            'month': 'DD MMM',
            'quarter': 'DD MMM',
            'year': 'DD MMM',
          }
        }
      }],
    },
    */
  };

  public lineChartColors:Array<any> = [
    { // grey
      backgroundColor: 'rgba(255,55,55,0.2)',
      borderColor: 'rgba(255,55,55,1)',
      pointBackgroundColor: 'rgba(255,55,55,1)',
      pointBorderColor: '#fff',
      pointHoverBackgroundColor: '#fff',
      pointHoverBorderColor: 'rgba(255,55,55,0.8)'
    },
  ];

  public lineChartLegend:boolean = true;
  public lineChartType:string = 'line';

  // events
  public chartClicked(e:any):void {
    console.log(e);
  }

  public chartHovered(e:any):void {
    console.log(e);
  }
}
</code>```

app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { ChartsModule } from 'ng2-charts/ng2-charts';

/*import { DataService } from './data.service';
import { DataComponent } from './data/data.component';*/

@NgModule({
  declarations: [
    AppComponent,
    /*DataComponent*/,
  ],
  imports: [
    BrowserModule,
    HttpModule,
    ChartsModule
  ],
  providers: [/*DataService*/],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

getAllNrs() gets an array of objects where each of those has a property named number.

getAllCount() gets an array of objects where each of those has a property named count.

The problem is that even if I try to map it into an array it tells me that this.nrs is undefined and cannot get its length (Err: Cannot read property 'length' of undefined). Do you have any idea why it does so?

If there is anything else you need let me know and I'll provide it.
Thanks!

答:
you can use Array.map to convert array of object to array of string( or what ever).

var arrOfObj = [
  {
    number: 100
  },{
    number: 200
  },{
    number: 300
  },{
    number: 400
  },{
    number: 500
  },{
    number: 600
  }
];

var arrOfStr = arrOfObj.map(function(item) {
  return item.number;
});

console.log(arrOfStr);```
</div>
</div>
</p>

<hr>

<p>As I commented, you can add the <code>Array.map</code> part directly into <code>http.get().map</code> but make sure <code>res.json()</code> is actually the <strong>object array</strong></p>

```this.http.get(this.apiAllUrl)
  .map((res:Response) => res.json().map(item => item.number))  // convert here
  .subscribe(
    data => { this.nrs = data},
    err => console.error(err),
    () => console.log(this.nrs)
  );
```

Plunker demo

Body:
I retrieve from an api with http.get() an array of objects. Each of item has only one property inside it: "number". I want that property to be stored in an array in my app.component. I will then use that array as data for a chart using chart.js, which for now works fine. It's more than a day that I am trying but can't figure out how to do it. Can you tell me please?

app.component.ts

import { Component } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/Rx';

import * as moment from 'moment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';

  nrs: any;
  count: any;
  public listNrs: Array<number> = [];

  private apiAllUrl: string = 'http://localhost:3000/api/all';
  private apiCountUrl: string = 'http://localhost:3000/api/count';
  //private apiBothUrl: string = 'http://localhost:3000/api/both';

  constructor(private http:Http) {
    let now = moment.locale("it");
  }

  ngOnInit() {
    this.getAllNrs();
    this.getCountNrs();
    this.getDataNumbers();
    //this.getCount();
    //this.loadData();
  }

  getAllNrs() {
    this.http.get(this.apiAllUrl)
      .map((res:Response) => res.json())
      .subscribe(
        data => { this.nrs = data},
        err => console.error(err),
        () => console.log(this.nrs)
      );
  }

  getCountNrs(){
    this.http.get(this.apiCountUrl)
      .map((res:Response) => res.json())
      .subscribe(
        data => { this.count = data},
        err => console.error(err),
        () => console.log(this.count)
      );
  }

  getDataNumbers(){

  }

  //tried using jsonp
  /*loadData() {
    this.jsonp.get(this.apiAllUrl)
        .map(res => res.json())
        .subscribe(data => console.log(data));
  }*/

  /*getCount(){
    this.getAllNrs();
    for(let nr of this.nrs){
      console.log(this.nrs.nr[1]);
    }
  }*/

  newDate(days) {
    return moment().add(days, 'days');
  }

  public lineChartData:Array<any> = [
    {data: [4, 5, 56, -23, 4,], label: 'Indexer meta served links'},
  ];

  public lineChartData1:Array<any> = [
    {data: [-23, 4, 4, 5, 56], label: 'Indexer served links'},
  ];

  public lineChartData2:Array<any> = [
    {data: [4, 5, 4, 56, -23], label: 'Real-Time served links'},
  ];

  public lineChartLabels:Array<any> = ['1 Lug 2017', '2 Lug 2017', '3 Lug 2017', '4 Lug 2017', '5 Lug 2017'];

  public lineChartOptions:any = {
    responsive: true,
    /*
    scales: {
      xAxes: [{
        type: 'time',
        time: {
          displayFormats: {
            'millisecond': 'DD MMM',
            'second': 'DD MMM',
            'minute': 'DD MMM',
            'hour': 'DD MMM',
            'day': 'DD MMM',
            'week': 'DD MMM',
            'month': 'DD MMM',
            'quarter': 'DD MMM',
            'year': 'DD MMM',
          }
        }
      }],
    },
    */
  };

  public lineChartColors:Array<any> = [
    { // grey
      backgroundColor: 'rgba(255,55,55,0.2)',
      borderColor: 'rgba(255,55,55,1)',
      pointBackgroundColor: 'rgba(255,55,55,1)',
      pointBorderColor: '#fff',
      pointHoverBackgroundColor: '#fff',
      pointHoverBorderColor: 'rgba(255,55,55,0.8)'
    },
  ];

  public lineChartLegend:boolean = true;
  public lineChartType:string = 'line';

  // events
  public chartClicked(e:any):void {
    console.log(e);
  }

  public chartHovered(e:any):void {
    console.log(e);
  }
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { ChartsModule } from 'ng2-charts/ng2-charts';

/*import { DataService } from './data.service';
import { DataComponent } from './data/data.component';*/

@NgModule({
  declarations: [
    AppComponent,
    /*DataComponent*/,
  ],
  imports: [
    BrowserModule,
    HttpModule,
    ChartsModule
  ],
  providers: [/*DataService*/],
  bootstrap: [AppComponent]
})
export class AppModule { }

getAllNrs() gets an array of objects where each of those has a property named number.

getAllCount() gets an array of objects where each of those has a property named count.

The problem is that even if I try to map it into an array it tells me that this.nrs is undefined and cannot get its length (Err: Cannot read property 'length' of undefined). Do you have any idea why it does so?

If there is anything else you need let me know and I'll provide it.
Thanks!

Body:
you can use Array.map to convert array of object to array of string( or what ever).

var arrOfObj = [
  {
    number: 100
  },{
    number: 200
  },{
    number: 300
  },{
    number: 400
  },{
    number: 500
  },{
    number: 600
  }
];

var arrOfStr = arrOfObj.map(function(item) {
  return item.number;
});

console.log(arrOfStr);

As I commented, you can add the Array.map part directly into http.get().map but make sure res.json() is actually the object array

this.http.get(this.apiAllUrl)
  .map((res:Response) => res.json().map(item => item.number))  // convert here
  .subscribe(
    data => { this.nrs = data},
    err => console.error(err),
    () => console.log(this.nrs)
  );

Plunker demo


问:
Spring4 internationalization multiple language
http://www.mkyong.com/spring-mvc/spring-mvc-internationalization-example/

Trying to follow this online tutorial to create a multi language web application the problem I am having is that I don't think my spring container is finding / loading my properties files.  I am not sure what is wrong.

File Structure

welcome.properties

```<code>welcome.springmvc = Happy learning Spring MVC
</code>```

welcome.properties

```<code>welcome.springmvc = \u5feb\u4e50\u5b66\u4e60 Spring MVC
</code>```

Index.jsp

```<code>Language : <a href="?language=en">English</a>|<a href="?language=zh_CN">Chinese</a>

    <h2>
    welcome.springmvc : <spring:message code="welcome.springmvc" text="default text" />
    </h2>

    Current Locale : ${pageContext.response.locale}
</code>```

app-dispatcher-servlet:
I am sure that my interceptors are working because index.jsp ${pageContext.response.locale} is showing en/zh_cn

Internationalization: Multi lang support

Resource:
http://www.mkyong.com/spring-mvc/spring-mvc-internationalization-example/
http://howtodoinjava.com/spring/spring-mvc/spring-mvc-internationalization-i18n-and-localization-i10n-example/

http://www.technicalkeeda.com/spring-tutorials/spring-mvc-internationalization-i18n-example

```<code><bean id="localeResolver"
    class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
    <property name="defaultLocale" value="en" />
</bean>

<mvc:interceptors>
    <bean id="localeChangeInterceptor"
        class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
        <property name="paramName" value="language" />
    </bean>
</mvc:interceptors>

<!-- <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" >
    <property name="interceptors">
       <list>
        <ref bean="localeChangeInterceptor" />
        </list>
    </property>
</bean>  -->

<!-- Register the welcome.properties -->
<bean id="messageSource"
    class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="welcome" />
</bean>

<!-- ViewResolver JSP -->
<bean id="jspViewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/html/"></property>
    <property name="suffix" value=".jsp"></property>
</bean>
</code>```

but my result in index.jsp is

Where it says "default text" should really show "Happy learning Spring MVC" from the properties files.

答:
I have changed my app-dispatcher-servlet.xml explicit state class path

From:

```<code><!-- Register the welcome.properties -->
 <bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="welcome" />
</bean>
</code>```

To:

```<code><bean id="messageSource"
    class="com.app.service.CustomMessageSource">
    <property name="basenames">
        <list>
            <value>classpath:com/app/properties/welcome</value>
        </list>
    </property>
    <property name="defaultEncoding" value="UTF-8" />

</bean>
</code>```

Body:
http://www.mkyong.com/spring-mvc/spring-mvc-internationalization-example/

Trying to follow this online tutorial to create a multi language web application the problem I am having is that I don't think my spring container is finding / loading my properties files.  I am not sure what is wrong.

File Structure

welcome.properties

welcome.springmvc = Happy learning Spring MVC

welcome.properties

welcome.springmvc = \u5feb\u4e50\u5b66\u4e60 Spring MVC

Index.jsp

Language : English|Chinese

    welcome.springmvc : <spring:message code="welcome.springmvc" text="default text" />

    Current Locale : ${pageContext.response.locale}

app-dispatcher-servlet:
I am sure that my interceptors are working because index.jsp ${pageContext.response.locale} is showing en/zh_cn

Internationalization: Multi lang support

Resource:
http://www.mkyong.com/spring-mvc/spring-mvc-internationalization-example/
http://howtodoinjava.com/spring/spring-mvc/spring-mvc-internationalization-i18n-and-localization-i10n-example/

http://www.technicalkeeda.com/spring-tutorials/spring-mvc-internationalization-i18n-example

<bean id="localeResolver"
    class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
    <property name="defaultLocale" value="en" />
</bean>

<mvc:interceptors>
    <bean id="localeChangeInterceptor"
        class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
        <property name="paramName" value="language" />
    </bean>
</mvc:interceptors>

<bean id="messageSource"
    class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="welcome" />
</bean>

<bean id="jspViewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/html/"></property>
    <property name="suffix" value=".jsp"></property>
</bean>

but my result in index.jsp is

Where it says "default text" should really show "Happy learning Spring MVC" from the properties files.

Body:
I have changed my app-dispatcher-servlet.xml explicit state class path

From:

<!-- Register the welcome.properties -->
 <bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="welcome" />
</bean>

To:

<bean id="messageSource"
    class="com.app.service.CustomMessageSource">
    <property name="basenames">
        <list>
            <value>classpath:com/app/properties/welcome</value>
        </list>
    </property>
    <property name="defaultEncoding" value="UTF-8" />

</bean>


问:
How to convert NSstring to Nsdate
I am getting response from service that

```<code>"created_at" = "Thu Jul 06 07:26:23 +0000 2017";
</code>```

i want to convert the string  into Nsdate  format
i do not know how to do it

答:
```<code>NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:@"E MMM d HH:mm:ss Z yyyy"];
NSDate *date = [f dateFromString:@"Thu Jul 06 07:26:23 +0000 2017"];
</code>```

Title: How to convert NSstring to Nsdate

Body:
I am getting response from service that

"created_at" = "Thu Jul 06 07:26:23 +0000 2017";

i want to convert the string  into Nsdate  format
i do not know how to do it


问:
store data on basis of date and time - Reservation system
I am making a restaurant table reservation project where a customer can book a particular table (according to where table is placed in restaurant).

What I thought -

A table bean(table's class) with attributes - id, isReserved(boolean) - to get which tables are not reserved yet. This bean class corresponds to a 'tables' relation in db. 'tables' will have 20 records(20 different tables with different locations).

Then there is a customer class which corresponds to customer table in db. Customer will be stored when he makes a reservation. Attributes - id, email, contact, reservedTable_id.

But now I think all this is useless because a customer books a table according to a date and time. Everytime he looks for a table on a different date, it should have 'isReserved' entry for that date. So, does that means I should limit the days for reservation(eg 10) and create 10  'tables' tables, 1 for each day. But still how will time be adjusted like for eg a table can be booked multiple times in a day.

I am really confused and I think I am missing something(or some concepts) or my approach to problem is not correct. I have googled this date and time  problem but I am not clear at all. If I am missing something, I am ready to read those concepts if someone guides me. Please help.

答:
Here some idea, hope it helps.
Create 3 Tables (Database Table):

Tables (Dinning Table)

Customer

Reservation

The 3rd table will hold the table_id, customer_id, reservation_date, reservation_hour columns.

Column Description:

table_id         => PK of table 1

customer_id      => PK of table 2

reservation_date => date of reservation

reservation_hour => specific time within the reservation date


问:
django - how to restrict number of pages an unauthenticated user can view
I am building a website using django (1.10). I want to restrict the number of pages that an unauthorised person (i.e. a user that is not logged in), can view.

The desired behaviour is that after visiting N different pages, the user is directed to a specific page.

In other web platforms I have used (Symfony), there is a way of doing this by writing custom "filters" and session variables - I think django provides similar affordances via it's concept of midleware - however, not sure if this is the way to go, to implement this requirement.

How best may I implement this requirement (unauthorised user directed to a custom page after viewing N different pages), using the django framework?

答:
Something like:

```<code>if has_attr(request, 'page_count'):
    request.page_count += 1
else:
    request.page_count = 1
</code>```

From the docs how to implement middleware:

```<code>def simple_middleware(get_response):
# One-time configuration and initialization.

def middleware(request):
    # Code to be executed for each request before
    # the view (and later middleware) are called.

    response = get_response(request)

    # Code to be executed for each request/response after
    # the view is called.

    return response

return middleware
</code>```

Or:

```<code>class SimpleMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.

        return response
</code>```

Edit:
If you are using a class implement it so:

```<code>def process_request(self, request):
    if request.page_count >= <count>:
        return redirect(<your redirect here>)
</code>```

Body:
Something like:

if has_attr(request, 'page_count'):
    request.page_count += 1
else:
    request.page_count = 1

From the docs how to implement middleware:

def simple_middleware(get_response):
# One-time configuration and initialization.

def middleware(request):
    # Code to be executed for each request before
    # the view (and later middleware) are called.

    response = get_response(request)

    # Code to be executed for each request/response after
    # the view is called.

    return response

return middleware

Or:

class SimpleMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.

        return response

Edit:
If you are using a class implement it so:

def process_request(self, request):
    if request.page_count >= <count>:
        return redirect(<your redirect here>)