问:
Firestore Security Rules - How to restrict users to reading only specific documents?
I want to display public information about users in a view, but I don't want the user to be able to get() a list of all users in my /users/{userID}/public collection. I know I can restrict access so that only the public collection is viewable. But that also would let someone scrub the entire database to see all the public users.

What sort of rules could I use to limit access so that a specific document is specified? For example:

```<code>db.collection('users').get()
</code>```

Would be denied. But:

```<code>db.collection('users').doc('abc123').collection('public').get()
</code>```

...would succeed.

答:
There's nothing about the relationship between /users/x and /users/x/public that makes it hard to protect them separately.  They are completely different collections and can be protected separately without conflict.  The only time you would have a problem is if you chose to use a glob wildcard, which is not normally used.

If you don't specify any rule for /users, then no access will be allowed.  The rule for your first request is to simply write no rule.  (Unless you want users to read their individual document, then just write that rule, and it will still also prevent anyone from getting a list of users.)

The rule for your second request can be enabled for everyone simply by writing:

```<code>match /users/{uid}/public/{id} {
  allow read;
}
</code>```

That rule will have no effect on the documents immediately in /users, because they don't match the pattern.  And any other rule that matches /users/{uid} wouldn't affect any subcollections for the same reason - no match.

Body:
I want to display public information about users in a view, but I don't want the user to be able to get() a list of all users in my /users/{userID}/public collection. I know I can restrict access so that only the public collection is viewable. But that also would let someone scrub the entire database to see all the public users.

What sort of rules could I use to limit access so that a specific document is specified? For example:

db.collection('users').get()

Would be denied. But:

db.collection('users').doc('abc123').collection('public').get()

...would succeed.

Body:
There's nothing about the relationship between /users/x and /users/x/public that makes it hard to protect them separately.  They are completely different collections and can be protected separately without conflict.  The only time you would have a problem is if you chose to use a glob wildcard, which is not normally used.

If you don't specify any rule for /users, then no access will be allowed.  The rule for your first request is to simply write no rule.  (Unless you want users to read their individual document, then just write that rule, and it will still also prevent anyone from getting a list of users.)

The rule for your second request can be enabled for everyone simply by writing:

match /users/{uid}/public/{id} {
  allow read;
}

That rule will have no effect on the documents immediately in /users, because they don't match the pattern.  And any other rule that matches /users/{uid} wouldn't affect any subcollections for the same reason - no match.


来源: stackexchange

问:
Which are the possible ways to retrain a model made in IBM Watson Knowledge Studio?
I am working on a knowledge based chatbot creation on ibm watson and I have trained my custom model on ibm watson knowledge studio for agricultural database. Now if someone asked about any information that is not available in our dataset then how can we retrained that model/improve the model with that new data ?

I am using knowledge graph to retrieve the information. Knowledge graph is made in Neo4J.

If any new data comes or admin wants to retrain the model with new data than the model should retrained without going to knowledge studio like rasa is ibm watson assistant provides feedback system.

答: IBM Watson Knowledge Studio does not support online training to retrain the existing model with new data. To adapt to new data, you need to train a brand new model with both the new data and the existing data.</p>

ContentLicense: CC BY-SA 4.0


问:
Use PHP to get xls(Excel files) PHPOffice PHPExcel
Hy guys.

Thank you for your help. The answers in this forum are great!

In my site, i want to see the content from a xls Excel Spreadsheet.
After long searching i found this Project:
https://github.com/PHPOffice/PHPExcel/

I get the classes and tried it. Works great!

It works so good, that i can't believe, that it is free.
Is it free to use?

at the top of my site, i got this error massage:
Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"? in test/Classes/PHPExcel/Shared/OLE.php on line 288

答:
Think this:

For break and continue, a switch is like a loop, that runs only once. break leaves every loop, and switch-loop too.

continue starts the next iteration of a loop. Because switch runs only once, it terminate the switch-loop.

To restart or leave outer loops (this includes outer switchtoo) use a positive integer behind break and continue.


答:
I just realized I sort of answered my own question. You can just grant read access to your users public sub-collection but block access to the specific user doc.

For those Googling here later, something like this:

```<code>service cloud.firestore {
    match /databases/{database}/documents {
        match /users/{userID} {
            allow read, write, delete: if isAdmin();

            match /public/{publicID} {
                allow read: if request.auth.uid != null;
            }
        }
    }
}
</code>```

Title: Firestore Security Rules - How to restrict users to reading only specific documents?

Body:
I just realized I sort of answered my own question. You can just grant read access to your users public sub-collection but block access to the specific user doc.

For those Googling here later, something like this:

service cloud.firestore {
    match /databases/{database}/documents {
        match /users/{userID} {
            allow read, write, delete: if isAdmin();

            match /public/{publicID} {
                allow read: if request.auth.uid != null;
            }
        }
    }
}


问:
Playing a Sound Notification when Specific Text on Page Appears
I'm trying to figure out a way to play a sound notification whenever the phrase "2 credits" appears in the top right corner on a specific website at: https://www.submithub.com/. As it stands, that specific area of the site oscillates between "0 credits" and "2 credits" depending on if you've submitted to the site within the last few hours. Once you are able to submit again, the text changes to "2 credits."

I have also provided a screenshot of what I am talking about:

I have been using code primarily derived from the following StackOverflow thread: How can I have a Tampermonkey userscript play a sound when a specific word appears on a page?

Here is the code that I am working with:

```<code>// ==UserScript==
// @name     SubmitHub Notification
// @include  https://www.submithub.com/
// @grant    none
// ==/UserScript==
/* eslint-disable no-multi-spaces */

//-- Set the watched terms using the awesome power of regex.
var watchRegx = /\b2 credits\b/i;
var alrtSound = new Audio ("data:audio/mp3;base64,[encoded data, 5072 characters]");

//-- Customize this next for your page or get lazy and use "body".
var cntnrNode = document.querySelector ("#mainArea");
if (typeof cntnrNode === "undefined")   console.error ("TM: Container node not found.");
else {
    var wordObsrv = new MutationObserver (alertOnWord);
    wordObsrv.observe (document.body, {childList: true, subtree: true} );
}
function alertOnWord (mutationRecords) {
    mutationRecords.forEach (muttn => {
        if (muttn.type === "childList"  &&  typeof muttn.addedNodes === "object") {
            muttn.addedNodes.forEach (newNode => {
                /*-- Restrict the kinds of nodes watched for better performance
                    and/or to avoid false positives.
                */
                if (newNode.nodeName === "DIV"  ||  newNode.nodeName === "SPAN"  ||  newNode.nodeName === "P") {
                    if (watchRegx.test (newNode.textContent) ) {
                        console.log ("Found new instance of target term!");
                        alrtSound.play ();
                    }
                }
            } );
        }
    } );
}
</code>```

As it stands, I cannot get "2 credits" to make any notification sounds via Regex, such as shown below, but I have been able to get just "credits" to work:

```<code>var watchRegx = /\b2 credits\b/i;
</code>```

Here is the HTML of the specific part of the page where "2 credits" lies on the site:

```<code><span class="grey black-text lighten-2 credit-counter"><span class="remaining">2</span> credits</span>
</code>```

The nature of the HTML indicates that this might not be as simple as using a Regex with "2 credits." Maybe there is an easy solution. Any and all advice would be wonderful. Thanks in advance.

答: I simply changed the RegEx code to var watchRegx = /2 credits/; A simple enough solution. Thanks for all the feedback

Body:
I'm trying to figure out a way to play a sound notification whenever the phrase "2 credits" appears in the top right corner on a specific website at: https://www.submithub.com/. As it stands, that specific area of the site oscillates between "0 credits" and "2 credits" depending on if you've submitted to the site within the last few hours. Once you are able to submit again, the text changes to "2 credits."

I have also provided a screenshot of what I am talking about:

I have been using code primarily derived from the following StackOverflow thread: How can I have a Tampermonkey userscript play a sound when a specific word appears on a page?

Here is the code that I am working with:

// ==UserScript==
// @name     SubmitHub Notification
// @include  https://www.submithub.com/
// @grant    none
// ==/UserScript==
/* eslint-disable no-multi-spaces */

//-- Set the watched terms using the awesome power of regex.
var watchRegx = /\b2 credits\b/i;
var alrtSound = new Audio ("data:audio/mp3;base64,[encoded data, 5072 characters]");

//-- Customize this next for your page or get lazy and use "body".
var cntnrNode = document.querySelector ("#mainArea");
if (typeof cntnrNode === "undefined")   console.error ("TM: Container node not found.");
else {
    var wordObsrv = new MutationObserver (alertOnWord);
    wordObsrv.observe (document.body, {childList: true, subtree: true} );
}
function alertOnWord (mutationRecords) {
    mutationRecords.forEach (muttn => {
        if (muttn.type === "childList"  &&  typeof muttn.addedNodes === "object") {
            muttn.addedNodes.forEach (newNode => {
                /*-- Restrict the kinds of nodes watched for better performance
                    and/or to avoid false positives.
                */
                if (newNode.nodeName === "DIV"  ||  newNode.nodeName === "SPAN"  ||  newNode.nodeName === "P") {
                    if (watchRegx.test (newNode.textContent) ) {
                        console.log ("Found new instance of target term!");
                        alrtSound.play ();
                    }
                }
            } );
        }
    } );
}

As it stands, I cannot get "2 credits" to make any notification sounds via Regex, such as shown below, but I have been able to get just "credits" to work:

var watchRegx = /\b2 credits\b/i;

Here is the HTML of the specific part of the page where "2 credits" lies on the site:

2 credits

The nature of the HTML indicates that this might not be as simple as using a Regex with "2 credits." Maybe there is an easy solution. Any and all advice would be wonderful. Thanks in advance.


问:
Git ignore compiled CSS but keep the latest version for production-ready state
I used to commit my compiled minified CSS files to the repo, then I realized each time, the entire file is sent since it's minified on a single line. So it means for each small modification, I save an entire CSS file in my history and it will quickly add up for no reason.

Can we ignore the CSS files compiled automatically by my Text Editor from a LESS file?

If I put these CSS files in .gitignore, they won't be in the repo but I also use the repository to immediately get a working website.

I always compile the LESS files from my local computer and I want to keep it that way (so don't suggest me to use Grunt or something to automatically compile when a user loads the page, please :P).

The ideal solution would be to only keep the latest file in the repo for CSS files only. For history I'd check the LESS files. The CSS files would be there only to make the site works right after a git clone/pull.

答:
don't commit the css file in git

don't use git push as a deployment script

do write a separate deployment script, which packs your code and the minified css from your local computer, and copies that to your production server

As far as sending files over a network go, if git can do it, scp can do it too.


问:
How to NOT ignore hyphens in MySQL
When I execute

select strcmp('ATKINSHUBBARD', binary 'ATKINS-HUBBARD');

I get a true (1) result.

How do get MySQL to recognize those as different strings and return a false result?

Using: MySql 5.6.15.56 (Percona). No, I do not have control over the updates.

答: Actually, I think you're confusing how STRCMP() function works in MySQL. STRCMP()returns 0 if the strings are the same. Check the documentation.

Title: How to NOT ignore hyphens in MySQL


问:
Deleting part of figure drawn with patch - MATLAB
So im trying to build a simple tetris game in Matlab.
I am drawing and updating the figure using the patch method with predefined position vectors for each shape.

So far so good, but when i need to delete a row (when the player fills a row), i am stuck as i don't know how to delete a block from the figure. I tried ROI but i can't delete the underlying patches.

Code that draws figures and patches:
...

```<code>figureH = figure('name','TETRIS Game','outerposition',[100 100 500 500],'color','g');
%draw game area
 patch(xBoard+[0,gameWidth,gameWidth,0],yBoard +[0,0,gameHeight,gameHeight],'w');
</code>```

...

```<code>%drawing shape in each step
activeShapePatch = patch((xBoard-1)+min(fcol)+x,yBoard+gameHeight-max(frow)+y,nextShape{1}{4});
</code>```

nextShape is just a cell array containing x-y vectors for each shape and color- this is for the patch arguments.

答:
I would need more details but consider storing patch handles into cell, or graphic object array (e.g. init as gobject(3,2) generates a 3x2 graphic object array), and then delete them at wish. In general, using handles and cells,</p>

```<code>cell_h_patch{ipatch} = patch(XData, YData, ZData, CData, ...)
...
row = ipatch;
delete(cell_h_patch{row})
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So im trying to build a simple tetris game in Matlab.
I am drawing and updating the figure using the patch method with predefined position vectors for each shape.

So far so good, but when i need to delete a row (when the player fills a row), i am stuck as i don't know how to delete a block from the figure. I tried ROI but i can't delete the underlying patches.

Code that draws figures and patches:
...

figureH = figure('name','TETRIS Game','outerposition',[100 100 500 500],'color','g');
%draw game area
 patch(xBoard+[0,gameWidth,gameWidth,0],yBoard +[0,0,gameHeight,gameHeight],'w');

...

%drawing shape in each step
activeShapePatch = patch((xBoard-1)+min(fcol)+x,yBoard+gameHeight-max(frow)+y,nextShape{1}{4});

nextShape is just a cell array containing x-y vectors for each shape and color- this is for the patch arguments.

Body:
I would need more details but consider storing patch handles into cell, or graphic object array (e.g. init as gobject(3,2) generates a 3x2 graphic object array), and then delete them at wish. In general, using handles and cells,

cell_h_patch{ipatch} = patch(XData, YData, ZData, CData, ...)
...
row = ipatch;
delete(cell_h_patch{row})


问:
Force gfortran to stop program at first NaN
To debug my application (fortran 90) I want to turn all NaNs to signalling NaN.

With default settings my program works without any signals and just outputs NaN data in file. I want find the point, where NaN is generated. If I can recompile program with signalling NaN, I will get an SIGFPE signal at first point where first wrong floating operation reside.

答:
The flag you're looking for is -ffpe-trap=invalid; I usually add ,zero,overflow to check for related floating point exceptions.

```<code>program nantest
    real :: a, b, c

    a = 1.
    b = 2.

    c = a/b
    print *, c,a,b

    a = 0.
    b = 0.

    c = a/b
    print *, c,a,b

    a = 2.
    b = 1.

    c = a/b
    print *,c,a,b
end program nantest
</code>```

Then compiling it and running it in a debugger gives:

```<code>$ gfortran -o nantest nantest.f90 -ffpe-trap=invalid,zero,overflow -g -static
$ gdb nantest
[...]
(gdb) run
Starting program: /scratch/ljdursi/Testing/fortran/nantest
  0.50000000       1.0000000       2.0000000

Program received signal SIGFPE, Arithmetic exception.
0x0000000000400384 in nantest () at nantest.f90:13
13          c = a/b
Current language:  auto; currently fortran
</code>```

With the intel fortran compiler (ifort), using the option -fpe0 will do the same thing.

It's a little tricker with C/C++ code; we have to actually insert a call to feenableexcept(), which enables floating point exceptions, and is defined in fenv.h;

```<code>#include <stdio.h>
#include <fenv.h>

int main(int argc, char **argv) {
    float a, b, c;
    feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);

    a = 1.;
    b = 2.;

    c = a/b;
    printf("%f %f %f\n", a, b, c);

    a = 0.;
    b = 0.;

    c = a/b;
    printf("%f %f %f\n", a, b, c);

    a = 2.;
    b = 1.;

    c = a/b;
    printf("%f %f %f\n", a, b, c);

    return 0;
}
</code>```

but the effect is the same:

```<code>$ gcc -o nantest nantest.c -lm -g
$ gdb ./nantest
[...]
(gdb) run
Starting program: /scratch/s/scinet/ljdursi/Testing/exception/nantest
1.000000 2.000000 0.500000

Program received signal SIGFPE, Arithmetic exception.
0x00000000004005d0 in main (argc=1, argv=0x7fffffffe4b8) at nantest.c:17
17        c = a/b;
</code>```

either way, you have a much better handle on where the errors are occuring.

Body:
The flag you're looking for is -ffpe-trap=invalid; I usually add ,zero,overflow to check for related floating point exceptions.

program nantest
    real :: a, b, c

    a = 1.
    b = 2.

    c = a/b
    print *, c,a,b

    a = 0.
    b = 0.

    c = a/b
    print *, c,a,b

    a = 2.
    b = 1.

    c = a/b
    print *,c,a,b
end program nantest

Then compiling it and running it in a debugger gives:

$ gfortran -o nantest nantest.f90 -ffpe-trap=invalid,zero,overflow -g -static
$ gdb nantest
[...]
(gdb) run
Starting program: /scratch/ljdursi/Testing/fortran/nantest
  0.50000000       1.0000000       2.0000000

Program received signal SIGFPE, Arithmetic exception.
0x0000000000400384 in nantest () at nantest.f90:13
13          c = a/b
Current language:  auto; currently fortran

With the intel fortran compiler (ifort), using the option -fpe0 will do the same thing.

It's a little tricker with C/C++ code; we have to actually insert a call to feenableexcept(), which enables floating point exceptions, and is defined in fenv.h;

#include <stdio.h>
#include <fenv.h>

int main(int argc, char **argv) {
    float a, b, c;
    feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);

    a = 1.;
    b = 2.;

    c = a/b;
    printf("%f %f %f\n", a, b, c);

    a = 0.;
    b = 0.;

    c = a/b;
    printf("%f %f %f\n", a, b, c);

    a = 2.;
    b = 1.;

    c = a/b;
    printf("%f %f %f\n", a, b, c);

    return 0;
}

but the effect is the same:

$ gcc -o nantest nantest.c -lm -g
$ gdb ./nantest
[...]
(gdb) run
Starting program: /scratch/s/scinet/ljdursi/Testing/exception/nantest
1.000000 2.000000 0.500000

Program received signal SIGFPE, Arithmetic exception.
0x00000000004005d0 in main (argc=1, argv=0x7fffffffe4b8) at nantest.c:17
17        c = a/b;

either way, you have a much better handle on where the errors are occuring.


问:
Neural network help on game of continuous snake
I'm trying to implement an AI for a game of 'continuous snake'. It's very different from a normal snake game, at least as far as the AI is concerned. Basically, the snake drives a bit like a car and the first one of the 2 players to crash into his trail or the other's trail loses the game. Also the screen wraps around its borders.

You can understand it better if you look at a video of my current progress:
https://www.youtube.com/watch?v=i9qU-r4COQ8

It's not too bad, but it still can't beat me (I'm yellow).
A winning AI would ideally need to exhibit these behaviors:

Avoid walls

Notice occasions when it can 'cut me short' (when next to me a bit ahead).

Avoid getting 'cut short'.

Have an idea of the topology of the current 2d space to try to enclose me in a smaller space / safeguard himself a bigger space.

My current approach uses the NEAT algorithm (http://www.cs.ucf.edu/~kstanley/neat.html).
It's a genetic algorithm that evolves neural networks over generations. It learned how to do 1,2 and 3 to some extent (but not great) but has no idea about 4.

For the inputs, I'm using:

the opponent angle relative to us

the opponent distance to us

the opponent heading relative to us

smart rays that probe in some directions with some amount of tree search (see video)

I'm a bit stuck now though and would like to know:

What's the class of algorithms I should look into ? Recurrent / RealTime / Continous / Unsupervised Neural networks, ... An explanation about these and how they would apply to my problem would be great.

Any specific algorithms I should research ?

What other sets of inputs could I use ? A human player gets to see all the pixels in the game which is a lot more information than my simple set of inputs. But I don't think feeding the 200x200 pixels in my example to my NN would work at all. Maybe if I discretize them and make them relative to the AI position/heading...sounds tricky.

I'm happy to make my code available if someone wants to see it (C#).

Thanks!

答:
First of all if you want good results use deep convolutional q-learning which takes the image as input. For further improvement you can feed in stack of three to four consecutive images which will help lot in determing a direction.I don't think you need to use lstm for this problem stacking multiple frames will do fine. For further improvement you can convert the same code into duelling network.

And if you prefer fast results and less computation you can use augmented random search but if not trained with care it may get into local maxima.


问:
JAVA Eclipselink query
I'm trying to write a JPA query that has 3 conditional where statements. But I don't seem to get the syntax correct.</p>

```<code>try {
    Query findCustomerQuery = entityManager.createQuery("SELECT c FROM Customer c WHERE " +
            "CASE " +
            "WHEN :customerNumber is not null THEN (c.customerNumber = :customerNumber)" +
            "WHEN :customerName is not null THEN (c.name = :customerName) " +
            "WHEN :customerFirstname is not NULL THEN (c.firstName = :customerFirstname) ELSE (c.customerNumber = 0) END");

    findCustomerQuery.setParameter("customerNumber",customerNumber);
    findCustomerQuery.setParameter("customerName", customerName);
    findCustomerQuery.setParameter("customerFirstname", customerFirstname);
    return (Customer) findCustomerQuery.getSingleResult();

}finally {
    entityManager.close();
}
</code>```

答:
It is convenient to use the JPA Criteria API for these cases.

Here is an example for your case:

```<code>// get a query builder
CriteriaBuilder builder = em.getCriteriaBuilder();
// build query for entity
CriteriaQuery<Customer> criteriaQuery = builder.createQuery( Customer.class );
// set FROM entity
Root<Customer> tags = criteriaQuery.from( Customer.class );
// get a basic predicate
Predicate p = builder.and();
// add WHERE conditions properly
if (customerNumber != null) {
    Predicate conditionPredicate = builder.and(
            builder.equal( tags.get("customerNumber"), customerNumber )
    );
    p = builder.and(p, conditionPredicate);
}
// do the same for customerName and customerFirstName
if (customerName != null) {
    Predicate conditionPredicate = builder.and(
            builder.equal( tags.get("customerName"), customerName )
    );
    p = builder.and(p, conditionPredicate);
}
if (customerFirstName != null) {
    Predicate conditionPredicate = builder.and(
            builder.equal( tags.get("customerFirstName"), customerFirstName )
    );
    p = builder.and(p, conditionPredicate);
}

// set predicate to query
criteriaQuery.where( p );

// call query and get results
TypedQuery<Customer> q = em.createQuery(criteriaQuery);
List<Customer> o = q.getResultList();
</code>```

Here are more examples if you need

Title: JAVA Eclipselink query

Body:
I'm trying to write a JPA query that has 3 conditional where statements. But I don't seem to get the syntax correct.

try {
    Query findCustomerQuery = entityManager.createQuery("SELECT c FROM Customer c WHERE " +
            "CASE " +
            "WHEN :customerNumber is not null THEN (c.customerNumber = :customerNumber)" +
            "WHEN :customerName is not null THEN (c.name = :customerName) " +
            "WHEN :customerFirstname is not NULL THEN (c.firstName = :customerFirstname) ELSE (c.customerNumber = 0) END");

    findCustomerQuery.setParameter("customerNumber",customerNumber);
    findCustomerQuery.setParameter("customerName", customerName);
    findCustomerQuery.setParameter("customerFirstname", customerFirstname);
    return (Customer) findCustomerQuery.getSingleResult();

}finally {
    entityManager.close();
}

Body:
It is convenient to use the JPA Criteria API for these cases.

Here is an example for your case:

// get a query builder
CriteriaBuilder builder = em.getCriteriaBuilder();
// build query for entity
CriteriaQuery<Customer> criteriaQuery = builder.createQuery( Customer.class );
// set FROM entity
Root<Customer> tags = criteriaQuery.from( Customer.class );
// get a basic predicate
Predicate p = builder.and();
// add WHERE conditions properly
if (customerNumber != null) {
    Predicate conditionPredicate = builder.and(
            builder.equal( tags.get("customerNumber"), customerNumber )
    );
    p = builder.and(p, conditionPredicate);
}
// do the same for customerName and customerFirstName
if (customerName != null) {
    Predicate conditionPredicate = builder.and(
            builder.equal( tags.get("customerName"), customerName )
    );
    p = builder.and(p, conditionPredicate);
}
if (customerFirstName != null) {
    Predicate conditionPredicate = builder.and(
            builder.equal( tags.get("customerFirstName"), customerFirstName )
    );
    p = builder.and(p, conditionPredicate);
}

// set predicate to query
criteriaQuery.where( p );

// call query and get results
TypedQuery<Customer> q = em.createQuery(criteriaQuery);
List<Customer> o = q.getResultList();

Here are more examples if you need


问:
DiscordJS Database Not Storing Information Ideally
I'm trying to get the Discord bot to create a database that is basically the user map (a row for each user and columns for ID, nick name, avatar URL, etc) when it receives a !getdata command.

I've gotten to the point where the database successfully takes data, in this case the username and user ID, but it displays all the unique values in two columns as long comma separated values (i.e. the username column displays 'user1,user2,user3').

I'm sure this is by design, but I'm really struggling with restructuring. I'd like to either have it take all the data from an object map (client.users or message.guild.members) but I cannot figure it out.

The other option, which is what I'm trying now, is to create a row for each user and then fill in the values that I want to store, but I'm getting nowhere fast.

I'm very new with SQLite (and node/DiscordJS/JS for that matter), so any advice is greatly appreciated.

Index.js

```<code>const Discord = require('discord.js');
const client = new Discord.Client();
const sql = require('sqlite3');

let db = new sql.Database("users.sqlite", (err) => {
    if (err) {
        console.log('Error connecting to the database', err)
    } else {
        console.log('Database connected.')
    }
})

let token = process.env.CLIENT_TOKEN;
let prefix = process.env.PREFIX ;

client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
    db.run(`CREATE TABLE IF NOT EXISTS users(username TEXT, id TEXT)`);
})

client.on('message', function(message) {

    if (!message.content.startsWith(prefix));

    const args = message.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();

    if (command === 'getdata') {
        let username = message.guild.members.map(m=>m.user.username);
        let userid = message.guild.members.map(m=>m.user.id);
        db.run(`INSERT OR REPLACE INTO users(username, id) VALUES(?,?)`, [`${username}`,`${userid}`]);
        return message.channel.send(`User database updated.`);
    }
});

client.login(token);
</code>```

If you're curious as to the formatting or way things are written, the answer is two fold:

I'm pretty new at this

This was the only way I could get the values in the database to return something other than null

Thanks in advance,

答:
First off, welcome to the site.

I hope that I can shine some light here without diving into refactoring your code or making you change anything major.

One thing sticks out to me as to why you are storing an array instead of a single value.

```<code>let username = message.guild.members.map(m=>m.user.username);
let userid = message.guild.members.map(m=>m.user.id);
</code>```

The .map call returns an array, not a single value.

Each user that issues a command is part of the message object. If I remember correctly, you would want this to be something like...

(simplified version)

```<code>const { username, id } = message.member.user;
db.run(`INSERT OR REPLACE INTO users(username, id) VALUES(?,?)`, [username, id]);
// ...
</code>```

User documentation can be found here

Edit:

If you wanted to build the database for all users in that one command you could do something like the following with a bulk insert... (quick and dirty)

```<code>db.serialize(() => {
  db.run('BEGIN TRANSACTION;');
  // execute inserts in transaction
  for (const m of message.guild.members) {
    db.run('INSERT OR REPLACE INTO users(username, id) VALUES(?,?);', [m.user.username, m.user.id]);
  }
  // commit all inserts :)
  db.run('COMMIT;')
});

message.channel.send('User database updated.');
</code>```

Control flow documenation

Hopefully this points you in the right direction :)

Body:
I'm trying to get the Discord bot to create a database that is basically the user map (a row for each user and columns for ID, nick name, avatar URL, etc) when it receives a !getdata command.

I've gotten to the point where the database successfully takes data, in this case the username and user ID, but it displays all the unique values in two columns as long comma separated values (i.e. the username column displays 'user1,user2,user3').

I'm sure this is by design, but I'm really struggling with restructuring. I'd like to either have it take all the data from an object map (client.users or message.guild.members) but I cannot figure it out.

The other option, which is what I'm trying now, is to create a row for each user and then fill in the values that I want to store, but I'm getting nowhere fast.

I'm very new with SQLite (and node/DiscordJS/JS for that matter), so any advice is greatly appreciated.

Index.js

const Discord = require('discord.js');
const client = new Discord.Client();
const sql = require('sqlite3');

let db = new sql.Database("users.sqlite", (err) => {
    if (err) {
        console.log('Error connecting to the database', err)
    } else {
        console.log('Database connected.')
    }
})

let token = process.env.CLIENT_TOKEN;
let prefix = process.env.PREFIX ;

client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
    db.run(`CREATE TABLE IF NOT EXISTS users(username TEXT, id TEXT)`);
})

client.on('message', function(message) {

    if (!message.content.startsWith(prefix));

    const args = message.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();

    if (command === 'getdata') {
        let username = message.guild.members.map(m=>m.user.username);
        let userid = message.guild.members.map(m=>m.user.id);
        db.run(`INSERT OR REPLACE INTO users(username, id) VALUES(?,?)`, [`${username}`,`${userid}`]);
        return message.channel.send(`User database updated.`);
    }
});

client.login(token);

If you're curious as to the formatting or way things are written, the answer is two fold:

I'm pretty new at this

This was the only way I could get the values in the database to return something other than null

Thanks in advance,

Body:
First off, welcome to the site.

I hope that I can shine some light here without diving into refactoring your code or making you change anything major.

One thing sticks out to me as to why you are storing an array instead of a single value.

let username = message.guild.members.map(m=>m.user.username);
let userid = message.guild.members.map(m=>m.user.id);

The .map call returns an array, not a single value.

Each user that issues a command is part of the message object. If I remember correctly, you would want this to be something like...

(simplified version)

const { username, id } = message.member.user;
db.run(`INSERT OR REPLACE INTO users(username, id) VALUES(?,?)`, [username, id]);
// ...

User documentation can be found here

Edit:

If you wanted to build the database for all users in that one command you could do something like the following with a bulk insert... (quick and dirty)

db.serialize(() => {
  db.run('BEGIN TRANSACTION;');
  // execute inserts in transaction
  for (const m of message.guild.members) {
    db.run('INSERT OR REPLACE INTO users(username, id) VALUES(?,?);', [m.user.username, m.user.id]);
  }
  // commit all inserts :)
  db.run('COMMIT;')
});

message.channel.send('User database updated.');

Control flow documenation

Hopefully this points you in the right direction :)


问:
React Joi uri validation optional
I'm using Joi validation in React with this schema:

```<code>...
intro_video_link:
    Joi.string()
    .uri()
    .label("Intro Video"),
...
</code>```

The intro_video_link is also required. I want Joi to validate field for uri if it is filled, but also allow it to be empty. There is no .required() called.

How?

Thank you

答:
You probably want to combine .allow() with .required():

```<code> intro_video_link:  Joi.string().uri().label("Intro Video").required().allow('')
</code>```

This way, the following objects will pass the validation:

```<code>{
   intro_video_link: ''
}

{
   intro_video_link: 'https://github.com'
}
</code>```

Title: React Joi uri validation optional

Body:
I'm using Joi validation in React with this schema:

...
intro_video_link:
    Joi.string()
    .uri()
    .label("Intro Video"),
...

The intro_video_link is also required. I want Joi to validate field for uri if it is filled, but also allow it to be empty. There is no .required() called.

How?

Thank you

Body:
You probably want to combine .allow() with .required():

 intro_video_link:  Joi.string().uri().label("Intro Video").required().allow('')

This way, the following objects will pass the validation:

{
   intro_video_link: ''
}

{
   intro_video_link: 'https://github.com'
}


问:
Highlight 2nd Instance duplicates in sheets
Trying to mark duplicates on google sheets, but I see that First Instance is highlighted when I use

```<code>=COUNTIF(A1:A100, A1)>1.
</code>```

I tried to use IF and COUNTIF together so that the 2nd Instance gets highlighted.

```<code>=IF(COUNTIF(A1:A97,A1)>1, "Duplicate", " ")
</code>```

but did not work.

I am trying to use this so that the cell gets highlighted as soon as I enter the duplicate number in the column.

答:
To Highlight 2nd Instance duplicates in sheets with COUNTIF select ColumnA and: Format > Conditional formatting..., Format cells if... Custom formula is and apply:

```<code>=and(countif(A$1:A,A1)>1,countif(A$1:A1,A1)>1)
</code>```

with highlighting of choice and Done.

Should format not only the second instance but all other than the first.

Body:
Trying to mark duplicates on google sheets, but I see that First Instance is highlighted when I use

=COUNTIF(A1:A100, A1)>1.

I tried to use IF and COUNTIF together so that the 2nd Instance gets highlighted.

=IF(COUNTIF(A1:A97,A1)>1, "Duplicate", " ")

but did not work.

I am trying to use this so that the cell gets highlighted as soon as I enter the duplicate number in the column.

Body:
To Highlight 2nd Instance duplicates in sheets with COUNTIF select ColumnA and: Format > Conditional formatting..., Format cells if... Custom formula is and apply:

=and(countif(A$1:A,A1)>1,countif(A$1:A1,A1)>1)

with highlighting of choice and Done.

Should format not only the second instance but all other than the first.


问:
Create PrivateKey from byte array
Is there a way to generate PrivateKey from byte array? I got this byte array using getEncoded() method, but now I have to convert it back to PrivateKey.

Thanks,
Vuk

答:
```<code>//ECDSA algo of signature type prime256 of key
Security.addProvider(new BouncyCastleProvider());
KeyFactory factory = KeyFactory.getInstance("ECDSA", "BC");
ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("prime256v1");
ECPrivateKeySpec ecPrivateKeySpec = new ECPrivateKeySpec(new BigInteger(1, privKey), spec);
PrivateKey privateKey = factory.generatePrivate(ecPrivateKeySpec);
</code>```

ContentLicense: CC BY-SA 2.5

Title: Create PrivateKey from byte array


问:
How to make a lua envoy filter work on the istio cluster?
I am trying to get a lua envoy filter to work with istio gateway, but I added to the cluster and it is working as if the filter does not exists.

I have configured my istio cluster on GKE using this guide https://istio.io/docs/setup/kubernetes/install/kubernetes/.

Have anyone had the same problem?

```<code>apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: edge-lua-filter
spec:
  workloadLabels:
    app: httpbin-gateway
  filters:
  - listenerMatch:
      listenerType: GATEWAY
    filterName: envoy.lua
    filterType: HTTP
    filterConfig:
      inlineCode: |
        -- Called on the request path.
        function envoy_on_request(request_handle)
            request_handle:headers():add("foo", "bar")
        end
        -- Called on the response path.
        function envoy_on_response(response_handle)
            body_size = response_handle:body():length()
            response_handle:headers():add("response-body-size", tostring(body_size))
        end
</code>```

```<code>apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  name: httpbin-gateway
  namespace: foo
spec:
  selector:
    istio: ingressgateway # use Istio default gateway implementation
  servers:
  - port:
      number: 80
      name: http
      protocol: HTTP
    hosts:
    - "*"
</code>```

```<code>apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: httpbin
  namespace: foo
spec:
  hosts:
  - "*"
  gateways:
  - httpbin-gateway
  http:
  - route:
    - destination:
        port:
          number: 8000
        host: httpbin.foo.svc.cluster.local
</code>```

答:
I agree with larsitto that you have probably problem with workloadLabels - try to leave it empty or specify some label that you specify in your deployment>spec>template>labels[]

This code works for me for example:

```<code>apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: hello_world
spec:
  workloadLabels:
  filters:
  - listenerMatch:
      listenerType: SIDECAR_INBOUND
      listenerProtocol: HTTP
    filterName: envoy.lua
    filterType: HTTP
    filterConfig:
      inlineCode: |
        ...
</code>```

Body:
I am trying to get a lua envoy filter to work with istio gateway, but I added to the cluster and it is working as if the filter does not exists.

I have configured my istio cluster on GKE using this guide https://istio.io/docs/setup/kubernetes/install/kubernetes/.

Have anyone had the same problem?

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: edge-lua-filter
spec:
  workloadLabels:
    app: httpbin-gateway
  filters:
  - listenerMatch:
      listenerType: GATEWAY
    filterName: envoy.lua
    filterType: HTTP
    filterConfig:
      inlineCode: |
        -- Called on the request path.
        function envoy_on_request(request_handle)
            request_handle:headers():add("foo", "bar")
        end
        -- Called on the response path.
        function envoy_on_response(response_handle)
            body_size = response_handle:body():length()
            response_handle:headers():add("response-body-size", tostring(body_size))
        end

apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  name: httpbin-gateway
  namespace: foo
spec:
  selector:
    istio: ingressgateway # use Istio default gateway implementation
  servers:
  - port:
      number: 80
      name: http
      protocol: HTTP
    hosts:
    - "*"

apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: httpbin
  namespace: foo
spec:
  hosts:
  - "*"
  gateways:
  - httpbin-gateway
  http:
  - route:
    - destination:
        port:
          number: 8000
        host: httpbin.foo.svc.cluster.local

Body:
I agree with larsitto that you have probably problem with workloadLabels - try to leave it empty or specify some label that you specify in your deployment>spec>template>labels[]

This code works for me for example:

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: hello_world
spec:
  workloadLabels:
  filters:
  - listenerMatch:
      listenerType: SIDECAR_INBOUND
      listenerProtocol: HTTP
    filterName: envoy.lua
    filterType: HTTP
    filterConfig:
      inlineCode: |
        ...


问:
Sigabrt error at bionic_setjmp_checksum_mismatch
I am running into issue with running native code. Application is running untill it gets to 1 place in code and then it crashes. I did gathered stack dump from debugger and some logcat info.

I did setup breakpoint at code that it might crashing.

This is where it crashing

```<code>cgs.media.charsetShader     = trap_R_RegisterShader("gfx/2d/hudchars");
</code>```

Logcat showed me this:

```<code>libc : setjmp checksum mismatch
</code>```

And now dump from stak:

```<code>tgkill 0x0000007f8d7cb558
pthread_kill 0x0000007f8d7c89e0
raise 0x0000007f8d783f2c
abort 0x0000007f8d77c9b0
__libc_fatal 0x0000007f8d780f38
__bionic_setjmp_checksum_mismatch 0x0000007f8d77c648
___lldb_unnamed_symbol4675$$libetl.so 0x0000007f6cc85b90
jpeg_CreateDecompress 0x0000007f6cccaaa8
___lldb_unnamed_symbol4677$$libetl.so 0x0000007f6cc85cf4
___lldb_unnamed_symbol4860$$libetl.so 0x0000007f6ccb6054
___lldb_unnamed_symbol4861$$libetl.so 0x0000007f6ccb62d4
___lldb_unnamed_symbol4578$$libetl.so 0x0000007f6cc6feec
___lldb_unnamed_symbol4582$$libetl.so 0x0000007f6cc702ac
___lldb_unnamed_symbol1031$$libetl.so 0x0000007f6ca304ac
___lldb_unnamed_symbol736$$libetl.so 0x0000007f6ca0baa8
___lldb_unnamed_symbol1025$$libcgame.mp.arm64-v8a.so 0x0000007f3dfbd774
___lldb_unnamed_symbol447$$libcgame.mp.arm64-v8a.so 0x0000007f3df55f68
___lldb_unnamed_symbol1024$$libcgame.mp.arm64-v8a.so 0x0000007f3dfbd680
___lldb_unnamed_symbol622$$libcgame.mp.arm64-v8a.so 0x0000007f3df75e8c
vmMain 0x0000007f3df6e064
___lldb_unnamed_symbol743$$libetl.so 0x0000007f6ca0c4c8
___lldb_unnamed_symbol1033$$libetl.so 0x0000007f6ca32024
___lldb_unnamed_symbol1246$$libetl.so 0x0000007f6ca43b9c
___lldb_unnamed_symbol273$$libetl.so 0x0000007f6c9dd3c0
___lldb_unnamed_symbol277$$libetl.so 0x0000007f6c9dd9c4
___lldb_unnamed_symbol1314$$libetl.so 0x0000007f6ca4d7ec
___lldb_unnamed_symbol1318$$libetl.so 0x0000007f6ca4e480
___lldb_unnamed_symbol1254$$libetl.so 0x0000007f6ca45528
___lldb_unnamed_symbol508$$libetl.so 0x0000007f6c9f6648
___lldb_unnamed_symbol509$$libetl.so 0x0000007f6c9f6820
___lldb_unnamed_symbol209$$libetl.so 0x0000007f6c9d8eb4
___lldb_unnamed_symbol1648$$libetl.so 0x0000007f6ca6e7f8
SDL_main 0x0000007f6ca6e904
Java_org_libsdl_app_SDLActivity_nativeRunMain 0x0000007f7012f8c8
art_quick_generic_jni_trampoline 0x0000007f8aa50d94
art_quick_invoke_static_stub 0x0000007f8aa47a6c
art::ArtMethod::Invoke(art::Thread*, unsigned int*, unsigned int, art::JValue*, char const*) 0x0000007f8aa544b4
art::interpreter::ArtInterpreterToCompiledCodeBridge(art::Thread*, art::ArtMethod*, art::DexFile::CodeItem const*, art::ShadowFrame*, art::JValue*) 0x0000007f8ac05640
bool art::interpreter::DoCall<false, false>(art::ArtMethod*, art::Thread*, art::ShadowFrame&, art::Instruction const*, unsigned short, art::JValue*) 0x0000007f8abfe61c
bool art::interpreter::DoInvoke<(art::InvokeType)0, false, false>(art::Thread*, art::ShadowFrame&, art::Instruction const*, unsigned short, art::JValue*) 0x0000007f8ac31230
art::JValue art::interpreter::ExecuteSwitchImpl<false, false>(art::Thread*, art::DexFile::CodeItem const*, art::ShadowFrame&, art::JValue, bool) 0x0000007f8ac24440
art::interpreter::Execute(art::Thread*, art::DexFile::CodeItem const*, art::ShadowFrame&, art::JValue, bool) 0x0000007f8abd79e0
art::interpreter::ArtInterpreterToInterpreterBridge(art::Thread*, art::DexFile::CodeItem const*, art::ShadowFrame*, art::JValue*) 0x0000007f8abdd6d8
bool art::interpreter::DoCall<false, false>(art::ArtMethod*, art::Thread*, art::ShadowFrame&, art::Instruction const*, unsigned short, art::JValue*) 0x0000007f8abfe600
bool art::interpreter::DoInvoke<(art::InvokeType)4, false, false>(art::Thread*, art::ShadowFrame&, art::Instruction const*, unsigned short, art::JValue*) 0x0000007f8ac309ec
art::JValue art::interpreter::ExecuteSwitchImpl<false, false>(art::Thread*, art::DexFile::CodeItem const*, art::ShadowFrame&, art::JValue, bool) 0x0000007f8ac24690
art::interpreter::Execute(art::Thread*, art::DexFile::CodeItem const*, art::ShadowFrame&, art::JValue, bool) 0x0000007f8abd79e0
artQuickToInterpreterBridge 0x0000007f8aec19b4
art_quick_to_interpreter_bridge 0x0000007f8aa50eb0
art_quick_invoke_stub 0x0000007f8aa477b8
art::ArtMethod::Invoke(art::Thread*, unsigned int*, unsigned int, art::JValue*, char const*) 0x0000007f8aa54484
art::InvokeWithArgArray(art::ScopedObjectAccessAlreadyRunnable const&, art::ArtMethod*, art::ArgArray*, art::JValue*, char const*) 0x0000007f8ada148c
art::InvokeVirtualOrInterfaceWithJValues(art::ScopedObjectAccessAlreadyRunnable const&, _jobject*, _jmethodID*, jvalue*) 0x0000007f8ada2794
art::Thread::CreateCallback(void*) 0x0000007f8adc1f28
__pthread_start(void*) 0x0000007f8d7c81e8
__start_thread 0x0000007f8d77dbc4
</code>```

I am nowhere expert in reading dump from stack.
I know that it shows memory addresses.

PS: Also I did some digging and checked that trap_R_RegisterShader. Program does not even enters that function. it just stops at it.

I am not sure what to do with jpeg_CreateDecompress 0x0000007f6cccaaa8 is it intended ?

答:
Fixed in https://github.com/etlegacy/etlegacy/commit/e3cfd59d2ca080b0fd5208ec8f9c275a6e0e50dc

setjmp was not set 1st and this was causing jpeg_create_decompress to send longjmp to not existed jmp

Body:
I am running into issue with running native code. Application is running untill it gets to 1 place in code and then it crashes. I did gathered stack dump from debugger and some logcat info.

I did setup breakpoint at code that it might crashing.

This is where it crashing

cgs.media.charsetShader     = trap_R_RegisterShader("gfx/2d/hudchars");

Logcat showed me this:

libc : setjmp checksum mismatch

And now dump from stak:

tgkill 0x0000007f8d7cb558
pthread_kill 0x0000007f8d7c89e0
raise 0x0000007f8d783f2c
abort 0x0000007f8d77c9b0
__libc_fatal 0x0000007f8d780f38
__bionic_setjmp_checksum_mismatch 0x0000007f8d77c648
___lldb_unnamed_symbol4675$$libetl.so 0x0000007f6cc85b90
jpeg_CreateDecompress 0x0000007f6cccaaa8
___lldb_unnamed_symbol4677$$libetl.so 0x0000007f6cc85cf4
___lldb_unnamed_symbol4860$$libetl.so 0x0000007f6ccb6054
___lldb_unnamed_symbol4861$$libetl.so 0x0000007f6ccb62d4
___lldb_unnamed_symbol4578$$libetl.so 0x0000007f6cc6feec
___lldb_unnamed_symbol4582$$libetl.so 0x0000007f6cc702ac
___lldb_unnamed_symbol1031$$libetl.so 0x0000007f6ca304ac
___lldb_unnamed_symbol736$$libetl.so 0x0000007f6ca0baa8
___lldb_unnamed_symbol1025$$libcgame.mp.arm64-v8a.so 0x0000007f3dfbd774
___lldb_unnamed_symbol447$$libcgame.mp.arm64-v8a.so 0x0000007f3df55f68
___lldb_unnamed_symbol1024$$libcgame.mp.arm64-v8a.so 0x0000007f3dfbd680
___lldb_unnamed_symbol622$$libcgame.mp.arm64-v8a.so 0x0000007f3df75e8c
vmMain 0x0000007f3df6e064
___lldb_unnamed_symbol743$$libetl.so 0x0000007f6ca0c4c8
___lldb_unnamed_symbol1033$$libetl.so 0x0000007f6ca32024
___lldb_unnamed_symbol1246$$libetl.so 0x0000007f6ca43b9c
___lldb_unnamed_symbol273$$libetl.so 0x0000007f6c9dd3c0
___lldb_unnamed_symbol277$$libetl.so 0x0000007f6c9dd9c4
___lldb_unnamed_symbol1314$$libetl.so 0x0000007f6ca4d7ec
___lldb_unnamed_symbol1318$$libetl.so 0x0000007f6ca4e480
___lldb_unnamed_symbol1254$$libetl.so 0x0000007f6ca45528
___lldb_unnamed_symbol508$$libetl.so 0x0000007f6c9f6648
___lldb_unnamed_symbol509$$libetl.so 0x0000007f6c9f6820
___lldb_unnamed_symbol209$$libetl.so 0x0000007f6c9d8eb4
___lldb_unnamed_symbol1648$$libetl.so 0x0000007f6ca6e7f8
SDL_main 0x0000007f6ca6e904
Java_org_libsdl_app_SDLActivity_nativeRunMain 0x0000007f7012f8c8
art_quick_generic_jni_trampoline 0x0000007f8aa50d94
art_quick_invoke_static_stub 0x0000007f8aa47a6c
art::ArtMethod::Invoke(art::Thread*, unsigned int*, unsigned int, art::JValue*, char const*) 0x0000007f8aa544b4
art::interpreter::ArtInterpreterToCompiledCodeBridge(art::Thread*, art::ArtMethod*, art::DexFile::CodeItem const*, art::ShadowFrame*, art::JValue*) 0x0000007f8ac05640
bool art::interpreter::DoCall<false, false>(art::ArtMethod*, art::Thread*, art::ShadowFrame&, art::Instruction const*, unsigned short, art::JValue*) 0x0000007f8abfe61c
bool art::interpreter::DoInvoke<(art::InvokeType)0, false, false>(art::Thread*, art::ShadowFrame&, art::Instruction const*, unsigned short, art::JValue*) 0x0000007f8ac31230
art::JValue art::interpreter::ExecuteSwitchImpl<false, false>(art::Thread*, art::DexFile::CodeItem const*, art::ShadowFrame&, art::JValue, bool) 0x0000007f8ac24440
art::interpreter::Execute(art::Thread*, art::DexFile::CodeItem const*, art::ShadowFrame&, art::JValue, bool) 0x0000007f8abd79e0
art::interpreter::ArtInterpreterToInterpreterBridge(art::Thread*, art::DexFile::CodeItem const*, art::ShadowFrame*, art::JValue*) 0x0000007f8abdd6d8
bool art::interpreter::DoCall<false, false>(art::ArtMethod*, art::Thread*, art::ShadowFrame&, art::Instruction const*, unsigned short, art::JValue*) 0x0000007f8abfe600
bool art::interpreter::DoInvoke<(art::InvokeType)4, false, false>(art::Thread*, art::ShadowFrame&, art::Instruction const*, unsigned short, art::JValue*) 0x0000007f8ac309ec
art::JValue art::interpreter::ExecuteSwitchImpl<false, false>(art::Thread*, art::DexFile::CodeItem const*, art::ShadowFrame&, art::JValue, bool) 0x0000007f8ac24690
art::interpreter::Execute(art::Thread*, art::DexFile::CodeItem const*, art::ShadowFrame&, art::JValue, bool) 0x0000007f8abd79e0
artQuickToInterpreterBridge 0x0000007f8aec19b4
art_quick_to_interpreter_bridge 0x0000007f8aa50eb0
art_quick_invoke_stub 0x0000007f8aa477b8
art::ArtMethod::Invoke(art::Thread*, unsigned int*, unsigned int, art::JValue*, char const*) 0x0000007f8aa54484
art::InvokeWithArgArray(art::ScopedObjectAccessAlreadyRunnable const&, art::ArtMethod*, art::ArgArray*, art::JValue*, char const*) 0x0000007f8ada148c
art::InvokeVirtualOrInterfaceWithJValues(art::ScopedObjectAccessAlreadyRunnable const&, _jobject*, _jmethodID*, jvalue*) 0x0000007f8ada2794
art::Thread::CreateCallback(void*) 0x0000007f8adc1f28
__pthread_start(void*) 0x0000007f8d7c81e8
__start_thread 0x0000007f8d77dbc4

I am nowhere expert in reading dump from stack.
I know that it shows memory addresses.

PS: Also I did some digging and checked that trap_R_RegisterShader. Program does not even enters that function. it just stops at it.

I am not sure what to do with jpeg_CreateDecompress 0x0000007f6cccaaa8 is it intended ?


问:
How to close specific Chrome profile that was opened with cmd/bat?
I need to close all windows of a specific Chrome profile. Suppose I execute:

```<code>chrome.exe -remote-debugging-port=4000 --user-data-dir=F://chrome
</code>```

in cmd/bat to open a new Chrome profile. I need to close this specific Chrome profile from cmd/bat.

I have tried this:

```<code>taskkill /IM chrome.exe -remote-debugging-port=4000 --user-data-dir=F://chrome
</code>```

but it's not working.

答:
You can accomplish this using the batch file below:

```<code>for /f "tokens=3 delims=," %%a in ('wmic process where "caption='chrome.exe'" get processID^,commandline /format:csv ^| FIND "-remote-debugging-port=4000 --user-data-dir=F://chrome"') do set _pid=%%a
taskkill /f /pid %_pid% /t
</code>```

Explanation

wmic process where "caption='chrome.exe'" get processID^,commandline /format:csv lists all chrome.exe processes with the command line used to launch them and the process ID that we will use to kill it.

Piping (|) this into FIND "-remote-debugging-port=4000 --user-data-dir=F://chrome" will return only the chrome.exe process started with the command you used.

for /f "tokens=3 delims=," %%a in ("...") do set _pid=%%a will set the _pid environment variable to the process ID of the process we want to kill.

The wmic command combined with the find command should only give us a single result. If you used the command multiple times, then this will only find the process ID of the last process in the list.

taskkill /f /pid %_pid% /t:

/f forces the task to end, because otherwise Chrome will remain open.

/pid %_pid% will supply the process ID we got in the for loop.

/t tells taskkill to kill the entire process tree.

Since every Chrome tab and extension runs in its own process, we want to make sure these get killed as well.

Body:
I need to close all windows of a specific Chrome profile. Suppose I execute:

chrome.exe -remote-debugging-port=4000 --user-data-dir=F://chrome

in cmd/bat to open a new Chrome profile. I need to close this specific Chrome profile from cmd/bat.

I have tried this:

taskkill /IM chrome.exe -remote-debugging-port=4000 --user-data-dir=F://chrome

but it's not working.

Body:
You can accomplish this using the batch file below:

for /f "tokens=3 delims=," %%a in ('wmic process where "caption='chrome.exe'" get processID^,commandline /format:csv ^| FIND "-remote-debugging-port=4000 --user-data-dir=F://chrome"') do set _pid=%%a
taskkill /f /pid %_pid% /t

Explanation

wmic process where "caption='chrome.exe'" get processID^,commandline /format:csv lists all chrome.exe processes with the command line used to launch them and the process ID that we will use to kill it.

Piping (|) this into FIND "-remote-debugging-port=4000 --user-data-dir=F://chrome" will return only the chrome.exe process started with the command you used.

for /f "tokens=3 delims=," %%a in ("...") do set _pid=%%a will set the _pid environment variable to the process ID of the process we want to kill.

The wmic command combined with the find command should only give us a single result. If you used the command multiple times, then this will only find the process ID of the last process in the list.

taskkill /f /pid %_pid% /t:

/f forces the task to end, because otherwise Chrome will remain open.

/pid %_pid% will supply the process ID we got in the for loop.

/t tells taskkill to kill the entire process tree.

Since every Chrome tab and extension runs in its own process, we want to make sure these get killed as well.


问:
Problem with jquery button click
I am facing a problem in the jquery click event.

My web page involves creating a button through javascript and assigning a class to the button ( call it A ). Now I want to detect the click of that button and I have written the following code for it :

```
 $(".A").click( function () {

    // do something

 });
```

To my surprise, this click event never gets called.

But when I make the button statically on the webpage ( during design time ), the same code works.

Is there a different approach to bind a button click with jquery in case a button is created dynamically?

答:
you have to use the live-function of jquery! In difference to the click-function, it watches for dom manipulations. as you can imagine its slightly slower than the .click().

```<code>$('.clickme').live('click', function() {
  // Live handler called.
});
</code>```

Felix

Title: Problem with jquery button click

Body:
I am facing a problem in the jquery click event.

My web page involves creating a button through javascript and assigning a class to the button ( call it A ). Now I want to detect the click of that button and I have written the following code for it :

 $(".A").click( function () {

    // do something

 });

To my surprise, this click event never gets called.

But when I make the button statically on the webpage ( during design time ), the same code works.

Is there a different approach to bind a button click with jquery in case a button is created dynamically?

Body:
you have to use the live-function of jquery! In difference to the click-function, it watches for dom manipulations. as you can imagine its slightly slower than the .click().

$('.clickme').live('click', function() {
  // Live handler called.
});

Felix


问:
Android mkdir() can't make folder inside root of removable micro SD-card
I use this code to get folder of removable SD-card:

```<code>var baseDir = Environment.getExternalStorageDirectory().absolutePath
val dirs = getExternalFilesDirs(null)
for (file in dirs){
    if(Environment.isExternalStorageRemovable(file)) {
        baseDir = file.absolutePath
        val idx = baseDir.indexOf("/Android/")
        if(idx > 0) {
            baseDir = baseDir.substring(0,idx)
            break
        }
    }
}
</code>```

And it work well enough, at least on test devices. After this code baseDir contain something like /storage/AB96-CD85. But when I try to make dir, I always get false result:

```<code>baseDir = baseDir + java.io.File.separator + name
var result: File? = null

if (Environment.getExternalStorageState() != Environment.MEDIA_MOUNTED) {
    Log.e(TAG, "SD-card not mounted.")
    return result
 }
 val dir = File(baseDir)
 if (!dir.exists()) {
     if (!dir.mkdir()) {
         Log.e(
                TAG,
                "Can't create directory $name"
            )
         return result
     }
 }
</code>```

minSdkVersion is 21. Before this code execution I've already requested WRITE_EXTERNAL_STORAGE permission and got positive response from user. I wrote permission block in Manifest in correct place (out of <application></application> block). The code above create folder without any problems on one device and cannot do the same on other (in the same time ES File manager work well on sdcard). What was tried:

App re-installation

Phone restart

Even unplag USB cable

Storage Access Framework(SAF)

What I should do to make mkdir() function work on the second device?
If I should add some other permission or move user to some system settings screen, how can I do that?
Why code above work on one device and doesn't work on other?

答:
I think it's about different Android versions.
To modify External SD card's filesystem, you need to get "special permision".
You can Google some libraries, that do it automatically. Just use one of these and you will gain that "special permission". It's weird but WRITE_EXTERNAL_STORAGE not providing you access to SD Card, only to eMMC memory.

Body:
I use this code to get folder of removable SD-card:

var baseDir = Environment.getExternalStorageDirectory().absolutePath
val dirs = getExternalFilesDirs(null)
for (file in dirs){
    if(Environment.isExternalStorageRemovable(file)) {
        baseDir = file.absolutePath
        val idx = baseDir.indexOf("/Android/")
        if(idx > 0) {
            baseDir = baseDir.substring(0,idx)
            break
        }
    }
}

And it work well enough, at least on test devices. After this code baseDir contain something like /storage/AB96-CD85. But when I try to make dir, I always get false result:

baseDir = baseDir + java.io.File.separator + name
var result: File? = null

if (Environment.getExternalStorageState() != Environment.MEDIA_MOUNTED) {
    Log.e(TAG, "SD-card not mounted.")
    return result
 }
 val dir = File(baseDir)
 if (!dir.exists()) {
     if (!dir.mkdir()) {
         Log.e(
                TAG,
                "Can't create directory $name"
            )
         return result
     }
 }

minSdkVersion is 21. Before this code execution I've already requested WRITE_EXTERNAL_STORAGE permission and got positive response from user. I wrote permission block in Manifest in correct place (out of <application></application> block). The code above create folder without any problems on one device and cannot do the same on other (in the same time ES File manager work well on sdcard). What was tried:

App re-installation

Phone restart

Even unplag USB cable

Storage Access Framework(SAF)

What I should do to make mkdir() function work on the second device?
If I should add some other permission or move user to some system settings screen, how can I do that?
Why code above work on one device and doesn't work on other?


问:
Missing number in array in C programming
Given an array C of size N-1 and given that there are numbers from 1 to N with one element missing, the missing number is to be found.

Input:
The first line of input contains an integer T denoting the number of test cases. For each test case first line contains N(size of array). The subsequent line contains N-1 array elements.

Output:
Print the missing number in array.

This problem is to find the missing number in a series of n integers. but, while using the below code I could not get the output as expected.

```<code>#include <stdio.h>

int main()
{
    //code
    int T,run,i;
    scanf("%d", &T);
    long N,res,C,en;
    long arra[1];
    for (run = 0;run <T; run++ )
    {
        long arra[T];
        scanf("%ld", &N);
        res =0;
        for (i = 0; i <N-1; i++)
        {
            scanf("%ld",&C);
            res = res + C;
        }
        en = ((N*(N+1))/2)- res; // subtracting the overall sum of array elements from N integers
        arra[run]=en; //saving it to array
    }
    for(run = 0; run < T; run++)
    {
        printf("%ld ",arra[run]);
    }
    return 0;
}
</code>```

I expected the below input and output:

```<code>Input:
2
5
1 2 3 5
10
1 2 3 4 5 6 7 8 10

Output:
4
9
</code>```

but actual output is

```<code>1 -8719623343620674816
</code>```

答:
correct code

declare the arra before the for loop else for every iteration the arra will be re declared deleting the previous values in it

```<code>#include <stdio.h>

int main()
{
    //code
    int T,run,i;
    scanf("%d", &T);
    long N,res,C,en;
    long arra[T];
    for (run = 0;run <T; run++ )
    {
        scanf("%ld", &N);
        res =0;
        for (i = 0; i <N-1; i++)
        {
            scanf("%ld",&C);
            res = res + C;
        }
        en = ((N*(N+1))/2)- res; // subtracting the overall sum of array elements from N integers
        arra[run]=en; //saving it to array
    }
    for(run = 0; run < T; run++)
    {
        printf("%ld ",arra[run]);
    }
    return 0;
}
</code>```

Body:
Given an array C of size N-1 and given that there are numbers from 1 to N with one element missing, the missing number is to be found.

Input:
The first line of input contains an integer T denoting the number of test cases. For each test case first line contains N(size of array). The subsequent line contains N-1 array elements.

Output:
Print the missing number in array.

This problem is to find the missing number in a series of n integers. but, while using the below code I could not get the output as expected.

#include <stdio.h>

int main()
{
    //code
    int T,run,i;
    scanf("%d", &T);
    long N,res,C,en;
    long arra[1];
    for (run = 0;run <T; run++ )
    {
        long arra[T];
        scanf("%ld", &N);
        res =0;
        for (i = 0; i <N-1; i++)
        {
            scanf("%ld",&C);
            res = res + C;
        }
        en = ((N*(N+1))/2)- res; // subtracting the overall sum of array elements from N integers
        arra[run]=en; //saving it to array
    }
    for(run = 0; run < T; run++)
    {
        printf("%ld ",arra[run]);
    }
    return 0;
}

I expected the below input and output:

Input:
2
5
1 2 3 5
10
1 2 3 4 5 6 7 8 10

Output:
4
9

but actual output is

1 -8719623343620674816

Body:
correct code

declare the arra before the for loop else for every iteration the arra will be re declared deleting the previous values in it

#include <stdio.h>

int main()
{
    //code
    int T,run,i;
    scanf("%d", &T);
    long N,res,C,en;
    long arra[T];
    for (run = 0;run <T; run++ )
    {
        scanf("%ld", &N);
        res =0;
        for (i = 0; i <N-1; i++)
        {
            scanf("%ld",&C);
            res = res + C;
        }
        en = ((N*(N+1))/2)- res; // subtracting the overall sum of array elements from N integers
        arra[run]=en; //saving it to array
    }
    for(run = 0; run < T; run++)
    {
        printf("%ld ",arra[run]);
    }
    return 0;
}


问:
UITableViewCell - hiding unused views or not even adding them?
I have a simple question for which I haven't found anything related online.

What is more practical?

Having a TableViewCell that has more than 10+ subviews (inside of a stackview), but generally only 3-4 is shown, others are hidden.

Or having an empty stackview, and adding every view by code if needed.

For example for the second option:

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell : PostCell

    guard let post = PostsStore.shared.posts.getPost(index: indexPath.row) else {
        return UITableViewCell()
    }

    // Remove reused cell's stackview's views
    cell.stackView.subviews.forEach({ $0.removeFromSuperview() })

    if post.voteAddon != nil {

        if let voteView = Bundle.main.loadNibNamed("VoteView", owner: self, options: nil)?.first as? VoteView {
            voteView.voteForLabel = "Vote for X or Y"

            voteView.buttonX.setTitle("\(post.votes.x) votes", for: .normal)
            voteView.buttonY.setTitle("\(post.votes.y) votes", for: .normal)

            cell.stackView.addArrangedSubview(voteView)
        }
    }
    if post.attachments != nil {

        if let attachmentsView = Bundle.main.loadNibNamed("AttachmentsView", owner: self, options: nil)?.first as? AttachmentsView {
            attachmentsView.attachmentImageView.image = UIImage()

            cell.stackView.addArrangedSubview(attachmentsView)
        }
    }

    cell.delegate = self

    return cell

}
</code>```

This is just an example, in reality those views are more complex.

What would be more practical? The first option is easier, but the second might be better for memory handling.. What are your thoughts about this?

答:
Having a TableViewCell that has more than 10+ subviews (inside of a stackview), but generally only 3-4 is shown, others are hidden

3-4 shown means that 7+ - 6+ are hidden but still in memory , so i prefer instant processing load of the Add/Remove to the permanent memory existence when the cell is visible

It's also worth saying that this heavily depend on the number of visible cells at a time for e.x if it's full screen then option 1 is better than 2 because cells are dequeued as number of visible cells increase option 2 becomes more better

Body:
I have a simple question for which I haven't found anything related online.

What is more practical?

Having a TableViewCell that has more than 10+ subviews (inside of a stackview), but generally only 3-4 is shown, others are hidden.

Or having an empty stackview, and adding every view by code if needed.

For example for the second option:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell : PostCell

    guard let post = PostsStore.shared.posts.getPost(index: indexPath.row) else {
        return UITableViewCell()
    }

    // Remove reused cell's stackview's views
    cell.stackView.subviews.forEach({ $0.removeFromSuperview() })

    if post.voteAddon != nil {

        if let voteView = Bundle.main.loadNibNamed("VoteView", owner: self, options: nil)?.first as? VoteView {
            voteView.voteForLabel = "Vote for X or Y"

            voteView.buttonX.setTitle("\(post.votes.x) votes", for: .normal)
            voteView.buttonY.setTitle("\(post.votes.y) votes", for: .normal)

            cell.stackView.addArrangedSubview(voteView)
        }
    }
    if post.attachments != nil {

        if let attachmentsView = Bundle.main.loadNibNamed("AttachmentsView", owner: self, options: nil)?.first as? AttachmentsView {
            attachmentsView.attachmentImageView.image = UIImage()

            cell.stackView.addArrangedSubview(attachmentsView)
        }
    }

    cell.delegate = self

    return cell

}

This is just an example, in reality those views are more complex.

What would be more practical? The first option is easier, but the second might be better for memory handling.. What are your thoughts about this?


问:
Convert vector<int> to integer
I was looking for pre-defined function for converting a vector of integers into a normal integer but i din't find one.

```<code>vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
</code>```

Need this:

```<code>int i=123 //directly converted from vector to int
</code>```

Is there a possible way to achieve this?

答:
Working solution for negative numbers too!

```<code>#include <iostream>
#include <vector>
using namespace std;

template <typename T> int sgn(T val) {
    return (T(0) < val) - (val < T(0));
}

int vectorToInt(vector<int> v) {
  int result = 0;
  if(!v.size()) return result;
  result = result * 10 + v[0];
  for (size_t i = 1; i < v.size(); ++i) {
    result = result * 10 + (v[i] * sgn(v[0]));
  }
  return result;
}

int main(void) {
  vector<int> negative_value = {-1, 9, 9};
  cout << vectorToInt(negative_value) << endl;

  vector<int> zero = {0};
  cout << vectorToInt(zero) << endl;

  vector<int> positive_value = {1, 4, 5, 3};
  cout << vectorToInt(positive_value) << endl;
  return 0;
}
</code>```

Output:

```<code>-199
0
1453
</code>```

Live Demo

The other answers (as of May '19) seem to assume positive integers only (maybe 0 too). I had negative inputs, thus, I extended their code to take into account the sign of the number as well.

Title: Convert vector<int> to integer

Body:
I was looking for pre-defined function for converting a vector of integers into a normal integer but i din't find one.

vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);

Need this:

int i=123 //directly converted from vector to int

Is there a possible way to achieve this?

Body:
Working solution for negative numbers too!

#include <iostream>
#include <vector>
using namespace std;

template <typename T> int sgn(T val) {
    return (T(0) < val) - (val < T(0));
}

int vectorToInt(vector<int> v) {
  int result = 0;
  if(!v.size()) return result;
  result = result * 10 + v[0];
  for (size_t i = 1; i < v.size(); ++i) {
    result = result * 10 + (v[i] * sgn(v[0]));
  }
  return result;
}

int main(void) {
  vector<int> negative_value = {-1, 9, 9};
  cout << vectorToInt(negative_value) << endl;

  vector<int> zero = {0};
  cout << vectorToInt(zero) << endl;

  vector<int> positive_value = {1, 4, 5, 3};
  cout << vectorToInt(positive_value) << endl;
  return 0;
}

Output:

-199
0
1453

Live Demo

The other answers (as of May '19) seem to assume positive integers only (maybe 0 too). I had negative inputs, thus, I extended their code to take into account the sign of the number as well.


问:
What exactly does dirty-chai.js do?
The package description for dirty-chai is a bit opaque for a newbie:

Function form for terminating assertion properties

What is an 'assertion property' in this context and what does terminating mean? Why are they not normally "terminated"? I have so many questions. An example without dirty-chai and and an example with, that shows the benefit would be great.

答:
I think one of the key reasons for dirty-chai is that it is not considered good practice to make assertions on property access (at least for some in the JavaScript community).

Without the plug-in chai allows you write tests like this:

chai.expect(someFunctionThatReturnsTrue(args)).to.be.true
```
<p>If the test failed, that means <code>someFunctionThatReturnsTrue(args)</code> must have been returning something other than <code>true</code> and from that you know to start debugging its code to see why.</p>
<p>However, for this test to function, accessing the <code>true</code> property needs to <em>make assertions and disrupt the code execution</em> if the assertion fails (for example, by throwing an Exception).</p>
<p>Linters generally do not know how property access is done and would by default assume that the accessing of a property will not have any side-effects (i.e. alter the environment), especially not things like throwing exceptions (or cause other control-flow disrupting consequences).</p>
<p>Therefore, if you write <code>something.true</code> (without parentheses), the linter will assume that you simply want to access a property of <code>something</code> named <code>true</code>. If the expression goes nowhere (not used in an assignment, as function parameters, or in other evaluations), the linter would flag this a a potential typo or something else. Therefore, the previous valid case in <code>chai</code> will generate a linter error.</p>
<p>And <strong>these kind of linter errors can be useful</strong> in some cases because JavaScript does not complain if you try to access properties that do not exist. For example, what if you do have a typo in your test code?</p>
<pre class="lang-js prettyprint-override"><code>chai.expect(someFunctionThatReturnsTrue(args)).to.be.ture
                                                  // ~~~~ not `true`, obviously a typo
</code>```

This test would pass no matter what someFunctionThatReturnsTrue(args) returns. Because accessing .ture simply returns undefined and will not throw an error. Then you may miss some coding errors in someFunctionThatReturnsTrue() if you are forced to ignore these linter errors by chai.

Worse, if there is any error, you may assume that it's not in someFunctionThatReturnsTrue() because that test (wrongly) passes.

Thus the plugin, dirty-chai, by converting assertions by property access (like .true) into calling these properties as function (.true()) make sure linters will know that these statements can change the control flow:

chai.expect(someFunctionThatReturnsTrue(args)).to.be.true()
// Linter now knows you are expecting something to happen during `.true()` call
// and won't complain anymore
```
<p>And now if you make a typo, the test will fail (by throwing an exception)</p>
<pre class="lang-js prettyprint-override"><code>chai.expect(someFunctionThatReturnsTrue(args)).to.be.ture()
                                                  // ~~~~ Will throw something like
                                                  // `...to.be.ture is not a function`
</code>```

Title: What exactly does dirty-chai.js do?

Body:
I think one of the key reasons for dirty-chai is that it is not considered good practice to make assertions on property access (at least for some in the JavaScript community).

Without the plug-in chai allows you write tests like this:

chai.expect(someFunctionThatReturnsTrue(args)).to.be.true

If the test failed, that means someFunctionThatReturnsTrue(args) must have been returning something other than true and from that you know to start debugging its code to see why.

However, for this test to function, accessing the true property needs to make assertions and disrupt the code execution if the assertion fails (for example, by throwing an Exception).

Linters generally do not know how property access is done and would by default assume that the accessing of a property will not have any side-effects (i.e. alter the environment), especially not things like throwing exceptions (or cause other control-flow disrupting consequences).

Therefore, if you write something.true (without parentheses), the linter will assume that you simply want to access a property of something named true. If the expression goes nowhere (not used in an assignment, as function parameters, or in other evaluations), the linter would flag this a a potential typo or something else. Therefore, the previous valid case in chai will generate a linter error.

And these kind of linter errors can be useful in some cases because JavaScript does not complain if you try to access properties that do not exist. For example, what if you do have a typo in your test code?

chai.expect(someFunctionThatReturnsTrue(args)).to.be.ture
                                                  // ~~~~ not `true`, obviously a typo

This test would pass no matter what someFunctionThatReturnsTrue(args) returns. Because accessing .ture simply returns undefined and will not throw an error. Then you may miss some coding errors in someFunctionThatReturnsTrue() if you are forced to ignore these linter errors by chai.

Worse, if there is any error, you may assume that it's not in someFunctionThatReturnsTrue() because that test (wrongly) passes.

Thus the plugin, dirty-chai, by converting assertions by property access (like .true) into calling these properties as function (.true()) make sure linters will know that these statements can change the control flow:

chai.expect(someFunctionThatReturnsTrue(args)).to.be.true()
// Linter now knows you are expecting something to happen during `.true()` call
// and won't complain anymore

And now if you make a typo, the test will fail (by throwing an exception)

chai.expect(someFunctionThatReturnsTrue(args)).to.be.ture()
                                                  // ~~~~ Will throw something like
                                                  // `...to.be.ture is not a function`