问:
Spring 3 Dependency Injcetion
I am using Spring3 with xml based configuration.
The problem is when the IOC container starts it loads/caches all the properties/fields defined in com.dao.MyDAOFactory class. I want to tell spring that only load/cache specific properties/fields.

The bean declaration is given below

```<code><bean  id="daoFactory" class="com.dao.MyDAOFactory" ></bean>
</code>```

Can any one help me ?

答:
You can use the lazy-init attribute to defer the loading of your beans, but eventually all of them will be loaded.

Also keep this in mind that if a non-lazy singleton bean depends on one or more lazy beans, the lazy beans will be loaded at startup.

Title: Spring 3 Dependency Injcetion

Body:
I am using Spring3 with xml based configuration.
The problem is when the IOC container starts it loads/caches all the properties/fields defined in com.dao.MyDAOFactory class. I want to tell spring that only load/cache specific properties/fields.

The bean declaration is given below

<bean  id="daoFactory" class="com.dao.MyDAOFactory" ></bean>

Can any one help me ?


来源: stackexchange

问:
Why do I always get performance errors in Codility?
I always seem to get timeout errors for almost every program that I do although it seems to be syntactically correct. For example this is my code for GenomicRangeQuery:

vector<int> solution(string &S, vector<int> &P, vector<int> &Q) {

    int i, n, j, B;
    int min;
    n=P.size();
    vector<int> C;
    for(i=0; i<n; i++)
    {
        min=4;
        for(j=P[i]; j<=Q[i]; j++)
        {
            switch(S[j])
            {
                case 'A':
                         B=1;
                         break;
                case 'C':
                         B=2;
                         break;
                case 'G':
                         B=3;
                         break;
                case 'T':
                         B=4;
                         break;
            }
            if(B<min)
            {
                min=B;
            }
        }
        C.push_back(min);

    }
    return C;
}
```

Syntactically it is correct but all three performance cases throw timeout errors.

答:
There are requirements per task regarding the performance; in most cases it's about the time-complexity. The aforementioned GenomicRangeQuery doesn't impose such hard limitations, but it requires an efficient solution.

To me the first possible optimization of your solution would be to early exit on the first occurance of A as it means that minimal impact factor for the whole sequence will for sure be 1. Imagine a sequence : ATTT[....]T (1 A and 99,999 times T). You can exit after first A and still the minimal impact is 1.

ContentLicense: CC BY-SA 4.0

Body:
I always seem to get timeout errors for almost every program that I do although it seems to be syntactically correct. For example this is my code for GenomicRangeQuery:

vector<int> solution(string &S, vector<int> &P, vector<int> &Q) {

    int i, n, j, B;
    int min;
    n=P.size();
    vector<int> C;
    for(i=0; i<n; i++)
    {
        min=4;
        for(j=P[i]; j<=Q[i]; j++)
        {
            switch(S[j])
            {
                case 'A':
                         B=1;
                         break;
                case 'C':
                         B=2;
                         break;
                case 'G':
                         B=3;
                         break;
                case 'T':
                         B=4;
                         break;
            }
            if(B<min)
            {
                min=B;
            }
        }
        C.push_back(min);

    }
    return C;
}

Syntactically it is correct but all three performance cases throw timeout errors.


问:
Anyone have a good idea for a basic timer in C#?
Does anyone have a good idea for a timer? I've tried using the stopwatch but I must have done something wrong, I simply wish to have a int value go up once per second and have to ability to reset it.

This is my failed piece of code:

```<code>//Timer systemet
Stopwatch Timer = new Stopwatch();
Timer.Start();

TimeSpan ts = Timer.Elapsed;
double seconds = ts.Seconds;

//interval
if(seconds >= 8)
{
    Text = Text + 1;
    Timer.Stop();
}
</code>```

答:
Easiest way is to use System.Timers.Timer.

Example:

```<code>using System.Timers;

class Program
{
        static void Main(string[] args)
        {
            Timer t = new Timer(_period);
            t.Elapsed += TimerTick;
            t.Start();

        }

        static void TimerTick(Object source, ElapsedEventArgs e)
        {
            //your code
        }
}
</code>```

If you need more variable Timer, you can use System.Threading.Timer (System.Timers.Timer is basically wrapper around this class).

Example:

```<code>using System.Threading;

class Program
{
        static void Main(string[] args)
        {
            Timer t = new Timer(TimerTick, new AutoResetEvent(false), _dueTime, _period);

        }

        static void TimerTick(Object state)
        {
            //your code
        }
}
</code>```

Body:
Does anyone have a good idea for a timer? I've tried using the stopwatch but I must have done something wrong, I simply wish to have a int value go up once per second and have to ability to reset it.

This is my failed piece of code:

//Timer systemet
Stopwatch Timer = new Stopwatch();
Timer.Start();

TimeSpan ts = Timer.Elapsed;
double seconds = ts.Seconds;

//interval
if(seconds >= 8)
{
    Text = Text + 1;
    Timer.Stop();
}

Body:
Easiest way is to use System.Timers.Timer.

Example:

using System.Timers;

class Program
{
        static void Main(string[] args)
        {
            Timer t = new Timer(_period);
            t.Elapsed += TimerTick;
            t.Start();

        }

        static void TimerTick(Object source, ElapsedEventArgs e)
        {
            //your code
        }
}

If you need more variable Timer, you can use System.Threading.Timer (System.Timers.Timer is basically wrapper around this class).

Example:

using System.Threading;

class Program
{
        static void Main(string[] args)
        {
            Timer t = new Timer(TimerTick, new AutoResetEvent(false), _dueTime, _period);

        }

        static void TimerTick(Object state)
        {
            //your code
        }
}


问:
spring-cloud-gateway webflux ProxyExchange returns 404
I would like to create a simple proxy and aggregator server with spring-cloud-gateway. I am using dependency spring-cloud-gateway-webflux and ProxyExchange to do that. I start the app in localhost and launch it from a browser, however, it returns 404 not found.

If I use spring-cloud-gateway-mvc instead of spring-cloud-gateway-webflux, surprising the proxy works and I can browse stackoverflow in my localhost. But I still would like to find out why spring-cloud-gateway-webflux is not working.

Can anyone help to point out anything that I am missing?

controller:

```<code>@RestController
public class RouteController {
    @RequestMapping(value="/**", method={ RequestMethod.GET, RequestMethod.POST })
    public Mono<ResponseEntity<byte[]>> proxy(ServerHttpRequest request, ServerHttpResponse response, ProxyExchange<byte[]> proxy) throws Exception {
        String path = proxy.path("/");
        if (request.getMethodValue().startsWith("GET")) {
            return proxy.uri("https://stackoverflow.com/" + path).get();
        } else {
            return proxy.uri("https://stackoverflow.com/" + path).post();
        }
    }
}
</code>```

application.yml:

```<code>server:
  port: 8080
</code>```

I tried with adding the following to application.yml but it doesn't work.

```<code>spring:
  cloud:
    gateway:
      httpclient:
        ssl:
          useInsecureTrustManager: true
</code>```

答:
In my situation, it's the problem of http headers. Add the following code, then everything works for me.

```<code>proxy.sensitive(HttpHeaders.HOST)
</code>```

It seems like ProxyExchange will pass down the http request header by default, and in the case of WebClient, there is no default http header.

Body:
I would like to create a simple proxy and aggregator server with spring-cloud-gateway. I am using dependency spring-cloud-gateway-webflux and ProxyExchange to do that. I start the app in localhost and launch it from a browser, however, it returns 404 not found.

If I use spring-cloud-gateway-mvc instead of spring-cloud-gateway-webflux, surprising the proxy works and I can browse stackoverflow in my localhost. But I still would like to find out why spring-cloud-gateway-webflux is not working.

Can anyone help to point out anything that I am missing?

controller:

@RestController
public class RouteController {
    @RequestMapping(value="/**", method={ RequestMethod.GET, RequestMethod.POST })
    public Mono<ResponseEntity<byte[]>> proxy(ServerHttpRequest request, ServerHttpResponse response, ProxyExchange<byte[]> proxy) throws Exception {
        String path = proxy.path("/");
        if (request.getMethodValue().startsWith("GET")) {
            return proxy.uri("https://stackoverflow.com/" + path).get();
        } else {
            return proxy.uri("https://stackoverflow.com/" + path).post();
        }
    }
}

application.yml:

server:
  port: 8080

I tried with adding the following to application.yml but it doesn't work.

spring:
  cloud:
    gateway:
      httpclient:
        ssl:
          useInsecureTrustManager: true

Body:
In my situation, it's the problem of http headers. Add the following code, then everything works for me.

proxy.sensitive(HttpHeaders.HOST)

It seems like ProxyExchange will pass down the http request header by default, and in the case of WebClient, there is no default http header.


问:
Copy entire directory contents to another directory?
Method to copy entire directory contents to another directory in java or groovy?</p>

答:
With regard to Java, there is no such method in the standard API. In Java 7, the java.nio.file.Files class will provide a copy convenience method.

References

The Java Tutorials

Copying files from one directory to another in Java

ContentLicense: CC BY-SA 3.0


问:
Close electron application using html button
I have a question,
i am making a electron application and i want to make it so that a user clicks a button thats in my index.html and that then the application closes.

i've tryed but nothing seems to work.. Annyone ideas?

Sorry for the bad English. im from Holland

BeldrNL

Here's a image from the button in the html, it says 'close' in dutch. i want it so that a user presses that button the app closes
img

答:
Nevermind i've did it myself. I have added a window.close() on my button as so:

```<code><button class="menu-btn" onclick="window.close()">Close</button>
</code>```

Thanks a lot!

Body:
Nevermind i've did it myself. I have added a window.close() on my button as so:

<button class="menu-btn" onclick="window.close()">Close</button>

Thanks a lot!


问:
Selection and extraction of points (shapefile) within a polygon in R
I have two shape-files; one is a point file (some information for world) and the other is a 21-countries shape-file.

I need to extract the points which falls with in a country.
I have to repeat this step in 21 times in QGIS or ArcGIS.

Is there any way to do this in R and if is in batch processing, that would be really great as I have to repeat this for other 4 data sets as well.
Thanks in advance

答:
So as an example how to use over() consider the following simulated data.

```<code>library(raster)
library(sp)

#generate point distribution | with (x,y) coordinates
set.seed(42);pts <- SpatialPoints(data.frame(x = runif(30, 1, 5), y = runif(30, 1, 5)))

#create polygons
df<-data.frame(X = c(rep(1,5),rep(2,5),rep(3,5),rep(4,5),rep(5,5)),
               Y = c(rep(seq(1,5,1),5)))
df$cell<-1:nrow(df) #polygon identifier (for later)

#make into spatial object (probably better way to do this)
coordinates(df) <- ~X+Y
rast <- raster(extent(df), ncol = 5, nrow = 5)
grid<-rasterize(df, rast, df$cell, FUN = max)
grid<-rasterToPolygons(grid) #create polygons

#plot to check
plot(grid); points(pts)

#and extract
pointsinpolygon = over(SpatialPolygons(grid@polygons), SpatialPoints(pts))
</code>```

The last bit you can also do as

df$pointsinpolygon <- over(SpatialPolygons(grid@polygons), SpatialPoints(pts))

to write the results directly to the dataframe.

Body:
So as an example how to use over() consider the following simulated data.

library(raster)
library(sp)

#generate point distribution | with (x,y) coordinates
set.seed(42);pts <- SpatialPoints(data.frame(x = runif(30, 1, 5), y = runif(30, 1, 5)))

#create polygons
df<-data.frame(X = c(rep(1,5),rep(2,5),rep(3,5),rep(4,5),rep(5,5)),
               Y = c(rep(seq(1,5,1),5)))
df$cell<-1:nrow(df) #polygon identifier (for later)

#make into spatial object (probably better way to do this)
coordinates(df) <- ~X+Y
rast <- raster(extent(df), ncol = 5, nrow = 5)
grid<-rasterize(df, rast, df$cell, FUN = max)
grid<-rasterToPolygons(grid) #create polygons

#plot to check
plot(grid); points(pts)

#and extract
pointsinpolygon = over(SpatialPolygons(grid@polygons), SpatialPoints(pts))

The last bit you can also do as

df$pointsinpolygon <- over(SpatialPolygons(grid@polygons), SpatialPoints(pts))

to write the results directly to the dataframe.


问:
NUXT SSR mounted hook
Is there anyway we can access DOM elements in SSR using Nuxt? The mounted hook is not called in SSR and created hook doesn't have the DOM loaded yet. </p>

答:
in both of them you can access the DOM. You just need an if() statement to check if you are on the server side or client side

```<code>created(){
   if(!process.server){
      //do stuff on client side
   }
}
</code>```

Title: NUXT SSR mounted hook

Body:
in both of them you can access the DOM. You just need an if() statement to check if you are on the server side or client side

created(){
   if(!process.server){
      //do stuff on client side
   }
}


问:
Django logging to multiple files at once even with RotatingFileHandler?
I am using Django with logging config as follow:

```<code>LOGGING = {
    'version':1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '{asctime} {process:d} {thread:d} {levelname} {name} {module} {funcName} {message}',
            'style': '{',
        }
    },
    'handlers': {
        'file': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': BASE_DIR+'/logs/django_logs.log',
            'backupCount': 14,
            'maxBytes': 52428800,
            'formatter': 'verbose'
        }
    },
    'loggers': {
        '': {
            'handlers': ['file'],
            'level': 'INFO'
        }
    },
}
</code>```

I am running 16 processes of django, few daphne for websockets and few gunicorn processess for normal API calls based on django rest framework. But when I am looking at logs, multiple files are getting logged at once. For example, django_logs.1 .... django.logs.14 are getting logged into simultaneously. Do I have to add something else to log to one file at once and rotate it only when it's size exceed the specified size of log file?

For extra info, I am using python 3.6.8 and I initialize logger in each project file as follow:

```<code>import logging
logger = logging.getLogger(__name__)
</code>```

答:
From docs.python.logging-cookbook:

Although logging is thread-safe, and logging to a single file from
  multiple threads in a single process is supported, logging to a single
  file from multiple processes is not supported, because there is no
  standard way to serialize access to a single file across multiple
  processes in Python. If you need to log to a single file from multiple
  processes, one way of doing this is to have all the processes log to a
  SocketHandler, and have a separate process which implements a socket
  server which reads from the socket and logs to file. (If you prefer,
  you can dedicate one thread in one of the existing processes to
  perform this function.)

A complete example of this approach is detailed also in the cookbook. See this section.

The docs also suggest a few alternatives to this approach:

Alternatively, you can use a Queue and a QueueHandler to send all
  logging events to one of the processes in your multi-process
  application

I've tested your logging configuration and it's working as expected when an unique process is logging to file handler. The file should rotate only when maxBytes is reached

Body:
I am using Django with logging config as follow:

LOGGING = {
    'version':1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '{asctime} {process:d} {thread:d} {levelname} {name} {module} {funcName} {message}',
            'style': '{',
        }
    },
    'handlers': {
        'file': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': BASE_DIR+'/logs/django_logs.log',
            'backupCount': 14,
            'maxBytes': 52428800,
            'formatter': 'verbose'
        }
    },
    'loggers': {
        '': {
            'handlers': ['file'],
            'level': 'INFO'
        }
    },
}

I am running 16 processes of django, few daphne for websockets and few gunicorn processess for normal API calls based on django rest framework. But when I am looking at logs, multiple files are getting logged at once. For example, django_logs.1 .... django.logs.14 are getting logged into simultaneously. Do I have to add something else to log to one file at once and rotate it only when it's size exceed the specified size of log file?

For extra info, I am using python 3.6.8 and I initialize logger in each project file as follow:

import logging
logger = logging.getLogger(__name__)


问:
Is there a way to get the file path for a loaded module in Node.js?
Is it possible, given a loaded module, to get its file path?

```<code>const MyModule = require('./MyModule');
const MyOtherModule = require('../otherfolder/MyOtherModule');

function print(){
   console.log(thisIsThePathTo(MyModule));  <--- Should print the absolute path of the loaded module
   console.log(thisIsThePathTo(MyOtherModule));  <--- Should print the absolute path of the loaded module
}
</code>```

I saw require.resolve but I need the opposite lookup...
Any ideas?

Thanks!

答:
The documentation for require.main describes the module object.

The module has an id and a path, however those are not exported. You can add those properties to the module.exports object to export them. Then, in a separate module, you can access them via MyOtherModule.id or MyOtherModule.path

For example,

In MyOtherModule/index.js:

myOtherModuleFunction = function() {
    console.log('This is module 2')
}

module.exports = {
    // spread all properties in module.exports
    ...module,
    // then add the exports
    exports: myOtherModuleFunction
}
```

<p>and in <code>MyModule/MyModule.js</code>, </p>

<pre class="lang-js prettyprint-override"><code>module.exports = {
    ...module,
    exports: { someFunction: () => console.log('MyModule') }
}
</code>```

and in MyModule/index.js:

const MyModule = require('./MyModule');
const MyOtherModule = require('../../MyOtherModule/');

function thisIsThePathTo(module) {
    return module.path
}

function print(){
    console.log(thisIsThePathTo(MyModule))
    console.log(thisIsThePathTo(MyOtherModule))
 }

print()
```

<p>Running <code>node src/MyModule/index.js</code> outputs:</p>

```/.../stackoverflow/62043302/src/MyModule/
/.../stackoverflow/62043302/src/MyOtherModule
```

<p>And if you print <code>module.id</code> instead of <code>module.path</code>, you'll get:</p>

```/.../stackoverflow/62043302/src/MyModule/index.js
/.../stackoverflow/62043302/src/MyOtherModule/index.js
```

<p>However, spreading all properties includes <code>module.children</code> and <code>module.parent</code>, and you'll also have to use <code>module.exports</code> when accessing the so you probably only want to include <code>id</code> or <code>path</code>, like so:</p>

<pre class="lang-js prettyprint-override"><code>myOtherModuleFunction = function() {
    console.log('This is module 2')
}

const { id, path } = module

module.exports = {
    id,
    path,
    myOtherModuleFunction,
}```

and require like so:

```js
const {id: otherModuleId, myOtherModuleFunction } = require('MyOtherModule')
</code>```

This can get messy. If you're importing modules you did not author, you will not have the option to lookup the id or path (unless the authors added it to module.exports).

Body:
Is it possible, given a loaded module, to get its file path?

const MyModule = require('./MyModule');
const MyOtherModule = require('../otherfolder/MyOtherModule');

function print(){
   console.log(thisIsThePathTo(MyModule));  <--- Should print the absolute path of the loaded module
   console.log(thisIsThePathTo(MyOtherModule));  <--- Should print the absolute path of the loaded module
}

I saw require.resolve but I need the opposite lookup...
Any ideas?

Thanks!

Body:
The documentation for require.main describes the module object.

The module has an id and a path, however those are not exported. You can add those properties to the module.exports object to export them. Then, in a separate module, you can access them via MyOtherModule.id or MyOtherModule.path

For example,

In MyOtherModule/index.js:

myOtherModuleFunction = function() {
    console.log('This is module 2')
}

module.exports = {
    // spread all properties in module.exports
    ...module,
    // then add the exports
    exports: myOtherModuleFunction
}

and in MyModule/MyModule.js,

module.exports = {
    ...module,
    exports: { someFunction: () => console.log('MyModule') }
}

and in MyModule/index.js:

const MyModule = require('./MyModule');
const MyOtherModule = require('../../MyOtherModule/');

function thisIsThePathTo(module) {
    return module.path
}

function print(){
    console.log(thisIsThePathTo(MyModule))
    console.log(thisIsThePathTo(MyOtherModule))
 }

print()

Running node src/MyModule/index.js outputs:

/.../stackoverflow/62043302/src/MyModule/
/.../stackoverflow/62043302/src/MyOtherModule

And if you print module.id instead of module.path, you'll get:

/.../stackoverflow/62043302/src/MyModule/index.js
/.../stackoverflow/62043302/src/MyOtherModule/index.js

However, spreading all properties includes module.children and module.parent, and you'll also have to use module.exports when accessing the so you probably only want to include id or path, like so:

myOtherModuleFunction = function() {
    console.log('This is module 2')
}

const { id, path } = module

module.exports = {
    id,
    path,
    myOtherModuleFunction,
}```

and require like so:

```js
const {id: otherModuleId, myOtherModuleFunction } = require('MyOtherModule')

This can get messy. If you're importing modules you did not author, you will not have the option to lookup the id or path (unless the authors added it to module.exports).


问:
Converting a string to decimal and comparing with Linq to NHibernate 3.1
I have a table like:

```<code>Name     Height
-------  ---------
Sam      "1.80"
Paul     "1.79"
Max      "1.81m"
Steve    "none"
</code>```

I want to filter only the peoples with height > 1.79.
To do this, I must convert to decimal and then compare. Ignoring the values that are not numerical, such as "none".
I tryed Decimal.Parse() and Convert.ToDecimal() but show a error System.NotSupportedException

```<code>peoples = peoples.Where(f => Convert.ToDecimal(f.Height) > 1.8);
peoples = peoples.Where(f => decimal.Parse(f.Height) > 1.8);
</code>```

Any solution??

Tks[]

Patrick Coelho

答:
The only way you will be able to compare the non-numeric values in the database against a number using NH.Linq is either:

Convert the column to a numeric column

Load all the values up and compare in memory (which is not recommended for big datasets.

Body:
I have a table like:

Name     Height
-------  ---------
Sam      "1.80"
Paul     "1.79"
Max      "1.81m"
Steve    "none"

I want to filter only the peoples with height > 1.79.
To do this, I must convert to decimal and then compare. Ignoring the values that are not numerical, such as "none".
I tryed Decimal.Parse() and Convert.ToDecimal() but show a error System.NotSupportedException

peoples = peoples.Where(f => Convert.ToDecimal(f.Height) > 1.8);
peoples = peoples.Where(f => decimal.Parse(f.Height) > 1.8);

Any solution??

Tks[]

Patrick Coelho


问:
PWA: No matching service worker detected. You may need to reload the page
I get this warning:

No matching service worker detected. You may need to reload the page,
  or check that the service worker for the current page also controls
  the start of the URL from the manifest.

The thing that my service worker is working.

I even tried with two other URLs, both of them with HTTPs.

Now I'm going to show you the code, I'm using:

site.webmanifest

```<code>{
    ...
    "start_url": "/",
    "display": "standalone"
    ...
}
</code>```

To create my service-worker, I use the webpack plugin: WorkboxPlugin combined with Laravel Mix:

webpack.mix.js

```<code>mix.webpackConfig({
    plugins: [
        build.jigsaw,
        build.browserSync(),
        build.watch(['source/**/*.md', 'source/**/*.php', 'source/**/*.scss', '!source/**/_tmp/*']),
        new WorkboxPlugin.GenerateSW({
            // these options encourage the ServiceWorkers to get in there fast
            // and not allow any straggling "old" SWs to hang around
            clientsClaim: true,
            skipWaiting: true,
        }),
    ],
    output: {
        publicPath: '/assets/build/', // fixes the output bug
    },
});
</code>```

It creates the service-worker.js:

```<code>importScripts("https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js");

importScripts(
  "/assets/build/precache-manifest.cb67a9edd02323d8ea51560852b6cc0d.js"
);

workbox.core.skipWaiting();

workbox.core.clientsClaim();

self.__precacheManifest = [].concat(self.__precacheManifest || []);
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});
</code>```

With the precache-manifest.js

```<code>self.__precacheManifest = (self.__precacheManifest || []).concat([
  {
    "revision": "4e264a665cf5133098ac",
    "url": "/assets/build//js/main.js"
  },
  {
    "revision": "4e264a665cf5133098ac",
    "url": "/assets/build/css/main.css"
  },
  {
    "url": "/assets/build/images/vendor/leaflet/dist/layers-2x.png?4f0283c6ce28e888000e978e537a6a56"
  },
  {
    "url": "/assets/build/images/vendor/leaflet/dist/layers.png?a6137456ed160d7606981aa57c559898"
  },
  {
    "url": "/assets/build/images/vendor/leaflet/dist/marker-icon.png?2273e3d8ad9264b7daa5bdbf8e6b47f8"
  }
]);
</code>```

What should I do with this warning?

答:
The easiest solution here would be, like mentioned in previous answer, to put the service worker file in the root directory along with site webmanifest file.

But if you're like people who prefer to group their assets in sub-directories then you can set the scope manually by setting scope option to / and add the Service-Worker-Allowed HTTP header to the response. This way your service worker file doesn't need to be in the root directory.

Refer to Example 11 in https://w3c.github.io/ServiceWorker/#service-worker-script-response

```<code>    // Set the scope to an upper path of the script location
    // Response included "Service-Worker-Allowed : /"
    navigator.serviceWorker.register("/js/sw.js", { scope: "/" }).then(() => {
        console.log("Install succeeded as the max allowed scope was overriden to
    '/'.");
    });
</code>```

Body:
I get this warning:

No matching service worker detected. You may need to reload the page,
  or check that the service worker for the current page also controls
  the start of the URL from the manifest.

The thing that my service worker is working.

I even tried with two other URLs, both of them with HTTPs.

Now I'm going to show you the code, I'm using:

site.webmanifest

{
    ...
    "start_url": "/",
    "display": "standalone"
    ...
}

To create my service-worker, I use the webpack plugin: WorkboxPlugin combined with Laravel Mix:

webpack.mix.js

mix.webpackConfig({
    plugins: [
        build.jigsaw,
        build.browserSync(),
        build.watch(['source/**/*.md', 'source/**/*.php', 'source/**/*.scss', '!source/**/_tmp/*']),
        new WorkboxPlugin.GenerateSW({
            // these options encourage the ServiceWorkers to get in there fast
            // and not allow any straggling "old" SWs to hang around
            clientsClaim: true,
            skipWaiting: true,
        }),
    ],
    output: {
        publicPath: '/assets/build/', // fixes the output bug
    },
});

It creates the service-worker.js:

importScripts("https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js");

importScripts(
  "/assets/build/precache-manifest.cb67a9edd02323d8ea51560852b6cc0d.js"
);

workbox.core.skipWaiting();

workbox.core.clientsClaim();

self.__precacheManifest = [].concat(self.__precacheManifest || []);
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});

With the precache-manifest.js

self.__precacheManifest = (self.__precacheManifest || []).concat([
  {
    "revision": "4e264a665cf5133098ac",
    "url": "/assets/build//js/main.js"
  },
  {
    "revision": "4e264a665cf5133098ac",
    "url": "/assets/build/css/main.css"
  },
  {
    "url": "/assets/build/images/vendor/leaflet/dist/layers-2x.png?4f0283c6ce28e888000e978e537a6a56"
  },
  {
    "url": "/assets/build/images/vendor/leaflet/dist/layers.png?a6137456ed160d7606981aa57c559898"
  },
  {
    "url": "/assets/build/images/vendor/leaflet/dist/marker-icon.png?2273e3d8ad9264b7daa5bdbf8e6b47f8"
  }
]);

What should I do with this warning?

Body:
The easiest solution here would be, like mentioned in previous answer, to put the service worker file in the root directory along with site webmanifest file.

But if you're like people who prefer to group their assets in sub-directories then you can set the scope manually by setting scope option to / and add the Service-Worker-Allowed HTTP header to the response. This way your service worker file doesn't need to be in the root directory.

Refer to Example 11 in https://w3c.github.io/ServiceWorker/#service-worker-script-response

    // Set the scope to an upper path of the script location
    // Response included "Service-Worker-Allowed : /"
    navigator.serviceWorker.register("/js/sw.js", { scope: "/" }).then(() => {
        console.log("Install succeeded as the max allowed scope was overriden to
    '/'.");
    });


问:
Internet Explorer(IE11) not opening basic authentication window
Tested on a few other computers, the basic authentication is definitely working on IE11 for other computers.  However, on my computer, I can't seem to get a username/password to prompt for IE11. It does work on all the other browsers installed on the computer.

I've tried reinstalling IE11, deleting all sorts of cache/credentials, changing various internet security levels, changing User Authentication to "Prompt for user name and password" on each zone.  I've also tried in private browsing.

I have a feeling it's either a windows setting or an IE11 setting at this point.  Any direction would be wonderful.

IE11 Version: 11.836.18362.0

答:
I am not sure what settings you have modified in the IE 11 browser so first I suggest you reset the IE browser.

After that set Logon option to Prompt for user name and password for the desires zone.

If you are trying to authenticate with a different origin then enabled the Access data sources across domains under Miscellaneous category.

Let us know, whether it helps to fix this issue or not.

If the issue persists then try to provide more detailed information. Like which OS build you are using and information about the site.


问:
Pod shows as "Terminating" after node is shutdown
There was a pod named n404-neo4j-core-1 running on k8s-slave2. After k8s-slave2 was turned off, the pod was stuck with the Terminating.

I was expecting the pod to be deleted and a new pod be created on another node.
If this problem is not resolved, the neo4j cluster failed to keep HA.

```<code>kubectl get pods -o wide
    NAME                                     READY   STATUS        RESTARTS   AGE     IP          NODE         NOMINATED NODE   READINESS GATES
    n404-neo4j-core-0                        1/1     Running       0          3d19h   ***   k8s-node1    <none>           <none>
    n404-neo4j-core-1                        1/1     Terminating   0          78m     ***   k8s-slave2   <none>           <none>

    kubectl describe pod n404-neo4j-core-1

Name:                      n404-neo4j-core-1
Namespace:                 default
Priority:                  0
PriorityClassName:         <none>
Node:                      k8s-slave2/10.176.6.67
Start Time:                Mon, 01 Jun 2020 23:53:13 -0700
Labels:                    app.kubernetes.io/component=core
                           app.kubernetes.io/instance=n404
                           app.kubernetes.io/managed-by=Helm
                           app.kubernetes.io/name=neo4j
                           controller-revision-hash=n404-neo4j-core-67484bd88
                           helm.sh/chart=neo4j-4.0.4-1
                           statefulset.kubernetes.io/pod-name=n404-neo4j-core-1
Annotations:               <none>
Status:                    Terminating (lasts 21m)
Termination Grace Period:  30s
IP:                        10.36.0.1
Controlled By:             StatefulSet/n404-neo4j-core
Containers:
  n404-neo4j:
    Container ID:  docker://a045d7747678ca62734800d153d01f634b9972b527289541d357cbc27456bf7b
    Image:         neo4j:4.0.4-enterprise
    Image ID:      docker-pullable://neo4j@sha256:714d83e56a5db61eb44d65c114720f8cb94b06cd044669e16957aac1bd1b5c34
    Ports:         5000/TCP, 7000/TCP, 6000/TCP, 7474/TCP, 7687/TCP, 3637/TCP
    Host Ports:    0/TCP, 0/TCP, 0/TCP, 0/TCP, 0/TCP, 0/TCP
    Command:
      /bin/bash
      -c
      export core_idx=$(hostname | sed 's|.*-||')

      # Processes key configuration elements and exports env vars we need.
      . /helm-init/init.sh

      # We advertise the discovery-lb addresses (see discovery-lb.yaml) because
      # it is for internal cluster comms and is limited to private ports.
      export DISCOVERY_HOST="discovery-n404-neo4j-${core_idx}.default.svc.cluster.local"
      export NEO4J_causal__clustering_discovery__advertised__address="$DISCOVERY_HOST:5000"
      export NEO4J_causal__clustering_transaction__advertised__address="$DISCOVERY_HOST:6000"
      export NEO4J_causal__clustering_raft__advertised__address="$DISCOVERY_HOST:7000"

      echo "Starting Neo4j CORE $core_idx on $HOST"
      exec /docker-entrypoint.sh "neo4j"

    State:          Running
      Started:      Mon, 01 Jun 2020 23:53:14 -0700
    Ready:          True
    Restart Count:  0
    Liveness:       tcp-socket :7687 delay=300s timeout=2s period=10s #success=1 #failure=3
    Readiness:      tcp-socket :7687 delay=120s timeout=2s period=10s #success=1 #failure=3
    Environment Variables from:
      n404-neo4j-common-config  ConfigMap  Optional: false
      n404-neo4j-core-config    ConfigMap  Optional: false
    Environment:
      NEO4J_SECRETS_PASSWORD:  <set to the key 'neo4j-password' in secret 'n404-neo4j-secrets'>  Optional: false
    Mounts:
      /data from datadir (rw)
      /helm-init from init-script (rw)
      /plugins from plugins (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from n404-neo4j-sa-token-jp7g9 (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   True
  PodScheduled      True
Volumes:
  datadir:
    Type:       PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)
    ClaimName:  datadir-n404-neo4j-core-1
    ReadOnly:   false
  init-script:
    Type:      ConfigMap (a volume populated by a ConfigMap)
    Name:      n404-init-script
    Optional:  false
  plugins:
    Type:       EmptyDir (a temporary directory that shares a pod's lifetime)
    Medium:
    SizeLimit:  <unset>
  n404-neo4j-sa-token-jp7g9:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  n404-neo4j-sa-token-jp7g9
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  svc=neo4j
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
</code>```

答:
From the docs here

Kubernetes (versions 1.5 or newer) will not delete Pods just because a Node is unreachable. The Pods running on an unreachable Node enter the ‘Terminating’ or ‘Unknown’ state after a timeout. Pods may also enter these states when the user attempts graceful deletion of a Pod on an unreachable Node. The only ways in which a Pod in such a state can be removed from the apiserver are as follows:

The Node object is deleted (either by you, or by the Node Controller).

The kubelet on the unresponsive Node starts responding, kills the Pod and removes the entry from the apiserver.

Force deletion of the Pod by the user.

The recommended best practice is to use the first or second approach. If a Node is confirmed to be dead (e.g. permanently disconnected from the network, powered down, etc), then delete the Node object. If the Node is suffering from a network partition, then try to resolve this or wait for it to resolve. When the partition heals, the kubelet will complete the deletion of the Pod and free up its name in the apiserver.
Normally, the system completes the deletion once the Pod is no longer running on a Node, or the Node is deleted by an administrator. You may override this by force deleting the Pod.

Body:
There was a pod named n404-neo4j-core-1 running on k8s-slave2. After k8s-slave2 was turned off, the pod was stuck with the Terminating.

I was expecting the pod to be deleted and a new pod be created on another node.
If this problem is not resolved, the neo4j cluster failed to keep HA.

kubectl get pods -o wide
    NAME                                     READY   STATUS        RESTARTS   AGE     IP          NODE         NOMINATED NODE   READINESS GATES
    n404-neo4j-core-0                        1/1     Running       0          3d19h   ***   k8s-node1    <none>           <none>
    n404-neo4j-core-1                        1/1     Terminating   0          78m     ***   k8s-slave2   <none>           <none>

    kubectl describe pod n404-neo4j-core-1

Name:                      n404-neo4j-core-1
Namespace:                 default
Priority:                  0
PriorityClassName:         <none>
Node:                      k8s-slave2/10.176.6.67
Start Time:                Mon, 01 Jun 2020 23:53:13 -0700
Labels:                    app.kubernetes.io/component=core
                           app.kubernetes.io/instance=n404
                           app.kubernetes.io/managed-by=Helm
                           app.kubernetes.io/name=neo4j
                           controller-revision-hash=n404-neo4j-core-67484bd88
                           helm.sh/chart=neo4j-4.0.4-1
                           statefulset.kubernetes.io/pod-name=n404-neo4j-core-1
Annotations:               <none>
Status:                    Terminating (lasts 21m)
Termination Grace Period:  30s
IP:                        10.36.0.1
Controlled By:             StatefulSet/n404-neo4j-core
Containers:
  n404-neo4j:
    Container ID:  docker://a045d7747678ca62734800d153d01f634b9972b527289541d357cbc27456bf7b
    Image:         neo4j:4.0.4-enterprise
    Image ID:      docker-pullable://neo4j@sha256:714d83e56a5db61eb44d65c114720f8cb94b06cd044669e16957aac1bd1b5c34
    Ports:         5000/TCP, 7000/TCP, 6000/TCP, 7474/TCP, 7687/TCP, 3637/TCP
    Host Ports:    0/TCP, 0/TCP, 0/TCP, 0/TCP, 0/TCP, 0/TCP
    Command:
      /bin/bash
      -c
      export core_idx=$(hostname | sed 's|.*-||')

      # Processes key configuration elements and exports env vars we need.
      . /helm-init/init.sh

      # We advertise the discovery-lb addresses (see discovery-lb.yaml) because
      # it is for internal cluster comms and is limited to private ports.
      export DISCOVERY_HOST="discovery-n404-neo4j-${core_idx}.default.svc.cluster.local"
      export NEO4J_causal__clustering_discovery__advertised__address="$DISCOVERY_HOST:5000"
      export NEO4J_causal__clustering_transaction__advertised__address="$DISCOVERY_HOST:6000"
      export NEO4J_causal__clustering_raft__advertised__address="$DISCOVERY_HOST:7000"

      echo "Starting Neo4j CORE $core_idx on $HOST"
      exec /docker-entrypoint.sh "neo4j"

    State:          Running
      Started:      Mon, 01 Jun 2020 23:53:14 -0700
    Ready:          True
    Restart Count:  0
    Liveness:       tcp-socket :7687 delay=300s timeout=2s period=10s #success=1 #failure=3
    Readiness:      tcp-socket :7687 delay=120s timeout=2s period=10s #success=1 #failure=3
    Environment Variables from:
      n404-neo4j-common-config  ConfigMap  Optional: false
      n404-neo4j-core-config    ConfigMap  Optional: false
    Environment:
      NEO4J_SECRETS_PASSWORD:  <set to the key 'neo4j-password' in secret 'n404-neo4j-secrets'>  Optional: false
    Mounts:
      /data from datadir (rw)
      /helm-init from init-script (rw)
      /plugins from plugins (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from n404-neo4j-sa-token-jp7g9 (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   True
  PodScheduled      True
Volumes:
  datadir:
    Type:       PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)
    ClaimName:  datadir-n404-neo4j-core-1
    ReadOnly:   false
  init-script:
    Type:      ConfigMap (a volume populated by a ConfigMap)
    Name:      n404-init-script
    Optional:  false
  plugins:
    Type:       EmptyDir (a temporary directory that shares a pod's lifetime)
    Medium:
    SizeLimit:  <unset>
  n404-neo4j-sa-token-jp7g9:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  n404-neo4j-sa-token-jp7g9
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  svc=neo4j
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s


问:
Uncaught Error: Rendered fewer hooks than expected. This may be caused by an accidental early return statement in React Hooks
Given the following component, when I press down on the age selector and change the value to 15, such that I render a form without the driver license field, I get the error:

```<code>Uncaught Error: Rendered fewer hooks than expected. This may be caused by an accidental early return statement.
    at invariant (react-dom.development.js:55)
    at finishHooks (react-dom.development.js:11581)
    at updateFunctionComponent (react-dom.development.js:14262)
    at beginWork (react-dom.development.js:15103)
    at performUnitOfWork (react-dom.development.js:17817)
    at workLoop (react-dom.development.js:17857)
    at HTMLUnknownElement.callCallback (react-dom.development.js:149)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:199)
    at invokeGuardedCallback (react-dom.development.js:256)
    at replayUnitOfWork (react-dom.development.js:17113)
    at renderRoot (react-dom.development.js:17957)
    at performWorkOnRoot (react-dom.development.js:18808)
    at performWork (react-dom.development.js:18716)
    at flushInteractiveUpdates$1 (react-dom.development.js:18987)
    at batchedUpdates (react-dom.development.js:2210)
    at dispatchEvent (react-dom.development.js:4946)
    at interactiveUpdates$1 (react-dom.development.js:18974)
    at interactiveUpdates (react-dom.development.js:2217)
    at dispatchInteractiveEvent (react-dom.development.js:4923)
</code>```

Example code below:

const {useState} = React;

function App() {
  const [name, setName] = useState('Mary');
  const [age, setAge] = useState(16);

  if (age < 16) {
    return (

        Name:{' '}
        <input
          value={name}
          onChange={e => {
            setName(e.target.value);
          }}
        />

        Age:{' '}
        <input
          value={age}
          type="number"
          onChange={e => {
            setAge(+e.target.value);
          }}
        />

    );
  }

  const [license, setLicense] = useState('A123456');

  return (

      Name:{' '}
      <input
        value={name}
        onChange={e => {
          setName(e.target.value);
        }}
      />

      Age:{' '}
      <input
        value={age}
        type="number"
        onChange={e => {
          setAge(+e.target.value);
        }}
      />

      Driver License:{' '}
      <input
        value={license}
        onChange={e => {
          setLicense(e.target.value);
        }}
      />

  );
}

ReactDOM.render(<App />, document.querySelector('#app'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>
<div id="app"></div></code>```

答:
I have resolved this issue by changing the order of React Hooks. The useEffect came after an early return.

So I have changed code from

```<code>function (){
    const [loading ,setLoading] = React.useState(false);

    if (loading) {
        return "loading ....."
    }

    useEffect(() => {
      if (condition) {
        doSomething();
      }
    }, []);

    return <div>component</div>
}
</code>```

to

```<code>function (){
    const [loading ,setLoading] = React.useState(false);

    useEffect(() => {
      if (condition) {
        doSomething();
      }
    }, []);

    if (loading){
      return "loading ....."
    }

    return <div>component</div>
}
</code>```

So, when loading becomes true then useEffect will not run and that will throw error. But if I declare loading JSX element after useEffect then it will work.

Body:
Given the following component, when I press down on the age selector and change the value to 15, such that I render a form without the driver license field, I get the error:

Uncaught Error: Rendered fewer hooks than expected. This may be caused by an accidental early return statement.
    at invariant (react-dom.development.js:55)
    at finishHooks (react-dom.development.js:11581)
    at updateFunctionComponent (react-dom.development.js:14262)
    at beginWork (react-dom.development.js:15103)
    at performUnitOfWork (react-dom.development.js:17817)
    at workLoop (react-dom.development.js:17857)
    at HTMLUnknownElement.callCallback (react-dom.development.js:149)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:199)
    at invokeGuardedCallback (react-dom.development.js:256)
    at replayUnitOfWork (react-dom.development.js:17113)
    at renderRoot (react-dom.development.js:17957)
    at performWorkOnRoot (react-dom.development.js:18808)
    at performWork (react-dom.development.js:18716)
    at flushInteractiveUpdates$1 (react-dom.development.js:18987)
    at batchedUpdates (react-dom.development.js:2210)
    at dispatchEvent (react-dom.development.js:4946)
    at interactiveUpdates$1 (react-dom.development.js:18974)
    at interactiveUpdates (react-dom.development.js:2217)
    at dispatchInteractiveEvent (react-dom.development.js:4923)

Example code below:

const {useState} = React;

function App() {
  const [name, setName] = useState('Mary');
  const [age, setAge] = useState(16);

  if (age < 16) {
    return (

        Name:{' '}
        <input
          value={name}
          onChange={e => {
            setName(e.target.value);
          }}
        />

        Age:{' '}
        <input
          value={age}
          type="number"
          onChange={e => {
            setAge(+e.target.value);
          }}
        />

    );
  }

  const [license, setLicense] = useState('A123456');

  return (

      Name:{' '}
      <input
        value={name}
        onChange={e => {
          setName(e.target.value);
        }}
      />

      Age:{' '}
      <input
        value={age}
        type="number"
        onChange={e => {
          setAge(+e.target.value);
        }}
      />

      Driver License:{' '}
      <input
        value={license}
        onChange={e => {
          setLicense(e.target.value);
        }}
      />

  );
}

ReactDOM.render(<App />, document.querySelector('#app'));

Body:
I have resolved this issue by changing the order of React Hooks. The useEffect came after an early return.

So I have changed code from

function (){
    const [loading ,setLoading] = React.useState(false);

    if (loading) {
        return "loading ....."
    }

    useEffect(() => {
      if (condition) {
        doSomething();
      }
    }, []);

    return <div>component</div>
}

to

function (){
    const [loading ,setLoading] = React.useState(false);

    useEffect(() => {
      if (condition) {
        doSomething();
      }
    }, []);

    if (loading){
      return "loading ....."
    }

    return <div>component</div>
}

So, when loading becomes true then useEffect will not run and that will throw error. But if I declare loading JSX element after useEffect then it will work.


问:
Can ConcurrentDictionary.GetOrAdd() be called recursively?
ConcurrentDictionary.GetOrAdd(TKey, Func<TKey, TValue>) accepts a factory function to allow lazy instantiation of the item to be put into the dictionary.

Is it safe to define a factory function that itself calls GetOrAdd(), i.e. GetOrAdd is being called within the context of a 'parent' GetOrAdd().

The following code demonstrates the pattern; It does appear to work, but is it safe?

```<code>class Program
{
    static ConcurrentDictionary<string,object> __dict = new ConcurrentDictionary<string, object>();

    static void Main(string[] args)
    {
        Foo foo = GetOrAddFoo();
        Console.WriteLine(foo._name);
        Console.WriteLine(foo._bar._name);
        Console.ReadKey();
    }

    static Bar GetOrAddBar()
    {
        Console.WriteLine("GetOrAddBar: enter");
        Func<string,Bar> factoryFn = (x) => LoadBar(x);
        Bar bar = __dict.GetOrAdd("bar", factoryFn) as Bar;
        Console.WriteLine("GetOrAddBar: exit");
        return bar;
    }

    static Foo GetOrAddFoo()
    {
        Console.WriteLine("GetOrAddFoo: enter");
        Func<string,Foo> factoryFn = (x) => LoadFoo(x);
        Foo foo = __dict.GetOrAdd("foo", factoryFn) as Foo;
        Console.WriteLine("GetOrAddFoo: exit");
        return foo;
    }

    static Bar LoadBar(string name)
    {
        Bar bar =  new Bar();
        bar._name = name;
        return bar;
    }

    static Foo LoadFoo(string name)
    {
        Foo foo = new Foo();
        foo._name = name;
        foo._bar = GetOrAddBar();
        return foo;
    }

    public class Foo
    {
       public string _name;
       public Bar _bar;
    }

    public class Bar
    {
        public string _name;
    }
}
</code>```

答:
When you decompile ConcurrentDictionary.GetOrAdd(TKey, Func) you will see line:

```<code>TryAddInternal(key, valueFactory(key), updateIfExists: false, acquireLock: true, out value);
</code>```

Which means that timeline of your call in one process/thread will be:

```<code>enter __dict.GetOrAdd("foo", factoryFn)
enter LoadFoo (from valueFactory(key) in line above)
enter GetOrAddBar
enter __dict.GetOrAdd("bar", factoryFn)
enter LoadBar
leave LoadBar
enter TryAddInternal with key "bar"
acquire lock ( Monitor.Enter(tables.m_locks[lockNo], ref lockTaken); )
add key "bar" with appropriate value
release lock ( Monitor.Exit(tables.m_locks[lockNo]); )
leave TryAddInternal with key "bar"
leave __dict.GetOrAdd("bar", factoryFn)
leave GetOrAddBar
leave LoadFoo
enter TryAddInternal with key "foo"
acquire lock ( Monitor.Enter(tables.m_locks[lockNo], ref lockTaken); )
add key "foo" with appropriate value
release lock ( Monitor.Exit(tables.m_locks[lockNo]); )
leave __dict.GetOrAdd("foo", factoryFn)
</code>```

You can see that it will lock and release twice and in between another process can jump in and create "foo" when this process have already created "bar". If it's safe depends on you.

And when you'd call recursively with the same key, most in-depth value will "win" because there is updateIfExists: false param in TryAddInternal so any subsequent call will not change it once it's there. There is also out value param so it will return first inserted value and will not fail.

Also interesting: TryAddInternal does not lock whole Dictionary but only a bucket (part of the dicionary) based on the key. It's performance improvement.

Body:
ConcurrentDictionary.GetOrAdd(TKey, Func<TKey, TValue>) accepts a factory function to allow lazy instantiation of the item to be put into the dictionary.

Is it safe to define a factory function that itself calls GetOrAdd(), i.e. GetOrAdd is being called within the context of a 'parent' GetOrAdd().

The following code demonstrates the pattern; It does appear to work, but is it safe?

class Program
{
    static ConcurrentDictionary<string,object> __dict = new ConcurrentDictionary<string, object>();

    static void Main(string[] args)
    {
        Foo foo = GetOrAddFoo();
        Console.WriteLine(foo._name);
        Console.WriteLine(foo._bar._name);
        Console.ReadKey();
    }

    static Bar GetOrAddBar()
    {
        Console.WriteLine("GetOrAddBar: enter");
        Func<string,Bar> factoryFn = (x) => LoadBar(x);
        Bar bar = __dict.GetOrAdd("bar", factoryFn) as Bar;
        Console.WriteLine("GetOrAddBar: exit");
        return bar;
    }

    static Foo GetOrAddFoo()
    {
        Console.WriteLine("GetOrAddFoo: enter");
        Func<string,Foo> factoryFn = (x) => LoadFoo(x);
        Foo foo = __dict.GetOrAdd("foo", factoryFn) as Foo;
        Console.WriteLine("GetOrAddFoo: exit");
        return foo;
    }

    static Bar LoadBar(string name)
    {
        Bar bar =  new Bar();
        bar._name = name;
        return bar;
    }

    static Foo LoadFoo(string name)
    {
        Foo foo = new Foo();
        foo._name = name;
        foo._bar = GetOrAddBar();
        return foo;
    }

    public class Foo
    {
       public string _name;
       public Bar _bar;
    }

    public class Bar
    {
        public string _name;
    }
}

Body:
When you decompile ConcurrentDictionary.GetOrAdd(TKey, Func) you will see line:

TryAddInternal(key, valueFactory(key), updateIfExists: false, acquireLock: true, out value);

Which means that timeline of your call in one process/thread will be:

enter __dict.GetOrAdd("foo", factoryFn)
enter LoadFoo (from valueFactory(key) in line above)
enter GetOrAddBar
enter __dict.GetOrAdd("bar", factoryFn)
enter LoadBar
leave LoadBar
enter TryAddInternal with key "bar"
acquire lock ( Monitor.Enter(tables.m_locks[lockNo], ref lockTaken); )
add key "bar" with appropriate value
release lock ( Monitor.Exit(tables.m_locks[lockNo]); )
leave TryAddInternal with key "bar"
leave __dict.GetOrAdd("bar", factoryFn)
leave GetOrAddBar
leave LoadFoo
enter TryAddInternal with key "foo"
acquire lock ( Monitor.Enter(tables.m_locks[lockNo], ref lockTaken); )
add key "foo" with appropriate value
release lock ( Monitor.Exit(tables.m_locks[lockNo]); )
leave __dict.GetOrAdd("foo", factoryFn)

You can see that it will lock and release twice and in between another process can jump in and create "foo" when this process have already created "bar". If it's safe depends on you.

And when you'd call recursively with the same key, most in-depth value will "win" because there is updateIfExists: false param in TryAddInternal so any subsequent call will not change it once it's there. There is also out value param so it will return first inserted value and will not fail.

Also interesting: TryAddInternal does not lock whole Dictionary but only a bucket (part of the dicionary) based on the key. It's performance improvement.


问:
listbox click vba excel
I have in an excel worksheet data arranged like this

I want to write a code to show the équipements (Column A to G) in a listbox and when I click on the equipement name I have the list of persons who know how to use the equipement to be displayed in another listox, the 2 listboxes are in the same userform.

I wrote this code but I didnt kow how to finish it : what should I write after additem ?

```<code>Private Sub ListBox_Equip_Click()

    fin_liste_equip = ws_Liste_Equip.Cells(1, 256).End(xlToLeft).Column

    curVal = Me.ListBox_Equip.Value
    For x = 2 To fin_liste_equip
        If ws_Liste_Equip.Cells(x, fin_liste_equip) = curVal Then
            Me.ListBox_Pers_Mait.AddItem ws_Liste_Equip
        End

 If
Next x
</code>```

you can see in the following picture that  ive only known how to populate my 1st listbox

答:
First you'll need to set the number of columns you want to use in your ListBox using (put this outside your loop)

```<code>Me.ListBox_Pers_Mait.ColumnCount = 7
</code>```

Then modify your If statement to use something like the following

```<code>With Me.ListBox_Pers_Mait
    .AddItem ws_List_Equip
    .List(.ListCount - 1, 1) = "Your Next Value"
    .List(.ListCount - 1, 2) = "Another Value"
    ' ......etc.
End With
</code>```

We subtract 1 off of the .ListCount as the index of the ListBox starts at 0.

Title: listbox click vba excel

Body:
I have in an excel worksheet data arranged like this

I want to write a code to show the équipements (Column A to G) in a listbox and when I click on the equipement name I have the list of persons who know how to use the equipement to be displayed in another listox, the 2 listboxes are in the same userform.

I wrote this code but I didnt kow how to finish it : what should I write after additem ?

Private Sub ListBox_Equip_Click()

    fin_liste_equip = ws_Liste_Equip.Cells(1, 256).End(xlToLeft).Column

    curVal = Me.ListBox_Equip.Value
    For x = 2 To fin_liste_equip
        If ws_Liste_Equip.Cells(x, fin_liste_equip) = curVal Then
            Me.ListBox_Pers_Mait.AddItem ws_Liste_Equip
        End

 If
Next x

you can see in the following picture that  ive only known how to populate my 1st listbox

Body:
First you'll need to set the number of columns you want to use in your ListBox using (put this outside your loop)

Me.ListBox_Pers_Mait.ColumnCount = 7

Then modify your If statement to use something like the following

With Me.ListBox_Pers_Mait
    .AddItem ws_List_Equip
    .List(.ListCount - 1, 1) = "Your Next Value"
    .List(.ListCount - 1, 2) = "Another Value"
    ' ......etc.
End With

We subtract 1 off of the .ListCount as the index of the ListBox starts at 0.


问:
How can I start a another activity in this Dialog?
I want when I click the 'OK' button I get to the 'PickSeatActivity'.
This is what I tried, but android studio underlines 'Intent' Object with a red line   </p>

```<code>        val builder = AlertDialog.Builder(this.requireActivity())

         // Dialog will have "Make a selection" as the title
         builder.setMessage("Details successfully captured.Do you wish to proceed and book your seat?")
             .setPositiveButton("OK") { dialogInterface: DialogInterface, i: Int ->
                 val intent = Intent(PickSeatActivity::class.java)
                 startActivity(intent)

             }
             // A "Cancel" button that does nothing
             .setNegativeButton("Cancel") { dialog, id ->
                 // Nothing happening here either
             }
</code>```

答:
Replace your code

```<code>val intent = Intent(PickSeatActivity::class.java)
             startActivity(intent)
</code>```

TO

```<code>val intent = Intent(this.requireActivity(), PickSeatActivity::class.java)
             startActivity(intent)
</code>```

Body:
I want when I click the 'OK' button I get to the 'PickSeatActivity'.
This is what I tried, but android studio underlines 'Intent' Object with a red line

        val builder = AlertDialog.Builder(this.requireActivity())

         // Dialog will have "Make a selection" as the title
         builder.setMessage("Details successfully captured.Do you wish to proceed and book your seat?")
             .setPositiveButton("OK") { dialogInterface: DialogInterface, i: Int ->
                 val intent = Intent(PickSeatActivity::class.java)
                 startActivity(intent)

             }
             // A "Cancel" button that does nothing
             .setNegativeButton("Cancel") { dialog, id ->
                 // Nothing happening here either
             }

Body:
Replace your code

val intent = Intent(PickSeatActivity::class.java)
             startActivity(intent)

TO

val intent = Intent(this.requireActivity(), PickSeatActivity::class.java)
             startActivity(intent)


问:
Error: Could not find or load main class org.apache.phoenix.queryserver.server.QueryServer with Apache Phoenix Queryserver starting
I have a setup with apache Hadoop 2.10.0, hbase 1.5, and Phoenix 4.14.  All working well.  However, when I am trying to connect python with Phoenix I need to enable queryserver.  Whenever I am trying to start, I am getting the below error and exit.  Can someone please help on this?

```<code>2020-06-01 16:59:24.860409 launching /usr/local/jdk1.8.0_251/bin/java -cp /hadoopStack/hbase-1.5.0/conf:/etc/hadoop/conf:/hadoopStack/apache-phoenix-4.15.0-HBase-1.5-bin/bin/../phoenix-4.15.0-HBase-1.5-client.jar:::/hadoopStack/hadoop-2.10.0/etc/hadoop:/hadoopStack/hadoop-2.10.0/share/hadoop/common/lib/*:/hadoopStack/hadoop-2.10.0/share/hadoop/common/*:/hadoopStack/hadoop-2.10.0/share/hadoop/hdfs:/hadoopStack/hadoop-2.10.0/share/hadoop/hdfs/lib/*:/hadoopStack/hadoop-2.10.0/share/hadoop/hdfs/*:/hadoopStack/hadoop-2.10.0/share/hadoop/yarn:/hadoopStack/hadoop-2.10.0/share/hadoop/yarn/lib/*:/hadoopStack/hadoop-2.10.0/share/hadoop/yarn/*:/hadoopStack/hadoop-2.10.0/share/hadoop/mapreduce/lib/*:/hadoopStack/hadoop-2.10.0/share/hadoop/mapreduce/*:/hadoopStack/hbase-1.5.0/lib/*:/hadoopStack/apache-phoenix-4.15.0-HBase-1.5-bin/*:/hadoopStack/hbase-1.5.0/conf
 -Dproc_phoenixserver -Dlog4j.configuration=file:/hadoopStack/apache-phoenix-4.15.0-HBase-1.5-bin/bin/log4j.properties -Dpsql.root.logger=INFO,DRFA -Dpsql.log.dir=/hadoopStack/apache-phoenix-4.15.0-HBase-1.5-bin -Dpsql.log.file=phoenix-hadoop-queryserver.log  org.apache.phoenix.queryserver.server.QueryServer

Error: Could not find or load main class org.apache.phoenix.queryserver.server.QueryServer

close failed in file object destructor:

IOError: [Errno 9] Bad file descriptor
</code>```

答:
The Phoenix Query Server is not include by default. It's a seperate jar phoenix-queryserver that you need to include in the classpath:

https://mvnrepository.com/artifact/org.apache.phoenix/phoenix-queryserver/4.14.3-HBase-1.4

Body:
I have a setup with apache Hadoop 2.10.0, hbase 1.5, and Phoenix 4.14.  All working well.  However, when I am trying to connect python with Phoenix I need to enable queryserver.  Whenever I am trying to start, I am getting the below error and exit.  Can someone please help on this?

2020-06-01 16:59:24.860409 launching /usr/local/jdk1.8.0_251/bin/java -cp /hadoopStack/hbase-1.5.0/conf:/etc/hadoop/conf:/hadoopStack/apache-phoenix-4.15.0-HBase-1.5-bin/bin/../phoenix-4.15.0-HBase-1.5-client.jar:::/hadoopStack/hadoop-2.10.0/etc/hadoop:/hadoopStack/hadoop-2.10.0/share/hadoop/common/lib/*:/hadoopStack/hadoop-2.10.0/share/hadoop/common/*:/hadoopStack/hadoop-2.10.0/share/hadoop/hdfs:/hadoopStack/hadoop-2.10.0/share/hadoop/hdfs/lib/*:/hadoopStack/hadoop-2.10.0/share/hadoop/hdfs/*:/hadoopStack/hadoop-2.10.0/share/hadoop/yarn:/hadoopStack/hadoop-2.10.0/share/hadoop/yarn/lib/*:/hadoopStack/hadoop-2.10.0/share/hadoop/yarn/*:/hadoopStack/hadoop-2.10.0/share/hadoop/mapreduce/lib/*:/hadoopStack/hadoop-2.10.0/share/hadoop/mapreduce/*:/hadoopStack/hbase-1.5.0/lib/*:/hadoopStack/apache-phoenix-4.15.0-HBase-1.5-bin/*:/hadoopStack/hbase-1.5.0/conf
 -Dproc_phoenixserver -Dlog4j.configuration=file:/hadoopStack/apache-phoenix-4.15.0-HBase-1.5-bin/bin/log4j.properties -Dpsql.root.logger=INFO,DRFA -Dpsql.log.dir=/hadoopStack/apache-phoenix-4.15.0-HBase-1.5-bin -Dpsql.log.file=phoenix-hadoop-queryserver.log  org.apache.phoenix.queryserver.server.QueryServer

Error: Could not find or load main class org.apache.phoenix.queryserver.server.QueryServer

close failed in file object destructor:

IOError: [Errno 9] Bad file descriptor


问:
Can't import turtle
I'm a complete novice, so I appreciate the answers.

I'm trying to get turtle on my powershell, because that's what the book I'm reading says to do but this shows up,

```<code>import : The term 'import' is not recognized as the name of a cmdlet,function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ import turtle
+ ~~~~~~
+ CategoryInfo          : ObjectNotFound: (import:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
</code>```

答: import turtle is Python but not PowerShell. Make sure you are in Python, not PowerShell, when you do import turtle.

Title: Can't import turtle

Body:
I'm a complete novice, so I appreciate the answers.

I'm trying to get turtle on my powershell, because that's what the book I'm reading says to do but this shows up,

import : The term 'import' is not recognized as the name of a cmdlet,function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ import turtle
+ ~~~~~~
+ CategoryInfo          : ObjectNotFound: (import:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException


问:
Creating a new Orchard site
I am currently configuring a new Orchard site.  I'd like to point the connectionstring to our development SQL database, but there is no option to do this.  Well, I say that, but I don't have an Orchard database in the first place to populate on the development server.  How do I create the Orchard database in the first place so that the developers can point to that instance?</p>

答: I have managed to figure this out.  I had to create an empty database and assign a user to that database.  Then, using the Orchard Setup, I was able to point the connection string to the new development database and this created all of the necessary tables.</p>

Title: Creating a new Orchard site


问:
Take the cell values more than one from ".CSV" to Powershell
I have . csv table in below;

```<code>name;location;id;number
space;usa;123;110001
sky;canada;124;110002
plane;peru;126;1100011
cloud;italy;127;1111033
</code>```

I want to reach the in 'name' column cell values for example 'space' cell in csv file , if it finds the 'space' after the I want to take its the location and/or id value in same ".csv" file by Powershell.

I used for $A = Import-Csv -Pathcode for take the .csv file. But I can not reach the name columnn or any cell as clearly.
$A.name or $A.location is not working in powershell I tried.

Thanks

答:
Powershell imports CSV files with a comma (,) as the delimiter by default. To import a file where a semicolon is the delimiter you need to use the delimiter switch:

```<code>$test = import-csv .\stackoverflowtest.csv -Delimiter ';'
</code>```

You can then address each line in your CSV like so:

```<code>$test[n].name
</code>```

Where n is the current number you want to access, starting with a 0.

Body:
I have . csv table in below;

name;location;id;number
space;usa;123;110001
sky;canada;124;110002
plane;peru;126;1100011
cloud;italy;127;1111033

I want to reach the in 'name' column cell values for example 'space' cell in csv file , if it finds the 'space' after the I want to take its the location and/or id value in same ".csv" file by Powershell.

I used for $A = Import-Csv -Pathcode for take the .csv file. But I can not reach the name columnn or any cell as clearly.
$A.name or $A.location is not working in powershell I tried.

Thanks

Body:
Powershell imports CSV files with a comma (,) as the delimiter by default. To import a file where a semicolon is the delimiter you need to use the delimiter switch:

$test = import-csv .\stackoverflowtest.csv -Delimiter ';'

You can then address each line in your CSV like so:

$test[n].name

Where n is the current number you want to access, starting with a 0.


问:
Mocking a method with prophet
Assume there is a method

```<code>public function updateTimestamp($sessionId, $data)
{
    return $this->memcached->touch($sessionId, time() + $this->ttl);
}
</code>```

that I'd like to test. Infection changes the + in time() + $this->ttl to - and all my tests are still passing. So I'd like to make a test that will mock Memcached's touch in it and will conditionally return true/false basing on the second argument passed to it.

So doing something like:

```<code>    // $ttl is set;
    $memcachedMock
        ->touch(
            'sessionId',
            $certainValuePassedToTouch
        )
        ->willReturn(
            $certainValuePassedToTouch >= time() + $ttl
                ? true
                : false
        )
        ;
</code>```

There are two problems now:

I don't know how to make such a condition for an arbitrary integer parameter passed to the method being mocked

basing on time() seems to be very unreliable, so how can I reliably test it if time() is used in the method itself?

答:
You can mock the time() function to return 0 and the return value of the touch() method will depend solely on the $ttl value. For the first, there are suggestions in other answers, and the second can be archived with returnCallback().

```<code>$memcachedMock
    ->method('touch')
    ->will($this->returnCallback(function ($key, $val) {
        return $val > 0;
    }));
</code>```

Title: Mocking a method with prophet

Body:
Assume there is a method

public function updateTimestamp($sessionId, $data)
{
    return $this->memcached->touch($sessionId, time() + $this->ttl);
}

that I'd like to test. Infection changes the + in time() + $this->ttl to - and all my tests are still passing. So I'd like to make a test that will mock Memcached's touch in it and will conditionally return true/false basing on the second argument passed to it.

So doing something like:

    // $ttl is set;
    $memcachedMock
        ->touch(
            'sessionId',
            $certainValuePassedToTouch
        )
        ->willReturn(
            $certainValuePassedToTouch >= time() + $ttl
                ? true
                : false
        )
        ;

There are two problems now:

I don't know how to make such a condition for an arbitrary integer parameter passed to the method being mocked

basing on time() seems to be very unreliable, so how can I reliably test it if time() is used in the method itself?

Body:
You can mock the time() function to return 0 and the return value of the touch() method will depend solely on the $ttl value. For the first, there are suggestions in other answers, and the second can be archived with returnCallback().

$memcachedMock
    ->method('touch')
    ->will($this->returnCallback(function ($key, $val) {
        return $val > 0;
    }));


问:
How to properly use a lambda expression with the scipy.derivative method?
I have written the following function to calculate the probability that a single reaction in a system of reaction fires and stores the output of the function, the probability of each reaction in the system firing, as an array:

```<code>def propensity_calc(LHS, popul_num, stoch_rate):
    propensity = np.zeros(len(LHS))
    for row in range(len(LHS)):
            a = stoch_rate[row]
            for i in range(len(popul_num)):
                if (popul_num[i] >= LHS[row, i]):
                    binom_rxn = binom(popul_num[i], LHS[row, i])
                    a = a*binom_rxn
                else:
                    a = 0
                    break
            propensity[row] = a
    return propensity
</code>```

The inputs for this function are 3 arrays popul_num has the discrete number of molecules of each reactant, LHS is a 2D array with the ratios between each molecule species for each reaction in the system and stoch_rate is the rate of each reaction.

I now want to call the propensity_calc function with the scipy.misc.derivative method in a different function to calculate the partial derivative: bji(x) = daj(x)/xi, where aj(x) is the result from the above propensity_calc function and xi is the corresponding elements of the popul_num array.

This is what I've got written so far:

```<code>from scipy.misc import derivative
from scipy import optimize

def time_step_calc(popul_num, state_change_array, a0):
    # equation 22:
    expctd_net_change = a0*state_change_array
    print("expected net change:\n", expctd_net_change)
    # equation 24 partial differentiation:
    for x in range(len(popul_num)):
        part_propensity_diff = derivative(lambda LHS, popul_num, stoch_rate: propensity_calc, popul_num[x])    <-- Error here with the number of arguments passed to lambda
    # equation 26:
    t_step = epsi*a0 / sum(expctd_net_change*part_propensity_diff)
    delta_t = optimize.fmin(t_step, 0.00012)
    print("calculated delta_t:\n", delta_t)
    return delta_t
</code>```

To pass the propensity_calc function to scipy.derviative I've tried to use a lambda function but I get the following error:

```<code>File "C:\Users\Mike\AppData\Local\Programs\Python\Python38-32\lib\site-packages\scipy\misc\common.py", line 119, in derivative
val += weights[k]*func(x0+(k-ho)*dx,*args)
TypeError: <lambda>() missing 2 required positional arguments: 'popul_num' and 'stoch_rate'
</code>```

I've read the lambda documentation but I still don't understand where I'm going wrong, any suggestions as to how I can fix this error and do the partial differentiation?

Cheers

答:
The lambda you defined is a constant function of three parameters that always return a function. Since you want a one-dimensional function (from my understanding), what you probably meant is:

lambda popul_num: propensity_calc(LHS, popul_num, stoch_rate)
```

This can be read as "The function that takes a parameter called popul_num and returns propensity_calc(LHS, popul_num, stoch_rate)".

By calling scipy.misc.derivative with the above lambda at point popul_num[x], you will get the value of the partial derivative of propensity_calc with respect to popul_num at point (LHS, popul_num, stoch_rate). It means that you have to define LHS and stoch_rate in this case. Indeed, don't forget that the partial derivative is still a function of three parameters.

Body:
I have written the following function to calculate the probability that a single reaction in a system of reaction fires and stores the output of the function, the probability of each reaction in the system firing, as an array:

def propensity_calc(LHS, popul_num, stoch_rate):
    propensity = np.zeros(len(LHS))
    for row in range(len(LHS)):
            a = stoch_rate[row]
            for i in range(len(popul_num)):
                if (popul_num[i] >= LHS[row, i]):
                    binom_rxn = binom(popul_num[i], LHS[row, i])
                    a = a*binom_rxn
                else:
                    a = 0
                    break
            propensity[row] = a
    return propensity

The inputs for this function are 3 arrays popul_num has the discrete number of molecules of each reactant, LHS is a 2D array with the ratios between each molecule species for each reaction in the system and stoch_rate is the rate of each reaction.

I now want to call the propensity_calc function with the scipy.misc.derivative method in a different function to calculate the partial derivative: bji(x) = daj(x)/xi, where aj(x) is the result from the above propensity_calc function and xi is the corresponding elements of the popul_num array.

This is what I've got written so far:

from scipy.misc import derivative
from scipy import optimize

def time_step_calc(popul_num, state_change_array, a0):
    # equation 22:
    expctd_net_change = a0*state_change_array
    print("expected net change:\n", expctd_net_change)
    # equation 24 partial differentiation:
    for x in range(len(popul_num)):
        part_propensity_diff = derivative(lambda LHS, popul_num, stoch_rate: propensity_calc, popul_num[x])    <-- Error here with the number of arguments passed to lambda
    # equation 26:
    t_step = epsi*a0 / sum(expctd_net_change*part_propensity_diff)
    delta_t = optimize.fmin(t_step, 0.00012)
    print("calculated delta_t:\n", delta_t)
    return delta_t

To pass the propensity_calc function to scipy.derviative I've tried to use a lambda function but I get the following error:

File "C:\Users\Mike\AppData\Local\Programs\Python\Python38-32\lib\site-packages\scipy\misc\common.py", line 119, in derivative
val += weights[k]*func(x0+(k-ho)*dx,*args)
TypeError: <lambda>() missing 2 required positional arguments: 'popul_num' and 'stoch_rate'

I've read the lambda documentation but I still don't understand where I'm going wrong, any suggestions as to how I can fix this error and do the partial differentiation?

Cheers

Body:
The lambda you defined is a constant function of three parameters that always return a function. Since you want a one-dimensional function (from my understanding), what you probably meant is:

lambda popul_num: propensity_calc(LHS, popul_num, stoch_rate)

This can be read as "The function that takes a parameter called popul_num and returns propensity_calc(LHS, popul_num, stoch_rate)".

By calling scipy.misc.derivative with the above lambda at point popul_num[x], you will get the value of the partial derivative of propensity_calc with respect to popul_num at point (LHS, popul_num, stoch_rate). It means that you have to define LHS and stoch_rate in this case. Indeed, don't forget that the partial derivative is still a function of three parameters.


问:
Why won't this plugin (for minecraft java) work?
I use eclipse (keep in mind, I'm a beginner), I have made a bukkit plugin which doesn't work - when it is put into the plugins folder of my Minecraft server, it doesn't change anything, and the custom commands don't work. I have installed the correct version of bukkit. Does anyone know what's wrong?

Pastebin - https://pastebin.com/PbhLFic2PbhLFic2

package customcommands;

import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;

public class customcommands extends JavaPlugin {

    @Override
    public void onEnable() {
        getLogger().info("This plugin is now on and fuctioning");
    }

    @Override
    public void onDisable() {

    }

    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {

        if (cmd.getName().equalsIgnoreCase("hello") && sender instanceof Player) {

            Player player = (Player) sender;

            player.sendMessage("Hello, " + player.getName() + "!");
        }
        return false;
    }

    public boolean onCommand1(CommandSender sender, Command cmd, String label, String[] args) {

        if (cmd.getName().equalsIgnoreCase("discord") && sender instanceof Player) {

            Player player = (Player) sender;

            player.sendMessage("§c§lDiscord §8§l- §e Want to connect with us? §e§dhttps://discord.gg/T9fhEDh");
        }
        return false;

    }

    public boolean onCommand2(CommandSender sender, Command cmd, String label, String[] args) {

        if (cmd.getName().equalsIgnoreCase("website") && sender instanceof Player) {

            Player player = (Player) sender;

            player.sendMessage("§c§lShop §8§l- §e Want to visit the server website?  §e§dhttps://noname-mc.enjin.com/");

            return true;
        }
        return false;
    }
}
```

答:
There are multiple issues with the snippet you have provided. I highly suggest you read through some tutorials, specifically for this problem, have a read of this Spigot Wiki post; the process is the same for Bukkit and Spigot.

Your command won't work because you haven't registered a CommandExecutor, you would need to make the following changes to customcommands:

```<code>public class customcommands extends JavaPlugin implements CommandExecutor {

    @Override
    public void onEnable() {
        getLogger().info("This plugin is now on and functioning");
        this.getCommand("hello").setExecutor(this);
    }
</code>```

But you have multiple onCommand methods, CommandExecutors don't work like that, you'll need to make a new CommandExecutor for each new /command, for which you will need to place in other classes and register them.

You're also returning false which will prompt the CommandExecutor to return back to the player the default usage for the command, as supplied in your plugin.yml; if the command was successful, you should return true.

I would suggest that you try Java tutorials first before diving into the Bukkit API as you will struggle otherwise.

Body:
There are multiple issues with the snippet you have provided. I highly suggest you read through some tutorials, specifically for this problem, have a read of this Spigot Wiki post; the process is the same for Bukkit and Spigot.

Your command won't work because you haven't registered a CommandExecutor, you would need to make the following changes to customcommands:

public class customcommands extends JavaPlugin implements CommandExecutor {

    @Override
    public void onEnable() {
        getLogger().info("This plugin is now on and functioning");
        this.getCommand("hello").setExecutor(this);
    }

But you have multiple onCommand methods, CommandExecutors don't work like that, you'll need to make a new CommandExecutor for each new /command, for which you will need to place in other classes and register them.

You're also returning false which will prompt the CommandExecutor to return back to the player the default usage for the command, as supplied in your plugin.yml; if the command was successful, you should return true.

I would suggest that you try Java tutorials first before diving into the Bukkit API as you will struggle otherwise.


问:
Itunes connect screenshots require ipad even though project only for iphone
In xcode project devices is set to iphone but in itunes connect when i try to upload my app to the app store in itunes connect, the screenshots require me to post screenshots for ipad and ipad pro,</p>

答:
I know it's a bit late but I am just posting this here in case somebody else needs it.
After universal apps, it seems that an XCode version shipped with a bug where the project.pbxproj thinks its a universal app (TARGETED_DEVICE_FAMILY = "1,2";) even though the iPad checkbox is unticked in the project info.

To solve this, you can either:
 - check and uncheck the iPad checkbox (I know...). You should see the difference with git status
 - manually change to TARGETED_DEVICE_FAMILY = "1";


问:
How to make a variable that can be detected as multiple items
```<code>bot.on('message', msg=>{
   if(msg.content.includes(“hi” or? “hello” or? “hey”)){
      msg.reply(“hi” or? “hello” or? “hey”);
   }
})
</code>```

I’m coding a discord bot on my server and I want to add a feature where it responds to people. I want to make it so that my bot can detect multiple ways a user greets and have it greet them back.

答:
```<code>const greetings = ['hi', 'hello', 'hey'];

if (greetings.includes(msg.content)) {...}
</code>```

Body:
bot.on('message', msg=>{
   if(msg.content.includes(“hi” or? “hello” or? “hey”)){
      msg.reply(“hi” or? “hello” or? “hey”);
   }
})

I’m coding a discord bot on my server and I want to add a feature where it responds to people. I want to make it so that my bot can detect multiple ways a user greets and have it greet them back.