问:
how to solve Execution failed for task ':app:compileFlutterBuildDebug'
I was trying to run my Flutter app and this shows up:

```<code>    Compiler message:
lib/main.dart:1:8: Error: Not found: 'dart:html'
import 'dart:html';
       ^
Invalid depfile: C:\Users\IMBA\AndroidStudioProjects\mi_card_flutter-master\.dart_tool\flutter_build\410385fb4867e1d74565d68665ecb577\kernel_snapshot.d
Invalid depfile: C:\Users\IMBA\AndroidStudioProjects\mi_card_flutter-master\.dart_tool\flutter_build\410385fb4867e1d74565d68665ecb577\kernel_snapshot.d
...
Compiler message:
lib/main.dart:1:8: Error: Not found: 'dart:html'
import 'dart:html';
       ^
Unhandled exception:
FileSystemException(uri=org-dartlang-untranslatable-uri:dart%3Ahtml; message=StandardFileSystem only supports file:* and data:* URIs)
#0      StandardFileSystem.entityForUri (package:front_end/src/api_prototype/standard_file_system.dart:33:7)
#1      asFileUri (package:vm/kernel_front_end.dart:567:37)
#2      writeDepfile (package:vm/kernel_front_end.dart:760:21)
<asynchronous suspension>
#3      FrontendCompiler.compile (package:frontend_server/frontend_server.dart:536:15)
<asynchronous suspension>
#4      _FlutterFrontendCompiler.compile (package:flutter_frontend_server/server.dart:40:22)
#5      starter (package:flutter_frontend_server/server.dart:178:27)
#6      main (file:///C:/b/s/w/ir/cache/builder/src/flutter/flutter_frontend_server/bin/starter.dart:8:30)
#7      _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:299:32)
#8      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)

Target kernel_snapshot failed: Exception: Errors during snapshot creation: null
build failed.

FAILURE: Build failed with an exception.

* Where:
Script 'C:\Users\IMBA\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 882

* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\Users\IMBA\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 16s
Exception: Gradle task assembleDebug failed with exit code 1
</code>```

And something else showed up after I used the --scan flag in the problem section.

```<code>java.lang.ClassNotFoundException: com.google.wireless.android.sdk.stats.IntellijIndexingStats$Index
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at com.intellij.util.indexing.counters.IndexCounters.<clinit>(IndexCounters.java:34)
    at com.intellij.util.indexing.impl.MapReduceIndex.<init>(MapReduceIndex.java:94)
    at com.intellij.util.indexing.impl.MapReduceIndex.<init>(MapReduceIndex.java:110)
    at org.jetbrains.jps.backwardRefs.index.CompilerReferenceIndex$CompilerMapReduceIndex.<init>(CompilerReferenceIndex.java:248)
    at org.jetbrains.jps.backwardRefs.index.CompilerReferenceIndex.<init>(CompilerReferenceIndex.java:84)
    at org.jetbrains.jps.backwardRefs.JavaCompilerBackwardReferenceIndex.<init>(JavaCompilerBackwardReferenceIndex.java:12)
    at org.jetbrains.jps.backwardRefs.JavaBackwardReferenceIndexWriter.initialize(JavaBackwardReferenceIndexWriter.java:80)
    at org.jetbrains.jps.incremental.java.JavaBuilder.buildStarted(JavaBuilder.java:149)
    at org.jetbrains.jps.incremental.IncProjectBuilder.runBuild(IncProjectBuilder.java:359)
    at org.jetbrains.jps.incremental.IncProjectBuilder.build(IncProjectBuilder.java:178)
    at org.jetbrains.jps.cmdline.BuildRunner.runBuild(BuildRunner.java:139)
    at org.jetbrains.jps.cmdline.BuildSession.runBuild(BuildSession.java:288)
    at org.jetbrains.jps.cmdline.BuildSession.run(BuildSession.java:121)
    at org.jetbrains.jps.cmdline.BuildMain$MyMessageHandler.lambda$channelRead0$0(BuildMain.java:228)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
</code>```

I took all the material of this Flutter app from the appbrewery Flutter course. This happens when I was trying to make the MIcard project. Any thoughts to solving this problem?

答:
This worked for me.

Deleted build and android/app/build.

Body:
I was trying to run my Flutter app and this shows up:

    Compiler message:
lib/main.dart:1:8: Error: Not found: 'dart:html'
import 'dart:html';
       ^
Invalid depfile: C:\Users\IMBA\AndroidStudioProjects\mi_card_flutter-master\.dart_tool\flutter_build\410385fb4867e1d74565d68665ecb577\kernel_snapshot.d
Invalid depfile: C:\Users\IMBA\AndroidStudioProjects\mi_card_flutter-master\.dart_tool\flutter_build\410385fb4867e1d74565d68665ecb577\kernel_snapshot.d
...
Compiler message:
lib/main.dart:1:8: Error: Not found: 'dart:html'
import 'dart:html';
       ^
Unhandled exception:
FileSystemException(uri=org-dartlang-untranslatable-uri:dart%3Ahtml; message=StandardFileSystem only supports file:* and data:* URIs)
#0      StandardFileSystem.entityForUri (package:front_end/src/api_prototype/standard_file_system.dart:33:7)
#1      asFileUri (package:vm/kernel_front_end.dart:567:37)
#2      writeDepfile (package:vm/kernel_front_end.dart:760:21)
<asynchronous suspension>
#3      FrontendCompiler.compile (package:frontend_server/frontend_server.dart:536:15)
<asynchronous suspension>
#4      _FlutterFrontendCompiler.compile (package:flutter_frontend_server/server.dart:40:22)
#5      starter (package:flutter_frontend_server/server.dart:178:27)
#6      main (file:///C:/b/s/w/ir/cache/builder/src/flutter/flutter_frontend_server/bin/starter.dart:8:30)
#7      _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:299:32)
#8      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)

Target kernel_snapshot failed: Exception: Errors during snapshot creation: null
build failed.

FAILURE: Build failed with an exception.

* Where:
Script 'C:\Users\IMBA\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 882

* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\Users\IMBA\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 16s
Exception: Gradle task assembleDebug failed with exit code 1

And something else showed up after I used the --scan flag in the problem section.

java.lang.ClassNotFoundException: com.google.wireless.android.sdk.stats.IntellijIndexingStats$Index
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at com.intellij.util.indexing.counters.IndexCounters.<clinit>(IndexCounters.java:34)
    at com.intellij.util.indexing.impl.MapReduceIndex.<init>(MapReduceIndex.java:94)
    at com.intellij.util.indexing.impl.MapReduceIndex.<init>(MapReduceIndex.java:110)
    at org.jetbrains.jps.backwardRefs.index.CompilerReferenceIndex$CompilerMapReduceIndex.<init>(CompilerReferenceIndex.java:248)
    at org.jetbrains.jps.backwardRefs.index.CompilerReferenceIndex.<init>(CompilerReferenceIndex.java:84)
    at org.jetbrains.jps.backwardRefs.JavaCompilerBackwardReferenceIndex.<init>(JavaCompilerBackwardReferenceIndex.java:12)
    at org.jetbrains.jps.backwardRefs.JavaBackwardReferenceIndexWriter.initialize(JavaBackwardReferenceIndexWriter.java:80)
    at org.jetbrains.jps.incremental.java.JavaBuilder.buildStarted(JavaBuilder.java:149)
    at org.jetbrains.jps.incremental.IncProjectBuilder.runBuild(IncProjectBuilder.java:359)
    at org.jetbrains.jps.incremental.IncProjectBuilder.build(IncProjectBuilder.java:178)
    at org.jetbrains.jps.cmdline.BuildRunner.runBuild(BuildRunner.java:139)
    at org.jetbrains.jps.cmdline.BuildSession.runBuild(BuildSession.java:288)
    at org.jetbrains.jps.cmdline.BuildSession.run(BuildSession.java:121)
    at org.jetbrains.jps.cmdline.BuildMain$MyMessageHandler.lambda$channelRead0$0(BuildMain.java:228)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

I took all the material of this Flutter app from the appbrewery Flutter course. This happens when I was trying to make the MIcard project. Any thoughts to solving this problem?


来源: stackexchange

问:
Can't create Mole for System.Environment class
I want to replace behavior of Environment.GetFolderPath in my unittest, but after generation moles for System assembly, System.Moles assembly does not contain definition of type MEnvironment.

答:
Have you tried stubbing in an interface type?  The sub can be passed in via constructor injection or via method input parameter.  For example, create interface IEnvironment, including the GetFolderPath method.  If you already know how to do this, then feel free to go on your way.  Otherwise, the following demonstrates how to stub in the Environment class.  (I am typing this on my phone, so bear with me ;)

```<code>public interface IEnvironment
{
  string GetFolderPath(Environment.SpecialFolder folder);
}
</code>```

Next, create a stub:

```<code>public class MyEnvironment : Environment, IEnvironment
{
  public string GetFolderPath(Environment.SpecialFolder folder)
  {
    return base.GetFolderPath(folder);
  }
}
</code>```

Pass the stub in to your method or class constructor as a parameter:

```<code>public void MyMethod(IEnvironment env)
{
  var path = env.GetFolderPath():
}
</code>```

For testing, create a mock type, or mole MyEnvironment.GetGolderPath.  Creating a mock is preferable to a moled type, for performance reasons.  The mock simply returns a value instead of calling the base method, just as the moled type would.  He stub is necessary, either way, so you may as well make the mock, as it can be reused for other tests.

ContentLicense: CC BY-SA 3.0

Body:
Have you tried stubbing in an interface type?  The sub can be passed in via constructor injection or via method input parameter.  For example, create interface IEnvironment, including the GetFolderPath method.  If you already know how to do this, then feel free to go on your way.  Otherwise, the following demonstrates how to stub in the Environment class.  (I am typing this on my phone, so bear with me ;)

public interface IEnvironment
{
  string GetFolderPath(Environment.SpecialFolder folder);
}

Next, create a stub:

public class MyEnvironment : Environment, IEnvironment
{
  public string GetFolderPath(Environment.SpecialFolder folder)
  {
    return base.GetFolderPath(folder);
  }
}

Pass the stub in to your method or class constructor as a parameter:

public void MyMethod(IEnvironment env)
{
  var path = env.GetFolderPath():
}

For testing, create a mock type, or mole MyEnvironment.GetGolderPath.  Creating a mock is preferable to a moled type, for performance reasons.  The mock simply returns a value instead of calling the base method, just as the moled type would.  He stub is necessary, either way, so you may as well make the mock, as it can be reused for other tests.


问:
Missing categories 2 months before sunset - Migration of Google My Business API
Maybe I am missing something with the current migration of Google MyBusiness API.

We have scripts running on the Google My Business API which will end in April 2022, replaced by several new Business APIs.

The problem is that it's February 8 and some features like reviews, posts, ..., that we use, are still not migrated to the new APIs.

I can't see how we're going to do the migration if they are delivered a few days before the deadline. Unless they are not migrated at all?

Am I the only one with this problem ?

Thanks for any news

答:
Only those parts of the GMB API that have published successors will be deprecated:

https://developers.google.com/my-business/content/sunset-dates

Neither the review nor the local post methods are marked for deprecation.

Update: the documentation tree also has indicators showing what is and is not deprecated (I added the green squares to signify that those examples are not deprecated yet).

ContentLicense: CC BY-SA 4.0


问:
404 Not Found nodejs to localhost
I am writing nodejs express to fetch the data to web page. an error appear 404 Not Found when open

http://127.0.0.1:3000/users

in the Dev tool on the browser show: users:1          GET http://127.0.0.1:3000/users 404 (Not Found)

below are the app.js and index.js and users.js files

I think I have an issue with the routes

app.js

```<code>var createError = require('http-errors');
 var express = require('express');
 var path = require('path');
 var cookieParser = require('cookie-parser');
 var logger = require('morgan');
 var expressValidator = require('express-validator');
 var flash = require('express-flash');
 var session = require('express-session');
 var bodyParser = require('body-parser');

 var mysql = require('mssql');
//  var connection  = require('./lib/db');

 var indexRouter = require('./routes/index');
 var usersRouter = require('./routes/users');

 var app = express();

// view engine setup
 app.set('views', path.join(__dirname, 'views'));
 app.set('view engine', 'ejs');

 app.use(logger('dev'));
 app.use(bodyParser.json());
 //I put false instead true
 app.use(bodyParser.urlencoded({ extended: true }));
 app.use(cookieParser());
 app.use(express.static(path.join(__dirname, 'public')));

 app.use(session({
     secret: '123456cat',
     resave: false,
     saveUninitialized: true,
     cookie: { maxAge: 60000 }
 }))

 app.use(flash());
 app.use(expressValidator());

 app.use('/', indexRouter);
 app.use('/list', usersRouter);

 // catch 404 and forward to error handler
 app.use(function(req, res, next) {
   next(createError(404));
 });

 // error handler
 app.use(function(err, req, res, next) {
   // set locals, only providing error in development
   res.locals.message = err.message;
   res.locals.error = req.app.get('env') === 'development' ? err : {};
 // render the error page
   res.status(err.status || 500);
   res.render('error');
 });

 module.exports = app;
</code>```

below are the routes files.
routes/index.js

```<code>var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;
</code>```

routes/users.js

```<code>var express = require('express');
var router = express.Router();
var connection  = require('../database.js');

/* GET home page. */
router.get('/', function(req, res, next) {

 connection.query('SELECT * FROM users',function(err,rows)     {

        if(err){
         req.flash('error', err);
         res.render('list',{page_title:"Users - Node.js",data:''});
        }else{

            res.render('list',{page_title:"Users - Node.js",data:rows});
        }

         });

    });

module.exports = router;
</code>```

答:
As I already mentioned in my comment, you don't have a /user route therefore you will get a 404 NotFound error.

Change this

```<code>app.use('/list', usersRouter);
</code>```

To this

```<code>app.use('/user', usersRouter);
</code>```

Title: 404 Not Found nodejs to localhost

Body:
I am writing nodejs express to fetch the data to web page. an error appear 404 Not Found when open

http://127.0.0.1:3000/users

in the Dev tool on the browser show: users:1          GET http://127.0.0.1:3000/users 404 (Not Found)

below are the app.js and index.js and users.js files

I think I have an issue with the routes

app.js

var createError = require('http-errors');
 var express = require('express');
 var path = require('path');
 var cookieParser = require('cookie-parser');
 var logger = require('morgan');
 var expressValidator = require('express-validator');
 var flash = require('express-flash');
 var session = require('express-session');
 var bodyParser = require('body-parser');

 var mysql = require('mssql');
//  var connection  = require('./lib/db');

 var indexRouter = require('./routes/index');
 var usersRouter = require('./routes/users');

 var app = express();

// view engine setup
 app.set('views', path.join(__dirname, 'views'));
 app.set('view engine', 'ejs');

 app.use(logger('dev'));
 app.use(bodyParser.json());
 //I put false instead true
 app.use(bodyParser.urlencoded({ extended: true }));
 app.use(cookieParser());
 app.use(express.static(path.join(__dirname, 'public')));

 app.use(session({
     secret: '123456cat',
     resave: false,
     saveUninitialized: true,
     cookie: { maxAge: 60000 }
 }))

 app.use(flash());
 app.use(expressValidator());

 app.use('/', indexRouter);
 app.use('/list', usersRouter);

 // catch 404 and forward to error handler
 app.use(function(req, res, next) {
   next(createError(404));
 });

 // error handler
 app.use(function(err, req, res, next) {
   // set locals, only providing error in development
   res.locals.message = err.message;
   res.locals.error = req.app.get('env') === 'development' ? err : {};
 // render the error page
   res.status(err.status || 500);
   res.render('error');
 });

 module.exports = app;

below are the routes files.
routes/index.js

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;

routes/users.js

var express = require('express');
var router = express.Router();
var connection  = require('../database.js');

/* GET home page. */
router.get('/', function(req, res, next) {

 connection.query('SELECT * FROM users',function(err,rows)     {

        if(err){
         req.flash('error', err);
         res.render('list',{page_title:"Users - Node.js",data:''});
        }else{

            res.render('list',{page_title:"Users - Node.js",data:rows});
        }

         });

    });

module.exports = router;

Body:
As I already mentioned in my comment, you don't have a /user route therefore you will get a 404 NotFound error.

Change this

app.use('/list', usersRouter);

To this

app.use('/user', usersRouter);


问:
Compare two list for differences - DateTime & String
Sorry but there is no code for this question... I hope thats ok.

So, I have a list of objects with two properties,  DateTime and String.

As a matter of fact, DateTime is just date (insertDate), for example 2022-02-04T00:00:00+01:00.
String is of course some text, a lot of text :)

I have to compare the list with these two properties with another list of identical structure.

To be more clear, those are the data returned by the API, so I have to compare is there any differences between these two lists.

答:
You can use a CustomComparator:

Given your base class for both lists:

```<code>public class BaseClass
{
    public DateTime date { get; set; }
    public string anyString { get; set; }
}
</code>```

Define the custom comparer for it

```<code>public class BaseClassComparer : IEqualityComparer<BaseClass>
{
    public bool Equals(BaseClass item1, BaseClass item2)
    {
        //Check whether the compared objects reference the same data.
        if (Object.ReferenceEquals(item1, item2)) return true;

        //Check whether any of the compared objects is null.
        if (Object.ReferenceEquals(item1, null) || Object.ReferenceEquals(item2, null))
        return false;

        //Check whether the required fields' properties are equal.
        return (item1.date == item2.date) && (item1.anyString == item2.anyString);
    }

    public int GetHashCode(BaseClass item)
    {
        //Check whether the object is null
        if (Object.ReferenceEquals(item, null)) return 0;

        //Get hash code for the Date field if it is not null.
        int hashItemDate = item.date == null ? 0 : item.date.GetHashCode();

        //Get hash code for the string field.
        int hashItemString = item.anyString.GetHashCode();

        //Calculate the hash code for the item.
        return hashItemDate ^ hashItemString;
    }
}
</code>```

Then you can use it as follows:

```<code>        List<BaseClass> class1 = new List<BaseClass>();
        List<BaseClass> class2 = new List<BaseClass>();
        BaseClass item1 = new BaseClass() {date = DateTime.Now, anyString = "Hello"};
        class1.Add(item1);
        class2.Add(item1); //<-Equal till here
        //class1.Add(item1); //<-uncomment for false
        bool result = class1.SequenceEqual(class2, new BaseClassComparer());
</code>```

Body:
You can use a CustomComparator:

Given your base class for both lists:

public class BaseClass
{
    public DateTime date { get; set; }
    public string anyString { get; set; }
}

Define the custom comparer for it

public class BaseClassComparer : IEqualityComparer<BaseClass>
{
    public bool Equals(BaseClass item1, BaseClass item2)
    {
        //Check whether the compared objects reference the same data.
        if (Object.ReferenceEquals(item1, item2)) return true;

        //Check whether any of the compared objects is null.
        if (Object.ReferenceEquals(item1, null) || Object.ReferenceEquals(item2, null))
        return false;

        //Check whether the required fields' properties are equal.
        return (item1.date == item2.date) && (item1.anyString == item2.anyString);
    }

    public int GetHashCode(BaseClass item)
    {
        //Check whether the object is null
        if (Object.ReferenceEquals(item, null)) return 0;

        //Get hash code for the Date field if it is not null.
        int hashItemDate = item.date == null ? 0 : item.date.GetHashCode();

        //Get hash code for the string field.
        int hashItemString = item.anyString.GetHashCode();

        //Calculate the hash code for the item.
        return hashItemDate ^ hashItemString;
    }
}

Then you can use it as follows:

        List<BaseClass> class1 = new List<BaseClass>();
        List<BaseClass> class2 = new List<BaseClass>();
        BaseClass item1 = new BaseClass() {date = DateTime.Now, anyString = "Hello"};
        class1.Add(item1);
        class2.Add(item1); //<-Equal till here
        //class1.Add(item1); //<-uncomment for false
        bool result = class1.SequenceEqual(class2, new BaseClassComparer());


问:
How to use LIKE Operator in LINQ to Entity Framework
I'm using Entity Framework.

Problem: search a name that start with 'a' in a list of strings:

```<code>var likeQuery = from k in dbContext.Categories
                where sqlMethod.Like(k.CategoryName, "a%" )  // name start with a
                select k;

foreach (var item in likeQuery)
{
    Console.WriteLine(Item.);
}
</code>```

答:
If this is EF Core than the following can be used.

```<code>public static  List<Categories> CategoriesLike(string keyword)
{
    using var dbContext = new NorthwindContext();

    return dbContext.Categories.Where(category =>
        EF.Functions.Like(category.CategoryName, $"{keyword}%"))
        .ToList();
}
</code>```

Body:
I'm using Entity Framework.

Problem: search a name that start with 'a' in a list of strings:

var likeQuery = from k in dbContext.Categories
                where sqlMethod.Like(k.CategoryName, "a%" )  // name start with a
                select k;

foreach (var item in likeQuery)
{
    Console.WriteLine(Item.);
}

Body:
If this is EF Core than the following can be used.

public static  List<Categories> CategoriesLike(string keyword)
{
    using var dbContext = new NorthwindContext();

    return dbContext.Categories.Where(category =>
        EF.Functions.Like(category.CategoryName, $"{keyword}%"))
        .ToList();
}


问:
How does Firefox process history to show in the location bar's small black down arrow popup?
There's a nice feature in Firefox's awesome bar. It displays your most popular sites in a dropdown list when clicking on a small black down arrow icon on the right side of bar.

There's also a Google Chrome extension which does almost the same but in a less usable way:
https://chrome.google.com/webstore/detail/logbmehmiacemkimbpcbjgaikobdndah

I want to optimize this extension a little so the results are like in Firefox. The main difference between Chrome's extension and Firefox's feature is that an extension doesn't process the urls to display shorter path versions. Firefox reduces urls and I often can see just domains without specified paths. However urls like twitter.com/username appear with the path part of url.

It would be great to learn the algorithm Firefox uses for that. I think it is dealing with frecencies somehow.

Any tips are welcome.
Thank you.

答:
I think that the algorithm is a very simple one:

If the "path" part of the URL is "/" - remove it. "http://example.com/" is transformed into "http://example.com" while "http://example.com/foo/" stays the same.

If the URL starts with "http://" - remove that part. "http://example.com" is transformed into "example.com" while "https://example.com" stays the same.

That seems to be it, it's just removing the URL parts that don't carry any information.

Edit: This behavior has been introduced in Firefox 7 and is controlled by the browser.urlbar.trimURLs preference. Looking at the source code (function trimURL) it works pretty much the way I said (with some additional restrictions).


问:
Disable persistent does not work in redis enterprise cluster on kubernetes
I try to creating redis enterprise cluster with redis operator.

For declaration of my cluster I write something like below

```<code>apiVersion: "app.redislabs.com/v1"
kind: "RedisEnterpriseCluster"
metadata:
  name: "harbor-cluster"
spec:
  nodes: 3
  persistentSpec:
    enabled: false
  redisEnterpriseNodeResources:
    limits:
      cpu: 1000m
      memory: 1Gi
    requests:
      cpu: 1000m
      memory: 1Gi
</code>```

But my problem is even I set presistentSpec to false, I see kubectl describe pvc redis-enterprise-storage-harbor-cluster-0  show redis try to claim pv and my bootstrapping of my pods is failed.

```<code>Name:          redis-enterprise-storage-harbor-cluster-0
Namespace:     default
StorageClass:
Status:        Pending
Volume:
Labels:        app=redis-enterprise
               redis.io/cluster=harbor-cluster
               redis.io/role=node
Annotations:   <none>
Finalizers:    [kubernetes.io/pvc-protection]
Capacity:
Access Modes:
VolumeMode:    Filesystem
Used By:       harbor-cluster-0
Events:
  Type    Reason         Age                      From                         Message
  ----    ------         ----                     ----                         -------
  Normal  FailedBinding  108s (x1321 over 5h31m)  persistentvolume-controller  no persistent volumes available for this claim and no storage class is set
</code>```

If I run kubectl get pods you can see harbor-cluster-0 does not ready (because bootstrapping of redis pod is failed)

```<code>NAME                                              READY   STATUS    RESTARTS   AGE
harbor-cluster-0                                  1/2     Running   0          72s
harbor-cluster-services-rigger-557b6f75c8-hgfzj   1/1     Running   0          73s
redis-enterprise-operator-7f8d8548c5-qvd48        2/2     Running   0          6h16m
</code>```

How to resolve it?

答:
Posting comment as the community wiki answer for better visibility

Is it possible that you had previously created a Redis Enterprise Cluster with the same name before? I am thinking the PVC could be from a previous run. Can you check if the PVC is older than the REC by comparing their creation timestamp?

Body:
I try to creating redis enterprise cluster with redis operator.

For declaration of my cluster I write something like below

apiVersion: "app.redislabs.com/v1"
kind: "RedisEnterpriseCluster"
metadata:
  name: "harbor-cluster"
spec:
  nodes: 3
  persistentSpec:
    enabled: false
  redisEnterpriseNodeResources:
    limits:
      cpu: 1000m
      memory: 1Gi
    requests:
      cpu: 1000m
      memory: 1Gi

But my problem is even I set presistentSpec to false, I see kubectl describe pvc redis-enterprise-storage-harbor-cluster-0  show redis try to claim pv and my bootstrapping of my pods is failed.

Name:          redis-enterprise-storage-harbor-cluster-0
Namespace:     default
StorageClass:
Status:        Pending
Volume:
Labels:        app=redis-enterprise
               redis.io/cluster=harbor-cluster
               redis.io/role=node
Annotations:   <none>
Finalizers:    [kubernetes.io/pvc-protection]
Capacity:
Access Modes:
VolumeMode:    Filesystem
Used By:       harbor-cluster-0
Events:
  Type    Reason         Age                      From                         Message
  ----    ------         ----                     ----                         -------
  Normal  FailedBinding  108s (x1321 over 5h31m)  persistentvolume-controller  no persistent volumes available for this claim and no storage class is set

If I run kubectl get pods you can see harbor-cluster-0 does not ready (because bootstrapping of redis pod is failed)

NAME                                              READY   STATUS    RESTARTS   AGE
harbor-cluster-0                                  1/2     Running   0          72s
harbor-cluster-services-rigger-557b6f75c8-hgfzj   1/1     Running   0          73s
redis-enterprise-operator-7f8d8548c5-qvd48        2/2     Running   0          6h16m

How to resolve it?


问:
Updating an existing List using Linq in C#
I have a list and data as follows.

```<code>public class Test
{
 public int Id {get;set;}
 public string Name {get;set;}
 public string Quality {get;set;}
}

Test test = new Test();
//db call to get test data
//test = [{1,'ABC','Good'},{2,'GEF','Bad'}]
</code>```

I have to modify the list such that Name should be only the first 2 characters and Quality should be the first letter.

Expected Output:

```<code>//test = [{1,'A','G'},{2,'GE','B'}]
</code>```

I tried to achieve with Linq foreach as follows. But I am not sure to write conditional statements inside forloop within Linq which resulted in error.

```<code>test.ForEach(x=> return x.Take(1))
</code>```

答:
You can use simply use String.Substring as follows:

```<code>test.ForEach(s =>
{
    s.Name = s.Name.Substring(0, 2);
    s.Quality = s.Quality.Substring(0, 1);
});
</code>```

Thanks, @Tim for pointing out that if Name or Quality is short then this code throws an exception. See Problem with Substring() - ArgumentOutOfRangeException for the possible solutions for that.

Body:
I have a list and data as follows.

public class Test
{
 public int Id {get;set;}
 public string Name {get;set;}
 public string Quality {get;set;}
}

Test test = new Test();
//db call to get test data
//test = [{1,'ABC','Good'},{2,'GEF','Bad'}]

I have to modify the list such that Name should be only the first 2 characters and Quality should be the first letter.

Expected Output:

//test = [{1,'A','G'},{2,'GE','B'}]

I tried to achieve with Linq foreach as follows. But I am not sure to write conditional statements inside forloop within Linq which resulted in error.

test.ForEach(x=> return x.Take(1))

Body:
You can use simply use String.Substring as follows:

test.ForEach(s =>
{
    s.Name = s.Name.Substring(0, 2);
    s.Quality = s.Quality.Substring(0, 1);
});

Thanks, @Tim for pointing out that if Name or Quality is short then this code throws an exception. See Problem with Substring() - ArgumentOutOfRangeException for the possible solutions for that.


问:
How do I convert an cv::Mat to float pointer?
I want to represent the matrix of cv::SIFT descriptors cv::Mat descriptors as float*. This is because I want to use GMM from VLFeat (if you have any better solution, please let me know). This is the code that I came up with:

```<code>if(!prova.isContinous()){
    std::err<<"Descriptor matrix not continuous!"<<std::endl;
    return 1;
}
float *data = new float[desc.total()];
std::memcpy(data,prova.data,prova.total() * sizeof(float));
</code>```

Trying this code with a toy matrix:

```<code>cv::Mat prova = (cv::Mat_<float>(3,3) << 0.1, 0.3, 2.1, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8);
</code>```

And print the values:

```<code>for(int i=0;i<prova.total();i++)
    std::cout<<*(data+i)<<std::endl;
</code>```

This works fine, but since we're dealing with pointers (and it's always a dangerous matter) I would like an opinion.

NOTE: just for giving a context, this is how I'm going to use data:

```<code>VlGMM* gmm = vl_gmm_new(VL_TYPE_FLOAT, desc.cols, 2) ;
vl_gmm_cluster (gmm, data, desc.rows);
</code>```

答:
the issue that can happen if stride not equal to number of columns*4

4= size of float, you can get holes in the data so the only way to be sure is to copy pixel by pixel

Body:
I want to represent the matrix of cv::SIFT descriptors cv::Mat descriptors as float*. This is because I want to use GMM from VLFeat (if you have any better solution, please let me know). This is the code that I came up with:

if(!prova.isContinous()){
    std::err<<"Descriptor matrix not continuous!"<<std::endl;
    return 1;
}
float *data = new float[desc.total()];
std::memcpy(data,prova.data,prova.total() * sizeof(float));

Trying this code with a toy matrix:

cv::Mat prova = (cv::Mat_<float>(3,3) << 0.1, 0.3, 2.1, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8);

And print the values:

for(int i=0;i<prova.total();i++)
    std::cout<<*(data+i)<<std::endl;

This works fine, but since we're dealing with pointers (and it's always a dangerous matter) I would like an opinion.

NOTE: just for giving a context, this is how I'm going to use data:

VlGMM* gmm = vl_gmm_new(VL_TYPE_FLOAT, desc.cols, 2) ;
vl_gmm_cluster (gmm, data, desc.rows);


问:
Print Answer using Facts
I am trying to print the values present in Facts. For example when I have the following Facts:

```<code>terrain(2,(2,4,3,1)).
terrain(2,(3,1,2,4)).
terrain(1,(4,3,1,2)).
terrain(3,(1,2,4,3)).
</code>```

Input:

```<code>v([1,2,3],R).
</code>```

It should give me:

```<code>R = [(4,3,1,2), (2,4,3,1), (3,1,2,4), (1,2,4,3)]
</code>```

But the code isn't printing the second value of 2 i.e. (3,1,2,4) present in Facts.
I am getting:

```<code>R = [(4,3,1,2), (2,4,3,1), (1,2,4,3)]
</code>```

How do I get all possible values for a certain value present in a Fact.

My code:

```<code>%Facts
terrain(2,(2,4,3,1)).
terrain(2,(3,1,2,4)).
terrain(1,(4,3,1,2)).
terrain(3,(1,2,4,3)).

v([],[]).
v([H|T],[Q|R]):-
    terrain(H,Q),
    v(T,R),!.
</code>```

Title: Print Answer using Facts

Body:
I am trying to print the values present in Facts. For example when I have the following Facts:

terrain(2,(2,4,3,1)).
terrain(2,(3,1,2,4)).
terrain(1,(4,3,1,2)).
terrain(3,(1,2,4,3)).

Input:

v([1,2,3],R).

It should give me:

R = [(4,3,1,2), (2,4,3,1), (3,1,2,4), (1,2,4,3)]

But the code isn't printing the second value of 2 i.e. (3,1,2,4) present in Facts.
I am getting:

R = [(4,3,1,2), (2,4,3,1), (1,2,4,3)]

How do I get all possible values for a certain value present in a Fact.

My code:

%Facts
terrain(2,(2,4,3,1)).
terrain(2,(3,1,2,4)).
terrain(1,(4,3,1,2)).
terrain(3,(1,2,4,3)).

v([],[]).
v([H|T],[Q|R]):-
    terrain(H,Q),
    v(T,R),!.

Body:
First of all, let's look at your definition. Why did you insert a cut here? Let's see what happens without it:

?- v([1,2,3],R).
   R = [(4,3,1,2),(2,4,3,1),(1,2,4,3)]
;  R = [(4,3,1,2),(3,1,2,4),(1,2,4,3)].

So with this cut you removed the second solution. Now you may not like it, but let's keep in mind your definition of v/2. To make it easier to read, I will use a generalization of your definition.

:- op(950, fy, *).
* _G_0. % to remove a goal

v([],[]).
v([H|T],[Q|R]):-
    * <s>terrain(H,Q)</s>,
    v(T,R).

So what remains is a relation that is true when both arguments are lists of the same length. And thus also with terrain/2 added this will hold. There is no way to make the second argument a list that is longer. If you really want to change this, you have to modify already that generalized part.

v2([], []).
v2([H|Hs], Vs0) :-
   setof(V, terrain(H, V), Vs),
   append(Vs, Vs1,Vs0),
   v2(Hs, Vs1).

?- v2([1,2,3],R).
   R = [(4,3,1,2),(2,4,3,1),(3,1,2,4),(1,2,4,3)].

Alternatively, and preferably, use a DCG:

seq([]) -->
   [].
seq([E|Es]) -->
   [E],
   seq(Es).

v([]) -->
   [].
v([H|Hs]) -->
   {setof(V, terrain(H, V), Vs)},
   seq(Vs),
   v(Hs).

?- phrase(v([1,2,3]), Vs).
   Vs = [(4,3,1,2),(2,4,3,1),(3,1,2,4),(1,2,4,3)].
?- length(Hs, 2), phrase(v(Hs), Vs).
   Hs = [1,1], Vs = [(4,3,1,2),(4,3,1,2)]
;  Hs = [1,2], Vs = [(4,3,1,2),(2,4,3,1),(3,1,2,4)]
;  Hs = [1,3], Vs = [(4,3,1,2),(1,2,4,3)]
;  Hs = [2,1], Vs = [(2,4,3,1),(3,1,2,4),(4,3,1,2)]
;  Hs = [2,2], Vs = [(2,4,3,1),(3,1,2,4),(2,4,3,1),(3,1,2,4)]
;  Hs = [2,3], Vs = [(2,4,3,1),(3,1,2,4),(1,2,4,3)]
;  Hs = [3,1], Vs = [(1,2,4,3),(4,3,1,2)]
;  Hs = [3,2], Vs = [(1,2,4,3),(2,4,3,1),(3,1,2,4)]
;  Hs = [3,3], Vs = [(1,2,4,3),(1,2,4,3)].
?- Hs = [A,B], dif(A,B), phrase(v(Hs), Vs).
   Hs = [1,2], A = 1, B = 2, Vs = [(4,3,1,2),(2,4,3,1),(3,1,2,4)]
;  Hs = [1,3], A = 1, B = 3, Vs = [(4,3,1,2),(1,2,4,3)]
;  Hs = [2,1], A = 2, B = 1, Vs = [(2,4,3,1),(3,1,2,4),(4,3,1,2)]
;  Hs = [2,3], A = 2, B = 3, Vs = [(2,4,3,1),(3,1,2,4),(1,2,4,3)]
;  Hs = [3,1], A = 3, B = 1, Vs = [(1,2,4,3),(4,3,1,2)]
;  Hs = [3,2], A = 3, B = 2, Vs = [(1,2,4,3),(2,4,3,1),(3,1,2,4)].

And, btw, in Prolog it is often preferred to write v(4,3,1,2)) instead of (4,3,1,2). Just say write_canonical((4,3,1,2)). to see why.


问:
Make Sqlalchemy Use Date In Filter Using Postgresql
I'm trying to perform the following query in Sqlalchemy.

```<code>Select * from "Mytable" where Date(date_time_field) = "2011-08-16";
</code>```

I have tried several methods. Some here on SO.
But none seems "realistic" since some do Casts Other String Formating ?!?! and not a plain simple Date() ( By Date i Mean the Postgresql Date not the Python One) at the ORM Field.

Is it possible at the ORM level to declare a Simple Date() around the queried field?

答:
To keep it clean for any web search.</p>
```<code>from sqlalchemy import Date, cast
from datetime import date

my_data = session.query(MyObject).\
filter(cast(MyObject.date_time,Date) == date.today()).all()
</code>```

Body:
I'm trying to perform the following query in Sqlalchemy.

Select * from "Mytable" where Date(date_time_field) = "2011-08-16";

I have tried several methods. Some here on SO.
But none seems "realistic" since some do Casts Other String Formating ?!?! and not a plain simple Date() ( By Date i Mean the Postgresql Date not the Python One) at the ORM Field.

Is it possible at the ORM level to declare a Simple Date() around the queried field?

Body:
To keep it clean for any web search.

from sqlalchemy import Date, cast
from datetime import date

my_data = session.query(MyObject).\
filter(cast(MyObject.date_time,Date) == date.today()).all()


问:
Flutter : Image Picker Exception
I'm trying to pick image by image picker package , it was working but now I get this error

Unhandled Exception: PlatformException(already_active, Image picker is
already active, null, null)

and this is the code which I'm using :

```<code> File _image;
 final picker = ImagePicker();

  Future getImage() async {
    var image = await picker.getImage(source: ImageSource.gallery);
    setState(() {
      _image = File(image.path);
      Navigator.pop(this.context);
    });
  }

  Future getCameraImage() async {
    var image = await picker.getImage(source: ImageSource.camera);
    setState(() {
      _image = File(image.path);
      Navigator.pop(this.context);
    });
  }
</code>```

Explain :
when clicking to pick image ( gallery or camera ) first time it was opening the gallery and after selecting image , the setState for _image = File(image.path); not work and after that I'm trying to click to pick image again then this exception is appear

答:
Try this-</p>
```<code>File _image;

  Future getImage() async {
    ImagePicker picker = ImagePicker();
    var image = await picker.getImage(source: ImageSource.gallery);
    setState(() {
      _image = File(image.path);
      Navigator.pop(this.context);
    });
  }

  Future getCameraImage() async {
    ImagePicker picker = ImagePicker();
    var image = await picker.getImage(source: ImageSource.camera);
    setState(() {
      _image = File(image.path);
      Navigator.pop(this.context);
    });
  }
</code>```

Title: Flutter : Image Picker Exception

Body:
I'm trying to pick image by image picker package , it was working but now I get this error

Unhandled Exception: PlatformException(already_active, Image picker is
already active, null, null)

and this is the code which I'm using :

 File _image;
 final picker = ImagePicker();

  Future getImage() async {
    var image = await picker.getImage(source: ImageSource.gallery);
    setState(() {
      _image = File(image.path);
      Navigator.pop(this.context);
    });
  }

  Future getCameraImage() async {
    var image = await picker.getImage(source: ImageSource.camera);
    setState(() {
      _image = File(image.path);
      Navigator.pop(this.context);
    });
  }

Explain :
when clicking to pick image ( gallery or camera ) first time it was opening the gallery and after selecting image , the setState for _image = File(image.path); not work and after that I'm trying to click to pick image again then this exception is appear

Body:
Try this-

File _image;

  Future getImage() async {
    ImagePicker picker = ImagePicker();
    var image = await picker.getImage(source: ImageSource.gallery);
    setState(() {
      _image = File(image.path);
      Navigator.pop(this.context);
    });
  }

  Future getCameraImage() async {
    ImagePicker picker = ImagePicker();
    var image = await picker.getImage(source: ImageSource.camera);
    setState(() {
      _image = File(image.path);
      Navigator.pop(this.context);
    });
  }


问:
How to get Substr when annotate Django
I'm try to sort by order_number had many kind

Input:

```<code>ADC123
ADC14
ADC23
ERD324
ERD12
</code>```

Sort default just sort by alphabet

Expected results (Sort only by number):

```<code>ERD12
ADC14
ADC23
ADC123
ERD324
</code>```

Code example:

```<code>Person.objects.annotate(
    order_only_number=AddField(Substr("order_number", 1))
).order_by("order_only_number")
</code>```

答:
Like the comment said you should Cast your field to integer, also you need to fix the Substr method because the index start from 1 and your numbers start from index 4.

Your query should be like this:

```<code>from django.db.models import IntegerField
from django.db.models.functions import Cast, Substr

Person.objects.annotate(
    order_only_number= Cast(Substr("order_number", 4), IntegerField())
).order_by("order_only_number")
</code>```

Title: How to get Substr when annotate Django

Body:
I'm try to sort by order_number had many kind

Input:

ADC123
ADC14
ADC23
ERD324
ERD12

Sort default just sort by alphabet

Expected results (Sort only by number):

ERD12
ADC14
ADC23
ADC123
ERD324

Code example:

Person.objects.annotate(
    order_only_number=AddField(Substr("order_number", 1))
).order_by("order_only_number")

Body:
Like the comment said you should Cast your field to integer, also you need to fix the Substr method because the index start from 1 and your numbers start from index 4.

Your query should be like this:

from django.db.models import IntegerField
from django.db.models.functions import Cast, Substr

Person.objects.annotate(
    order_only_number= Cast(Substr("order_number", 4), IntegerField())
).order_by("order_only_number")


问:
How to set Horizontal scrollbar to single select tag (dropdown)?
I am trying to set the horizontal scrollbar to the single select dropdown which has long text in its option text.
I tried it by adding div and setting the style , but it showing the scrollbar before popping the list..
How to set Horizontal scrollbar to single select tag (dropdown) ???</p>

答:
you can give your selector box a fixed width to keep it smaller. but when clicking on it, there will be a scrollbar from your browser. if you want to change this, you need to create your own select box with javascript.

Oh and.. if you have that long select dropdowns, you're not really doing something which a user will like. Provide radio buttons or check boxes if you need to display a lot of text.


问:
IDE support for debugging multithreaded programs in Java
Are there any IDEs out there for Java development that have built-in support (or available plugins/extensions) for visual debugging of multithreaded programs in the same vein as Visual Studio allows you to visualise parallel stacks of multiple concurrent threads? I'm aware this has probably been asked many times before, but perhaps new tools have cropped up since previous discussions.

For ref, here's an example of what I'm talking about in VS, where the stacks for more than one thread are visualised:

答: Regarding the question at hand, IntelliJ allows you to visually see all the threads that currently exist/alive at runtime, from the tab called Threads, inside the debug session window (where you can view the individual stacks that correspond to each): Thread groups


问:
Tried using Python flask to make data sent from HTML <form> a tuple to match selected data from a MySQL table if exit, but something went wrong
```<code>// SELECT
myDatabaseCursor.execute("SELECT username, password FROM member")
myDatabase.commit()

// get data from form to make a tuple
userCheck = (request.form["signInUsername"], request.form["signInPassword"])

// iterate selected data tuple into a list
results = []
for selectedData in myDatabaseCursor:
    results.append(selectedData)

// check if there is a match in MySQL database
if userCheck in results:
    session["status"]="logged"
    session["user_name"]=request.form["signInUsername"]
    return redirect("/member")
else:
    return redirect("/error/?message=wrong username or password")
</code>```

When I ran my server and tried typing in the username and the right password, successfully logged in; tried typing in the username and the wrong password, which, didn't have any match in the database, got rejected logging in. ALL GOOD...

BUT, when I tried typing in the username and the wrong password, which, HAS A MATCH IN THE PASSWORD COLUMN THOUGH DOESN'T BELONG TO THE RIGHT USERNAME, still successfully logged in.

I am really confused now, hope you guys have any idea about this situation.

Thanks, appreciate your replies.

答:
Probably the problem lies in the session['status']. You never set it to e.g. "unlogged", so if you don't close the browser, the status will always be 'logged' after first successful login.

Try to initialize your variable at the beginning of the script, i.e. session["status"]=None and then in every other page check that the status is actually 'Logged' as you're probably already doing.

```<code>session["status"]=None

// SELECT
myDatabaseCursor.execute("SELECT username, password FROM member")
myDatabase.commit()

// get data from form to make a tuple
userCheck = (request.form["signInUsername"], request.form["signInPassword"])

// iterate selected data tuple into a list
results = []
for selectedData in myDatabaseCursor:
    results.append(selectedData)

// check if there is a match in MySQL database
if userCheck in results:
    session["status"]="logged"
    session["user_name"]=request.form["signInUsername"]
    return redirect("/member")
else:
    return redirect("/error/?message=wrong username or password")
</code>```

In any case, for the sake of best practice, you should amend your code to apply the logic depicted by @matthewking, retrieving just the password you need to check.

Body:
// SELECT
myDatabaseCursor.execute("SELECT username, password FROM member")
myDatabase.commit()

// get data from form to make a tuple
userCheck = (request.form["signInUsername"], request.form["signInPassword"])

// iterate selected data tuple into a list
results = []
for selectedData in myDatabaseCursor:
    results.append(selectedData)

// check if there is a match in MySQL database
if userCheck in results:
    session["status"]="logged"
    session["user_name"]=request.form["signInUsername"]
    return redirect("/member")
else:
    return redirect("/error/?message=wrong username or password")

When I ran my server and tried typing in the username and the right password, successfully logged in; tried typing in the username and the wrong password, which, didn't have any match in the database, got rejected logging in. ALL GOOD...

BUT, when I tried typing in the username and the wrong password, which, HAS A MATCH IN THE PASSWORD COLUMN THOUGH DOESN'T BELONG TO THE RIGHT USERNAME, still successfully logged in.

I am really confused now, hope you guys have any idea about this situation.

Thanks, appreciate your replies.

Body:
Probably the problem lies in the session['status']. You never set it to e.g. "unlogged", so if you don't close the browser, the status will always be 'logged' after first successful login.

Try to initialize your variable at the beginning of the script, i.e. session["status"]=None and then in every other page check that the status is actually 'Logged' as you're probably already doing.

session["status"]=None

// SELECT
myDatabaseCursor.execute("SELECT username, password FROM member")
myDatabase.commit()

// get data from form to make a tuple
userCheck = (request.form["signInUsername"], request.form["signInPassword"])

// iterate selected data tuple into a list
results = []
for selectedData in myDatabaseCursor:
    results.append(selectedData)

// check if there is a match in MySQL database
if userCheck in results:
    session["status"]="logged"
    session["user_name"]=request.form["signInUsername"]
    return redirect("/member")
else:
    return redirect("/error/?message=wrong username or password")

In any case, for the sake of best practice, you should amend your code to apply the logic depicted by @matthewking, retrieving just the password you need to check.


问:
How to reference to packages from Maven local repository?
In my project I need to reference to the package installed by Maven to local repository. I've added the dependency to pom.xml, but the project doesn't want to build as it wouldn't even see the package. Here's the pom.xml fragment with dependencies:

```<code><dependencies>
  ...
  <dependency>
    <groupId>libraryweb</groupId>
    <artifactId>classes</artifactId>
    <version>1.0SNAPSHOT</version>
  </dependency>
</dependencies>
</code>```

When I try to import the package "libraryweb" I get

Cannot resolve symbol 'libraryweb'

error. What can I do to use the package?

Edit: Intellij prompts me classes from the package when I try to use them, but I still get "cannot resolve symbol" error.

答:
Note that groupIds and package names are not necessarily the same.

So while your JAR is installed under a certain groupId, artifactId and version, the actual package that you need to import  in your Java code may have a different name.

In doubt, unpack the JAR and look at the directory structure.

Body:
In my project I need to reference to the package installed by Maven to local repository. I've added the dependency to pom.xml, but the project doesn't want to build as it wouldn't even see the package. Here's the pom.xml fragment with dependencies:

<dependencies>
  ...
  <dependency>
    <groupId>libraryweb</groupId>
    <artifactId>classes</artifactId>
    <version>1.0SNAPSHOT</version>
  </dependency>
</dependencies>

When I try to import the package "libraryweb" I get

Cannot resolve symbol 'libraryweb'

error. What can I do to use the package?

Edit: Intellij prompts me classes from the package when I try to use them, but I still get "cannot resolve symbol" error.


问:
Warnings issued when saving tensorflow 2.0 model via keras API
When calling Model.save() method provided by keras in tensorflow 2.0, two warnings about deprecated operations were raised. A simple reproduction in interactive mode is appended below

```<code>Python 3.8.3 (default, Jul  2 2020, 16:21:59)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow
2020-10-28 13:49:38.380026: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudart.so.10.1
>>> from tensorflow import keras
>>> inputs = keras.layers.Input(shape=(10, 10, 1), dtype="float32")
>>> outputs = keras.layers.Dense(2, activation="softmax")(inputs)
2020-10-28 13:50:33.646242: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcuda.so.1
2020-10-28 13:50:34.487222: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1716] Found device 0 with properties:
pciBusID: 0000:65:00.0 name: GeForce RTX 2080 Ti computeCapability: 7.5
coreClock: 1.545GHz coreCount: 68 deviceMemorySize: 10.76GiB deviceMemoryBandwidth: 573.69GiB/s
2020-10-28 13:50:34.487258: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudart.so.10.1
2020-10-28 13:50:34.488671: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcublas.so.10
2020-10-28 13:50:34.490066: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcufft.so.10
2020-10-28 13:50:34.490334: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcurand.so.10
2020-10-28 13:50:34.491816: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcusolver.so.10
2020-10-28 13:50:34.492589: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcusparse.so.10
2020-10-28 13:50:34.495732: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudnn.so.7
2020-10-28 13:50:34.496509: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1858] Adding visible gpu devices: 0
2020-10-28 13:50:34.496780: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN)to use the following CPU instructions in performance-critical operations:  AVX2 AVX512F FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2020-10-28 13:50:34.519843: I tensorflow/core/platform/profile_utils/cpu_utils.cc:104] CPU Frequency: 3799900000 Hz
2020-10-28 13:50:34.520483: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x5584831adac0 initialized for platform Host (this does not guarantee that XLA will be used). Devices:
2020-10-28 13:50:34.520504: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): Host, Default Version
2020-10-28 13:50:34.592987: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x558483219530 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:
2020-10-28 13:50:34.593047: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): GeForce RTX 2080 Ti, Compute Capability 7.5
2020-10-28 13:50:34.594379: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1716] Found device 0 with properties:
pciBusID: 0000:65:00.0 name: GeForce RTX 2080 Ti computeCapability: 7.5
coreClock: 1.545GHz coreCount: 68 deviceMemorySize: 10.76GiB deviceMemoryBandwidth: 573.69GiB/s
2020-10-28 13:50:34.594439: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudart.so.10.1
2020-10-28 13:50:34.594477: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcublas.so.10
2020-10-28 13:50:34.594503: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcufft.so.10
2020-10-28 13:50:34.594528: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcurand.so.10
2020-10-28 13:50:34.594553: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcusolver.so.10
2020-10-28 13:50:34.594578: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcusparse.so.10
2020-10-28 13:50:34.594603: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudnn.so.7
2020-10-28 13:50:34.595938: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1858] Adding visible gpu devices: 0
2020-10-28 13:50:34.595979: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudart.so.10.1
2020-10-28 13:50:34.981431: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1257] Device interconnect StreamExecutor with strength 1 edge matrix:
2020-10-28 13:50:34.981470: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1263]      0
2020-10-28 13:50:34.981475: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1276] 0:   N
2020-10-28 13:50:34.982333: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1402] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10063 MB memory) -> physical GPU (device: 0, name: GeForce RTX 2080 Ti, pci bus id: 0000:65:00.0, compute capability: 7.5)
>>> model = keras.Model(inputs=inputs, outputs=outputs)
>>> model.save("test")
WARNING:tensorflow:From /home/boris/anaconda3/lib/python3.8/site-packages/tensorflow/python/training/tracking/tracking.py:111: Model.state_updates (from tensorflow.python.keras.engine.training) is deprecated and will be removed in a future version.
Instructions for updating:
This property should not be used in TensorFlow 2.0, as updates are applied automatically.
2020-10-28 13:51:05.487175: W tensorflow/python/util/util.cc:348] Sets are not currently considered sequences, but this may change in the future, so consider avoiding using them.
WARNING:tensorflow:From /home/boris/anaconda3/lib/python3.8/site-packages/tensorflow/python/training/tracking/tracking.py:111: Layer.updates (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.
Instructions for updating:
This property should not be used in TensorFlow 2.0, as updates are applied automatically.
INFO:tensorflow:Assets written to: test/assets
>>>
</code>```

This warning message appears even when saving a very simple model, which confuses me.

The exact version I am working on is tensorflow 2.3.1 and python 3.8.3.

答:
These are the warnings about deprecated functions, which tells Tensorflow user that it will be removed in the future version. You can suppress these warnings using below code.</p>
```<code>import logging, os
logging.disable(logging.WARNING)
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
import tensorflow as tf
</code>```

Body:
When calling Model.save() method provided by keras in tensorflow 2.0, two warnings about deprecated operations were raised. A simple reproduction in interactive mode is appended below

Python 3.8.3 (default, Jul  2 2020, 16:21:59)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow
2020-10-28 13:49:38.380026: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudart.so.10.1
>>> from tensorflow import keras
>>> inputs = keras.layers.Input(shape=(10, 10, 1), dtype="float32")
>>> outputs = keras.layers.Dense(2, activation="softmax")(inputs)
2020-10-28 13:50:33.646242: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcuda.so.1
2020-10-28 13:50:34.487222: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1716] Found device 0 with properties:
pciBusID: 0000:65:00.0 name: GeForce RTX 2080 Ti computeCapability: 7.5
coreClock: 1.545GHz coreCount: 68 deviceMemorySize: 10.76GiB deviceMemoryBandwidth: 573.69GiB/s
2020-10-28 13:50:34.487258: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudart.so.10.1
2020-10-28 13:50:34.488671: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcublas.so.10
2020-10-28 13:50:34.490066: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcufft.so.10
2020-10-28 13:50:34.490334: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcurand.so.10
2020-10-28 13:50:34.491816: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcusolver.so.10
2020-10-28 13:50:34.492589: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcusparse.so.10
2020-10-28 13:50:34.495732: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudnn.so.7
2020-10-28 13:50:34.496509: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1858] Adding visible gpu devices: 0
2020-10-28 13:50:34.496780: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN)to use the following CPU instructions in performance-critical operations:  AVX2 AVX512F FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2020-10-28 13:50:34.519843: I tensorflow/core/platform/profile_utils/cpu_utils.cc:104] CPU Frequency: 3799900000 Hz
2020-10-28 13:50:34.520483: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x5584831adac0 initialized for platform Host (this does not guarantee that XLA will be used). Devices:
2020-10-28 13:50:34.520504: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): Host, Default Version
2020-10-28 13:50:34.592987: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x558483219530 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:
2020-10-28 13:50:34.593047: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): GeForce RTX 2080 Ti, Compute Capability 7.5
2020-10-28 13:50:34.594379: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1716] Found device 0 with properties:
pciBusID: 0000:65:00.0 name: GeForce RTX 2080 Ti computeCapability: 7.5
coreClock: 1.545GHz coreCount: 68 deviceMemorySize: 10.76GiB deviceMemoryBandwidth: 573.69GiB/s
2020-10-28 13:50:34.594439: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudart.so.10.1
2020-10-28 13:50:34.594477: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcublas.so.10
2020-10-28 13:50:34.594503: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcufft.so.10
2020-10-28 13:50:34.594528: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcurand.so.10
2020-10-28 13:50:34.594553: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcusolver.so.10
2020-10-28 13:50:34.594578: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcusparse.so.10
2020-10-28 13:50:34.594603: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudnn.so.7
2020-10-28 13:50:34.595938: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1858] Adding visible gpu devices: 0
2020-10-28 13:50:34.595979: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudart.so.10.1
2020-10-28 13:50:34.981431: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1257] Device interconnect StreamExecutor with strength 1 edge matrix:
2020-10-28 13:50:34.981470: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1263]      0
2020-10-28 13:50:34.981475: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1276] 0:   N
2020-10-28 13:50:34.982333: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1402] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10063 MB memory) -> physical GPU (device: 0, name: GeForce RTX 2080 Ti, pci bus id: 0000:65:00.0, compute capability: 7.5)
>>> model = keras.Model(inputs=inputs, outputs=outputs)
>>> model.save("test")
WARNING:tensorflow:From /home/boris/anaconda3/lib/python3.8/site-packages/tensorflow/python/training/tracking/tracking.py:111: Model.state_updates (from tensorflow.python.keras.engine.training) is deprecated and will be removed in a future version.
Instructions for updating:
This property should not be used in TensorFlow 2.0, as updates are applied automatically.
2020-10-28 13:51:05.487175: W tensorflow/python/util/util.cc:348] Sets are not currently considered sequences, but this may change in the future, so consider avoiding using them.
WARNING:tensorflow:From /home/boris/anaconda3/lib/python3.8/site-packages/tensorflow/python/training/tracking/tracking.py:111: Layer.updates (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.
Instructions for updating:
This property should not be used in TensorFlow 2.0, as updates are applied automatically.
INFO:tensorflow:Assets written to: test/assets
>>>

This warning message appears even when saving a very simple model, which confuses me.

The exact version I am working on is tensorflow 2.3.1 and python 3.8.3.

Body:
These are the warnings about deprecated functions, which tells Tensorflow user that it will be removed in the future version. You can suppress these warnings using below code.

import logging, os
logging.disable(logging.WARNING)
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
import tensorflow as tf


问:
Azure ARM with Multiple Extensions and multiple VMs
I am bit struggling to understand this Azure ARM template containing multiple "Microsoft.Compute/virtualMachines/extensions" and multiple VMs:

kafka-on-ubuntu/azuredeploy.json

Assuming there will be 4 VMs: 1 for zookeeper and 3 for Kafka cluster repsectively, how can be ensured that the extension (+script) for Zookeper will run on exactly that one Zookeper VM, and how to ensure that the extension (+script ) for Kafka cluster will run on exactly those 3 Kafka VMs?
I am more tempted to believe that each extension run on all VMs.

答:
This behavior seems to be poorly documented, but from the documentation page for the Windows custom script extension:

The name of the resource has to be in the format virtualMachineName/extensionName, if this extension is used as a standalone resource in the Azure Resource Manager template.

Which seems to imply that the resolution for where the custom script extension should be executed is based on the name. I imagine this is the case for Linux VMs too.

For the particular example that you are looking at, the name of one of the vms is:

```<code>"name": "[concat('zookprvm', copyindex())]",
</code>```

whereas that of the extension is:

```<code>"name": "[concat('zookprvm', copyindex(), '/installzoo')]",
</code>```

so the prefix of the name of the extension must be identical to the VM name.

Body:
This behavior seems to be poorly documented, but from the documentation page for the Windows custom script extension:

The name of the resource has to be in the format virtualMachineName/extensionName, if this extension is used as a standalone resource in the Azure Resource Manager template.

Which seems to imply that the resolution for where the custom script extension should be executed is based on the name. I imagine this is the case for Linux VMs too.

For the particular example that you are looking at, the name of one of the vms is:

"name": "[concat('zookprvm', copyindex())]",

whereas that of the extension is:

"name": "[concat('zookprvm', copyindex(), '/installzoo')]",

so the prefix of the name of the extension must be identical to the VM name.