问:
Handling single page application url and django url
I have a single page application created in Vue.js that utilizes the HTML5 History Mode for routing, and the html file is served with Django.

The urls.py of django is like so:

```<code>urlpatterns = [
    url(r'^$', views.home),
    url(r'^admin/', admin.site.urls),
    url(r'^api-token-auth/', obtain_jwt_token),
]
</code>```

And views.home:

```<code>def home(request):
    return render(request, 'index.html')
</code>```

Consider the following scenario:

User visits the home page (i.e., /)

Since, the home page responds with required index.html for the Single page Vuejs app, it works like its supposed to.

From there the user navigates to the about page (i.e., /username/12).

Its still working fine, as its navigating with the Vue router.

Now, the user refreshes the page.

Since there's no /username/12 in the urls.py patterns, it will show Page not found (404).

Now, I could provide another pattern in urls.py to catch all pattern in the last order as this:

```<code>urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api-token-auth/', obtain_jwt_token),
    url(r'^.*$', views.home),
]
</code>```

But other urls like the media or static urls will also point to the same catch all pattern regex. How can I solve this problem?

答:
I solved the issue by using the negative look-ahead regex, so basically anything inside (?!ignore1|ignore2) will be ignored.

```<code>urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api-token-auth/', obtain_jwt_token),
    url(r'^(?!admin|api-token-auth|static).*$', views.home),
]
</code>```

Note: I tried not including admin and api-token-auth inside the negative look-ahead and it didn't work for me, it will still route path that starts with admin to the views.home, not sure why as according to my understanding, django should match the earlier ones first.

Body:
I have a single page application created in Vue.js that utilizes the HTML5 History Mode for routing, and the html file is served with Django.

The urls.py of django is like so:

urlpatterns = [
    url(r'^$', views.home),
    url(r'^admin/', admin.site.urls),
    url(r'^api-token-auth/', obtain_jwt_token),
]

And views.home:

def home(request):
    return render(request, 'index.html')

Consider the following scenario:

User visits the home page (i.e., /)

Since, the home page responds with required index.html for the Single page Vuejs app, it works like its supposed to.

From there the user navigates to the about page (i.e., /username/12).

Its still working fine, as its navigating with the Vue router.

Now, the user refreshes the page.

Since there's no /username/12 in the urls.py patterns, it will show Page not found (404).

Now, I could provide another pattern in urls.py to catch all pattern in the last order as this:

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api-token-auth/', obtain_jwt_token),
    url(r'^.*$', views.home),
]

But other urls like the media or static urls will also point to the same catch all pattern regex. How can I solve this problem?

Body:
I solved the issue by using the negative look-ahead regex, so basically anything inside (?!ignore1|ignore2) will be ignored.

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api-token-auth/', obtain_jwt_token),
    url(r'^(?!admin|api-token-auth|static).*$', views.home),
]

Note: I tried not including admin and api-token-auth inside the negative look-ahead and it didn't work for me, it will still route path that starts with admin to the views.home, not sure why as according to my understanding, django should match the earlier ones first.


来源: stackexchange

问:
jboss connection pooling
I have a question related to Prepared Steatement pooling (across all connections). Here's the config file

```<code><datasources>
  <local-tx-datasource>
    <jndi-name>JNDI-NAME</jndi-name>
    <connection-url>jdbc:mysql://<server_name>/<database_name>?useServerPrepStmts=true</connection-url>
    <driver-class>com.mysql.jdbc.Driver</driver-class>
    <user-name>xxx</user-name>
    <password>xxxxx</password>
    <min-pool-size>10</min-pool-size>
    <max-pool-size>20</max-pool-size>
    <idle-timeout-minutes>20</idle-timeout-minutes>
    <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
    <valid-connection-checker-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLValidConnectionChecker</valid-connection-checker-class-name>
    <background-validation>true</background-validation>
    <background-validation-minutes>5</background-validation-minutes>
    <prepared-statement-cache-size>100</prepared-statement-cache-size>
    <share-prepared-statements>true</share-prepared-statements>
    <!-- sql to call when connection is created
    <new-connection-sql>some arbitrary sql</new-connection-sql>
      -->
    <!-- sql to call on an existing pooled connection when it is obtained from pool - MySQLValidConnectionChecker is preferred for newer drivers
    <check-valid-connection-sql>some arbitrary sql</check-valid-connection-sql>
      -->
    <!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml -->
    <metadata>
       <type-mapping>mySQL</type-mapping>
    </metadata>
  </local-tx-datasource>
</datasources>
</code>```

It seems that this line:

```<code><background-validation-minutes>5</background-validation-minutes>
</code>```

doesn't cause any problems with Prepared Statements, but:

```<code><idle-timeout-minutes>20</idle-timeout-minutes>
</code>```

causes that all connections are removed and re-created if there was no traffic for the last 20 minutes. Because of that existing Prepared Statements are removed from the pool of cached Prepared Statements. How to overcome this issue? I have to use idle-timeout-minutes because MySQL server closes the connection after 8h

答:
You must be using PreparedStatement for a wrong purpose. PreparedStament is mainly used to execute the same query multiple times with different arguments in a single flow. Once it's need is done, it should be closed  shown below.

```<code>PreparedStatement pstmt = con.prepareStatement("insert into Emp(name) values(?)");
pstmt.setString(1, "foo");
int i1=stmt.executeUpdate();  // inserted one record
pstmt.setString(1, "bar");
int i2=stmt.executeUpdate(); // inserted 2nd record
pstmt.close(); // close prepared statement
con.close();
</code>```

It looks like, a CallableStatement is more relevant than PreparedStatement for your requirements.

Explore CallableStatement in jdbc here

OwnerDisplayName: Web

ContentLicense: CC BY-SA 2.5

Title: jboss connection pooling

Body:
I have a question related to Prepared Steatement pooling (across all connections). Here's the config file

<datasources>
  <local-tx-datasource>
    <jndi-name>JNDI-NAME</jndi-name>
    <connection-url>jdbc:mysql://<server_name>/<database_name>?useServerPrepStmts=true</connection-url>
    <driver-class>com.mysql.jdbc.Driver</driver-class>
    <user-name>xxx</user-name>
    <password>xxxxx</password>
    <min-pool-size>10</min-pool-size>
    <max-pool-size>20</max-pool-size>
    <idle-timeout-minutes>20</idle-timeout-minutes>
    <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
    <valid-connection-checker-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLValidConnectionChecker</valid-connection-checker-class-name>
    <background-validation>true</background-validation>
    <background-validation-minutes>5</background-validation-minutes>
    <prepared-statement-cache-size>100</prepared-statement-cache-size>
    <share-prepared-statements>true</share-prepared-statements>

    <metadata>
       <type-mapping>mySQL</type-mapping>
    </metadata>
  </local-tx-datasource>
</datasources>

It seems that this line:

<background-validation-minutes>5</background-validation-minutes>

doesn't cause any problems with Prepared Statements, but:

<idle-timeout-minutes>20</idle-timeout-minutes>

causes that all connections are removed and re-created if there was no traffic for the last 20 minutes. Because of that existing Prepared Statements are removed from the pool of cached Prepared Statements. How to overcome this issue? I have to use idle-timeout-minutes because MySQL server closes the connection after 8h

Body:
You must be using PreparedStatement for a wrong purpose. PreparedStament is mainly used to execute the same query multiple times with different arguments in a single flow. Once it's need is done, it should be closed  shown below.

PreparedStatement pstmt = con.prepareStatement("insert into Emp(name) values(?)");
pstmt.setString(1, "foo");
int i1=stmt.executeUpdate();  // inserted one record
pstmt.setString(1, "bar");
int i2=stmt.executeUpdate(); // inserted 2nd record
pstmt.close(); // close prepared statement
con.close();

It looks like, a CallableStatement is more relevant than PreparedStatement for your requirements.

Explore CallableStatement in jdbc here

ContentLicense: CC BY-SA 4.0


问:
Get an Image from CameraPreview
Is there a way I can get an image from a camera preview? The purpose of this would be to overlay an emoji over the face of the camera preview, and I can't overlay the emoji images without first having a Bitmap image as follows:

```<code>private void processAndSetImage()
{
    mResultsBitmap = OverlayEmoji.detectFacesandOverlayEmoji(this, mResultsBitmap);

    mImageView.setImageBitmap(mResultsBitmap);
}
</code>```

Is there a way that mImageView could have the value of a camera preview? Any links to other SO posts, or articles (in java) would be greatly appreciated!

答:
Is there a way I can get an image from a camera preview?

No.

First, there are thousands of Android device models. These devices will have dozens, if not hundreds, of "android native camera" apps, as many device manufacturers frequently ship a customized camera app.

Second, there is no requirement that all camera apps have an identical user interface. The size and position of the camera preview can vary. Not only will they vary between apps, but even the same app might vary the size and position of the camera preview between versions of that app, as apps can and do get updated.

Third , you have no good way of determining when any of these camera apps happens to be in the foreground.

Title: Get an Image from CameraPreview

Body:
Is there a way I can get an image from a camera preview? The purpose of this would be to overlay an emoji over the face of the camera preview, and I can't overlay the emoji images without first having a Bitmap image as follows:

private void processAndSetImage()
{
    mResultsBitmap = OverlayEmoji.detectFacesandOverlayEmoji(this, mResultsBitmap);

    mImageView.setImageBitmap(mResultsBitmap);
}

Is there a way that mImageView could have the value of a camera preview? Any links to other SO posts, or articles (in java) would be greatly appreciated!


问:
PHP MVC - One view class for all controllers vs a view class for each controller
I am creating an MVC inspired PHP framework, mainly for learning purposes.
I basically have the framework created and am building an app on it and improving the framework as i go along.

I am still confused/not sure about certain aspects of this sort of architecture, and at the moment i am questioning my implementation of the View part.

How i have set up my framework:

Its a very simple set up, for example: you go to the url /post/post_id, this will load index.php which will instantiate the router. The router will then check the url and instantiate the correct controller and method based on the url. In this case it would be PostController, and the method would be a default method that would use the post_id to get the posts data from the relevant model. Next the controller would set up a "data" variable that will hold the data to pass on to the View, and this is where i am confused - should it send to its own View object (a view class file dedicated to the PostController), or to a generally used View class that is used by all controllers to load an html file?

At the moment my controller is sending data to the View class, this data includes what template file should be included/shown, and the actual data for the page (what we got from the Model through the controller).

My question is this:

Should this type of system have one View object that renders all of the views (html files) based on what data is given to the "render" method, or, should each controller that eventually sends data to the View have its own View object/class?

Meaning, should PostController send a request to the general view class, the same one that is used by all controllers to renders pages, or should the PostController send to a dedicated View Class (call it PostView if it makes it clearer), and this class will then render the specific html file?

Basically if it should be one View class for all controllers that will render what ever html file the controller tells it to, or if there should be many View classes, one for each page load.

NOTE:
I know a lot of questions have already been asked about MVC in PHP, but i could not find an answer to my question in any of the answers.

答:
A bit about MVC:

In the original MVC pattern (presented by Trygve Reenskaug in 1979), the controller updates the model, the model notifies the view about the changes, and the view pulls its data from it. Though the pattern was thought for desktop applications - each M-V-C "triad" beeing related to a single control in a window (a button, a textbox, a checkbox, etc). So, each control on the screen had an MVC "attached" to it.

Since, in web applications, the model-to-view notification step is not (or can not be) present, the original pattern can not be applied as is to them.
But a most similar approach can still be relatively easily implemented: the controller updates the model, the view pulls data from it (irrespective of the controller). I think it's called "Web MVC Model 2".

There is a multitude of web MVC variations. You are using one in which the controller takes the role of an intermediary between the model and the view.
So the controller is the only one component communicating with the model.

The view's responsibility:

The responsibility of the view component is the presentation logic - which should not be assumed by the controller at all. Beside loading and rendering template files, this kind of logic involves the preparation of the data fetched from the model for displaying purposes. The result of the preparation should, preferably, be a list of values of primitive types (strings, booleans, integers, arrays, etc) which can be easily "injected" into the template files during the load-and-render process.

Examples of presentation logic:

Example #1: If you would fetch the value 123.45 (from the column amount of a table revenues) from the model, the presentation logic would consist of formatting it to the string 123.45 USD, in order to be displayed in a template file.

Example #2: Formatting a fetched date value of 28/05/2019 to 2019-05-28 by using a code snippet like this:

```<code>$fetchedDateFromModel = '28/05/2019';
$time = strtotime($fetchedDateFromModel);
$formattedDate = date('Y-m-d', $time);
</code>```

The value of $formattedDate would then be "injected" into a template file.

Example #3: Setting a boolean value based on some model data, in order to be used in a template file for deciding if a button ("Get Bonus") should be active or not.

```<code>$paidAmount = 512.79; /* model data */
$isActiveGetBonusButton = false;

if ($paidAmount > 500) {
    $isActiveGetBonusButton = true;
}
</code>```

The answer (in respect of your chosen MVC approach):

By using a View instance in all controllers, you would be forced to perform specific presentation logic in each controller - before passing its result (e.g. the list of the prepared values) to the used View instance, in order to further just be "injected" in a specific template file.

Whereas, if you are implementing a dedicated view class (like PostView - which, preferably, inherit a base class View containing the render() method) for a controller class (like PostController) - so a 1:1 relationship, but see it as a loose one! - you can pass the data fetched from the model, in an unprepared form, from the controller to the view. The view class would then correctly take the responsibility of preparing the data for displaying prior to actually load and render a specific template file. E.g. of performing the whole specific presentation logic.

Note: In "Web MVC Model 2" - where, ideally, the controller has no knowledge of the view component - the above argument is more obvious:

the PostController just updates the model (when an update step is required);

the PostView fetches data from model, prepares it for display, and displays it (by loading & rendering a template file like posts.html.twig, for example). In other words, the view component performs the whole presentation logic by itself.

Body:
A bit about MVC:

In the original MVC pattern (presented by Trygve Reenskaug in 1979), the controller updates the model, the model notifies the view about the changes, and the view pulls its data from it. Though the pattern was thought for desktop applications - each M-V-C "triad" beeing related to a single control in a window (a button, a textbox, a checkbox, etc). So, each control on the screen had an MVC "attached" to it.

Since, in web applications, the model-to-view notification step is not (or can not be) present, the original pattern can not be applied as is to them.
But a most similar approach can still be relatively easily implemented: the controller updates the model, the view pulls data from it (irrespective of the controller). I think it's called "Web MVC Model 2".

There is a multitude of web MVC variations. You are using one in which the controller takes the role of an intermediary between the model and the view.
So the controller is the only one component communicating with the model.

The view's responsibility:

The responsibility of the view component is the presentation logic - which should not be assumed by the controller at all. Beside loading and rendering template files, this kind of logic involves the preparation of the data fetched from the model for displaying purposes. The result of the preparation should, preferably, be a list of values of primitive types (strings, booleans, integers, arrays, etc) which can be easily "injected" into the template files during the load-and-render process.

Examples of presentation logic:

Example #1: If you would fetch the value 123.45 (from the column amount of a table revenues) from the model, the presentation logic would consist of formatting it to the string 123.45 USD, in order to be displayed in a template file.

Example #2: Formatting a fetched date value of 28/05/2019 to 2019-05-28 by using a code snippet like this:

$fetchedDateFromModel = '28/05/2019';
$time = strtotime($fetchedDateFromModel);
$formattedDate = date('Y-m-d', $time);

The value of $formattedDate would then be "injected" into a template file.

Example #3: Setting a boolean value based on some model data, in order to be used in a template file for deciding if a button ("Get Bonus") should be active or not.

$paidAmount = 512.79; /* model data */
$isActiveGetBonusButton = false;

if ($paidAmount > 500) {
    $isActiveGetBonusButton = true;
}

The answer (in respect of your chosen MVC approach):

By using a View instance in all controllers, you would be forced to perform specific presentation logic in each controller - before passing its result (e.g. the list of the prepared values) to the used View instance, in order to further just be "injected" in a specific template file.

Whereas, if you are implementing a dedicated view class (like PostView - which, preferably, inherit a base class View containing the render() method) for a controller class (like PostController) - so a 1:1 relationship, but see it as a loose one! - you can pass the data fetched from the model, in an unprepared form, from the controller to the view. The view class would then correctly take the responsibility of preparing the data for displaying prior to actually load and render a specific template file. E.g. of performing the whole specific presentation logic.

Note: In "Web MVC Model 2" - where, ideally, the controller has no knowledge of the view component - the above argument is more obvious:

the PostController just updates the model (when an update step is required);

the PostView fetches data from model, prepares it for display, and displays it (by loading & rendering a template file like posts.html.twig, for example). In other words, the view component performs the whole presentation logic by itself.


问:
Alternative to opencv warpPerspective
I am using opencv warpPerspective() function to warp the found countour in the image to find contour i am using findContours().

This is shown in this image:

but the warpPerspective() function takes "more time" to warp to full image is there any alternative to this function to warp the object in image to full image as shown in figure.
OR will traversing help?but this would be difficult to do so that i can reduce the time the warpPerspective() function takes.

答:
You can try to work on rotation and translation matrices (or roto-translational matrix, a combination of both), which can warp image as you wish. The function warpPerspective() utilizes similar approach, so you will basically will have an opportunity to look inside the function.

The approach is:

You calculate the matrix, then multiply the height and width of
the original image to find dimensions of the output image.

Go through all pixels in the original image and multiply their
(x,y) coordinates to the matrix R
(rotation/translation/roto-translation matrix) to get the
coordinates on the output image (xo,yo).

On every calculated coordinate (xo,yo) assign value from the
corresponding original image coordinate (x,y).

Interpolate using median filter/bilinear/bicubic/etc. method as
sometimes there may be empty points left on the output image

However, if you work in Python your implementation may work even slower than warpPerspective(), so you may consider C++. Another thing is that OpenCV uses C++ compiler and I am pretty sure that implementation of warpPerspective() in OpenCV is very efficient.

So, I think that you can go around warpPerspective(), however, I am not sure if you can do it faster than in OpenCV without any boosts (like GPU, powerful CPU etc.) :)

Good luck!

Title: Alternative to opencv warpPerspective


问:
ES6 getter/method without curly braces
I have some classes which consist of many short getters/methods.

Example:

```<code>get jQuery() {
  return this.pageConfig.jQuery || jQuery;
}
</code>```

An arrow function with similar content may be written as follows:

```<code>() => this.pageConfig.jQuery || jQuery;
</code>```

Which is a one-liner and thus consumes only 1/3 of vertical space.

But it is not a getter nor a method.

Is there a recommended way of writing getters/methods in the form of a one-liner? (if possible without curly braces and without the return keyword)

My getters and methods need not modify the object. They are just reading.

答:
I was thinking of building a babel library to handle this
I think something like this would look fancy </p>

```<code>const weekDays = [
            {
                day: 'Sunday',
                get input() {
                    return TimeRange(this.day)
                }
                // something like this
                // get input() => TimeRange(this.day)
            }
]
</code>```

ContentLicense: CC BY-SA 3.0

Title: ES6 getter/method without curly braces

Body:
I have some classes which consist of many short getters/methods.

Example:

get jQuery() {
  return this.pageConfig.jQuery || jQuery;
}

An arrow function with similar content may be written as follows:

() => this.pageConfig.jQuery || jQuery;

Which is a one-liner and thus consumes only 1/3 of vertical space.

But it is not a getter nor a method.

Is there a recommended way of writing getters/methods in the form of a one-liner? (if possible without curly braces and without the return keyword)

My getters and methods need not modify the object. They are just reading.

Body:
I was thinking of building a babel library to handle this
I think something like this would look fancy

const weekDays = [
            {
                day: 'Sunday',
                get input() {
                    return TimeRange(this.day)
                }
                // something like this
                // get input() => TimeRange(this.day)
            }
]


问:
Axios - Interceptors not working on request error - 401 code
I have a simple react app that is using a third API to fetch data. Before making any requests, a token must be retrieved in order to use it in the headers. This token is created by using the same API by passing the client id and secret id - the API is Artsy API. This token has an expiration date so this API must be requested if the token doesn't not exist. After getting the token, then I can call other requests without a problem.

I have set up the API requests in a separate file, like so:
Apis.js

```<code>import Axios from 'axios';
const baseURL = 'https://api.artsy.net/api';

// set up xap-token and set tot default headers
const instance = Axios.create({
    baseURL: baseURL + '/tokens/xapp_token',
    params: {
        'client_id': process.env.CLIENTID,
        'client_secret': process.env.CLIENTSECRET
    }
});

instance.interceptors.request.use(undefined, err => {
    const status = err.response ? err.response.status : null;
    console.log("auth",err.response)

    if(status === 401){
        console.log("auth",err.response)
        return 'hello'
        // this.getAuthToken();
    }
});

export default{

    getArtworks: function(){
        return new Promise((resolve, reject) => {
            instance.get(baseURL + '/artworks')
            .then(res => {
                resolve(res)
            })
            .catch(err => {
                reject(err);
            });
        });
    },

    getArtists: function(){
        return new Promise((resolve, reject) => {
            instance.get(baseURL + '/artists')
            .then(res => {
                resolve(res)
            })
            .catch(err => {
                reject(err);
            });
        });

    },

    getTest: function(){
        return 'hello';
    }
};
</code>```

Not really sure how to use the create and interceptors, but I created an Axios instance. So the idea is to create some sort of middleware, create an instance and then use it as an interceptor if there is a request on that error.  If there is, then apply the token to that instance and proceed with the request, retry.  Also not sure how to set the the token in the instance.

So far I'm getting a 401 error in the getArtists method, this api gets called when the page loads, it's under componentDidMount.

App.jsx

```<code>import React, { Component } from 'react';
import Apis from './utils/Api';
import Gallery from './components/Gallery';

class App extends Component{
    constructor(props){
        super(props);
        this.state = {
            artWorks: []
        }
    }

    componentDidMount = () => {
        // Apis.getArtists();
        Apis.getArtists().then(res => {
            console.log(res)
            // this.setState({
            //     artWorks: res.data
            // })
        });
    }

    render(){
        return(
            <div>
                <Gallery artists={this.state.artWorks}/>
            </div>
        )
    }
}

export default App;
</code>```

This is the api doc links for authentication.

Can anybody help? not really sure how to use the instance as a "middleware"? new to Axios.  I would like to avoid 3rd library middleware, I prefer to learn in a manual way than using 3rd libraries.  Your help will be much appreciated

Update:

I was able to get this somewhat working, i modified the instance.interceptor:

```<code>instance.interceptors.response.use(undefined, err => {
    const status = err.response ? err.response.status : null;
    if(status === 401){
        console.log("auth",err.response)

        instance.post(err.config.authURL, err.config.auth).then(res => {
            let token = res.data.token;
            err.config.headers['X-XAPP-Token'] = token;
            console.log('calling',err.response)
            return instance.request(err.config)
        });
    }

    // return Promise.reject(err);
});
</code>```

But I'm getting undefined in the getArtists response. Not sure what's going on here.  Here is a screenshot of the console:

答:
You should use instance.interceptors.response rather than instance.interceptors.request .

Because the request interceptor is called before Ajax request send.  I think the response interceptor is actually what you want here.

About BaseURL, you should set like below

const instance = Axios.create({
    baseURL: 'https://api.artsy.net/api'
})
// because you set the baseURL of the instance
// this will request url https://api.artsy.net/api/artworks
instance.get('/artworks')
```

<ol start="2">
<li>About 401 Error you get, from the api doc you give.I think you should request to get the token before your app start.</li>
</ol>

<pre class="lang-js prettyprint-override"><code>instance.post('tokens/xapp_token').then(res => {
  /* here is the response
{
  "type" : "xapp_token",
  "token" : "...",
  "expires_at" : "2014-09-05T12:39:09.200Z"
}
  */

  // you can set common request headers like this
  // or use request interceptors here to set headers
  // then every request you sent by instance after will have X-XAPP-Token header
  instance.defaults.headers.common['X-XAPP-Token'] = res.token
})
</code>```

Actually err.config.headers['X-XAPP-Token'] = token; this code will not affect the request headers.

Body:
I have a simple react app that is using a third API to fetch data. Before making any requests, a token must be retrieved in order to use it in the headers. This token is created by using the same API by passing the client id and secret id - the API is Artsy API. This token has an expiration date so this API must be requested if the token doesn't not exist. After getting the token, then I can call other requests without a problem.

I have set up the API requests in a separate file, like so:
Apis.js

import Axios from 'axios';
const baseURL = 'https://api.artsy.net/api';

// set up xap-token and set tot default headers
const instance = Axios.create({
    baseURL: baseURL + '/tokens/xapp_token',
    params: {
        'client_id': process.env.CLIENTID,
        'client_secret': process.env.CLIENTSECRET
    }
});

instance.interceptors.request.use(undefined, err => {
    const status = err.response ? err.response.status : null;
    console.log("auth",err.response)

    if(status === 401){
        console.log("auth",err.response)
        return 'hello'
        // this.getAuthToken();
    }
});

export default{

    getArtworks: function(){
        return new Promise((resolve, reject) => {
            instance.get(baseURL + '/artworks')
            .then(res => {
                resolve(res)
            })
            .catch(err => {
                reject(err);
            });
        });
    },

    getArtists: function(){
        return new Promise((resolve, reject) => {
            instance.get(baseURL + '/artists')
            .then(res => {
                resolve(res)
            })
            .catch(err => {
                reject(err);
            });
        });

    },

    getTest: function(){
        return 'hello';
    }
};

Not really sure how to use the create and interceptors, but I created an Axios instance. So the idea is to create some sort of middleware, create an instance and then use it as an interceptor if there is a request on that error.  If there is, then apply the token to that instance and proceed with the request, retry.  Also not sure how to set the the token in the instance.

So far I'm getting a 401 error in the getArtists method, this api gets called when the page loads, it's under componentDidMount.

App.jsx

import React, { Component } from 'react';
import Apis from './utils/Api';
import Gallery from './components/Gallery';

class App extends Component{
    constructor(props){
        super(props);
        this.state = {
            artWorks: []
        }
    }

    componentDidMount = () => {
        // Apis.getArtists();
        Apis.getArtists().then(res => {
            console.log(res)
            // this.setState({
            //     artWorks: res.data
            // })
        });
    }

    render(){
        return(

                <Gallery artists={this.state.artWorks}/>

        )
    }
}

export default App;

This is the api doc links for authentication.

Can anybody help? not really sure how to use the instance as a "middleware"? new to Axios.  I would like to avoid 3rd library middleware, I prefer to learn in a manual way than using 3rd libraries.  Your help will be much appreciated

Update:

I was able to get this somewhat working, i modified the instance.interceptor:

instance.interceptors.response.use(undefined, err => {
    const status = err.response ? err.response.status : null;
    if(status === 401){
        console.log("auth",err.response)

        instance.post(err.config.authURL, err.config.auth).then(res => {
            let token = res.data.token;
            err.config.headers['X-XAPP-Token'] = token;
            console.log('calling',err.response)
            return instance.request(err.config)
        });
    }

    // return Promise.reject(err);
});

But I'm getting undefined in the getArtists response. Not sure what's going on here.  Here is a screenshot of the console:

Body:
You should use instance.interceptors.response rather than instance.interceptors.request .

Because the request interceptor is called before Ajax request send.  I think the response interceptor is actually what you want here.

About BaseURL, you should set like below

const instance = Axios.create({
    baseURL: 'https://api.artsy.net/api'
})
// because you set the baseURL of the instance
// this will request url https://api.artsy.net/api/artworks
instance.get('/artworks')

About 401 Error you get, from the api doc you give.I think you should request to get the token before your app start.

instance.post('tokens/xapp_token').then(res => {
  /* here is the response
{
  "type" : "xapp_token",
  "token" : "...",
  "expires_at" : "2014-09-05T12:39:09.200Z"
}
  */

  // you can set common request headers like this
  // or use request interceptors here to set headers
  // then every request you sent by instance after will have X-XAPP-Token header
  instance.defaults.headers.common['X-XAPP-Token'] = res.token
})

Actually err.config.headers['X-XAPP-Token'] = token; this code will not affect the request headers.


答:
It looks like a bug. See here, where the warning appears in line 547, but msg.UCV is not defined anywhere around (in fact, only in line 419, which is not reached). Given that a variable is simply undefined at that stage, a workaround would be to define it in the global environment:

```<code>msg.UCV <- "A WORKAROUND"

robust::lmRob(
  data = df,
  formula = value ~ parameter,
  control = robust::lmRob.control(
    tlo = 1e-100,
    tua = 1.5e-100,
    tl = 1e-100,
    mxr = 10000,
    mxf = 10000,
    mxs = 10000,
    final.alg = "Adaptive"
  ),
  nrep = 100000
)
# Call:
# robust::lmRob(formula = value ~ parameter, data = df, nrep = 1e+05,
#     control = robust::lmRob.control(tlo = 1e-100, tua = 1.5e-100,
#         tl = 1e-100, mxr = 10000, mxf = 10000, mxs = 10000, final.alg = "Adaptive"))
#
# Coefficients:
# (Intercept)    parameter
#           0            0
#
# Warning message:
# In lmRob.fit.compute(x, y, x1.idx = x1.idx, nrep = nrep, robust.control =  robust.control,  :
#   A WORKAROUND  when refining initial estimates.
</code>```

Title: robust regression not working - "object 'msg.UCV' not found"

Body:
I am trying to run robust linear regression using the robust package in R. But it doesn't work and fails with a rather cryptic error.

Here are the setup details and data to reproduce this analysis-

# setup
set.seed(123)
library(tidyverse)
library(robust)
#> Loading required package: fit.models

# data
df <- structure(list(value = c(0.833333333333333, 0, 0, 0, 0, 0.166666666666667,
                         0.166666666666667, 0, 0, 0.166666666666667, 0, 0, 0, 0.333333333333333,
                         0.333333333333333, 0, 0, 0, 0.5, 0, 0, 0.166666666666667, 0,
                         0, 0.166666666666667, 0, 0, 0, 0, 0.166666666666667, 0, 0, 0.5,
                         0.166666666666667, 0, 0, 0, 0.333333333333333, 0, 0.5, 0.333333333333333,
                         0.5, 0, 0.166666666666667, 0.333333333333333, 0.166666666666667,
                         0, 0, 0.166666666666667, 0, 0.833333333333333, 0, 0, 0.333333333333333,
                         0, 0, 0.166666666666667, 0, 0.166666666666667, 0.5, 0, 0, 0,
                         0.166666666666667, 0, 0, 0.166666666666667, 0.166666666666667,
                         0, 0, 0, 0, 0, 0, 0, 0, 0.166666666666667, 0.166666666666667,
                         0.166666666666667, 0.666666666666667, 0, 0, 0, 0.166666666666667,
                         0.166666666666667, 0, 0.166666666666667, 0, 0, 0, 0.166666666666667,
                         0, 0, 0, 0.166666666666667, 0, 0.333333333333333, 0.166666666666667,
                         0.166666666666667, 0, 0.166666666666667, 0.166666666666667, 0,
                         0, 0, 0, 0, 0.166666666666667, 0.166666666666667, 0, 0, 0, 0.333333333333333,
                         0, 0, 0, 0, 0.333333333333333, 0, 0, 0, 0.166666666666667, 0.166666666666667,
                         0.166666666666667, 0.166666666666667, 0, 0.166666666666667, 0.166666666666667,
                         0.166666666666667, 0.166666666666667, 0, 0.666666666666667, 0.333333333333333,
                         0.166666666666667, 0, 0.166666666666667, 0.333333333333333, 0.333333333333333,
                         0, 0.166666666666667, 0, 0.166666666666667, 0.333333333333333,
                         0.333333333333333, 0, 0.166666666666667, 0.166666666666667, 0.666666666666667,
                         0.5, 0, 0, 0, 0, 0.666666666666667, 0.166666666666667, 0, 0.333333333333333,
                         0.166666666666667), parameter = c(-0.26053156261281, 0.294881565797054,
                                                           0.294881565797054, -0.260531562612809, -1.37135781943254, 0.294881565797054,
                                                           0.850294694206917, -1.37135781943254, -0.260531562612809, -1.37135781943254,
                                                           -0.26053156261281, 1.40570782261678, -0.26053156261281, 0.850294694206917,
                                                           1.96112095102664, -0.260531562612809, -1.9267709478424, 0.850294694206917,
                                                           1.40570782261678, 0.850294694206917, -1.37135781943254, -0.26053156261281,
                                                           0.294881565797054, -2.48218407625226, 0.850294694206917, 1.40570782261678,
                                                           -0.260531562612809, 0.294881565797053, 0.294881565797054, -0.260531562612809,
                                                           -0.260531562612809, -1.37135781943254, 0.294881565797054, 0.294881565797054,
                                                           0.294881565797054, 0.850294694206917, 1.96112095102664, 0.850294694206917,
                                                           0.294881565797054, 0.294881565797054, -0.815944691022672, 0.294881565797054,
                                                           0.850294694206917, -0.260531562612809, 0.850294694206917, -1.37135781943254,
                                                           -1.37135781943254, -0.815944691022673, -1.37135781943254, -1.9267709478424,
                                                           1.40570782261678, -1.37135781943254, 0.294881565797054, -0.815944691022673,
                                                           0.850294694206917, 0.850294694206917, -0.260531562612809, 0.850294694206917,
                                                           -0.26053156261281, 0.850294694206917, -1.37135781943254, -1.9267709478424,
                                                           1.40570782261678, 1.96112095102664, 0.850294694206917, -0.815944691022672,
                                                           -0.260531562612809, 0.850294694206917, 0.850294694206917, -0.815944691022673,
                                                           0.294881565797053, -0.260531562612809, -0.260531562612809, -1.9267709478424,
                                                           -0.815944691022673, -1.9267709478424, -1.9267709478424, 0.294881565797054,
                                                           0.294881565797054, -1.9267709478424, 0.850294694206917, 0.850294694206917,
                                                           -0.815944691022672, -0.815944691022672, -1.9267709478424, 1.40570782261678,
                                                           -0.815944691022673, 0.294881565797054, 0.850294694206917, -1.37135781943254,
                                                           0.850294694206917, 0.294881565797054, -0.260531562612809, -1.9267709478424,
                                                           1.40570782261678, -0.815944691022673, -0.260531562612809, 1.40570782261678,
                                                           0.294881565797054, 1.40570782261678, -0.815944691022672, -0.815944691022673,
                                                           -0.815944691022673, 0.850294694206917, -1.37135781943254, 0.294881565797054,
                                                           1.96112095102664, -0.260531562612809, -0.26053156261281, 0.294881565797054,
                                                           0.850294694206917, 0.850294694206917, -0.260531562612809, 0.294881565797054,
                                                           1.96112095102664, -0.260531562612809, 1.40570782261678, 1.96112095102664,
                                                           -0.815944691022672, 0.294881565797054, -0.815944691022672, -0.815944691022672,
                                                           -0.815944691022673, 0.850294694206917, -1.9267709478424, -1.37135781943254,
                                                           -1.37135781943254, -0.815944691022672, 1.96112095102664, 0.850294694206917,
                                                           -0.26053156261281, -0.815944691022672, 0.850294694206917, 0.294881565797054,
                                                           0.294881565797053, -0.815944691022672, 0.850294694206917, -0.815944691022673,
                                                           1.40570782261678, 1.96112095102664, -0.815944691022673, 0.294881565797054,
                                                           0.850294694206917, -0.260531562612809, 0.294881565797054, 1.40570782261678,
                                                           0.850294694206917, 1.96112095102664, -0.260531562612809, 2.51653407943651,
                                                           0.294881565797054, 0.294881565797054, 0.294881565797053, -0.815944691022672,
                                                           -1.37135781943254, -1.37135781943254, -1.37135781943254, 0.294881565797054
                         )), row.names = c(NA, -158L), class = c("tbl_df", "tbl", "data.frame"
                         ))

This is the exact error I get-

# running robust linear model
# using robust
robust::lmRob(
  data = df,
  formula = value ~ parameter,
  control = robust::lmRob.control(
    tlo = 1e-100,
    tua = 1.5e-100,
    tl = 1e-100,
    mxr = 10000,
    mxf = 10000,
    mxs = 10000,
    final.alg = "Adaptive"
  ),
  nrep = 100000
)
#> Error in paste(msg.UCV, " when refining initial estimates."): object 'msg.UCV' not found

On the other hand, if I use robustbase package, it gives me a possible reason as to why-

# using robustbase
robustbase::lmrob(data = df,
                  formula = value ~ parameter,
                  method = "MM")
#> Warning in lmrob.S(x, y, control = control): S-estimated scale == 0:
#> Probably exact fit; check your data
#>
#> Call:
#> robustbase::lmrob(formula = value ~ parameter, data = df, method = "MM")
#>
#> Exact fit detected
#>
#> Coefficients:
#> (Intercept)    parameter
#>           0            0

So I wanted to know if there is any way I can similarly get the robust::lmRob function with the data I have.

This is because I am running the same analysis across all levels of a grouping variable and the function fails for only one level and, as a result, the entire analysis fails. I would much prefer a more failsafe approach.

Body:
It looks like a bug. See here, where the warning appears in line 547, but msg.UCV is not defined anywhere around (in fact, only in line 419, which is not reached). Given that a variable is simply undefined at that stage, a workaround would be to define it in the global environment:

msg.UCV <- "A WORKAROUND"

robust::lmRob(
  data = df,
  formula = value ~ parameter,
  control = robust::lmRob.control(
    tlo = 1e-100,
    tua = 1.5e-100,
    tl = 1e-100,
    mxr = 10000,
    mxf = 10000,
    mxs = 10000,
    final.alg = "Adaptive"
  ),
  nrep = 100000
)
# Call:
# robust::lmRob(formula = value ~ parameter, data = df, nrep = 1e+05,
#     control = robust::lmRob.control(tlo = 1e-100, tua = 1.5e-100,
#         tl = 1e-100, mxr = 10000, mxf = 10000, mxs = 10000, final.alg = "Adaptive"))
#
# Coefficients:
# (Intercept)    parameter
#           0            0
#
# Warning message:
# In lmRob.fit.compute(x, y, x1.idx = x1.idx, nrep = nrep, robust.control =  robust.control,  :
#   A WORKAROUND  when refining initial estimates.


问:
What is the most impressive Lisp application?
I know that this is subjective and all, but still, can you provide some list of serious applications that were written in Lisp (perhaps along with what Lisp it is)?</p>

答:
Whitehouse Publication Server

During the Clinton administration a Lisp application was used to inform the US citizens about government news. The application was written in Common Lisp and ran on top of the CL-HTTP web server on two Symbolics Lisp Machines (later on the Open Genera virtual Lisp Machine). It also used the Statice object-oriented database. The application provided a taxonomy of government areas which could be queried with a web or an email interface for publications. For example citizens could find out what the vice president Al Gore said about environmental issues in a certain week. This was application was shut down by George W. Bush when he came into office.

OwnerDisplayName: Bartosz Radaczyński

LastEditorDisplayName: starblue

OwnerDisplayName: foo


问:
Customize React Big Calendar colors
I am new to React Big Calendar and it seems very useful but I'm stuck. I am creating a dark mode web site the default buttons work for what I want but the text is black and doesn't show up well on a dark background. Is there a way to not create a custom toolbar but to only change the text color (active button, hover button, and non active button text colors) ?  I have seen custom toolbars but that seems like over kill to just change the text color of the default buttons.

thanks for the help.

I am using
React
Typescript
of course React Big Calendar

答:
If you use sass you can change a range of variables which should give you what you require.

@import 'react-big-calendar/lib/sass/styles';

$out-of-range-color: lighten(#333, 40%);
$out-of-range-bg-color: lighten(#333, 70%);

$calendar-border: #DDD;
$cell-border: #DDD;

$border-color: #CCC;

$segment-width: percentage(1 / 7);

$time-selection-color: white;
$time-selection-bg-color: rgba(0,0,0, .50);
$date-selection-bg-color: rgba(0,0,0, .10);

$event-bg: #3174ad;
$event-border: darken(#3174ad, 10%);
$event-outline: #3b99fc;
$event-color: #fff;
$event-border-radius: 5px;
$event-padding: 2px 5px;
$event-zindex: 4;

$btn-color: #373a3c;
$btn-bg: #fff;
$btn-border: #ccc;

$current-time-color: #74ad31;

$rbc-css-prefix: rbc-i;

$today-highlight-bg: #eaf6ff;
```

Title: Customize React Big Calendar colors


问:
Cypher : Union between queries, with an initial node retrieval
I am trying to write a Cypher query which is kind of a "union" query, basically something like :

```<code>MATCH (myNodeUsedInAllSubQueries)
WITH myNodeUsedInAllSubQueries
MATCH (a)-[...]->(myNodeUsedInAllSubQueries)
RETURN a
UNION
MATCH (b)-[...]->(myNodeUsedInAllSubQueries)
RETURN b
...
</code>```

I want to match (myNodeUsedInAllSubQueries) once at the beginning because this node is used in all subqueries.
Of course, the retrieval of this node in my example is not just as simple as this (it involves relationships and a WHERE clause, but I'll keep it simple here).

I'll try to explain this with a simple example and what I've tried so far.

Example

Graphically, the graph structure is the following :

```<code>(John: Person) ----------[LIKES]----------> (pizza: Food)
                                               ^
        (Developers: Group) ------[LIKES]------┘

(Jim: Person) --[BELONGS_TO]--> (Business: Group) --[LIKES]--> (apple: Food)
</code>```

The example is accessible here in Neo4J console. The import script is here (in case you want to reproduce the issue locally) :

```<code>CREATE (john: Person{name: "John"});
CREATE (jim: Person{name: "Jim"});

CREATE (devs: Group{name: "Developers"});
CREATE (business: Group{name: "Business"});

CREATE (pizza: Food{name: "pizza"});
CREATE (apple: Food{name: "apple"});

MATCH (john: Person{name: "John"}), (pizza: Food{name: "pizza"})
CREATE (john)-[:LIKES]->(pizza);

MATCH (jim: Person{name: "Jim"}), (business: Group{name: "Business"})
CREATE (jim)-[:BELONGS_TO]->(business);

MATCH (devs: Group{name: "Developers"}), (pizza: Food{name: "pizza"})
CREATE (devs)-[:LIKES]->(pizza);

MATCH (business: Group{name: "Business"}), (apple: Food{name: "apple"})
CREATE (business)-[:LIKES]->(apple);
</code>```

For that particular example, my question is : how to retrieve all Person nodes who likes pizza? Knowing that :

A Person can like Food (direct relation)

A Group can like Food, and transitively if person A BELONGS_TO a group,
he LIKES also the food that the group LIKES (but there is no direct relation
between Person and Food in that case)

I'd also like to retrieve the pizza node once. As I said in introduction, in my real example, the retrieval of pizza could be quite complicated, so I don't want to duplicate the MATCH in each case.

What I've tried

Using UNION

```<code>MATCH (pizza: Food{name: "pizza"})
WITH pizza
MATCH (p: Person)-[:LIKES]->(pizza)
RETURN p
UNION
MATCH (p: Person)-[:BELONGS_TO]->(g: Group)-[:LIKES]->(pizza)
RETURN p
</code>```

This query returns surprinsingly 2 nodes : John and Jim. After investigating, I have understood that
this is because (pizza) in the 2nd UNION clause does not refer to the pizza node
returned by the first MATCH, but rather any node. We can confirm that by running :

```<code>MATCH (pizza: Food{name: "pizza"})
WITH pizza
MATCH (p: Person)-[:LIKES]->(pizza)
RETURN p
UNION
MATCH (p: Person)-[:BELONGS_TO]->(g: Group)-[:LIKES]->(anything)
WHERE anything = pizza
RETURN p
</code>```

This returns an error :

```<code>Neo.ClientError.Statement.SyntaxError: Variable `pizza` not defined (line 7, column 18 (offset: 184))
"WHERE anything = pizza"
</code>```

, validating the fact that pizza node is not propagated to the second MATCH.

Using WITH and COLLECT

This fixes the problem of the pizza node that cannot be passed from the first MATCH to the 3nd MATCH.

```<code>MATCH (pizza: Food{name: "pizza"})
WITH pizza
MATCH (p: Person)-[:LIKES]->(pizza)
WITH pizza, COLLECT(p) AS people
MATCH (p: Person)-[:BELONGS_TO]->(g: Group)-[:LIKES]->(pizza)
RETURN people + COLLECT(p) AS people
</code>```

But this query does not return anything : this is because the 3nd MATCH does not return anything
(there are no Person in a Group that LIKES pizza).

If I add a Person in the Developers Group :

```<code>MATCH (devs: Group{name: "Developers"})
CREATE (emma: Person{name: "Emma"})-[:BELONGS_TO]->(devs)
</code>```

The previous query returns successfully John and Emma because the last MATCH returns at least one Person.
But in my case, it is possible that this MATCH does not return anything, so that does not work.

I hope this example is simple and clear. In this case, the query I'm looking for should return only John, because he's the only Person here who likes pizza.

答:
As an alternate to cybersam's answer, if your graph structure is such that MATCH (p:Person)-[:BELONGS_TO|LIKES*..2]->(food:Food) won't work (for example if you're working on a graph where people can like each other, and you don't want to return a person who likes another person who likes pizza, which would adhere to your pattern), you can use a 0..1 length relationship to represent an optional step in the pattern:

```<code>MATCH (p:Person)-[:BELONGS_TO*0..1]->()-[:LIKES]->(food:Food)
WHERE food.name = "pizza"
RETURN COLLECT(p) AS people;
</code>```

This allows matching to both of these patterns at the same time:

(p:Person)-[:LIKES]->(food:Food)

and

(p:Person)-[:BELONGS_TO]->()-[:LIKES]->(food:Food)

I've written up a knowledge base article on this approach.

Body:
I am trying to write a Cypher query which is kind of a "union" query, basically something like :

MATCH (myNodeUsedInAllSubQueries)
WITH myNodeUsedInAllSubQueries
MATCH (a)-[...]->(myNodeUsedInAllSubQueries)
RETURN a
UNION
MATCH (b)-[...]->(myNodeUsedInAllSubQueries)
RETURN b
...

I want to match (myNodeUsedInAllSubQueries) once at the beginning because this node is used in all subqueries.
Of course, the retrieval of this node in my example is not just as simple as this (it involves relationships and a WHERE clause, but I'll keep it simple here).

I'll try to explain this with a simple example and what I've tried so far.

Example

Graphically, the graph structure is the following :

(John: Person) ----------[LIKES]----------> (pizza: Food)
                                               ^
        (Developers: Group) ------[LIKES]------┘

(Jim: Person) --[BELONGS_TO]--> (Business: Group) --[LIKES]--> (apple: Food)

The example is accessible here in Neo4J console. The import script is here (in case you want to reproduce the issue locally) :

CREATE (john: Person{name: "John"});
CREATE (jim: Person{name: "Jim"});

CREATE (devs: Group{name: "Developers"});
CREATE (business: Group{name: "Business"});

CREATE (pizza: Food{name: "pizza"});
CREATE (apple: Food{name: "apple"});

MATCH (john: Person{name: "John"}), (pizza: Food{name: "pizza"})
CREATE (john)-[:LIKES]->(pizza);

MATCH (jim: Person{name: "Jim"}), (business: Group{name: "Business"})
CREATE (jim)-[:BELONGS_TO]->(business);

MATCH (devs: Group{name: "Developers"}), (pizza: Food{name: "pizza"})
CREATE (devs)-[:LIKES]->(pizza);

MATCH (business: Group{name: "Business"}), (apple: Food{name: "apple"})
CREATE (business)-[:LIKES]->(apple);

For that particular example, my question is : how to retrieve all Person nodes who likes pizza? Knowing that :

A Person can like Food (direct relation)

A Group can like Food, and transitively if person A BELONGS_TO a group,
he LIKES also the food that the group LIKES (but there is no direct relation
between Person and Food in that case)

I'd also like to retrieve the pizza node once. As I said in introduction, in my real example, the retrieval of pizza could be quite complicated, so I don't want to duplicate the MATCH in each case.

What I've tried

Using UNION

MATCH (pizza: Food{name: "pizza"})
WITH pizza
MATCH (p: Person)-[:LIKES]->(pizza)
RETURN p
UNION
MATCH (p: Person)-[:BELONGS_TO]->(g: Group)-[:LIKES]->(pizza)
RETURN p

This query returns surprinsingly 2 nodes : John and Jim. After investigating, I have understood that
this is because (pizza) in the 2nd UNION clause does not refer to the pizza node
returned by the first MATCH, but rather any node. We can confirm that by running :

MATCH (pizza: Food{name: "pizza"})
WITH pizza
MATCH (p: Person)-[:LIKES]->(pizza)
RETURN p
UNION
MATCH (p: Person)-[:BELONGS_TO]->(g: Group)-[:LIKES]->(anything)
WHERE anything = pizza
RETURN p

This returns an error :

Neo.ClientError.Statement.SyntaxError: Variable `pizza` not defined (line 7, column 18 (offset: 184))
"WHERE anything = pizza"

, validating the fact that pizza node is not propagated to the second MATCH.

Using WITH and COLLECT

This fixes the problem of the pizza node that cannot be passed from the first MATCH to the 3nd MATCH.

MATCH (pizza: Food{name: "pizza"})
WITH pizza
MATCH (p: Person)-[:LIKES]->(pizza)
WITH pizza, COLLECT(p) AS people
MATCH (p: Person)-[:BELONGS_TO]->(g: Group)-[:LIKES]->(pizza)
RETURN people + COLLECT(p) AS people

But this query does not return anything : this is because the 3nd MATCH does not return anything
(there are no Person in a Group that LIKES pizza).

If I add a Person in the Developers Group :

MATCH (devs: Group{name: "Developers"})
CREATE (emma: Person{name: "Emma"})-[:BELONGS_TO]->(devs)

The previous query returns successfully John and Emma because the last MATCH returns at least one Person.
But in my case, it is possible that this MATCH does not return anything, so that does not work.

I hope this example is simple and clear. In this case, the query I'm looking for should return only John, because he's the only Person here who likes pizza.

Body:
As an alternate to cybersam's answer, if your graph structure is such that MATCH (p:Person)-[:BELONGS_TO|LIKES*..2]->(food:Food) won't work (for example if you're working on a graph where people can like each other, and you don't want to return a person who likes another person who likes pizza, which would adhere to your pattern), you can use a 0..1 length relationship to represent an optional step in the pattern:

MATCH (p:Person)-[:BELONGS_TO*0..1]->()-[:LIKES]->(food:Food)
WHERE food.name = "pizza"
RETURN COLLECT(p) AS people;

This allows matching to both of these patterns at the same time:

(p:Person)-[:LIKES]->(food:Food)

and

(p:Person)-[:BELONGS_TO]->()-[:LIKES]->(food:Food)

I've written up a knowledge base article on this approach.


问:
Is it possible to add custom CSS to a WebView in Xamarin using ONLY ONE stylesheet in my Assets folder?
I've seen multiple tutorials adding a GetBaseUrl separately for IOS and Android, but they don't answer my question. I was wondering if there is  no other way to add custom CSS to a webview and only use 1 stylesheet (default.css). The reason why I want to do this is because my stylesheet is identical for both IOS and Android and contains little styling.

This is what I've tried:
I have a WebView:

```<code> <WebView.Source >
        <HtmlWebViewSource Html="{Binding Data.Content}" />
    </WebView.Source>
</code>```

The Source of this WebView is a string that looks like this:

```<code>string  contentString =   @"<html>
                            <head>" +
                            "<link rel='stylesheet' href='default.css'"
                            "</head>" +
                            "<body style='text-align:left;background-color:white;font-size:16px;margin:0;'>" +
                            value +
                            "</body>" +
                            "</html>";
</code>```

The default.css  file mentioned above is in my Assets folder and has Build Action EmbeddedResource, located in the root directory of my project:

Can anyone help? Thanks in advance.

答:
There are some ways to do this, one is to use HtmlWebViewSource, the html is like this:

```<code>htmlSource.Html = @"<html>
<head>
<link rel=""stylesheet"" href=""default.css"">
</head>
<body>
<h1>Xamarin.Forms</h1>
<p>The CSS and image are loaded from local files!</p>
<img src='XamarinLogo.png'/>
<p><a href=""local.html"">next page</a></p>
</body>
</html>";
</code>```

Another way is to use WebView.loadDataWithBaseURL, there is the same thread that you can take a look:

Rendering HTML in a WebView with custom CSS

Body:
I've seen multiple tutorials adding a GetBaseUrl separately for IOS and Android, but they don't answer my question. I was wondering if there is  no other way to add custom CSS to a webview and only use 1 stylesheet (default.css). The reason why I want to do this is because my stylesheet is identical for both IOS and Android and contains little styling.

This is what I've tried:
I have a WebView:

 <WebView.Source >
        <HtmlWebViewSource Html="{Binding Data.Content}" />
    </WebView.Source>

The Source of this WebView is a string that looks like this:

string  contentString =   @"
                            " +
                            "<link rel='stylesheet' href='default.css'"
                            "" +
                            "" +
                            value +
                            "" +
                            "";

The default.css  file mentioned above is in my Assets folder and has Build Action EmbeddedResource, located in the root directory of my project:

Can anyone help? Thanks in advance.

Body:
There are some ways to do this, one is to use HtmlWebViewSource, the html is like this:

htmlSource.Html = @"<html>
<head>
<link rel=""stylesheet"" href=""default.css"">
</head>
<body>
<h1>Xamarin.Forms</h1>
<p>The CSS and image are loaded from local files!</p>
<img src='XamarinLogo.png'/>
<p><a href=""local.html"">next page</a></p>
</body>
</html>";

Another way is to use WebView.loadDataWithBaseURL, there is the same thread that you can take a look:

Rendering HTML in a WebView with custom CSS


问:
127.0.0.1 refused to connect in docker django
I'm trying to connect to an instance of django running in docker.  As far as i can tell I've opened the correct port, and see in docker ps that there is tcp on port 8000, but it there is no forwarding to the port.

After reading the docker compose docs on ports, i would expect this to work (I can view pgadmin on 127.0.0.1:9000 too).

My docker compose:

```<code>version: '3'

services:
  postgresql:
    restart: always
    image: postgres:latest
    environment:
      POSTGRES_USER: pguser
      POSTGRES_PASSWORD: pgpassword
      POSTGRES_DB: pgdb

  pgadmin:
    restart: always
    image: dpage/pgadmin4:latest
    environment:
      PGADMIN_DEFAULT_EMAIL: admin@admin.com
      PGADMIN_DEFAULT_PASSWORD: admin
      GUNICORN_THREADS: 4
      PGADMIN_LISTEN_PORT: 9000
    volumes:
      - ./utility/pgadmin4-servers.json:/pgadmin4/servers.json
    depends_on:
      - postgresql
    ports:
      - "9000:9000"

  app:
    build: .
    environment:
      POSTGRES_DB: pgdb
      POSTGRES_USER: pguser
      POSTGRES_PASSWORD: pgpassword
      POSTGRES_HOST: postgresql
    volumes:
      - .:/code
    ports:
      - "127.0.0.1:8000:8000"
      - "5555:5555"
    depends_on:
      - postgresql
      - pgadmin
</code>```

I have tried with the following combinations for (app) ports, as are suggested here:

```<code>app:
  ...
  ports:
    - "8000"
    - "8000:8000"
    - "127.0.0.1:8000:8000"
</code>```

but i still see This site can’t be reached 127.0.0.1 refused to connect. on trying to access the site.

I'm sure that this is a port forwarding problem, and that my server is turning correctly in django because i can run a docker attach to the container and curl a url with the expected response.

What am i doing wrong?

答: If you are running docker inside a virtual machine then you need to access your application through the  virtual machine IP address and not using localhost or 127.0.0.1. Try to get the virtual machine IP. Also please specify in which platform/environment you installed and running the docker.

Body:
I'm trying to connect to an instance of django running in docker.  As far as i can tell I've opened the correct port, and see in docker ps that there is tcp on port 8000, but it there is no forwarding to the port.

After reading the docker compose docs on ports, i would expect this to work (I can view pgadmin on 127.0.0.1:9000 too).

My docker compose:

version: '3'

services:
  postgresql:
    restart: always
    image: postgres:latest
    environment:
      POSTGRES_USER: pguser
      POSTGRES_PASSWORD: pgpassword
      POSTGRES_DB: pgdb

  pgadmin:
    restart: always
    image: dpage/pgadmin4:latest
    environment:
      PGADMIN_DEFAULT_EMAIL: admin@admin.com
      PGADMIN_DEFAULT_PASSWORD: admin
      GUNICORN_THREADS: 4
      PGADMIN_LISTEN_PORT: 9000
    volumes:
      - ./utility/pgadmin4-servers.json:/pgadmin4/servers.json
    depends_on:
      - postgresql
    ports:
      - "9000:9000"

  app:
    build: .
    environment:
      POSTGRES_DB: pgdb
      POSTGRES_USER: pguser
      POSTGRES_PASSWORD: pgpassword
      POSTGRES_HOST: postgresql
    volumes:
      - .:/code
    ports:
      - "127.0.0.1:8000:8000"
      - "5555:5555"
    depends_on:
      - postgresql
      - pgadmin

I have tried with the following combinations for (app) ports, as are suggested here:

app:
  ...
  ports:
    - "8000"
    - "8000:8000"
    - "127.0.0.1:8000:8000"

but i still see This site can’t be reached 127.0.0.1 refused to connect. on trying to access the site.

I'm sure that this is a port forwarding problem, and that my server is turning correctly in django because i can run a docker attach to the container and curl a url with the expected response.

What am i doing wrong?


问:
Algorithm for finding a formula that connects inputs and outputs
I seem to recall having learned a method for finding the formula that connects inputs and outputs from a table. For example:

```<code>a b c | r
1 1 0 | 0
0 1 1 | 1
1 1 1 | 1
</code>```

where "r" is the result, and a, b and c are the inputs. The method involved equations with many unknowns and ended up with a formula that explained it all. (This is an example that is not that meaningful, since r = c, but you get the idea).

However, I can not remember the details, and not enough keywords to be able to find it on the web. The subject teaching this method also included a lot of boolean algebra.

I know this is a vague question, but what could this method for finding the formula from a table of values be?

答: Are you referring to Karnaugh maps?</p>

Body:
I seem to recall having learned a method for finding the formula that connects inputs and outputs from a table. For example:

a b c | r
1 1 0 | 0
0 1 1 | 1
1 1 1 | 1

where "r" is the result, and a, b and c are the inputs. The method involved equations with many unknowns and ended up with a formula that explained it all. (This is an example that is not that meaningful, since r = c, but you get the idea).

However, I can not remember the details, and not enough keywords to be able to find it on the web. The subject teaching this method also included a lot of boolean algebra.

I know this is a vague question, but what could this method for finding the formula from a table of values be?

Body: Are you referring to Karnaugh maps?


问:
When finding the prime factors of a number some numbers work but others dont
When testing numbers some work for example 48, but others don't. I'm not sure what the best way to approach finding all the factors of a number.

Prime Factorization

```<code>def find_primes(n):
    factors = []
    i = 2
    if n == 0:
        return 0
    if n == 1:
        return 1
    if n >= 2:
        while n % i == 0:
            next_n = n / i
            factors.append(i)
            n = next_n
            if n % i != 0:
                i += 1
                continue
            elif i == n:
                break
    if len(factors) == 0:
        return "{} is a prime number.\n".format(initial_n)
    else:
        return "The prime factors of {} are: {}\n".format(initial_n, factors)

n = int(input("Enter a number to find all the Prime Factors:"))
initial_n = n
print('\n')
print(find_primes(n))
</code>```

I am expecting to get a list of all the factors of a number.

答:
The function to calculate the prime factors below is much simpler than the one above. The rest is just sanity checking of user input.</p>

```<code>###########################################################
#Main function to calculate prime factors
def find_prime_factors(n):
    factors = []
    p = 2
    while n > p ** 2:
        if n % p == 0:
            factors.append(p)
            n //= p
        else:
            p += 1
    factors.append(n)
    return factors
###########################################################

# Get User input
n = input('Enter a number to find all the Prime Factors: ')

# Check if the entered value is a number
while not n.isnumeric():
    print('Entered number was not numeric.')
    n = input('Enter a NUMBER to find all the Prime Factors: ')

# Check the entered value is greater than one (1)
# Prime Factor check happens on only positive numbers that are greater than one (1)

while int(n) < 2:
    print("Please enter a positive number that is greater than one (1).")
    n = input('Enter a NUMBER to find all the Prime Factors: ')

#Python 3.7 string formating
print(f'The prime factor(s) of {n}: {find_prime_factors(int(n))} ')
</code>```

Body:
When testing numbers some work for example 48, but others don't. I'm not sure what the best way to approach finding all the factors of a number.

Prime Factorization

def find_primes(n):
    factors = []
    i = 2
    if n == 0:
        return 0
    if n == 1:
        return 1
    if n >= 2:
        while n % i == 0:
            next_n = n / i
            factors.append(i)
            n = next_n
            if n % i != 0:
                i += 1
                continue
            elif i == n:
                break
    if len(factors) == 0:
        return "{} is a prime number.\n".format(initial_n)
    else:
        return "The prime factors of {} are: {}\n".format(initial_n, factors)

n = int(input("Enter a number to find all the Prime Factors:"))
initial_n = n
print('\n')
print(find_primes(n))

I am expecting to get a list of all the factors of a number.

Body:
The function to calculate the prime factors below is much simpler than the one above. The rest is just sanity checking of user input.

###########################################################
#Main function to calculate prime factors
def find_prime_factors(n):
    factors = []
    p = 2
    while n > p ** 2:
        if n % p == 0:
            factors.append(p)
            n //= p
        else:
            p += 1
    factors.append(n)
    return factors
###########################################################

# Get User input
n = input('Enter a number to find all the Prime Factors: ')

# Check if the entered value is a number
while not n.isnumeric():
    print('Entered number was not numeric.')
    n = input('Enter a NUMBER to find all the Prime Factors: ')

# Check the entered value is greater than one (1)
# Prime Factor check happens on only positive numbers that are greater than one (1)

while int(n) < 2:
    print("Please enter a positive number that is greater than one (1).")
    n = input('Enter a NUMBER to find all the Prime Factors: ')

#Python 3.7 string formating
print(f'The prime factor(s) of {n}: {find_prime_factors(int(n))} ')


问:
JSONPath - Get full JSON (as is) using expression
Can I get the full JSON string using JSONPath?

I failed using different combinations $ * $..* $*

$ The root element to query. This starts all path expressions.

* Wildcard. Available anywhere a name or numeric are required.

I'm using JMeter's JSON Extractor and sometimes I need to retrieve all/full response using JSONPath expression

EDIT

Same results with $[*] as @Daniel suggested

答:
Try

```<code>$[*]
</code>```

Although $.* (and $..*) should work too. All work with Jayway and Goessner.

Daniel

Body:
Try

$[*]

Although $.* (and $..*) should work too. All work with Jayway and Goessner.

Daniel


问:
How to remove the "Input Methods" menu from my context menu
I'm developing a RCP application at Centos7, and GTK version is gtk3-3.22.30-3.el7.x86_64.

but there is a sub menu "Input Methods" appeared in all content menu.
SubMenu.png

How can I remove this sub menu.

答:
Finally, my colleague given me an answer.

There is a internal static String variable in org.eclipse.swt.widgets.Composite named NO_INPUT_METHOD, all we need to do is just set this val not be null by display.setData("org.eclipse.swt.internal.gtk.noInputMethod", true);, then everything is OK!


问:
C# foreach iterating rule for collections
How .NET decides for order of items when iterating through collections ?

For example:

```<code>list<string> myList = new List<string>();

myList.Add("a");
myList.Add("b");
myList.Add("c");

foreach (string item in myList)
{
    // What's the order of items? a -> b -> c ?
}
</code>```

I need this order (accessing collection members):

```<code>for (int i = 1; i < myList.Count; i++)
{
    string item = myList[i - 1]; // This is the order I need
}
</code>```

Can I safely use foreach with List? What about other types of collections?

答:
Don't worry, use foreach.</p>

```
list myList = new List();

myList.Add("a");
myList.Add("b");
myList.Add("c");

foreach (string item in myList)
{
    // It's in right order! a -> b -> c !
}
```

Body:
How .NET decides for order of items when iterating through collections ?

For example:

list<string> myList = new List<string>();

myList.Add("a");
myList.Add("b");
myList.Add("c");

foreach (string item in myList)
{
    // What's the order of items? a -> b -> c ?
}

I need this order (accessing collection members):

for (int i = 1; i < myList.Count; i++)
{
    string item = myList[i - 1]; // This is the order I need
}

Can I safely use foreach with List? What about other types of collections?

Body:
Don't worry, use foreach.

list myList = new List();

myList.Add("a");
myList.Add("b");
myList.Add("c");

foreach (string item in myList)
{
    // It's in right order! a -> b -> c !
}


问:
Re-naming chart legend in Access 2007
In an auto-generated chart based on a query (I dragged the chart object onto a blank form to start it), the chart itself is displaying and updating properly, datawise, but I want to change the Legend from reading "SumOfAvgOfield1" and "SumOfAvgOfield2" to regular words suitable for final presentations. But I can't find a way to change it!</p>

答:
This could help

Select xxxxx, yyyyy from zzzz

Chart0.ChartSeriesCollection(0).DisplayName = ![XXXXX]
Chart0.ChartSeriesCollection(1).DisplayName = ![YYYYY]

Was very difficult to me to find a way to do it.

Title: Re-naming chart legend in Access 2007


问:
Solve equation using optim()
I have 2 equation that need to be solved by using optim

```<code>{(4x^2-20x+1/4 y^2+8=0
  1/2 xy^2+2x-5y+8=0)
</code>```

I have already run the code,but I'm confused if there should be 1 answer or 2 because function will only return the results for the last line

Should I do like this

```<code>> myfunc=function(x){
+  4*x[1]^2-20*x[1]+(x[2]^2/4)+8
+  }
> optim(c(0,0),myfunc,method="BFGS")
</code>```

and

```<code>>  myfunc=function(x){
+  (1/2)*(x[1]*x[2]^2)+2*x[1]-5*x[2]+8
+  }
> optim(c(0,0),myfunc,method="BFGS")
</code>```

or should I do like this

```<code>> myfunc=function(x){
+  4*x[1]^2-20*x[1]+(x[2]^2/4)+8
+  (1/2)*(x[1]*x[2]^2)+2*x[1]-5*x[2]+8
+  }
> optim(c(0,0),myfunc,method="BFGS")
</code>```

For the second one it still give me only the answer for the second function so which method is correct.

答:
Minimize the sum of the squares of the two expressions that should equal zero and ensure that the value at the optimum equals 0 (up to floating point approximation).

```<code>myfunc <- function(z) {
  x <- z[1]
  y <- z[2]
  (4*x^2-20* x + 1/4*y^2 + 8)^2 + (1/2 * x*y^2 + 2*x- 5*y + 8)^2
}
optim(c(0, 0), myfunc)
</code>```

giving:

```<code>$par
[1] 0.5000553 2.0002986

$value
[1] 1.291233e-06

$counts
function gradient
      67       NA

$convergence
[1] 0

$message
NULL
</code>```

Title: Solve equation using optim()

Body:
I have 2 equation that need to be solved by using optim

{(4x^2-20x+1/4 y^2+8=0
  1/2 xy^2+2x-5y+8=0)

I have already run the code,but I'm confused if there should be 1 answer or 2 because function will only return the results for the last line

Should I do like this

> myfunc=function(x){
+  4*x[1]^2-20*x[1]+(x[2]^2/4)+8
+  }
> optim(c(0,0),myfunc,method="BFGS")

and

>  myfunc=function(x){
+  (1/2)*(x[1]*x[2]^2)+2*x[1]-5*x[2]+8
+  }
> optim(c(0,0),myfunc,method="BFGS")

or should I do like this

> myfunc=function(x){
+  4*x[1]^2-20*x[1]+(x[2]^2/4)+8
+  (1/2)*(x[1]*x[2]^2)+2*x[1]-5*x[2]+8
+  }
> optim(c(0,0),myfunc,method="BFGS")

For the second one it still give me only the answer for the second function so which method is correct.

Body:
Minimize the sum of the squares of the two expressions that should equal zero and ensure that the value at the optimum equals 0 (up to floating point approximation).

myfunc <- function(z) {
  x <- z[1]
  y <- z[2]
  (4*x^2-20* x + 1/4*y^2 + 8)^2 + (1/2 * x*y^2 + 2*x- 5*y + 8)^2
}
optim(c(0, 0), myfunc)

giving:

$par
[1] 0.5000553 2.0002986

$value
[1] 1.291233e-06

$counts
function gradient
      67       NA

$convergence
[1] 0

$message
NULL


问:
Common parent view in Swift
Given an arbitrary set of 2 or more views (UIView), I want to determine what is the (closest) common parent for those views. What is the most efficient algorithm for this in Swift?

Based on these hierarchies:

```<code>                    ┌─────┐
                    │  A  │
                    └─────┘
                       ▲
          ┌────────────┴────────────┐
          │                         │
       ┌─────┐                   ┌─────┐                ┌─────┐
       │  B  │                   │  C  │                │  X  │
       └─────┘                   └─────┘                └─────┘
          ▲                         ▲                      ▲
   ┌──────┴──────┐           ┌──────┴──────┐               │
   │             │           │             │               │
┌─────┐       ┌─────┐     ┌─────┐       ┌─────┐         ┌─────┐       ┌─────┐
│  D  │       │  E  │     │  F  │       │  G  │         │  Y  │       │  Z  │
└─────┘       └─────┘     └─────┘       └─────┘         └─────┘       └─────┘
</code>```

If no views provided, return nil.

If 1 view provided, return superview or nil.

If any view does not have a superview (e.g. "A", "X" or "Z"), return nil.

If views do not belong to the same hierarchy (e.g. "A" or "X" hierarchy), return nil.

Examples:

```<code>// no views
[].commonParent()      // nil
// 1 view
[D].commonParent()     // B
// siblings
[D,E].commonParent()   // B
// child/parent
[D,B].commonParent()   // A
// cousins
[D,F].commonParent()   // A
// > 2 views
[D,E,F].commonParent() // A
// with root view
[D,A].commonParent()   // nil
// unrelated hierarchies
[D,Y].commonParent()   // nil
// unrelated view
[D,Z].commonParent()   // nil
</code>```

答:
I realize this is old, but I heard about this interview question and did some searching to see how it's set up, and found this. For those that come here after me, I feel it's important to let you know the current solution is not efficient, O(n^2). You will not pass a tech interview with that. I did it here in objective-c, but it should be straight forward to anyone doing Swift. The idea is to use memoization to keep you from having to search 'n' elements 'm' times, resulting in a O(n). Happy hunting!

```<code>- (UIView *)commonParentIn:(UIView *)v1 view:(UIView *)v2 {
    // key all parent views of one view
    NSMutableSet *parentSet = [[NSMutableSet alloc] init];
    while (v2) {
        [parentSet addObject:v2];
        v2 = [v2 superview];
    }

    // search for all parent views of other view in set and return first found
    while (v1) {
        if ([parentSet containsObject:v1]) {
            return v1;
        }
        v1 = [v1 superview];
    }

    return nil;
}
</code>```

Here's some test code:

```<code>UIView *v1 = [[UIView alloc] init];
UIView *v2 = [[UIView alloc] init];
UIView *v3 = [[UIView alloc] init];
UIView *v4 = [[UIView alloc] init];
UIView *v5 = [[UIView alloc] init];
UIView *v6 = [[UIView alloc] init];
UIView *v7 = [[UIView alloc] init];
UIView *v8 = [[UIView alloc] init];
UIView *v9 = [[UIView alloc] init];
UIView *v10 = [[UIView alloc] init];
UIView *v11 = [[UIView alloc] init];
UIView *singleParent = [[UIView alloc] init];
UIView *onlyChild = [[UIView alloc] init];

[v1 addSubview:v2];
[v1 addSubview:v3];
[v1 addSubview:v4];
[v2 addSubview:v5];
[v2 addSubview:v9];
[v5 addSubview:v6];
[v5 addSubview:v10];
[v10 addSubview:v11];
[v4 addSubview:v7];
[v4 addSubview:v8];
[singleParent addSubview:onlyChild];

UIView *found = [self commonParentIn:v11 view:onlyChild];
</code>```

It helps to draw a tree of the views, that way you know when and where they should have a shared parent view. Then, just change the passed in views for testing.

Title: Common parent view in Swift

Body:
Given an arbitrary set of 2 or more views (UIView), I want to determine what is the (closest) common parent for those views. What is the most efficient algorithm for this in Swift?

Based on these hierarchies:

                    ┌─────┐
                    │  A  │
                    └─────┘
                       ▲
          ┌────────────┴────────────┐
          │                         │
       ┌─────┐                   ┌─────┐                ┌─────┐
       │  B  │                   │  C  │                │  X  │
       └─────┘                   └─────┘                └─────┘
          ▲                         ▲                      ▲
   ┌──────┴──────┐           ┌──────┴──────┐               │
   │             │           │             │               │
┌─────┐       ┌─────┐     ┌─────┐       ┌─────┐         ┌─────┐       ┌─────┐
│  D  │       │  E  │     │  F  │       │  G  │         │  Y  │       │  Z  │
└─────┘       └─────┘     └─────┘       └─────┘         └─────┘       └─────┘

If no views provided, return nil.

If 1 view provided, return superview or nil.

If any view does not have a superview (e.g. "A", "X" or "Z"), return nil.

If views do not belong to the same hierarchy (e.g. "A" or "X" hierarchy), return nil.

Examples:

// no views
[].commonParent()      // nil
// 1 view
[D].commonParent()     // B
// siblings
[D,E].commonParent()   // B
// child/parent
[D,B].commonParent()   // A
// cousins
[D,F].commonParent()   // A
// > 2 views
[D,E,F].commonParent() // A
// with root view
[D,A].commonParent()   // nil
// unrelated hierarchies
[D,Y].commonParent()   // nil
// unrelated view
[D,Z].commonParent()   // nil

Body:
I realize this is old, but I heard about this interview question and did some searching to see how it's set up, and found this. For those that come here after me, I feel it's important to let you know the current solution is not efficient, O(n^2). You will not pass a tech interview with that. I did it here in objective-c, but it should be straight forward to anyone doing Swift. The idea is to use memoization to keep you from having to search 'n' elements 'm' times, resulting in a O(n). Happy hunting!

- (UIView *)commonParentIn:(UIView *)v1 view:(UIView *)v2 {
    // key all parent views of one view
    NSMutableSet *parentSet = [[NSMutableSet alloc] init];
    while (v2) {
        [parentSet addObject:v2];
        v2 = [v2 superview];
    }

    // search for all parent views of other view in set and return first found
    while (v1) {
        if ([parentSet containsObject:v1]) {
            return v1;
        }
        v1 = [v1 superview];
    }

    return nil;
}

Here's some test code:

UIView *v1 = [[UIView alloc] init];
UIView *v2 = [[UIView alloc] init];
UIView *v3 = [[UIView alloc] init];
UIView *v4 = [[UIView alloc] init];
UIView *v5 = [[UIView alloc] init];
UIView *v6 = [[UIView alloc] init];
UIView *v7 = [[UIView alloc] init];
UIView *v8 = [[UIView alloc] init];
UIView *v9 = [[UIView alloc] init];
UIView *v10 = [[UIView alloc] init];
UIView *v11 = [[UIView alloc] init];
UIView *singleParent = [[UIView alloc] init];
UIView *onlyChild = [[UIView alloc] init];

[v1 addSubview:v2];
[v1 addSubview:v3];
[v1 addSubview:v4];
[v2 addSubview:v5];
[v2 addSubview:v9];
[v5 addSubview:v6];
[v5 addSubview:v10];
[v10 addSubview:v11];
[v4 addSubview:v7];
[v4 addSubview:v8];
[singleParent addSubview:onlyChild];

UIView *found = [self commonParentIn:v11 view:onlyChild];

It helps to draw a tree of the views, that way you know when and where they should have a shared parent view. Then, just change the passed in views for testing.


问:
How to get lines from the last match to the end of file?
Need to print lines after the last match to the end of file. The number of matches could be anything and not definite. I have some text as shown below.

```<code>MARKER
aaa
bbb
ccc
MARKER
ddd
eee
fff
MARKER
ggg
hhh
iii
MARKER
jjj
kkk
lll
</code>```

Output desired is

```<code>jjj
kkk
lll
</code>```

Do I use awk with RS and FS to get the desired output?

答:
You can actually do it with awk (gawk) without using any pipe.

```<code>$ awk -v RS='(^|\n)MARKER\n' 'END{printf "%s", $0}' file
jjj
kkk
lll
</code>```

Explanations:

You define your record separator as (^|\n)MARKER\n via RS='(^|\n)MARKER\n', by default it is the EOL char

'END{printf "%s", $0}' => at the end of the file, you print the whole line, as RS is set at (^|\n)MARKER\n, $0 will include all the lines until EOF.

Another option is to use grep (GNU):

```<code>$ grep -zoP '(?<=MARKER\n)(?:(?!MARKER)[^\0])+\Z' file
jjj
kkk
lll
</code>```

Explanations:

-z to use the ASCII NUL character as delimiter

-o to print only the matching

-P to activate the perl mode

PCRE regex: (?<=MARKER\n)(?:(?!MARKER)[^\0])+\Z explained here https://regex101.com/r/RpQBUV/2/

Last but not least, the following sed approach can also been used:

```<code>sed -n '/^MARKER$/{n;h;b};H;${x;p}' file
jjj
kkk
lll
</code>```

Explanations:

n jump to next line

h replace the hold space with the current line

H do the same but instead of replacing, append

${x;p} at the end of the file exchange (x) hold space and pattern space and print (p)

that can be turned into:

```<code>tac file |  sed -n '/^MARKER$/q;p' | tac
</code>```

if we use tac.

Body:
Need to print lines after the last match to the end of file. The number of matches could be anything and not definite. I have some text as shown below.

MARKER
aaa
bbb
ccc
MARKER
ddd
eee
fff
MARKER
ggg
hhh
iii
MARKER
jjj
kkk
lll

Output desired is

jjj
kkk
lll

Do I use awk with RS and FS to get the desired output?

Body:
You can actually do it with awk (gawk) without using any pipe.

$ awk -v RS='(^|\n)MARKER\n' 'END{printf "%s", $0}' file
jjj
kkk
lll

Explanations:

You define your record separator as (^|\n)MARKER\n via RS='(^|\n)MARKER\n', by default it is the EOL char

'END{printf "%s", $0}' => at the end of the file, you print the whole line, as RS is set at (^|\n)MARKER\n, $0 will include all the lines until EOF.

Another option is to use grep (GNU):

$ grep -zoP '(?<=MARKER\n)(?:(?!MARKER)[^\0])+\Z' file
jjj
kkk
lll

Explanations:

-z to use the ASCII NUL character as delimiter

-o to print only the matching

-P to activate the perl mode

PCRE regex: (?<=MARKER\n)(?:(?!MARKER)[^\0])+\Z explained here https://regex101.com/r/RpQBUV/2/

Last but not least, the following sed approach can also been used:

sed -n '/^MARKER$/{n;h;b};H;${x;p}' file
jjj
kkk
lll

Explanations:

n jump to next line

h replace the hold space with the current line

H do the same but instead of replacing, append

${x;p} at the end of the file exchange (x) hold space and pattern space and print (p)

that can be turned into:

tac file |  sed -n '/^MARKER$/q;p' | tac

if we use tac.


问:
Implementing Single Responsibility Principle (SRP) in Class
I'd like to re-factor Cache class so it does not violate Single Responsibility Principle (SRP).

However, I'm having a tough time figuring out how I can re-factor unnecessary steps in Cache class into memoize function. Ideally I would have two methods in the Cache class get and set

```<code>function isObject(arg) {
  const typeOfObj = typeof arg;
  return (typeOfObj === 'object' || typeOfObj === 'function') && arg !== null;
}

class Cache {
  constructor() {
    this.map = new Map();
    this.weakmap = new WeakMap();
  }

  // create or retrieve a nested Cache instance based on an arguments object
  get(args) {
    let cache = this;

    for (const key of args) {
      const map = cache[isObject(key) ? 'weakmap' : 'map'];
      cache = map.get(key) || map.set(key, new Cache()).get(key);
    }

    return cache;
  }
}

function memoize(fn) {
  const cache = new Cache();

  return (...args) => {
    // get (or create) a cache item

    const item = cache.get(args);
    if (Reflect.has(item, 'value')) {
      return item.value;
    }
    return (item.value = fn(args));
  };
}

let counter = 1;
function foo() {
  counter += 1;
  return counter;
}

const id1 = Symbol('id');
const id2 = Symbol('id');
const obj1 = { a: 1 };
const obj2 = { a: 1 };

const memoizedFoo = memoize(foo);
console.log(memoizedFoo(id1)); // 2
console.log(memoizedFoo(id1)); // 2
console.log(memoizedFoo(id2)); // 3
console.log(memoizedFoo(id2)); // 3
console.log(memoizedFoo(obj1)); // 4
console.log(memoizedFoo(obj1)); // 4
console.log(memoizedFoo(obj2)); // 5
console.log(memoizedFoo(obj2)); // 5
console.log(memoizedFoo(5)); // 6
console.log(memoizedFoo(5)); // 6
console.log(memoizedFoo(4)); // 7
console.log(memoizedFoo(4)); // 7
</code>```

答:
One option is to have 3 methods on a NestedCache class:

getNestedMap, to iterate through the maps, given an array of keys

getMap, to get the value at a key in a particular Map

setKeyIfNeeded, to set the value at a key for a Map, if it doesn't exist yet

You can use reduce to iterate through the array of keys instead of continually reassigning the cache variable, to be a bit more functional, if you want.

function isObject(arg) {
  const typeOfObj = typeof arg;
  return (typeOfObj === 'object' || typeOfObj === 'function') && arg !== null;
}

class NestedCache {
  constructor() {
    this.map = new Map();
    this.weakmap = new WeakMap();
  }

  // retrieve a nested Cache instance based on an array of keys
  getNestedMap(keys) {
    return keys.reduce((cache, key) => cache.getMap(key), this);
  }
  // return a Cache's value at a key
  getMap(key) {
    const map = this[isObject(key) ? 'weakmap' : 'map'];
    this.setKeyIfNeeded(map, key);
    return map.get(key);
  }
  // create a Cache's key, if needed
  setKeyIfNeeded(map, key) {
    if (!map.has(key)) {
      map.set(key, new NestedCache());
    }
  }
}

function memoize(fn) {
  const cache = new NestedCache();

  return (...args) => {
    // get (or create) a cache item
    const item = cache.getNestedMap(args);
    if (Reflect.has(item, 'value')) {
      return item.value;
    }
    return (item.value = fn(args));
  };
}

let counter = 1;
function foo() {
  counter += 1;
  return counter;
}

const id1 = Symbol('id');
const id2 = Symbol('id');
const obj1 = { a: 1 };
const obj2 = { a: 1 };

const memoizedFoo = memoize(foo);
console.log(memoizedFoo(id1)); // 2
console.log(memoizedFoo(id1)); // 2
console.log(memoizedFoo(id2)); // 3
console.log(memoizedFoo(id2)); // 3
console.log(memoizedFoo(obj1)); // 4
console.log(memoizedFoo(obj1)); // 4
console.log(memoizedFoo(obj2)); // 5
console.log(memoizedFoo(obj2)); // 5
console.log(memoizedFoo(5)); // 6
console.log(memoizedFoo(5)); // 6
console.log(memoizedFoo(4)); // 7
console.log(memoizedFoo(4)); // 7```

Body:
I'd like to re-factor Cache class so it does not violate Single Responsibility Principle (SRP).

However, I'm having a tough time figuring out how I can re-factor unnecessary steps in Cache class into memoize function. Ideally I would have two methods in the Cache class get and set

function isObject(arg) {
  const typeOfObj = typeof arg;
  return (typeOfObj === 'object' || typeOfObj === 'function') && arg !== null;
}

class Cache {
  constructor() {
    this.map = new Map();
    this.weakmap = new WeakMap();
  }

  // create or retrieve a nested Cache instance based on an arguments object
  get(args) {
    let cache = this;

    for (const key of args) {
      const map = cache[isObject(key) ? 'weakmap' : 'map'];
      cache = map.get(key) || map.set(key, new Cache()).get(key);
    }

    return cache;
  }
}

function memoize(fn) {
  const cache = new Cache();

  return (...args) => {
    // get (or create) a cache item

    const item = cache.get(args);
    if (Reflect.has(item, 'value')) {
      return item.value;
    }
    return (item.value = fn(args));
  };
}

let counter = 1;
function foo() {
  counter += 1;
  return counter;
}

const id1 = Symbol('id');
const id2 = Symbol('id');
const obj1 = { a: 1 };
const obj2 = { a: 1 };

const memoizedFoo = memoize(foo);
console.log(memoizedFoo(id1)); // 2
console.log(memoizedFoo(id1)); // 2
console.log(memoizedFoo(id2)); // 3
console.log(memoizedFoo(id2)); // 3
console.log(memoizedFoo(obj1)); // 4
console.log(memoizedFoo(obj1)); // 4
console.log(memoizedFoo(obj2)); // 5
console.log(memoizedFoo(obj2)); // 5
console.log(memoizedFoo(5)); // 6
console.log(memoizedFoo(5)); // 6
console.log(memoizedFoo(4)); // 7
console.log(memoizedFoo(4)); // 7


问:
Eclipse RCP - remove context menu entry 'Input Methods'
I have a Eclipse RCP app. The main editor a a GMF diagram. When I do a right click on the diagram, I get a context menu that has a entry 'Input Methods'. This entry itself has sub-menu-entries.

I need to remove that 'Input Methods' menu entry. Does anyone know how to do that?
I can't find the id of that entry.

(Update: It turned out that this context menu entry only appears on linux (tested with Ubuntu 10.04). It does not appear under Windows XP and MacOs (not sure of the version))

答:
There is a internal setting "org.eclipse.swt.widgets.composite.NO_INPUT_METHOD" can control.
You can set it after display created.</p>

```<code>display.setData("org.eclipse.swt.internal.gtk.noInputMethod",true);
</code>```

Body:
There is a internal setting "org.eclipse.swt.widgets.composite.NO_INPUT_METHOD" can control.
You can set it after display created.

display.setData("org.eclipse.swt.internal.gtk.noInputMethod",true);


问:
How to setup 2 android emulators in android studio to test react native app
I added one more android emulator for react native 0.59 app test. I am able to launch 2 emulators. The adb devices command has the following output:

```<code>List of devices attached
emulator-5554   device
emulator-5556   device
</code>```

When there is one emulator, I use on cmd terminal to do react-native run-android and another one to do react-native log-android. The backend server is running on the same PC. Here is the virtual devices in android studio:

What I would like to do is to launch 2 app representing 2 users connecting to the backend at the same time for testing. I tried to launched one app when 2 emulators are running and the loading of the app is extremely slow. It seems that the 2 app need to be launched on 2 different ports and the solutions I found online seems not working here. Also react-native log-android throws error when encountering 2 emulators.

答:
Try running the metro-bundler at 2 different ports. Open up one terminal in you project root and use the default command as below,

react-native start

This starts one server at port 8081 default.

And in another terminal run

react-native start --port=9090

This starts another server at port 9090

Now in a third terminal run

react-native run-android

This will compile and start the apps in both your running emulators at default port.

When the apps start up properly, select one emulator and open up the dev menu using Ctrl+M.

Click Dev Settings button at the bottom.

Click Debug server host & port for device button.

Type localhost:9090 or ip_address:9090 and click OK button

Reload the app and it will fetch the js bundle from your react-native server running at 9090 port

Body:
I added one more android emulator for react native 0.59 app test. I am able to launch 2 emulators. The adb devices command has the following output:

List of devices attached
emulator-5554   device
emulator-5556   device

When there is one emulator, I use on cmd terminal to do react-native run-android and another one to do react-native log-android. The backend server is running on the same PC. Here is the virtual devices in android studio:

What I would like to do is to launch 2 app representing 2 users connecting to the backend at the same time for testing. I tried to launched one app when 2 emulators are running and the loading of the app is extremely slow. It seems that the 2 app need to be launched on 2 different ports and the solutions I found online seems not working here. Also react-native log-android throws error when encountering 2 emulators.


问:
Text Selection Title Bugs
I'm not sure what's causing this, it is nowhere else in my app except when i select text from an Alert Dialog...

Usually the Select Text Title  looks normal but this happens from using EditText inside Alert Dialog.

Here's the normal Text Select

Any solutions to Edit Text inside an Alert Dialog ...

Any information on why this is happening would be great, i can not find any documentation on Customizing or even Changing that Selection Title etc....

答:
In order to make the text selection actionMode background color, use the below in your style:</p>

```<code><item name="windowActionModeOverlay">true</item>
<item name="actionModeBackground">@color/yourcolor</item>
</code>```

Title: Text Selection Title Bugs

Body:
In order to make the text selection actionMode background color, use the below in your style:

<item name="windowActionModeOverlay">true</item>
<item name="actionModeBackground">@color/yourcolor</item>