问:
Java executor model that allows running tasks only on instantiating thread
I am writing a multithreaded application where I've got the situation that I have certain library-related methods that can only be run on the main-thread. Currently I am running a simple, self-written, solution that listens on a queue for tasks and then executes them serially as they come in.

This works so far although it gets ugly when I need return values etc. (Which I am currently solving the c-way by passing along datastructures with the tasks and then have a busy-loop checking if the structure has been written to on the site of the method that queues a task.

This is not really the cleanest solution, and while it works, I was hoping to find a better way of doing this..

Q: Is there anything in the JDK or in a single specialized library that does what I need? Or is there any programming pattern that addresses my needs in  a clean and structured way?

答:
A possible solution with CompletableFuture:

```<code>class Job<T> {
    private final Supplier<T> computation;
    private final CompletableFuture<T> future;

    Job(Supplier<T> computation, CompletableFuture<T> future) {
        this.future = future;
        this.computation = computation;
    }

    public Supplier<T> getComputation() {
        return computation;
    }

    public CompletableFuture<T> getFuture() {
        return future;
    }
}

public void client() {
    // on the client:
    CompletableFuture<String> future = new CompletableFuture<>();
    Supplier<String> computation = () -> "Here I am!";

    enqueue(new Job<>(computation, future));

    String resultString = future.get();
}

public <T> void server(Job<T> job) {
    // on the server; job is taken from the queue
    CompletableFuture<T> future = job.getFuture();
    future.complete(job.getComputation().get());
}
</code>```

Here, on the client, future.get() will wait infinitely until the result is available. There is also another form:

```<code>future.get(1, TimeUnit.MINUTES)
</code>```

would only wait for one minute and then return. This for can be used for polling.

Body:
A possible solution with CompletableFuture:

class Job<T> {
    private final Supplier<T> computation;
    private final CompletableFuture<T> future;

    Job(Supplier<T> computation, CompletableFuture<T> future) {
        this.future = future;
        this.computation = computation;
    }

    public Supplier<T> getComputation() {
        return computation;
    }

    public CompletableFuture<T> getFuture() {
        return future;
    }
}

public void client() {
    // on the client:
    CompletableFuture<String> future = new CompletableFuture<>();
    Supplier<String> computation = () -> "Here I am!";

    enqueue(new Job<>(computation, future));

    String resultString = future.get();
}

public <T> void server(Job<T> job) {
    // on the server; job is taken from the queue
    CompletableFuture<T> future = job.getFuture();
    future.complete(job.getComputation().get());
}

Here, on the client, future.get() will wait infinitely until the result is available. There is also another form:

future.get(1, TimeUnit.MINUTES)

would only wait for one minute and then return. This for can be used for polling.


来源: stackexchange

问:
Export list of installed packages in SublimeText
I am aware that I can see all installed packages in Sublime using Ctrl+Shift+P and selecting Package Control: List Packages.

I have many packages installed (>20) and I need a way to export their names (and ideally also the link to their https://packagecontrol.io/ page) to a text file or similar output.

Can this be done at all?

答:
You can easily get the list of installed packages by looking at Package Control's user preferences file: Preferences -> Package Settings -> Package Control -> Preferences - User and checking the installed_packages value.

Getting the URL as well is a bit more complicated, but can be done for example by executing the following in ST's Python console (View menu -> Show Console):

```<code>import os; [(os.path.dirname(file)[len('Packages/'):], sublime.decode_value(sublime.load_resource(file))['url']) for file in sublime.find_resources('package-metadata.json')]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can easily get the list of installed packages by looking at Package Control's user preferences file: Preferences -> Package Settings -> Package Control -> Preferences - User and checking the installed_packages value.

Getting the URL as well is a bit more complicated, but can be done for example by executing the following in ST's Python console (View menu -> Show Console):

import os; [(os.path.dirname(file)[len('Packages/'):], sublime.decode_value(sublime.load_resource(file))['url']) for file in sublime.find_resources('package-metadata.json')]

ContentLicense: CC BY-SA 3.0


问:
before_filter :except doesn't seem to be working
I must be doing something silly. Any ideas on why this wouldn't be working. I get prompted to authenticate when making a request to the controller with the below config:

```<code>class ApplicationController < ActionController::Base

before_filter :auth, :except => [:aboutus]
</code>```

The auth method is just this. It works fine but applies to all controllers including aboutus

```<code>  #Simple HTTP Auth during development
  def auth
    authenticate_or_request_with_http_basic do |username, password|
      username == "REDACTED" && password == "REDACTED"
    end
  end
</code>```

Thanks

答:
This configuration would apply to the "aboutus" action of ApplicationController. Have you tried putting the before_filter definition in the controller that actually has the "aboutus" method/action?

You can put this in ApplicationController:

```<code>before_filter :auth
</code>```

then, in the controller containing the aboutus method:

```<code>skip_before_filter :auth, :only => :aboutus
</code>```

this way you don't repeat code and everything looks nice.

ContentLicense: CC BY-SA 2.5

Body:
I must be doing something silly. Any ideas on why this wouldn't be working. I get prompted to authenticate when making a request to the controller with the below config:

class ApplicationController < ActionController::Base

before_filter :auth, :except => [:aboutus]

The auth method is just this. It works fine but applies to all controllers including aboutus

  #Simple HTTP Auth during development
  def auth
    authenticate_or_request_with_http_basic do |username, password|
      username == "REDACTED" && password == "REDACTED"
    end
  end

Thanks

Body:
This configuration would apply to the "aboutus" action of ApplicationController. Have you tried putting the before_filter definition in the controller that actually has the "aboutus" method/action?

You can put this in ApplicationController:

before_filter :auth

then, in the controller containing the aboutus method:

skip_before_filter :auth, :only => :aboutus

this way you don't repeat code and everything looks nice.


问:
How to allow <input type="file"> to accept only image files?
I need to upload only image file through <input type="file"> tag.

Right now, it accepts all file types. But, I want to restrict it to only specific image file extensions which include .jpg, .gif etc.

How can I achieve this functionality?

答:
Steps:

 1. Add accept attribute to input tag

 2. Validate with javascript

 3. Add server side validation to verify if the content is really an expected file type

For HTML and javascript:

```<code><html>
<body>
<input name="image" type="file" id="fileName" accept=".jpg,.jpeg,.png" onchange="validateFileType()"/>
<script type="text/javascript">
    function validateFileType(){
        var fileName = document.getElementById("fileName").value;
        var idxDot = fileName.lastIndexOf(".") + 1;
        var extFile = fileName.substr(idxDot, fileName.length).toLowerCase();
        if (extFile=="jpg" || extFile=="jpeg" || extFile=="png"){
            //TO DO
        }else{
            alert("Only jpg/jpeg and png files are allowed!");
        }
    }
</script>
</body>
</html>
</code>```

Explanation:

The accept attribute filters the files that will be displayed in the
file chooser popup. However, it is not a validation. It is only a
hint to the browser. The user can still change the options in the
popup.

The javascript only validates for file extension, but cannot
really verify if the select file is an actual jpg or png.

So you have to write for file content validation on server side.

Body:
Steps:

 1. Add accept attribute to input tag

 2. Validate with javascript

 3. Add server side validation to verify if the content is really an expected file type

For HTML and javascript:

<html>
<body>
<input name="image" type="file" id="fileName" accept=".jpg,.jpeg,.png" onchange="validateFileType()"/>
<script type="text/javascript">
    function validateFileType(){
        var fileName = document.getElementById("fileName").value;
        var idxDot = fileName.lastIndexOf(".") + 1;
        var extFile = fileName.substr(idxDot, fileName.length).toLowerCase();
        if (extFile=="jpg" || extFile=="jpeg" || extFile=="png"){
            //TO DO
        }else{
            alert("Only jpg/jpeg and png files are allowed!");
        }
    }
</script>
</body>
</html>

Explanation:

The accept attribute filters the files that will be displayed in the
file chooser popup. However, it is not a validation. It is only a
hint to the browser. The user can still change the options in the
popup.

The javascript only validates for file extension, but cannot
really verify if the select file is an actual jpg or png.

So you have to write for file content validation on server side.


问:
AngularJS and the Browser
I'm trying to wrap my head around timing in AngularJS (1.6.4) and the browser.

When the webpage loads one can see HTML and CSS load first and AngularJS variables load later. That is, the browser is not showing the raw variables in curly braces {{}}, but the correctly-formatted AngularJS content - just one bit later.

I applied the ng-cloak directive to the body tag, and added what AngularJS recommends to my CSS.

That did not resolve the flickering. So what I did was load my JS assets before my CSS assets, and vualá the trick worked and the flickering disappeared. But I read that wouldn't work in older browsers, so not perfect either.

How does asset-loading work in the browser?

答:
It is bad practice to load the scripts first, it should be loaded after all the css and the main structure of the page (which is HTML) is rendered in your browser. If you are using ng-cloak in the body make sure to add this css part</p>

```<code>.ng-cloak,[ng-cloak],[ng\:cloak] {
     display: none!important
}
</code>```

Title: AngularJS and the Browser

Body:
It is bad practice to load the scripts first, it should be loaded after all the css and the main structure of the page (which is HTML) is rendered in your browser. If you are using ng-cloak in the body make sure to add this css part

.ng-cloak,[ng-cloak],[ng\:cloak] {
     display: none!important
}


问:
Why name of module not accessible when importing through 'from'
I observed that even if you import modules in python through from
e.g

```<code>from b import x
</code>```

whole module is loaded. It can be seen in sys.modules dictionary. So why the name of the module b is not accessible to our program. What am i missing?

It looks like namespace of the main(top-level) file does not have module name.

But I can not verify this as I am not able to see main file namespace. It also does not feel ok, just to remove one entry from __dict__ without many advantages. Can somebody clear this in detail?

答: Because that's what that syntax does; it only imports the names you specify, not the containing module. If you want the module itself, just do import b.

Body:
I observed that even if you import modules in python through from
e.g

from b import x

whole module is loaded. It can be seen in sys.modules dictionary. So why the name of the module b is not accessible to our program. What am i missing?

It looks like namespace of the main(top-level) file does not have module name.

But I can not verify this as I am not able to see main file namespace. It also does not feel ok, just to remove one entry from __dict__ without many advantages. Can somebody clear this in detail?


问:
/angularfire2/index has no exported member 'AngularFire'
Can't fix this problem:

app.component.ts

```<code>import { AngularFire, AuthProviders, AuthMethods } from 'angularfire2';

/angularfire2/index has no exported member 'AngularFire',
/angularfire2/index has no exported member 'AuthProviders',
/angularfire2/index has no exported member 'AuthMethods '
</code>```

but in app.module.ts

```<code>import { AngularFireModule } from 'angularfire2';
</code>```

works fine and I can initialize the app

package.json

```<code>"angularfire2": "^4.0.0-rc.0",
"core-js": "^2.4.1",
"firebase": "^3.9.0",
...
"devDependencies": {...
"ts-node": "~2.0.0",
"tslint": "~4.5.0",
"typescript": "~2.2.0"
</code>```

答:
Upgrading to AngularFire2 4.0 solve my issue

Migration Guide:
https://github.com/angular/angularfire2/blob/master/docs/version-4-upgrade.md

Body:
Can't fix this problem:

app.component.ts

import { AngularFire, AuthProviders, AuthMethods } from 'angularfire2';

/angularfire2/index has no exported member 'AngularFire',
/angularfire2/index has no exported member 'AuthProviders',
/angularfire2/index has no exported member 'AuthMethods '

but in app.module.ts

import { AngularFireModule } from 'angularfire2';

works fine and I can initialize the app

package.json

"angularfire2": "^4.0.0-rc.0",
"core-js": "^2.4.1",
"firebase": "^3.9.0",
...
"devDependencies": {...
"ts-node": "~2.0.0",
"tslint": "~4.5.0",
"typescript": "~2.2.0"


问:
C++ Will copy elision happen when returning a temporary object
If I understand correctly copy elision will happen if an object is returned like this:

```<code>CSomeObject getObject(){

    //....
    //....
    return CSomeObject(...);
}
</code>```

Is it safe to assume that copy elision will also happen here:

```<code>CSomeObject getObject(){

    CSomeObject some_object;
    some_object.setStuff();
    some_object.setMoreStuff();
    //....
    //....
    return some_object;
}

CSomeObject some_object = getObject();
</code>```

There is only one return statement and always the same temporary object is returned. What about when the return is delegated / indirect:

```<code>CSomeObject getObject_2(){
    //....
    return getObject();
}

CSomeObject some_object = getObject_2();
</code>```

答: "C++ Will copy elision happen when returning a temporary object" - it may. It's not guaranteed until C++17 (and even there, certain conditions apply). But, most compilers will elide the copy. </p>

Body:
If I understand correctly copy elision will happen if an object is returned like this:

CSomeObject getObject(){

    //....
    //....
    return CSomeObject(...);
}

Is it safe to assume that copy elision will also happen here:

CSomeObject getObject(){

    CSomeObject some_object;
    some_object.setStuff();
    some_object.setMoreStuff();
    //....
    //....
    return some_object;
}

CSomeObject some_object = getObject();

There is only one return statement and always the same temporary object is returned. What about when the return is delegated / indirect:

CSomeObject getObject_2(){
    //....
    return getObject();
}

CSomeObject some_object = getObject_2();


问:
How to serialize a large list without stackoverflow error?
One class in my program has one LinkedList which usually contains a large number of elements. When serializing this class, one Stackoverflow error occurred. I understand this is due to the recursive manner of serializing links in a list. So I want to override the writeObject of this list to an iterative way, but I don't know how to do this.</p>

答:
If one of the elements is your Object MyObject which have reference to MyObject for example:

```<code>public class MyObject implements Serializable {
  private MyObject nextObject;
  public void setNextObject(MyObject nextObject) {
    this.nextObject = nextObject;
...
}
</code>```

if each MyObject link to next/previous MyObject the serialization process will:
Start to write first MyObject and before it finish writing the first it will start to write second MyObject and so on until last object.

This structure can cause serialization stackoverflow exception with large number of elements.

Solution is to save unique Id for next object as: private int nextObjectId;

Body:
If one of the elements is your Object MyObject which have reference to MyObject for example:

public class MyObject implements Serializable {
  private MyObject nextObject;
  public void setNextObject(MyObject nextObject) {
    this.nextObject = nextObject;
...
}

if each MyObject link to next/previous MyObject the serialization process will:
Start to write first MyObject and before it finish writing the first it will start to write second MyObject and so on until last object.

This structure can cause serialization stackoverflow exception with large number of elements.

Solution is to save unique Id for next object as: private int nextObjectId;


问:
How to hide all the names when input is empty?
In the following code, when input is empty, all the names are shown. I want no name when the input field is empty.

<input ng-model="search.$">

    {{ x }}

```

Thanks

答:
Just add a ng-if

```<code> <ul ng-if="search.$">
</code>```

DEMO

<input ng-model="search.$">

    {{ x }}

```

Body:
In the following code, when input is empty, all the names are shown. I want no name when the input field is empty.

<input ng-model="search.$">

    {{ x }}

Thanks

Body:
Just add a ng-if

 <ul ng-if="search.$">

DEMO

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="namesCtrl">
<input ng-model="search.$"></label> <br>
<ul ng-if="search.$">
  <li ng-repeat="x in names | filter : search">
    {{ x }}
  </li>
</ul>
</div>

<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.names = [
        'Jani',
        'Carl',
        'Margareth',
        'Hege',
        'Joe',
        'Gustav',
        'Birgit',
        'Mary',
        'Kai'
    ];
});
</script>


问:
How to set to an instance of an object as below code?
I want your help to my problem, Please:
From my test class, I try run my test code:

```<code>[setUp]
public void setup()
{
BrowserFactory.InitBrowser("Chrome");
}
</code>```

But, it failed, because it didn’t initialized the “driver” variable.

(I got msg: system.nullReferenceException: The WebDriver browser instance was not initialized. You should first call the method InitBrowser)

Below code of InitBrowser() function as I copied from  http://toolsqa.com/selenium-webdriver/c-sharp/browser-factory-or-webdriver-factory/

```<code>using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
using System;
using System.Collections.Generic;

namespace _AutomationTests.WrapperFactory
{
   public class BrowserFactory
   {
       private static readonly IDictionary<string, IWebDriver> Drivers = new Dictionary<string, IWebDriver>();
        private static IWebDriver driver;

    public static IWebDriver Driver
    {
        get
        {
            if (driver == null)
                throw new NullReferenceException("The WebDriver browser instance was not initialized. You should first call the method InitBrowser.");
            return driver;
        }
        private set
        {
            driver = value;
        }
    }

    public static void InitBrowser(string browserName)
    {
        switch (browserName)
        {
            case "Firefox":
                if (Driver == null)
                {
                    driver = new FirefoxDriver();
                    Drivers.Add("Firefox", Driver);
                }
                break;

            case "IE":
                if (Driver == null)
                {
                    driver = new InternetExplorerDriver(@"C:\PathTo\IEDriverServer");
                    Drivers.Add("IE", Driver);
                }
                break;

            case "Chrome":
                if (Driver == null)
                {
                    driver = new ChromeDriver();//@"C:\PathTo\CHDriverServer"
                    Drivers.Add("Chrome", Driver);
                }
                break;
        }
    }

    public static void LoadApplication(string url)
    {
        Driver.Url = url;
        driver.Manage().Window.Maximize();
        driver.Navigate().GoToUrl("javascript:document.getElementById('overridelink').click()");
    }

    public static void CloseAllDrivers()
    {
        foreach (var key in Drivers.Keys)
        {
            Drivers[key].Close();
            Drivers[key].Quit();
        }
    }
}
</code>```

}

thank alot!

答:
Mar, try to paste the full source code of your project. Where are those C# classes of ChromeDriver(), FirefoxDriver(),InternetExplorerDriver() in project. Have you coded them upfront ?
Here IWebDriver Driver is a property

Null check is not required in getter of public static IWebDriver Driver

```<code>public BrowserFactory()
        {
            Driver = new FirefoxDriver();
        }

        public static IWebDriver Driver
        {
            get
            {

                return driver;
            }
            private set
            {
                driver = value;
            }
        }
</code>```

Set the property of IWebDriver Driver to an instance while the class is loaded in a static initializer or Constructor like :

Even before the driver could be initialized the get property is called which evalutates the null check to true & hence throwing exception.

Questions to be asked to yourself:

Have you added library files for Firefox,Chrome & IE ??

Is it a part of your project configuration file ?

If not added the best way to add is using Nuget Package manager in visual studio
4.Those references should be part of your project. Let me post a screenshot of a similar project I tried

5.See the pic of Nuget Package Manager

6.Click Manage Nuget Packages, browse for Available Packages
7.

Finally, you are not setting a new instance of driver

[pre]

```<code>{
    class Driver
    {
        public enum Browser
        {
            chrome,
            firefox,
            ie,
        }
        public IWebDriver getDriver(string browser_type)
        {
            Browser parsed_browser_type; IWebDriver driver=null;
            bool passed_type = browser_type != null ? true : false;
            if (passed_type)
            {
                Enum.TryParse(browser_type, out parsed_browser_type);

                switch (browser_type.ToLower())
                {

                    case "chrome":
                       driver= new ChromeDriver(new ChromeOptions { Proxy = null });
                        break;
                    case "firefox":
                       driver= new FirefoxDriver();
                        break;
                    case "ie":
                        driver= new InternetExplorerDriver(new InternetExplorerOptions { Proxy = null });
                        break;
                    default:
                    case "":
                       throw new Exception("Browser cannot be null");
                }
            }
            return driver;
        }
    }
}
</code>```

[/pre]

Body:
I want your help to my problem, Please:
From my test class, I try run my test code:

[setUp]
public void setup()
{
BrowserFactory.InitBrowser("Chrome");
}

But, it failed, because it didn’t initialized the “driver” variable.

(I got msg: system.nullReferenceException: The WebDriver browser instance was not initialized. You should first call the method InitBrowser)

Below code of InitBrowser() function as I copied from  http://toolsqa.com/selenium-webdriver/c-sharp/browser-factory-or-webdriver-factory/

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
using System;
using System.Collections.Generic;

namespace _AutomationTests.WrapperFactory
{
   public class BrowserFactory
   {
       private static readonly IDictionary<string, IWebDriver> Drivers = new Dictionary<string, IWebDriver>();
        private static IWebDriver driver;

    public static IWebDriver Driver
    {
        get
        {
            if (driver == null)
                throw new NullReferenceException("The WebDriver browser instance was not initialized. You should first call the method InitBrowser.");
            return driver;
        }
        private set
        {
            driver = value;
        }
    }

    public static void InitBrowser(string browserName)
    {
        switch (browserName)
        {
            case "Firefox":
                if (Driver == null)
                {
                    driver = new FirefoxDriver();
                    Drivers.Add("Firefox", Driver);
                }
                break;

            case "IE":
                if (Driver == null)
                {
                    driver = new InternetExplorerDriver(@"C:\PathTo\IEDriverServer");
                    Drivers.Add("IE", Driver);
                }
                break;

            case "Chrome":
                if (Driver == null)
                {
                    driver = new ChromeDriver();//@"C:\PathTo\CHDriverServer"
                    Drivers.Add("Chrome", Driver);
                }
                break;
        }
    }

    public static void LoadApplication(string url)
    {
        Driver.Url = url;
        driver.Manage().Window.Maximize();
        driver.Navigate().GoToUrl("javascript:document.getElementById('overridelink').click()");
    }

    public static void CloseAllDrivers()
    {
        foreach (var key in Drivers.Keys)
        {
            Drivers[key].Close();
            Drivers[key].Quit();
        }
    }
}

}

thank alot!

Body:
Mar, try to paste the full source code of your project. Where are those C# classes of ChromeDriver(), FirefoxDriver(),InternetExplorerDriver() in project. Have you coded them upfront ?
Here IWebDriver Driver is a property

Null check is not required in getter of public static IWebDriver Driver

public BrowserFactory()
        {
            Driver = new FirefoxDriver();
        }

        public static IWebDriver Driver
        {
            get
            {

                return driver;
            }
            private set
            {
                driver = value;
            }
        }

Set the property of IWebDriver Driver to an instance while the class is loaded in a static initializer or Constructor like :

Even before the driver could be initialized the get property is called which evalutates the null check to true & hence throwing exception.

Questions to be asked to yourself:

Have you added library files for Firefox,Chrome & IE ??

Is it a part of your project configuration file ?

If not added the best way to add is using Nuget Package manager in visual studio
4.Those references should be part of your project. Let me post a screenshot of a similar project I tried

5.See the pic of Nuget Package Manager

6.Click Manage Nuget Packages, browse for Available Packages
7.

Finally, you are not setting a new instance of driver

[pre]

{
    class Driver
    {
        public enum Browser
        {
            chrome,
            firefox,
            ie,
        }
        public IWebDriver getDriver(string browser_type)
        {
            Browser parsed_browser_type; IWebDriver driver=null;
            bool passed_type = browser_type != null ? true : false;
            if (passed_type)
            {
                Enum.TryParse(browser_type, out parsed_browser_type);

                switch (browser_type.ToLower())
                {

                    case "chrome":
                       driver= new ChromeDriver(new ChromeOptions { Proxy = null });
                        break;
                    case "firefox":
                       driver= new FirefoxDriver();
                        break;
                    case "ie":
                        driver= new InternetExplorerDriver(new InternetExplorerOptions { Proxy = null });
                        break;
                    default:
                    case "":
                       throw new Exception("Browser cannot be null");
                }
            }
            return driver;
        }
    }
}

[/pre]


问:
How to remove object from array in local storage?
I have array like this:

```<code>var myMovie = [];
</code>```

And object like this:

```<code>var first = {id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}
</code>```

I added object into local storage array via OnClick() on button.

```<code>$(document).ready(function() {
   $(".btn.btn-outline-success").click(function () {

    myMovie.push(first);

    localStorage.setItem('myMovie', JSON.stringify(myMovie));
    var output = JSON.parse(localStorage.getItem('myMovie'));
</code>```

After adding object into local storage, local storage looks like this:

```<code>[{id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}]
</code>```

My question here is, how could I remove whole object via variable name? I want to remove object first from myMovie. Index position of object may be different each time.

```<code>[{id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}, [{id:"tt9574821", title:"Ghost Protocol", year:"2012", type:"Action, Adventure"}]
</code>```

答:
I would advice you to have your object in format

```<code>var first = {"tt3783958": { title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}}
</code>```

ID will make your object have unique keys. Update will also be easy.

And store these in a JSON object and not an array like

```<code>myMovie = {}; //note its an object
</code>```

This would make it easier for you to query and delete items.

Body:
I have array like this:

var myMovie = [];

And object like this:

var first = {id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}

I added object into local storage array via OnClick() on button.

$(document).ready(function() {
   $(".btn.btn-outline-success").click(function () {

    myMovie.push(first);

    localStorage.setItem('myMovie', JSON.stringify(myMovie));
    var output = JSON.parse(localStorage.getItem('myMovie'));

After adding object into local storage, local storage looks like this:

[{id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}]

My question here is, how could I remove whole object via variable name? I want to remove object first from myMovie. Index position of object may be different each time.

[{id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}, [{id:"tt9574821", title:"Ghost Protocol", year:"2012", type:"Action, Adventure"}]

Body:
I would advice you to have your object in format

var first = {"tt3783958": { title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}}

ID will make your object have unique keys. Update will also be easy.

And store these in a JSON object and not an array like

myMovie = {}; //note its an object

This would make it easier for you to query and delete items.


问:
What I found so far the blinking text isnt working
I would like to have blinking email link and also the line that says Hello Professor. What i have found so far hasnt worked. Any help would be great. This is what I have tried so far text-decoration:blink; with no luck</p>

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>Randy's first html web page !</title>
<style type="text/css">
body
{background-image:url('Koala.gif');}
h1
{
text-align:center;
font-size:500%;
}
h2
{
text-align:center;
font-size:250%;
}
p
{
text-align:center;
font-size:200%;
color:#00fff0;
}
div
{
background-color:#efffff;
}
a
{
text-align:center;
}
th
{
background-color:green;
}
tr
{
background-color:green;
}
table
{
width: 200px;
margin-left: auto;
margin-right: auto;
}
#google-link
{
margin: 0 auto;
display: block;
font-size:250%;
color:#00ff00;
}
#Mail-link
{
margin: 0 auto;
display: block;
font-size:250%;
color:#00ff00;
text-decoration:blink;
}
</style>
</head>
<h1> Hello Professor</h1>
<h2> By: Randy White</h2>
<P> It's getting better as the term goes on.</P>
<P>Week 2</P>
<P><img src="Hydrangeas.jpg" width="150" height="100" alt="Hydrangeas.jpg"></P>
<table border="1">
<tr>
<th>Month</th>
<th>Day</th>
<th>Year</th>
</tr>
<tr>
<td>December</td>
<td>13</td>
<td>2010</td>
</tr>
</table>
<a id="google-link" href="http://www.google.com">Visit Google!</a>
<a id="Mail-link" href="mailto:randywhite30@neb.rr.com"> Contact Me!</a>
</body>
</html>
</code>```

答:
IE (and probably other browsers) don't support text-decoration: blink.  Just don't do this anyhow - blink is the epitome of bad taste and design on the web.  You may as well have an animated background and MIDI music.  I think Google may even hurt your ranking, and it will hurt my feelings.  ;)

Let me reassure you - there are much better ways to draw attention to page elements.

Body:
I would like to have blinking email link and also the line that says Hello Professor. What i have found so far hasnt worked. Any help would be great. This is what I have tried so far text-decoration:blink; with no luck

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">

<title>Randy's first html web page !</title>

 Hello Professor

 By: Randy White

 It's getting better as the term goes on.

Week 2

Month
Day
Year

December
13
2010

Visit Google!
 Contact Me!


问:
ADT with for comprehension
I have an use case where I need to use for comprehension with ADT in Scala. I could write the same code using flatMaps but it seems a bit unreadable. Below is the piece of code.

```<code>case class MovieRecord(movie: Movie,
                       screenId: String,
                       availableSeats: Int,
                       reservedSeats: Option[Int] = None) {
  def movieInfo = new MovieInfoResponse(movie.imdbId, screenId, movie.title, availableSeats, reservedSeats.getOrElse(0))
}

sealed trait MovieBookingInformation
case class MovieBookingInformationFetched(bookMovie: MovieRecord) extends MovieBookingInformation
case object MovieBookingInformationFetchError extends MovieBookingInformation

def modifyBooking(reserveMovie: MovieSelected): Future[String] = {
 fetchRecordByImdbAndScreenId(reserveMovie.imdbId, reserveMovie.screenId) flatMap {
    case MovieBookingInformationFetched(m) if (m.availableSeats > 0) =>
      updateSeatReservationByImdbAndScreenId(m.copy(availableSeats = m.availableSeats - 1, reservedSeats = Some(m.reservedSeats.getOrElse(0) + 1))) flatMap {
        case MovieBookingUpdated(updatedMovieBooking) =>
          Future.successful(s"One seat reserved at Screen - ${updatedMovieBooking.screenId}")
        case MovieBookingUpdateFailed =>
          Future.successful(s"Movie seat reservation failed at screen ${reserveMovie.screenId}")
      }
    case MovieBookingInformationFetched(m) =>
      Future.successful(s"Sorry! No more seats available for ${m.movie.title} at Screen - ${m.screenId}")
    case MovieBookingInformationFetchError => Future.successful(s"No movie with IMDB ID ${reserveMovie.imdbId} found at ${reserveMovie.screenId}")
  }
}
</code>```

In the above code, the next method is invoked on a resultant ADT content and result of if statement. How do I include the if statement in the for-comprehension to achieve the same.

Thanks in advance.

答:
You can put pattern matching and if statements in a for comprehension on Future:

```<code>for {
  MovieBookingInformationFetched(m) <- future1
  if m.availableSeats > 0
  MovieBookingUpdated(updatedMovieBooking) <- future2(m)
} yield updatedMovieBooking
</code>```

However, this will be translated into Future.filter, so if the predicate is not satisfied, or the pattern cannot be matched, you'll end up with

```<code>Future.failed(new NoSuchElementException("Future.filter predicate was not satisfied")
</code>```

You can then catch this failure in a recover statement, after the for-comp. The problem is that you want to catch three different "errors": the fact that there are no more available seats, the fact that fetchRecordByImdbAndScreenId can return a MovieBookingInformationFetchError, and the fact that updateSeatReservationByImdbAndScreenId can return a MovieBookingUpdateFailed.

You won't be able to dissociate between these three using only for comprehension, unless you define custom exceptions, instead of custom result types (and recover these exceptions afterwards).

Title: ADT with for comprehension

Body:
I have an use case where I need to use for comprehension with ADT in Scala. I could write the same code using flatMaps but it seems a bit unreadable. Below is the piece of code.

case class MovieRecord(movie: Movie,
                       screenId: String,
                       availableSeats: Int,
                       reservedSeats: Option[Int] = None) {
  def movieInfo = new MovieInfoResponse(movie.imdbId, screenId, movie.title, availableSeats, reservedSeats.getOrElse(0))
}

sealed trait MovieBookingInformation
case class MovieBookingInformationFetched(bookMovie: MovieRecord) extends MovieBookingInformation
case object MovieBookingInformationFetchError extends MovieBookingInformation

def modifyBooking(reserveMovie: MovieSelected): Future[String] = {
 fetchRecordByImdbAndScreenId(reserveMovie.imdbId, reserveMovie.screenId) flatMap {
    case MovieBookingInformationFetched(m) if (m.availableSeats > 0) =>
      updateSeatReservationByImdbAndScreenId(m.copy(availableSeats = m.availableSeats - 1, reservedSeats = Some(m.reservedSeats.getOrElse(0) + 1))) flatMap {
        case MovieBookingUpdated(updatedMovieBooking) =>
          Future.successful(s"One seat reserved at Screen - ${updatedMovieBooking.screenId}")
        case MovieBookingUpdateFailed =>
          Future.successful(s"Movie seat reservation failed at screen ${reserveMovie.screenId}")
      }
    case MovieBookingInformationFetched(m) =>
      Future.successful(s"Sorry! No more seats available for ${m.movie.title} at Screen - ${m.screenId}")
    case MovieBookingInformationFetchError => Future.successful(s"No movie with IMDB ID ${reserveMovie.imdbId} found at ${reserveMovie.screenId}")
  }
}

In the above code, the next method is invoked on a resultant ADT content and result of if statement. How do I include the if statement in the for-comprehension to achieve the same.

Thanks in advance.

Body:
You can put pattern matching and if statements in a for comprehension on Future:

for {
  MovieBookingInformationFetched(m) <- future1
  if m.availableSeats > 0
  MovieBookingUpdated(updatedMovieBooking) <- future2(m)
} yield updatedMovieBooking

However, this will be translated into Future.filter, so if the predicate is not satisfied, or the pattern cannot be matched, you'll end up with

Future.failed(new NoSuchElementException("Future.filter predicate was not satisfied")

You can then catch this failure in a recover statement, after the for-comp. The problem is that you want to catch three different "errors": the fact that there are no more available seats, the fact that fetchRecordByImdbAndScreenId can return a MovieBookingInformationFetchError, and the fact that updateSeatReservationByImdbAndScreenId can return a MovieBookingUpdateFailed.

You won't be able to dissociate between these three using only for comprehension, unless you define custom exceptions, instead of custom result types (and recover these exceptions afterwards).


问:
best way to include header and footer on HTML using any client side framework
Having HTML project want to include header and footer , so it will reduce rework.
Please suggest any good way.

I tried AngularJS with ng-include and below code

```<code>var app = angular.module("arstlApp", []);
app.controller("arstlCtrl", function($scope, $rootScope,$timeout) {
  $rootScope.$on('$includeContentLoaded', function() {
    $timeout(function(){
         _autoload();
    });
  });
});
</code>```

but <ng-include increase number of call JS function.

答:
use ui-router like this :

```<code>app.config(['$stateProvider', function($stateProvider){
        $stateProvider
        .state('root',{
          url: '',
          abstract: true,
          views: {
            'header': {
              templateUrl: 'header.html',
              controller: 'HeaderCtrl'
            },
            'footer':{
              templateUrl: 'footer.html',
              controller: 'FooterCtrl'
            }
          }
        })
        .state('root.home', {
          url: '/',
          views: {
            'container@': {
              templateUrl: 'homePage.html'
            }
          }
        })
        .state('root.other', {
          url: '/about',
          views: {
            'container@': {
              templateUrl: 'aboutPage.html'
            }
          }
        });

    }]);
</code>```

and in index.html :

```<code><header>
    <div ui-view="header"></div>
</header>
<div ui-view="container">
</div>
<footer ui-view="footer">
</footer>
</code>```

Body:
Having HTML project want to include header and footer , so it will reduce rework.
Please suggest any good way.

I tried AngularJS with ng-include and below code

var app = angular.module("arstlApp", []);
app.controller("arstlCtrl", function($scope, $rootScope,$timeout) {
  $rootScope.$on('$includeContentLoaded', function() {
    $timeout(function(){
         _autoload();
    });
  });
});

but <ng-include increase number of call JS function.

Body:
use ui-router like this :

app.config(['$stateProvider', function($stateProvider){
        $stateProvider
        .state('root',{
          url: '',
          abstract: true,
          views: {
            'header': {
              templateUrl: 'header.html',
              controller: 'HeaderCtrl'
            },
            'footer':{
              templateUrl: 'footer.html',
              controller: 'FooterCtrl'
            }
          }
        })
        .state('root.home', {
          url: '/',
          views: {
            'container@': {
              templateUrl: 'homePage.html'
            }
          }
        })
        .state('root.other', {
          url: '/about',
          views: {
            'container@': {
              templateUrl: 'aboutPage.html'
            }
          }
        });

    }]);

and in index.html :

<header>
    <div ui-view="header"></div>
</header>
<div ui-view="container">
</div>
<footer ui-view="footer">
</footer>


答:
Use  ng-if

<input ng-model="search.$">

    {{ x }}

```

Title: How to hide all the names when input is empty?

Body:
Use  ng-if

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="namesCtrl">
<input ng-model="search.$"></label> <br>
<ul>
  <li ng-if="search.$" ng-repeat="x in names | filter : search">
    {{ x }}
  </li>
</ul>
</div>

<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.names = [
        'Jani',
        'Carl',
        'Margareth',
        'Hege',
        'Joe',
        'Gustav',
        'Birgit',
        'Mary',
        'Kai'
    ];
});
</script>


问:
Tumblr Theme - Different Style for each post type
I'm creating a Tumblr theme, and I've run into a problem, of sorts. I like all of my posts to be these big circles with a different coloured border per post type. I don't know how to do this. Right now I can put ALL post to have a border and be rounded to the size I want, but, for example, I'd like text posts to have a red border, and photo posts to have an orange border. I've tried putting a div around text posts in the coding and adding the border that way, but it creates a secondary border (around the one I already set for ALL posts) and doesn't include the post's info (i.e the date and tags and such).

Does anyone know how to add different borders around each post type that includes the WHOLE post?

Here's the theme live for reference https://rainbowdotsinspiredthemetestblog.tumblr.com/

Heres the coding I have so far (my posts are labeled as stuff)

```<code>#stuff {
                float:left;
                width:400px;
                height:400px;
                margin-top:25px;
                margin-left:25px;
                text-align:justify;
                font-size:11px;
                line-height:90%;
                padding:5px;
                letter-spacing:0px;
                border:5px #24E4D8 solid;
                border-radius:200px;
                overflow:scroll;
                overflow-x:hidden;
                }
<!--TEXT POSTS-->
<div class="testingtext">
{block:Text}{block:Title}<h3>{Title}</h3>{/block:Title}{Body}{/block:Text}</div>
</code>```

This is what I tired and does NOT work

```<code>#stuff .testingtext{
        border:5px red solid;
    }
#stuff>.testingtext{
            border:5px red solid;
        }
#stuff:.testingtext{
            border:5px red solid;
        }
</code>```

答:
Firstly, you should be using a class stuff and not and ID. An ID should be unique and not repeated anywhere on a page.

Secondly, you can solve your problem with something like this:

```<code><div class="stuff {PostType}-post">
    [post stuff]
</div>
</code>```

{PostType} is the name of the current post type.

Then your CSS would just be like:

```<code>.text-post { border-color: red; }
.photo-post { border-color: orange; }
.chat-post { border-color: yellow; }
</code>```

etc.

Body:
I'm creating a Tumblr theme, and I've run into a problem, of sorts. I like all of my posts to be these big circles with a different coloured border per post type. I don't know how to do this. Right now I can put ALL post to have a border and be rounded to the size I want, but, for example, I'd like text posts to have a red border, and photo posts to have an orange border. I've tried putting a div around text posts in the coding and adding the border that way, but it creates a secondary border (around the one I already set for ALL posts) and doesn't include the post's info (i.e the date and tags and such).

Does anyone know how to add different borders around each post type that includes the WHOLE post?

Here's the theme live for reference https://rainbowdotsinspiredthemetestblog.tumblr.com/

Heres the coding I have so far (my posts are labeled as stuff)

#stuff {
                float:left;
                width:400px;
                height:400px;
                margin-top:25px;
                margin-left:25px;
                text-align:justify;
                font-size:11px;
                line-height:90%;
                padding:5px;
                letter-spacing:0px;
                border:5px #24E4D8 solid;
                border-radius:200px;
                overflow:scroll;
                overflow-x:hidden;
                }

{block:Text}{block:Title}
{Title}
{/block:Title}{Body}{/block:Text}

This is what I tired and does NOT work

#stuff .testingtext{
        border:5px red solid;
    }
#stuff>.testingtext{
            border:5px red solid;
        }
#stuff:.testingtext{
            border:5px red solid;
        }

Body:
Firstly, you should be using a class stuff and not and ID. An ID should be unique and not repeated anywhere on a page.

Secondly, you can solve your problem with something like this:

<div class="stuff {PostType}-post">
    [post stuff]
</div>

{PostType} is the name of the current post type.

Then your CSS would just be like:

.text-post { border-color: red; }
.photo-post { border-color: orange; }
.chat-post { border-color: yellow; }

etc.


问:
How to put PHP inside javascript
I am trying to add a else if statement in my Javascript code but so far it is not succesfull.

Here is the original script:

```<code>{ "targets": 4, "render": function ( data, type, full, meta ) { return  '+data+'; } }
</code>```

+data+ returns a 0 or 1

I tried:

```<code>{ "targets": 4, "render": function ( data, type, full, meta ) { return  '<?php if ('+data+' == 0){ <font color=red> } else if ('+data+' == 1){ <font color=blue> } ?>'+data+'</font>'; } }
</code>```

But when I run this I get a browser error.

Can someone help me with it?

Edit 1:

I am not trying to pass variables and data from PHP to JavaScript. I am trying to get data from Javascript and pass it to my PHP.

答:
That's not how PHP works. You have a simple check here, why don't you use javascript conditionals? Here's how you can do it with JS.</p>

```<code>var test = {
    "targets": 4,
    "render": function (data, type, full, meta) {
        return '<font color="'+ (data === 0 ? 'red' : 'blue') +'">'+data+'</font>';
    }
};

// Or

var test = {
    "targets": 4,
    "render": function (data, type, full, meta) {
        if (data === 0) {
            return '<font color="red">'+data+'</font>';
        }

        return '<font color="blue">'+data+'</font>';
    }
};
</code>```

Title: How to put PHP inside javascript

Body:
I am trying to add a else if statement in my Javascript code but so far it is not succesfull.

Here is the original script:

{ "targets": 4, "render": function ( data, type, full, meta ) { return  '+data+'; } }

+data+ returns a 0 or 1

I tried:

{ "targets": 4, "render": function ( data, type, full, meta ) { return  '<?php if ('+data+' == 0){  } else if ('+data+' == 1){  } ?>'+data+''; } }

But when I run this I get a browser error.

Can someone help me with it?

Edit 1:

I am not trying to pass variables and data from PHP to JavaScript. I am trying to get data from Javascript and pass it to my PHP.

Body:
That's not how PHP works. You have a simple check here, why don't you use javascript conditionals? Here's how you can do it with JS.

var test = {
    "targets": 4,
    "render": function (data, type, full, meta) {
        return '<font color="'+ (data === 0 ? 'red' : 'blue') +'">'+data+'</font>';
    }
};

// Or

var test = {
    "targets": 4,
    "render": function (data, type, full, meta) {
        if (data === 0) {
            return '<font color="red">'+data+'</font>';
        }

        return '<font color="blue">'+data+'</font>';
    }
};


问:
Can't find Python.h file on CentOS
I am trying to compile a Python extension written in C on a CentOS machine. I am getting

```<code>error: Python.h: No such file or directory
</code>```

It works fine on ubuntu, where I have python-dev installed using apt-get.

I tried installing python-devel using

```<code>yum install python-devel
</code>```

but it is already installed. How do I fix this error?

答: I had a similar problem where default Python was 2.7 but pip was running against 3.4, and I wanted to use 2.7. So I did: yum remove python34-pip and yum install python2-pip. Solved it!

Title: Can't find Python.h file on CentOS

Body:
I am trying to compile a Python extension written in C on a CentOS machine. I am getting

error: Python.h: No such file or directory

It works fine on ubuntu, where I have python-dev installed using apt-get.

I tried installing python-devel using

yum install python-devel

but it is already installed. How do I fix this error?


问:
PrefixAgain solution in codingbat
I'm currently doing codingbat problems for fun, and I just done this problem.

"Given a string, consider the prefix string made of the first N chars of the string. Does that prefix string appear somewhere else in the string? Assume
that the string is not empty and that N is in the range 1..str.length(). prefixAgain("abXYabc", 1) → true prefixAgain("abXYabc", 2) → true prefixAgain("abXYabc",
3) → false"
http://codingbat.com/prob/p136417

And my solution is:

```<code>public boolean prefixAgain(String str, int n) {
    return (str.replaceFirst(Character.toString(str.charAt(n-1)),"").contains(Character.toString(str.charAt(n-1))));
}
</code>```

Now, I didn't really understand the problem while writing this code and I thought only to find the occurance of the character of the specified index and
ignore the characters before it using the .contains() method. So I'm really not finding the prefix as the problem instructed. I just found my mistake after submitting it. However, this solution passed the exercise.
When I test it with my own input, such as

```<code>prefixAgain("abcccccbx", 2);
</code>```

it returned true instead of false. So am I missing some reason why codingbat accepted my solution even though it's totally wrong?

答:
public boolean prefixAgain(String str, int n) {

return (str.substring(n).contains(str.substring(0,n)));
}

Title: PrefixAgain solution in codingbat

Body:
I'm currently doing codingbat problems for fun, and I just done this problem.

"Given a string, consider the prefix string made of the first N chars of the string. Does that prefix string appear somewhere else in the string? Assume
that the string is not empty and that N is in the range 1..str.length(). prefixAgain("abXYabc", 1) → true prefixAgain("abXYabc", 2) → true prefixAgain("abXYabc",
3) → false"
http://codingbat.com/prob/p136417

And my solution is:

public boolean prefixAgain(String str, int n) {
    return (str.replaceFirst(Character.toString(str.charAt(n-1)),"").contains(Character.toString(str.charAt(n-1))));
}

Now, I didn't really understand the problem while writing this code and I thought only to find the occurance of the character of the specified index and
ignore the characters before it using the .contains() method. So I'm really not finding the prefix as the problem instructed. I just found my mistake after submitting it. However, this solution passed the exercise.
When I test it with my own input, such as

prefixAgain("abcccccbx", 2);

it returned true instead of false. So am I missing some reason why codingbat accepted my solution even though it's totally wrong?


问:
Cruft code. IoC to the rescue
In question about usefulness of IoC Container, the winning submitter mentioned that with an IoC container you can take this:

```<code>public class UglyCustomer : INotifyPropertyChanged
{
    private string _firstName;
    public string FirstName
    {
        get { return _firstName; }
        set
        {
            string oldValue = _firstName;
            _firstName = value;
            if(oldValue != value)
                OnPropertyChanged("FirstName");
        }
    }

    private string _lastName;
    public string LastName
    {
        get { return _lastName; }
        set
        {
            string oldValue = value;
            _lastName = value;
            if(oldValue != value)
                OnPropertyChanged("LastName");
        }
    }
}
</code>```

to this:

```<code>var bindingFriendlyInstance = IoC.Resolve<Customer>(new NotifyPropertyChangedWrapper());
</code>```

Questions:

Which magic IoC container provides this goodness?

An example implementing this?

Any downsides?

In a project with complex dependencies, will I be crying when I try to apply data binding to these objects?

答: I've never used it, but you can supposedly create something like this using PostSharp.</p>

Title: Cruft code. IoC to the rescue

Body:
In question about usefulness of IoC Container, the winning submitter mentioned that with an IoC container you can take this:

public class UglyCustomer : INotifyPropertyChanged
{
    private string _firstName;
    public string FirstName
    {
        get { return _firstName; }
        set
        {
            string oldValue = _firstName;
            _firstName = value;
            if(oldValue != value)
                OnPropertyChanged("FirstName");
        }
    }

    private string _lastName;
    public string LastName
    {
        get { return _lastName; }
        set
        {
            string oldValue = value;
            _lastName = value;
            if(oldValue != value)
                OnPropertyChanged("LastName");
        }
    }
}

to this:

var bindingFriendlyInstance = IoC.Resolve<Customer>(new NotifyPropertyChangedWrapper());

Questions:

Which magic IoC container provides this goodness?

An example implementing this?

Any downsides?

In a project with complex dependencies, will I be crying when I try to apply data binding to these objects?


问:
VueJS + VUEX + Firebase: Where To Hook Up Firebase?
I would like to integrate Firebase in my Vue.JS app.

I wonder WHERE to put the references to Firebase.

答:
To install firebase as a dependency in your project cd into your project directory and run the following command in the command line

```<code>npm install --save firebase
</code>```

Now in your main.js file add this

```<code>import Vue from 'vue'
import App from './App.vue'
import * as firebase from 'firebase'
import { store } from './store/store'

const config = {
    apiKey: "xxxxxxx",
    authDomain: "xxxxxxx",
    databaseURL: "xxxxxxx",
    storageBucket: "xxxxxxxx",
    messagingSenderId: "xxxxxxx"
  };

firebase.initializeApp(config);
Vue.prototype.$firebase = firebase;

new Vue({
  el: '#app',
  store,
  render: h => h(App)
})
</code>```

you can also add your firebase credentials in an external js file and import it in the main.js file as follows:

firebase-config.js

```<code>export const config = {
    apiKey: "xxxxxxx",
    authDomain: "xxxxxxx",
    databaseURL: "xxxxxxx",
    storageBucket: "xxxxxxxx",
    messagingSenderId: "xxxxxxx"
  };
</code>```

Now in your main.js do as follows

```<code>import Vue from 'vue'
import App from './App.vue'
import * as firebase from 'firebase'
import { store } from './store/store'
import { config } from './firebase-config'

firebase.initializeApp(config);
Vue.prototype.$firebase = firebase;

new Vue({
  el: '#app',
  store,
  render: h => h(App)
})
</code>```

adding firebase to the Vue.prototype allows usage of firebase in your vue components by using this.$firebase

if you don't want this behavior you can just initialize firebase using firebase.initializeApp(config);

now coming to your vuex store you can just import the firebase module as below

```<code>import Vue from 'vue'
import Vuex from 'vuex'
import * as firebase from 'firebase'

Vue.use(Vuex);

export const store = new Vuex.Store({
    state:{},
    mutations:{},
    actions:{
        myFirebaseAction: ({commit}) => {
            //you can use firebase like this
            var ref = firebase.database().ref()
        }
    }
});
</code>```

Credits to @umang for suggesting to add the firebase global namespace to the Vue.prototype instead of the firebase app instance.

Body:
To install firebase as a dependency in your project cd into your project directory and run the following command in the command line

npm install --save firebase

Now in your main.js file add this

import Vue from 'vue'
import App from './App.vue'
import * as firebase from 'firebase'
import { store } from './store/store'

const config = {
    apiKey: "xxxxxxx",
    authDomain: "xxxxxxx",
    databaseURL: "xxxxxxx",
    storageBucket: "xxxxxxxx",
    messagingSenderId: "xxxxxxx"
  };

firebase.initializeApp(config);
Vue.prototype.$firebase = firebase;

new Vue({
  el: '#app',
  store,
  render: h => h(App)
})

you can also add your firebase credentials in an external js file and import it in the main.js file as follows:

firebase-config.js

export const config = {
    apiKey: "xxxxxxx",
    authDomain: "xxxxxxx",
    databaseURL: "xxxxxxx",
    storageBucket: "xxxxxxxx",
    messagingSenderId: "xxxxxxx"
  };

Now in your main.js do as follows

import Vue from 'vue'
import App from './App.vue'
import * as firebase from 'firebase'
import { store } from './store/store'
import { config } from './firebase-config'

firebase.initializeApp(config);
Vue.prototype.$firebase = firebase;

new Vue({
  el: '#app',
  store,
  render: h => h(App)
})

adding firebase to the Vue.prototype allows usage of firebase in your vue components by using this.$firebase

if you don't want this behavior you can just initialize firebase using firebase.initializeApp(config);

now coming to your vuex store you can just import the firebase module as below

import Vue from 'vue'
import Vuex from 'vuex'
import * as firebase from 'firebase'

Vue.use(Vuex);

export const store = new Vuex.Store({
    state:{},
    mutations:{},
    actions:{
        myFirebaseAction: ({commit}) => {
            //you can use firebase like this
            var ref = firebase.database().ref()
        }
    }
});

Credits to @umang for suggesting to add the firebase global namespace to the Vue.prototype instead of the firebase app instance.


问:
How can i repeat a XWPFTable header on subsequent pages with Apache-POI api for java (MS-Word)
How do you get the row header to repeat itself

this is a simular question: With POI Word API, how to repeat a table heading on subsequent pages?

The code that i am currently running doing is this

```<code>XWPFTable contentTable = pXWPFDocument.createTable(50, 6);

List<XWPFTableRow> rows = contentTable.getRows();
XWPPFTableRow firstRow = rows.get(0);
firstRow.setRepeatHeader(true);
List<XWPFTableCell> tableCells = firstRow.getTableCells();
//Some code to fill the first row (header)

//I skip the first row (the header row) and continue with the rest
for (int i = 1; i < rows.size(); i++)
{
  XWPFTableRow row = rows.get(i);
  addDummy(row);
}
</code>```

As you can see i have marked the first row with a setRepeatHeader.
But when i have a new page the table header is not repeated.
What did i do wrong?
Please help me.
Thx in advance!

答:
I found the solution:
the api info defines the following: "NOTE - for a row to be repeated, all preceding rows in the table must also be repeated."

This information can be misleading (as it was for me) the method setRepeatHeader ONLY has to be defined on the firstRow (the headerRow)

What I did wrong was that i did a setRepeatHeader for every dummyRow

Body:
How do you get the row header to repeat itself

this is a simular question: With POI Word API, how to repeat a table heading on subsequent pages?

The code that i am currently running doing is this

XWPFTable contentTable = pXWPFDocument.createTable(50, 6);

List<XWPFTableRow> rows = contentTable.getRows();
XWPPFTableRow firstRow = rows.get(0);
firstRow.setRepeatHeader(true);
List<XWPFTableCell> tableCells = firstRow.getTableCells();
//Some code to fill the first row (header)

//I skip the first row (the header row) and continue with the rest
for (int i = 1; i < rows.size(); i++)
{
  XWPFTableRow row = rows.get(i);
  addDummy(row);
}

As you can see i have marked the first row with a setRepeatHeader.
But when i have a new page the table header is not repeated.
What did i do wrong?
Please help me.
Thx in advance!


问:
Bucket a continuous variable into distinct boundary buckets
How to bucket continuous variables into fixed number of buckets such that the boundaries don't overlap?

Ex : Lets say I have 500 numbers with 302 1s, 120 2s and a bunch of other values that range from 3 - 40. How do I bucket these into 5 bins without looking at the distribution?

Percentile buckets would mean 1s present in 1,2 & 3 buckets while they are all effectively just one bin.

答: I would suggest using. one of the cluster analysis procedures (e.g. proc fastclus), requesting 5 1-d clusters.


问:
Physics material Friction works only in forward direction - used with wheel joint 2D
I have created a car vehicle using 2D sprite, and connected circular wheel sprites to it using Wheel joint 2D. In controller script, When movement variable is non- zero i am creating instance of motor and enabling it.

```<code>if (movement == 0f) {

            backWheel.useMotor = false;
        } else {

            backWheel.useMotor = true;
            JointMotor2D motor = new JointMotor2D{ motorSpeed = movement, maxMotorTorque = backWheel.motor.maxMotorTorque };
            backWheel.motor = motor;
        }
</code>```

I am controlling direction by setting movement variable +ve or -ve. It is working perfectly in forward direction. However when i press left, on a moving car, it stops but than tire slips in backward direction , as if there were no friction. I have added physics material to both tire and ground, and behavior in forward direction is normal ( no slips).

is there friction only in one direction ? Or am i missing something here ?

答:
Okay I found what was wrong. Well, late night work has its pro and cons. cons mostly.

Anyhow, direction friction made no sense. In case you noticed I am applying motor to back wheel only. So when I was pressing brakes(changing direction) it was loosing touch with the ground. Thus slippery.

I could have never noticed this behavior in case I had applied motor to both wheels, but that wasn't required of my vehicle behaviour.

I solved the problem by adding more weight to back wheel, so that it was always in touch with the ground. Thus no slips.

Body:
I have created a car vehicle using 2D sprite, and connected circular wheel sprites to it using Wheel joint 2D. In controller script, When movement variable is non- zero i am creating instance of motor and enabling it.

if (movement == 0f) {

            backWheel.useMotor = false;
        } else {

            backWheel.useMotor = true;
            JointMotor2D motor = new JointMotor2D{ motorSpeed = movement, maxMotorTorque = backWheel.motor.maxMotorTorque };
            backWheel.motor = motor;
        }

I am controlling direction by setting movement variable +ve or -ve. It is working perfectly in forward direction. However when i press left, on a moving car, it stops but than tire slips in backward direction , as if there were no friction. I have added physics material to both tire and ground, and behavior in forward direction is normal ( no slips).

is there friction only in one direction ? Or am i missing something here ?


问:
Vectorised solution to for loop
Is there a vectorised solution for the below for loop. It is a large dataset containing admission data to a medical facility.

EDITED

```<code>library(lubridate)

dateSeq  <- as.Date(c("2015-01-01", "2015-02-01"))

admissionDate  <- as.Date(c("2015-01-03", "2015-01-06", "2015-01-10", "2015-01-05", "2015-01-07", "2015-02-03", "2015-02-06"))
Dfactor  <- c("elective", "acute", "elective", "acute", "acute", "elective", "acute")
Dfactor  <- factor(Dfactor)
df  <- data.frame(admissionDate, Dfactor)
# loop through large dataset collecting tabulated data from a factorised vector for each month (admissions date) based on 'dateSeq'

Dfactorsums  <- c()

for (i in 1:length(dateSeq)) {
    monthSub  <- df[(df$admissionDate >= as.Date(timeFirstDayInMonth(dateSeq[i]))) & (df$admissionDate <= as.Date(timeLastDayInMonth(dateSeq[i]))), ]
    x  <- table(monthSub$Dfactor)
    Dfactorsums[i]  <- as.numeric((x[1]))
}

print(Dfactorsums)
# Outcome = [1] 3 1
# Question is rather than use a for loop is there a 'vectorized' solution.
</code>```

答:
This isn't technically "vectorised", but should do what you're after, and should be pretty quick.

```<code>library( data.table )
setDT( df )

df[ , month := format( AdmissionsDate, "%m" ) ]
df[ , table( Dfactor )[2], by = month ]
</code>```

We set a column as the month in order to make subsetting by month easier, then extract the value you need for each month. This should output a two column data table, with the second column equal to your Dfactor output vector.

Title: Vectorised solution to for loop

Body:
Is there a vectorised solution for the below for loop. It is a large dataset containing admission data to a medical facility.

EDITED

library(lubridate)

dateSeq  <- as.Date(c("2015-01-01", "2015-02-01"))

admissionDate  <- as.Date(c("2015-01-03", "2015-01-06", "2015-01-10", "2015-01-05", "2015-01-07", "2015-02-03", "2015-02-06"))
Dfactor  <- c("elective", "acute", "elective", "acute", "acute", "elective", "acute")
Dfactor  <- factor(Dfactor)
df  <- data.frame(admissionDate, Dfactor)
# loop through large dataset collecting tabulated data from a factorised vector for each month (admissions date) based on 'dateSeq'

Dfactorsums  <- c()

for (i in 1:length(dateSeq)) {
    monthSub  <- df[(df$admissionDate >= as.Date(timeFirstDayInMonth(dateSeq[i]))) & (df$admissionDate <= as.Date(timeLastDayInMonth(dateSeq[i]))), ]
    x  <- table(monthSub$Dfactor)
    Dfactorsums[i]  <- as.numeric((x[1]))
}

print(Dfactorsums)
# Outcome = [1] 3 1
# Question is rather than use a for loop is there a 'vectorized' solution.

Body:
This isn't technically "vectorised", but should do what you're after, and should be pretty quick.

library( data.table )
setDT( df )

df[ , month := format( AdmissionsDate, "%m" ) ]
df[ , table( Dfactor )[2], by = month ]

We set a column as the month in order to make subsetting by month easier, then extract the value you need for each month. This should output a two column data table, with the second column equal to your Dfactor output vector.


问:
Taking Date input into a query in MS Access VBA from TextBox
I am trying to take input from a form, and I want to execute a insert query (append query) when a button is clicked.

Here is my Code:

```<code>Private Sub Command103_Click()
    Dim enrollment As String
    enrollment = Form_Form1!tbEnrollment

    Dim amount As String
    amount = Form_Form1!tbAmount

    Dim year As Integer
    year = Form_Form1!tbYear

    Dim date1 As Date
    date1 = Form_Form1!tbDate

    Dim month As Integer
    month = Form_Form1!cbMonth

    Dim sqlqry As String

    Dim db As DAO.Database
    Set db = CurrentDb
    sqlqry = "INSERT INTO StudentFeeMonthly( StudentID, FeeMonth, FeeYear, Amount, DateOfPayment, ReceiptNo ) SELECT TOP 1 (SELECT DISTINCT StudentDetails.StudentID FROM StudentDetails WHERE StudentDetails.EnrollmentNo = '" & enrollment & "') AS Expr1, '" & month & "' AS Expr2, '" & year & "' AS Expr3, '" & amount & "' AS Expr4, '" & date1 & "' AS Expr5, ""Hello"" AS Expr6 FROM StudentFeeMonthly;"
    MsgBox (sqlqry)

    db.Execute sqlqry

    MsgBox ("done")

End Sub
</code>```

Everything works fine, except the column with the date value remains blank after addition of the record.

The textbox format is set to "General Date", and it uses a date picker to select the date.

答:
You concatenate all values as if they were text but they are not.

You can use this function to correctly convert your values to string expressions:

```<code>' Converts a value of any type to its string representation.
' The function can be concatenated into an SQL expression as is
' without any delimiters or leading/trailing white-space.
'
' Examples:
'   SQL = "Select * From TableTest Where [Amount]>" & CSql(12.5) & "And [DueDate]<" & CSql(Date) & ""
'   SQL -> Select * From TableTest Where [Amount]> 12.5 And [DueDate]< #2016/01/30 00:00:00#
'
'   SQL = "Insert Into TableTest ( [Street] ) Values (" & CSql(" ") & ")"
'   SQL -> Insert Into TableTest ( [Street] ) Values ( Null )
'
' Trims text variables for leading/trailing Space and secures single quotes.
' Replaces zero length strings with Null.
' Formats date/time variables as safe string expressions.
' Uses Str to format decimal values to string expressions.
' Returns Null for values that cannot be expressed with a string expression.
'
' 2016-01-30. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function CSql( _
    ByVal Value As Variant) _
    As String

    Const vbLongLong    As Integer = 20
    Const SqlNull       As String = " Null"

    Dim Sql             As String
    Dim LongLong        As Integer

    #If Win32 Then
        LongLong = vbLongLong
    #End If
    #If Win64 Then
        LongLong = VBA.vbLongLong
    #End If

    Select Case VarType(Value)
        Case vbEmpty            '    0  Empty (uninitialized).
            Sql = SqlNull
        Case vbNull             '    1  Null (no valid data).
            Sql = SqlNull
        Case vbInteger          '    2  Integer.
            Sql = Str(Value)
        Case vbLong             '    3  Long integer.
            Sql = Str(Value)
        Case vbSingle           '    4  Single-precision floating-point number.
            Sql = Str(Value)
        Case vbDouble           '    5  Double-precision floating-point number.
            Sql = Str(Value)
        Case vbCurrency         '    6  Currency.
            Sql = Str(Value)
        Case vbDate             '    7  Date.
            Sql = Format(Value, " \#yyyy\/mm\/dd hh\:nn\:ss\#")
        Case vbString           '    8  String.
            Sql = Replace(Trim(Value), "'", "''")
            If Sql = "" Then
                Sql = SqlNull
            Else
                Sql = " '" & Sql & "'"
            End If
        Case vbObject           '    9  Object.
            Sql = SqlNull
        Case vbError            '   10  Error.
            Sql = SqlNull
        Case vbBoolean          '   11  Boolean.
            Sql = Str(Abs(Value))
        Case vbVariant          '   12  Variant (used only with arrays of variants).
            Sql = SqlNull
        Case vbDataObject       '   13  A data access object.
            Sql = SqlNull
        Case vbDecimal          '   14  Decimal.
            Sql = Str(Value)
        Case vbByte             '   17  Byte.
            Sql = Str(Value)
        Case LongLong           '   20  LongLong integer (Valid on 64-bit platforms only).
            Sql = Str(Value)
        Case vbUserDefinedType  '   36  Variants that contain user-defined types.
            Sql = SqlNull
        Case vbArray            ' 8192  Array.
            Sql = SqlNull
        Case Else               '       Should not happen.
            Sql = SqlNull
    End Select

    CSql = Sql & " "

End Function
</code>```

Body:
I am trying to take input from a form, and I want to execute a insert query (append query) when a button is clicked.

Here is my Code:

Private Sub Command103_Click()
    Dim enrollment As String
    enrollment = Form_Form1!tbEnrollment

    Dim amount As String
    amount = Form_Form1!tbAmount

    Dim year As Integer
    year = Form_Form1!tbYear

    Dim date1 As Date
    date1 = Form_Form1!tbDate

    Dim month As Integer
    month = Form_Form1!cbMonth

    Dim sqlqry As String

    Dim db As DAO.Database
    Set db = CurrentDb
    sqlqry = "INSERT INTO StudentFeeMonthly( StudentID, FeeMonth, FeeYear, Amount, DateOfPayment, ReceiptNo ) SELECT TOP 1 (SELECT DISTINCT StudentDetails.StudentID FROM StudentDetails WHERE StudentDetails.EnrollmentNo = '" & enrollment & "') AS Expr1, '" & month & "' AS Expr2, '" & year & "' AS Expr3, '" & amount & "' AS Expr4, '" & date1 & "' AS Expr5, ""Hello"" AS Expr6 FROM StudentFeeMonthly;"
    MsgBox (sqlqry)

    db.Execute sqlqry

    MsgBox ("done")

End Sub

Everything works fine, except the column with the date value remains blank after addition of the record.

The textbox format is set to "General Date", and it uses a date picker to select the date.

Body:
You concatenate all values as if they were text but they are not.

You can use this function to correctly convert your values to string expressions:

' Converts a value of any type to its string representation.
' The function can be concatenated into an SQL expression as is
' without any delimiters or leading/trailing white-space.
'
' Examples:
'   SQL = "Select * From TableTest Where [Amount]>" & CSql(12.5) & "And [DueDate]<" & CSql(Date) & ""
'   SQL -> Select * From TableTest Where [Amount]> 12.5 And [DueDate]< #2016/01/30 00:00:00#
'
'   SQL = "Insert Into TableTest ( [Street] ) Values (" & CSql(" ") & ")"
'   SQL -> Insert Into TableTest ( [Street] ) Values ( Null )
'
' Trims text variables for leading/trailing Space and secures single quotes.
' Replaces zero length strings with Null.
' Formats date/time variables as safe string expressions.
' Uses Str to format decimal values to string expressions.
' Returns Null for values that cannot be expressed with a string expression.
'
' 2016-01-30. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function CSql( _
    ByVal Value As Variant) _
    As String

    Const vbLongLong    As Integer = 20
    Const SqlNull       As String = " Null"

    Dim Sql             As String
    Dim LongLong        As Integer

    #If Win32 Then
        LongLong = vbLongLong
    #End If
    #If Win64 Then
        LongLong = VBA.vbLongLong
    #End If

    Select Case VarType(Value)
        Case vbEmpty            '    0  Empty (uninitialized).
            Sql = SqlNull
        Case vbNull             '    1  Null (no valid data).
            Sql = SqlNull
        Case vbInteger          '    2  Integer.
            Sql = Str(Value)
        Case vbLong             '    3  Long integer.
            Sql = Str(Value)
        Case vbSingle           '    4  Single-precision floating-point number.
            Sql = Str(Value)
        Case vbDouble           '    5  Double-precision floating-point number.
            Sql = Str(Value)
        Case vbCurrency         '    6  Currency.
            Sql = Str(Value)
        Case vbDate             '    7  Date.
            Sql = Format(Value, " \#yyyy\/mm\/dd hh\:nn\:ss\#")
        Case vbString           '    8  String.
            Sql = Replace(Trim(Value), "'", "''")
            If Sql = "" Then
                Sql = SqlNull
            Else
                Sql = " '" & Sql & "'"
            End If
        Case vbObject           '    9  Object.
            Sql = SqlNull
        Case vbError            '   10  Error.
            Sql = SqlNull
        Case vbBoolean          '   11  Boolean.
            Sql = Str(Abs(Value))
        Case vbVariant          '   12  Variant (used only with arrays of variants).
            Sql = SqlNull
        Case vbDataObject       '   13  A data access object.
            Sql = SqlNull
        Case vbDecimal          '   14  Decimal.
            Sql = Str(Value)
        Case vbByte             '   17  Byte.
            Sql = Str(Value)
        Case LongLong           '   20  LongLong integer (Valid on 64-bit platforms only).
            Sql = Str(Value)
        Case vbUserDefinedType  '   36  Variants that contain user-defined types.
            Sql = SqlNull
        Case vbArray            ' 8192  Array.
            Sql = SqlNull
        Case Else               '       Should not happen.
            Sql = SqlNull
    End Select

    CSql = Sql & " "

End Function


问:
Golang on eclipse: "Resource doesn't have a corresponding Go package" on Mac
As stated in the title, I have a problem running the Golang code on Eclipse. I'm currently using Mac, and I installed go by using homebrew.

Currently, the folder where go is installed is as follows.

/usr/local/Cellar/go/1.5.2/..

and after running Terminal and typing open ~/.bash_profile I added the following.

```<code>export GOROOT="/usr/local/Cellar/go/1.5.2/"
export PATH=$PATH:$GOROOT/bin
</code>```

Am I still missing something else?

PS If I run the code using Terminal like go run main.go, I have absolutely no problem. The problem must be due to some misconfiguration in Eclipse.

答: I had the same error. Putting the source file under a sub-folder in src fixed it.</p>

Body:
As stated in the title, I have a problem running the Golang code on Eclipse. I'm currently using Mac, and I installed go by using homebrew.

Currently, the folder where go is installed is as follows.

/usr/local/Cellar/go/1.5.2/..

and after running Terminal and typing open ~/.bash_profile I added the following.

export GOROOT="/usr/local/Cellar/go/1.5.2/"
export PATH=$PATH:$GOROOT/bin

Am I still missing something else?

PS If I run the code using Terminal like go run main.go, I have absolutely no problem. The problem must be due to some misconfiguration in Eclipse.


答:
For your second code snippet to work, NotifyPropertyChangedWrapper would certainly have to use reflection (or dynamic) to generate a class that provides an interface compatible with Customer and implements the automatic property notification.  There shouldn't be any data binding issues, but there would be a little overhead.

An simplified implementation that uses a dynamic object could look something like this:

```<code>public class NotifyPropertyChangedWrapper<T>
    : DynamicObject, INotifyPropertyChanged
{
    private T _obj;

    public NotifyPropertyChangedWrapper(T obj)
    {
        _obj = obj;
    }

    public override bool TryGetMember(
        GetMemberBinder binder, out object result)
    {
        result = typeof(T).GetProperty(binder.Name).GetValue(_obj);
        return true;
    }

    // If you try to set a value of a property that is
    // not defined in the class, this method is called.
    public override bool TrySetMember(
        SetMemberBinder binder, object value)
    {
        typeof(T).GetProperty(binder.Name).SetValue(_obj, value);
        OnPropertyChanged(binder.Name);
        return true;
    }

    // Implement OnPropertyChanged...
}
</code>```

Obviously, any code that consumes one of these objects would lose any static type safety.  The other option is to generate a class implementing the same interface as the class being wrapped.  There are lots of examples for this on the web.  The main requirement is that your Customer would have to either be an interface or it would need all of its properties to be virtual.

Title: Cruft code. IoC to the rescue

Body:
For your second code snippet to work, NotifyPropertyChangedWrapper would certainly have to use reflection (or dynamic) to generate a class that provides an interface compatible with Customer and implements the automatic property notification.  There shouldn't be any data binding issues, but there would be a little overhead.

An simplified implementation that uses a dynamic object could look something like this:

public class NotifyPropertyChangedWrapper<T>
    : DynamicObject, INotifyPropertyChanged
{
    private T _obj;

    public NotifyPropertyChangedWrapper(T obj)
    {
        _obj = obj;
    }

    public override bool TryGetMember(
        GetMemberBinder binder, out object result)
    {
        result = typeof(T).GetProperty(binder.Name).GetValue(_obj);
        return true;
    }

    // If you try to set a value of a property that is
    // not defined in the class, this method is called.
    public override bool TrySetMember(
        SetMemberBinder binder, object value)
    {
        typeof(T).GetProperty(binder.Name).SetValue(_obj, value);
        OnPropertyChanged(binder.Name);
        return true;
    }

    // Implement OnPropertyChanged...
}

Obviously, any code that consumes one of these objects would lose any static type safety.  The other option is to generate a class implementing the same interface as the class being wrapped.  There are lots of examples for this on the web.  The main requirement is that your Customer would have to either be an interface or it would need all of its properties to be virtual.


问:
Android geofence stop working when app is not running
I'm working on an Android app that uses Google Geofence API.
My code seems to work fine while the app is on foreground, but as soon as the app move to Pause state the geofence broadcast receiver stop receiving events.
I'm pretty sure that the geofence is getting removed when the app move to background but I don't know why this is happening.

Breafly, I create a list of geofences

```<code>Geofence geofence = new Geofence.Builder()
            .setRequestId(id)
            .setCircularRegion(lat, lng, GEOFENCE_RADIUS)
            .setExpirationDuration(Geofence.NEVER_EXPIRE)
            .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_DWELL)
            .setLoiteringDelay(1000)
            .build();
        geofences.add(geofence);
</code>```

Then I create a request

```<code>geofenceRequest = new GeofencingRequest.Builder()
        .setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_DWELL)
        .addGeofences(geofences)
        .build();
</code>```

At this point I add the geofence

```<code>LocationServices.GeofencingApi.addGeofences(googleApiClient, request, createGeofencePendingIntent()).setResultCallback(this);
</code>```

And finally I start the broadcast receiver

```<code>String GEOFENCE_ACTION = "gac.broadcast.geofence";
    if (geoFencePendingIntent != null)
    {
        GoogleApiClientManager.setGeofencePendingIntent(geoFencePendingIntent);
        return geoFencePendingIntent;
    }
    Intent intent = new Intent(GEOFENCE_ACTION);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), GEOFENCE_REQ_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    GoogleApiClientManager.setGeofencePendingIntent(pendingIntent);
    return pendingIntent;
</code>```

As I've already said, everything work perfectly while running in foreground, but as soon as the app moves to background the geofence event stop being sent to receiver.

ADDITIONAL INFOS (not related to broadcast receiver issue):
I tried to do the following:

I start the map fragment and the geofence is working fine, so the app show a notification

I move to home screen so the app move to Pause state and no notification is no longer received

I move back to the app checking that location update and google api client are still working, and they actually work

Finally geofencing is not working anymore

Hope that everything is clear and that someone of you can help me.
Thanks in advance

答:
Actually the problem was on defining the receiver intent.

I changed

```<code>Intent intent = new Intent(GEOFENCE_ACTION);
</code>```

to

```<code>Intent intent = new Intent(context, GeofenceBroadcastReceiver.class);
</code>```

Now the receiver is notified in background as well as in foreground.
Hope this can help someone else too.

Body:
I'm working on an Android app that uses Google Geofence API.
My code seems to work fine while the app is on foreground, but as soon as the app move to Pause state the geofence broadcast receiver stop receiving events.
I'm pretty sure that the geofence is getting removed when the app move to background but I don't know why this is happening.

Breafly, I create a list of geofences

Geofence geofence = new Geofence.Builder()
            .setRequestId(id)
            .setCircularRegion(lat, lng, GEOFENCE_RADIUS)
            .setExpirationDuration(Geofence.NEVER_EXPIRE)
            .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_DWELL)
            .setLoiteringDelay(1000)
            .build();
        geofences.add(geofence);

Then I create a request

geofenceRequest = new GeofencingRequest.Builder()
        .setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_DWELL)
        .addGeofences(geofences)
        .build();

At this point I add the geofence

LocationServices.GeofencingApi.addGeofences(googleApiClient, request, createGeofencePendingIntent()).setResultCallback(this);

And finally I start the broadcast receiver

String GEOFENCE_ACTION = "gac.broadcast.geofence";
    if (geoFencePendingIntent != null)
    {
        GoogleApiClientManager.setGeofencePendingIntent(geoFencePendingIntent);
        return geoFencePendingIntent;
    }
    Intent intent = new Intent(GEOFENCE_ACTION);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), GEOFENCE_REQ_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    GoogleApiClientManager.setGeofencePendingIntent(pendingIntent);
    return pendingIntent;

As I've already said, everything work perfectly while running in foreground, but as soon as the app moves to background the geofence event stop being sent to receiver.

ADDITIONAL INFOS (not related to broadcast receiver issue):
I tried to do the following:

I start the map fragment and the geofence is working fine, so the app show a notification

I move to home screen so the app move to Pause state and no notification is no longer received

I move back to the app checking that location update and google api client are still working, and they actually work

Finally geofencing is not working anymore

Hope that everything is clear and that someone of you can help me.
Thanks in advance

Body:
Actually the problem was on defining the receiver intent.

I changed

Intent intent = new Intent(GEOFENCE_ACTION);

to

Intent intent = new Intent(context, GeofenceBroadcastReceiver.class);

Now the receiver is notified in background as well as in foreground.
Hope this can help someone else too.


问:
Move "n" files in Seperate Folder with PowerShell
I have found a PowerShell script which is capable of moving 'n' number of files from 'D:\source' to 'E:\Dest' directory. It will take the first 'n' number of files in the source folder and move them to the specified subfolder. It can create folders as long as they are needed.

Code:

```<code>$filesperfolder = 150
$sourcePath = "D:\source"
$destPath = "E:\Dest"
$i = 0;
$folderNum = 1;

Get-ChildItem "$sourcePath\*.jpg" | % {

    New-Item -Path ($destPath + "\" + $folderNum) -Type Directory -Force
    Move-Item $_ ($destPath + "\" + $folderNum);

    $i++;

    if ($i -eq $filesperfolder){
        $folderNum++;
        $i = 0 ;
    }
}
</code>```

So far this script is working fine but, how do I set its working directory. I mean, if the script is on 'C:\test' folder, then it should search that current folder for '*.jpg' files and create folders on that same directory.

答:
Whilst it may operate from C:\Test, you are still providing full addresses to other locations so as long as it has access and permission to those files in D:\Source and E:\Dest, it won't touch anything to do with C:\Test except for run from that location. What is your intention, you haven't actually asked us for any help with anything.

If you want to set the working directory you would use this:

```<code>Set-Location "D:\SourceFiles"
</code>```

This way, regardless of where you started your script from, it would work from 'D:\SourceFiles'.

Body:
I have found a PowerShell script which is capable of moving 'n' number of files from 'D:\source' to 'E:\Dest' directory. It will take the first 'n' number of files in the source folder and move them to the specified subfolder. It can create folders as long as they are needed.

Code:

$filesperfolder = 150
$sourcePath = "D:\source"
$destPath = "E:\Dest"
$i = 0;
$folderNum = 1;

Get-ChildItem "$sourcePath\*.jpg" | % {

    New-Item -Path ($destPath + "\" + $folderNum) -Type Directory -Force
    Move-Item $_ ($destPath + "\" + $folderNum);

    $i++;

    if ($i -eq $filesperfolder){
        $folderNum++;
        $i = 0 ;
    }
}

So far this script is working fine but, how do I set its working directory. I mean, if the script is on 'C:\test' folder, then it should search that current folder for '*.jpg' files and create folders on that same directory.

Body:
Whilst it may operate from C:\Test, you are still providing full addresses to other locations so as long as it has access and permission to those files in D:\Source and E:\Dest, it won't touch anything to do with C:\Test except for run from that location. What is your intention, you haven't actually asked us for any help with anything.

If you want to set the working directory you would use this:

Set-Location "D:\SourceFiles"

This way, regardless of where you started your script from, it would work from 'D:\SourceFiles'.


问:
How does a server know which browser or tab I am using?
I had this question for an interview.
Can you tell me how a server know which tab or browser I am using for a specific website?</p>

答:
There is a header called User-Agent that is sent to the server when a user makes a request from the browser. It looks like this:

```<code>User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20100101 Firefox/12.0
</code>```

It clearly tells you that the browser is mozilla, although there is some extra information for historical reasons that you souldn't worry about.

A header is a type of meta information that the users doesn't see but helps the server communicate with the client by sharing this kind of information. So you are able to serve different pages to different pages if the client is using an outdated browser.

You can't know what tab the client is using.

Body:
There is a header called User-Agent that is sent to the server when a user makes a request from the browser. It looks like this:

User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20100101 Firefox/12.0

It clearly tells you that the browser is mozilla, although there is some extra information for historical reasons that you souldn't worry about.

A header is a type of meta information that the users doesn't see but helps the server communicate with the client by sharing this kind of information. So you are able to serve different pages to different pages if the client is using an outdated browser.

You can't know what tab the client is using.