问:
Return all fields from a document as an array from Firebase cloud Firestore - ionic 4
I am trying to return all fields from a document from Firebase cloud Firestore. The problem arises when I wish to store this document as an array on my page for use. In whatever instance I try I cannot seem to be able to take the array outside of the .subscribe() method. outside of the subscribe the array is undefined. I assume I am not understanding a process in typescript.

quiz.service.ts

```<code> export interface Quiz{
 q1: string;
 q2: string;
 q3: string;
 q4: string;

 }
 @Injectable({
   providedIn: 'root'
 })
 export class QuizService {
   quizss: Quiz[];
   quiz: Quiz;
   private quizCollection: AngularFirestoreCollection<Quiz>;
   private quizs: Observable<Quiz[]>;

   constructor(db: AngularFirestore) {
     this.quizCollection = db.collection<Quiz>('quiz');

     this.quizs = this.quizCollection.snapshotChanges().pipe(
       map(actions =>{
           return actions.map(a => {
             const data = a.payload.doc.data();
             const id = a.payload.doc.id;
             return{ id, ...data};
           });
       })
     );
    }

   getQuiz(id){
     return this.quizCollection.doc<Quiz>(id).valueChanges().pipe(
       map(response => response)
     );
   }
 }
</code>```

I get undefined with the following at the console.log in ngOnInit:

```<code> ngOnInit() {
     this.route.queryParams.subscribe((res) => {
       id = res.name;
     });
     answerNumber= 0;
     this.question2 = this.quizService.getQuiz(id);
     console.log("question pull "+ this.question2[0]);
 }
 returnQuiz( answerNumber) {
     this.quizService.getQuiz(id)
       .subscribe(res =>{
       this.quiz = res;
       let newPoint = {
         q1: this.quiz.q1,
         q2: this.quiz.q2,
         q3: this.quiz.q3,
         q4: this.quiz.q4,
       }
       this.question1[0] = newPoint.q1;
       this.question1[1] = newPoint.q2;
       this.question1[2] = newPoint.q3;
       this.question1[3] = newPoint.q4;

       return this.question1;
     });
  }
</code>```

I have also tried this with the same error on the console log returning undefined:

```<code> ngOnInit() {
     this.route.queryParams.subscribe((res) => {
       id = res.name;
     });
     answerNumber= 0;
     this.quizService.getQuiz(id)
       .subscribe(res =>{
       this.quiz = res;
       let newPoint = {
         q1: this.quiz.q1,
         q2: this.quiz.q2,
         q3: this.quiz.q3,
         q4: this.quiz.q4,
       }
       this.question1[0] = newPoint.q1;
       this.question1[1] = newPoint.q2;
       this.question1[2] = newPoint.q3;
       this.question1[3] = newPoint.q4;
     });
      console.log("question pull "+ this.question1[0]);
 }
</code>```

答:
this is because of asynchronous behavior. console.log is out of subscribe that's why console.log execute before setting value of this.question1
move console.log in side subscribe method.
like this

```<code>`
ngOnInit() {
    this.route.queryParams.subscribe((res) => {
        id = res.name;
        answerNumber= 0;
        this.quizService.getQuiz(id)
        .subscribe(res =>{
            this.quiz = res;
            let newPoint = {
               q1: this.quiz.q1,
                 q2: this.quiz.q2,
                 q3: this.quiz.q3,
                 q4: this.quiz.q4,
               }
               this.question1[0] = newPoint.q1;
               this.question1[1] = newPoint.q2;
               this.question1[2] = newPoint.q3;
               this.question1[3] = newPoint.q4;
               console.log("question pull "+ this.question1[0]);
           });
         });
     }`
</code>```

Body:
I am trying to return all fields from a document from Firebase cloud Firestore. The problem arises when I wish to store this document as an array on my page for use. In whatever instance I try I cannot seem to be able to take the array outside of the .subscribe() method. outside of the subscribe the array is undefined. I assume I am not understanding a process in typescript.

quiz.service.ts

 export interface Quiz{
 q1: string;
 q2: string;
 q3: string;
 q4: string;

 }
 @Injectable({
   providedIn: 'root'
 })
 export class QuizService {
   quizss: Quiz[];
   quiz: Quiz;
   private quizCollection: AngularFirestoreCollection<Quiz>;
   private quizs: Observable<Quiz[]>;

   constructor(db: AngularFirestore) {
     this.quizCollection = db.collection<Quiz>('quiz');

     this.quizs = this.quizCollection.snapshotChanges().pipe(
       map(actions =>{
           return actions.map(a => {
             const data = a.payload.doc.data();
             const id = a.payload.doc.id;
             return{ id, ...data};
           });
       })
     );
    }

   getQuiz(id){
     return this.quizCollection.doc<Quiz>(id).valueChanges().pipe(
       map(response => response)
     );
   }
 }

I get undefined with the following at the console.log in ngOnInit:

 ngOnInit() {
     this.route.queryParams.subscribe((res) => {
       id = res.name;
     });
     answerNumber= 0;
     this.question2 = this.quizService.getQuiz(id);
     console.log("question pull "+ this.question2[0]);
 }
 returnQuiz( answerNumber) {
     this.quizService.getQuiz(id)
       .subscribe(res =>{
       this.quiz = res;
       let newPoint = {
         q1: this.quiz.q1,
         q2: this.quiz.q2,
         q3: this.quiz.q3,
         q4: this.quiz.q4,
       }
       this.question1[0] = newPoint.q1;
       this.question1[1] = newPoint.q2;
       this.question1[2] = newPoint.q3;
       this.question1[3] = newPoint.q4;

       return this.question1;
     });
  }

I have also tried this with the same error on the console log returning undefined:

 ngOnInit() {
     this.route.queryParams.subscribe((res) => {
       id = res.name;
     });
     answerNumber= 0;
     this.quizService.getQuiz(id)
       .subscribe(res =>{
       this.quiz = res;
       let newPoint = {
         q1: this.quiz.q1,
         q2: this.quiz.q2,
         q3: this.quiz.q3,
         q4: this.quiz.q4,
       }
       this.question1[0] = newPoint.q1;
       this.question1[1] = newPoint.q2;
       this.question1[2] = newPoint.q3;
       this.question1[3] = newPoint.q4;
     });
      console.log("question pull "+ this.question1[0]);
 }

Body:
this is because of asynchronous behavior. console.log is out of subscribe that's why console.log execute before setting value of this.question1
move console.log in side subscribe method.
like this

`
ngOnInit() {
    this.route.queryParams.subscribe((res) => {
        id = res.name;
        answerNumber= 0;
        this.quizService.getQuiz(id)
        .subscribe(res =>{
            this.quiz = res;
            let newPoint = {
               q1: this.quiz.q1,
                 q2: this.quiz.q2,
                 q3: this.quiz.q3,
                 q4: this.quiz.q4,
               }
               this.question1[0] = newPoint.q1;
               this.question1[1] = newPoint.q2;
               this.question1[2] = newPoint.q3;
               this.question1[3] = newPoint.q4;
               console.log("question pull "+ this.question1[0]);
           });
         });
     }`


来源: stackexchange

问:
How do I view the Explain Plan in Oracle Sql developer?
I have few SQL queries which has very low query running performance and I want to check the query execution plan for this query. I am trying to execute the below query but its not showing any query execution plan. Its only display message plan FOR succeeded. I dont know is there any settings that we have to do in oracle sql developer to vies explain plan for query :</p>

```<code>EXPLAIN PLAN FOR
Select SO.P_OPTION_ID FROM
SIMSIM
   JOIN P_TYPE PT on PT.KEY=SIM.P_TYPE_KEY JOIN P_CONFIG PC ON PC.ID=PT.PRODUCT_CONFIG_ID
JOIN P_OPTION PO ON PO.OPTION_KEY=PC.DEFAULT_PRODUCT_OPTIONS JOIN S_OPTION SO ON SO.SERVICE_ID=SIM.ASSIGNED_TO_SERVICE_ID
JOIN AVV_NO AN ON SIM.ASSIGNED_ANUMBER_ID = AN.ID
 where SO.STATUS_ID IN (20,40)
 and SO.ID < to_char(SYSDATE - numtodsinterval (  1,'MINUTE' ), 'YYYYMMDDHH24MISS')||'0000'
 and SO.ID > to_char(SYSDATE - numtodsinterval (  1, 'HOUR' ), 'YYYYMMDDHH24MISS')||'0000'
and NOT EXISTS(SELECT ID from TEMP_BPL T WHERE T.ID = SO.ID );
</code>```

答: We use Oracle PL/SQL Developer(Version 12.0.7). And we use F5 button to view the explain plan.

ContentLicense: CC BY-SA 3.0

Body:
I have few SQL queries which has very low query running performance and I want to check the query execution plan for this query. I am trying to execute the below query but its not showing any query execution plan. Its only display message plan FOR succeeded. I dont know is there any settings that we have to do in oracle sql developer to vies explain plan for query :

EXPLAIN PLAN FOR
Select SO.P_OPTION_ID FROM
SIMSIM
   JOIN P_TYPE PT on PT.KEY=SIM.P_TYPE_KEY JOIN P_CONFIG PC ON PC.ID=PT.PRODUCT_CONFIG_ID
JOIN P_OPTION PO ON PO.OPTION_KEY=PC.DEFAULT_PRODUCT_OPTIONS JOIN S_OPTION SO ON SO.SERVICE_ID=SIM.ASSIGNED_TO_SERVICE_ID
JOIN AVV_NO AN ON SIM.ASSIGNED_ANUMBER_ID = AN.ID
 where SO.STATUS_ID IN (20,40)
 and SO.ID < to_char(SYSDATE - numtodsinterval (  1,'MINUTE' ), 'YYYYMMDDHH24MISS')||'0000'
 and SO.ID > to_char(SYSDATE - numtodsinterval (  1, 'HOUR' ), 'YYYYMMDDHH24MISS')||'0000'
and NOT EXISTS(SELECT ID from TEMP_BPL T WHERE T.ID = SO.ID );

ContentLicense: CC BY-SA 4.0


Title: interval in months between two columns in r

Body:
I have this data

"code";"min";"max"
"CM106";2016-12-01;2018-08-01
"CM107";2017-10-01;2019-11-01
"CM109";2017-01-01;2019-02-01
"CM113";2018-02-01;2019-03-01
"CM114";2016-10-01;2017-12-01
"CM118";2018-04-01;2018-11-01
"CM121";2018-05-01;2020-02-01
"CM126";2018-08-01;2018-11-01
"CM129";2017-01-01;2018-04-01
"CM131";2018-09-01;2020-05-01
"CM144";2018-02-01;2019-11-01
"CM150";2018-10-01;2019-04-01
"CM153";2018-05-01;2018-09-01
"CM154";2016-05-01;2019-06-01

the format of the dates: year-month-day

I want to create a new column with the interval in months that exist between the "min" and "max" columns

I tried to follow this answer but didn't work Count the months between two dates in a data.table

I get this:

intervalos[, 2:3 := lapply(.SD, as.IDate, format = "%Y.%m.%d"), .SDcols = 2:3]

Error in [.tbl_df(intervalos, , :=(2:3, lapply(.SD, as.IDate, format = "%Y.%m.%d")),  :
  unused argument (.SDcols = 2:3)

Body:
1.Create reproducible minimal example

df <- structure(list(c = c("CM106", "CM107", "CM109", "CM113", "CM114", "CM118", "CM121", "CM126", "CM129", "CM131", "CM144", "CM150", "CM153", "CM154"),
                     min = c("2016-12-01", "2017-10-01", "2017-01-01", "2018-02-01", "2016-10-01", "2018-04-01", "2018-05-01", "2018-08-01", "2017-01-01", "2018-09-01", "2018-02-01", "2018-10-01", "2018-05-01", "2016-05-01"),
                     max = c("2018-08-01", "2019-11-01", "2019-02-01", "2019-03-01", "2017-12-01", "2018-11-01", "2020-02-01", "2018-11-01", "2018-04-01", "2020-05-01", "2019-11-01", "2019-04-01", "2018-09-01", "2019-06-01")),
                class = "data.frame", row.names = c(NA, -14L))

2.Solution using base R:

Use as.Date

df$min <- as.Date(df$min, "%Y-%m-%d")
df$max <- as.Date(df$max, "%Y-%m-%d")

Calculate difference:

Calculate difference:

df$diff_days <- df$max - df$min
df$diff_months <- as.numeric(df$diff_days) /(365.25/12)

df$diff_days is now:

Time differences in days
 [1]  608  761  761  393  426  214
 [7]  641   92  455  608  638  182
[13]  123 1126

and df$diff_months is:

 [1] 19.975359 25.002053 25.002053 12.911704 13.995893
 [6]  7.030801 21.059548  3.022587 14.948665 19.975359
[11] 20.960986  5.979466  4.041068 36.993840


问:
Practicing linked lists
So we learned about lists in class lately and I wanted to practice them. The program doesn't run. Did I fail in filling the nodes? I'm too dizzy to focus on finding the missing key. Sorry for posting such triviality!</p>

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

typedef struct node{
    int val;
    struct node *next;
}node_t;

node_t* create_node(int value,node_t *nextnode) {
    node_t *newnode=(node_t*)malloc(sizeof(node_t));
    if(newnode==NULL) {
        printf("ERROR ALLOCATING");
        exit(0);
    }
    newnode->val=value;
    newnode->next=nextnode;
    return newnode;
}

void fill_list(node_t *head) {
    int i=1;
    node_t *current;
    for(;i<21;i++) {
        current=create_node(i,head);
        head=current;
    }
}

void print_list(node_t *head) {
    node_t *current=head;
    while(current) {
        printf("%d",current->val);
        current=current->next;
    }
}

int main() {
    node_t *head=NULL;
    fill_list(head);
    print_list(head);
    return 0;
}
</code>```

答:
Within the function fill_list the parameter head is being changed.

```<code>void fill_list(node_t *head) {
    int i=1;
    node_t *current;
    for(;i<21;i++) {
        current=create_node(i,head);
        head=current;
    }
}
</code>```

But the function deals with a copy of the argument passed to the function. So the original pointer head defined in main knows nothing about these changes.

You have to return the value of the parameter head of the function from the function and assign it to the pointer head defined in main.

So the function can look like

```<code>node_t * fill_list(node_t *head) {
    for( int i = 1; i < 21; i++ )
    {
        head = create_node( i, head );
    }

    return head;
}
</code>```

and in main there must be

```<code>node_t *head = NULL;
head = fill_list( head );
</code>```

Another way is to pass the pointer head to the function fill_list by reference. In this case the function can look

```<code>void fill_list( node_t **head ) {
    for ( int i = 1; i < 21; i++ ) {
        *head = create_node( i, *head );
    }
}
</code>```

And in main you should write

```<code>node_t *head = NULL;
fill_list( &head );
</code>```

Title: Practicing linked lists

Body:
So we learned about lists in class lately and I wanted to practice them. The program doesn't run. Did I fail in filling the nodes? I'm too dizzy to focus on finding the missing key. Sorry for posting such triviality!

#include <stdio.h>
#include <stdlib.h>

typedef struct node{
    int val;
    struct node *next;
}node_t;

node_t* create_node(int value,node_t *nextnode) {
    node_t *newnode=(node_t*)malloc(sizeof(node_t));
    if(newnode==NULL) {
        printf("ERROR ALLOCATING");
        exit(0);
    }
    newnode->val=value;
    newnode->next=nextnode;
    return newnode;
}

void fill_list(node_t *head) {
    int i=1;
    node_t *current;
    for(;i<21;i++) {
        current=create_node(i,head);
        head=current;
    }
}

void print_list(node_t *head) {
    node_t *current=head;
    while(current) {
        printf("%d",current->val);
        current=current->next;
    }
}

int main() {
    node_t *head=NULL;
    fill_list(head);
    print_list(head);
    return 0;
}

Body:
Within the function fill_list the parameter head is being changed.

void fill_list(node_t *head) {
    int i=1;
    node_t *current;
    for(;i<21;i++) {
        current=create_node(i,head);
        head=current;
    }
}

But the function deals with a copy of the argument passed to the function. So the original pointer head defined in main knows nothing about these changes.

You have to return the value of the parameter head of the function from the function and assign it to the pointer head defined in main.

So the function can look like

node_t * fill_list(node_t *head) {
    for( int i = 1; i < 21; i++ )
    {
        head = create_node( i, head );
    }

    return head;
}

and in main there must be

node_t *head = NULL;
head = fill_list( head );

Another way is to pass the pointer head to the function fill_list by reference. In this case the function can look

void fill_list( node_t **head ) {
    for ( int i = 1; i < 21; i++ ) {
        *head = create_node( i, *head );
    }
}

And in main you should write

node_t *head = NULL;
fill_list( &head );


问:
A simple "javac" style command-line C/C++ compiler for Windows 7
Over the last couple of months I practiced console programming with Java just with the help of JDK and a text editor of my choice (Notepad++). And I loved the simplicity as a program can be compiled from the command line plainly using javac and run using java.

Now, I'm looking for similar compiler for C/C++, such that I create a .c or .cpp file and compile it in the command prompt, and all it does is create a "native" executable that can be run directly from the command prompt. Thus, without any need of bloated IDE. The reason I'm looking for such simple compiler is because it is going to be used by high-school students so I'm advised to avoid any IDE as far as possible, so students can practice all the concepts of C/C++ languages without having to go for IDE. Which compiler can I use that does this job? also, I must work across all the versions Windows starting from Windows XP.

答: A very simple solution woul be cygwin and MinGW, which provides an environment very similar to a UNIX shell. Then you can use the make utilities to compile your program.


问:
What is the exact import for resolving triple equals in Cats?
What is the exact import for the triple equals?

Before I was importing "cats.implicits._" and it was working fine but I can't do that anymore as it causes ambiguities with other imports.

答:
Triple equals resides in package cats.evidence

https://github.com/typelevel/cats/blob/master/core/src/main/scala/cats/evidence/package.scala

Moreover, some of its instances reside in cats.evidence.Is:

https://github.com/typelevel/cats/blob/master/core/src/main/scala/cats/evidence/Is.scala

Then, probably cats.evidence._ cats.evidence.Is._ would be enough.

The general way of figuring out which implicit instance is used by function (at least in Intellij Idea) is Ctrl+Shift+P for arguments, and Ctrl+Shift+Q for implicit conversions.


问:
Reactive Form Validity based on IP Addresses RegEx
Update: I find that this behavior is reproducible using a simple regex such as /^[0-9]+$/. It is also reproducible using a custom validator function such as

export function textareaPattern(pattern: RegExp): ValidatorFn {
    return (control: AbstractControl): {[key: string]: any} | null => {
        const values = control.value.split('\n');
        let mismatch = false;
        values.forEach(val => {
            mismatch = !pattern.test(val);
            if(mismatch) {
                return {textareaPattern: {value: control.value}}
            }
        });
        return null;
    }
}
```

<hr>

<p><strong>Original post:</strong> I have a regex that is intended to validate that a user has entered multiple, valid IP addresses- one per line- in a text area.</p>

<blockquote>
  <p>/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(/([0-9]|[1-2][0-9]|3[0-2]))?$\n?/gim</p>
</blockquote>

<p>The regex works on a happy path, but gets weird once both a valid entry and an invalid entry are present. </p>

<p>If I enter all valid values, the form control is valid, as expected. Example:</p>

```10.1.121.2
10.2.121.3
10.3.121.4
```

<p>If I enter all invalid values, the form control is not valid, as expected. Example: </p>

```butter
potato
123
```

<p>If I enter a combination of valid and invalid values, the form control alternates between valid and invalid, depending on the length of the entry. If the entry's length is even, it's invalid, and odd is valid. How odd.</p>

<p>length: 12, Invalid</p>

```10.1.121.1
f
```

<p>length: 13, Valid</p>

```10.1.121.1
fo
```

<p>I'd think the problem lies in the RegEx, but I'll admit I'm far from comfortable deciphering such a behemoth of a RegEx.</p>

<p>The RegEx should match:</p>

```192.168.1.1
255.203.232.1
1.0.12.1
```

<p>The RegEx should not match:</p>

```256.1.12.1
1934.1.22.3
201.foobar.201.1
```

Minimal, Reproducible Example (updated with solution): https://stackblitz.com/edit/angular-v4f35a?file=src%2Fapp%2Fapp.component.ts

答:
So this boiled down to two issues.

The first problem was that the global flag for RegExes causes the JS engine to track a lastIndex property from which the next search will start when myRegex.test() is called again. Since the regex object is the same throughout the validation process, that lastIndex is updated and referenced as you type, and the form re-validates.

The second problem is that without global, the form would be considered valid as long as one line is correct. So my input could be

```<code>192.168.foobar
192.168.1.1
hello world!
</code>```

and the form is valid because of line 2.

My Solution

I've implemented a custom validator for textareas. It accepts my regex (sans g flag) and splits the contents of the textarea on \n. It immediately assumes no mismatches, then for each line, checks that the line matches the RegEx. If not, it mismatches and returns an object containing the contents of the textarea:

import {AbstractControl, ValidatorFn} from '@angular/forms';

export function multilinePattern(pattern: RegExp): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} | null => {
    const values = control.value.split('\n');
    if (values.length === 1 && values[0] === '') {
      return null;
    }
    let mismatch = false;
    values.forEach((val: string) => {
      if (!pattern.test(val)) {
        mismatch = true;
      }
    });
    return mismatch ? {multilinePattern: {value: control.value}} : null;
  };
}
```

Body:
Update: I find that this behavior is reproducible using a simple regex such as /^[0-9]+$/. It is also reproducible using a custom validator function such as

export function textareaPattern(pattern: RegExp): ValidatorFn {
    return (control: AbstractControl): {[key: string]: any} | null => {
        const values = control.value.split('\n');
        let mismatch = false;
        values.forEach(val => {
            mismatch = !pattern.test(val);
            if(mismatch) {
                return {textareaPattern: {value: control.value}}
            }
        });
        return null;
    }
}

Original post: I have a regex that is intended to validate that a user has entered multiple, valid IP addresses- one per line- in a text area.

/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(/([0-9]|[1-2][0-9]|3[0-2]))?$\n?/gim

The regex works on a happy path, but gets weird once both a valid entry and an invalid entry are present.

If I enter all valid values, the form control is valid, as expected. Example:

10.1.121.2
10.2.121.3
10.3.121.4

If I enter all invalid values, the form control is not valid, as expected. Example:

butter
potato
123

If I enter a combination of valid and invalid values, the form control alternates between valid and invalid, depending on the length of the entry. If the entry's length is even, it's invalid, and odd is valid. How odd.

length: 12, Invalid

10.1.121.1
f

length: 13, Valid

10.1.121.1
fo

I'd think the problem lies in the RegEx, but I'll admit I'm far from comfortable deciphering such a behemoth of a RegEx.

The RegEx should match:

192.168.1.1
255.203.232.1
1.0.12.1

The RegEx should not match:

256.1.12.1
1934.1.22.3
201.foobar.201.1

Minimal, Reproducible Example (updated with solution): https://stackblitz.com/edit/angular-v4f35a?file=src%2Fapp%2Fapp.component.ts

Body:
So this boiled down to two issues.

The first problem was that the global flag for RegExes causes the JS engine to track a lastIndex property from which the next search will start when myRegex.test() is called again. Since the regex object is the same throughout the validation process, that lastIndex is updated and referenced as you type, and the form re-validates.

The second problem is that without global, the form would be considered valid as long as one line is correct. So my input could be

192.168.foobar
192.168.1.1
hello world!

and the form is valid because of line 2.

My Solution

I've implemented a custom validator for textareas. It accepts my regex (sans g flag) and splits the contents of the textarea on \n. It immediately assumes no mismatches, then for each line, checks that the line matches the RegEx. If not, it mismatches and returns an object containing the contents of the textarea:

import {AbstractControl, ValidatorFn} from '@angular/forms';

export function multilinePattern(pattern: RegExp): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} | null => {
    const values = control.value.split('\n');
    if (values.length === 1 && values[0] === '') {
      return null;
    }
    let mismatch = false;
    values.forEach((val: string) => {
      if (!pattern.test(val)) {
        mismatch = true;
      }
    });
    return mismatch ? {multilinePattern: {value: control.value}} : null;
  };
}


问:
How to extract image from a live photo?
I know how to extract video from a live photo. Explained here.

Use the PHAssetResourceManager to get the video file from the PHAssetResource.

```<code>PHAssetResourceManager.defaultManager().writeDataForAssetResource(assetRes,
    toFile: fileURL, options: nil, completionHandler:
  {
     // Video file has been written to path specified via fileURL
  }
</code>```

But how to extract image URL from PHLivePhoto. The motivation behind this is to get both video and image URL in order to upload it to the server.

答:
You can also write an image data to file path, just like with video in your question.
Both asset resources are available in live photo asset (video & image):</p>

```<code> let resources = PHAssetResource.assetResources(for: asset)
</code>```

Title: How to extract image from a live photo?

Body:
I know how to extract video from a live photo. Explained here.

Use the PHAssetResourceManager to get the video file from the PHAssetResource.

PHAssetResourceManager.defaultManager().writeDataForAssetResource(assetRes,
    toFile: fileURL, options: nil, completionHandler:
  {
     // Video file has been written to path specified via fileURL
  }

But how to extract image URL from PHLivePhoto. The motivation behind this is to get both video and image URL in order to upload it to the server.

Body:
You can also write an image data to file path, just like with video in your question.
Both asset resources are available in live photo asset (video & image):

 let resources = PHAssetResource.assetResources(for: asset)


问:
Remove Zeros Before Decimal- PowerBI
Numbers under 1 are currently being represented with a leading zero before the decimal point (example: 0.50). Because I'm working with baseball statistics (which almost never have the zero before the decimal) I would like to remove that. I want to keep the number before the decimal if its greater than 1 though. How would I do that?

For instance if I'm working with this measure. Is there something I can add to that?

```<code>AVG = SUM(Batter[H])/sum(Batter[AB])
</code>```

Thanks. I appreciate the help.

Here is some sample data

```<code>Name            AB  H
Gleyber Torres  546 152
Brett Gardner   491 123
Aaron Judge     378 103
Adam Ottavino   0   0
Aroldis Chapman 0   0
</code>```

答:
Unfortunately, it isn't directly possible. However, in the last step (the visualization of the data), you can convert the decimal number to text and format it as you want. For example, your measure could be like this:

```<code>AVG = FORMAT(SUM(Batter[H])/SUM(Batter[AB]), "#,###.00")
</code>```

This will give you 2 decimal places (0 means that there will be a digit displayed at this position), but the digits before the decimal are optional (# means it will show a digit, but will omit the leading zeros) or here are some examples:

Title: Remove Zeros Before Decimal- PowerBI

Body:
Numbers under 1 are currently being represented with a leading zero before the decimal point (example: 0.50). Because I'm working with baseball statistics (which almost never have the zero before the decimal) I would like to remove that. I want to keep the number before the decimal if its greater than 1 though. How would I do that?

For instance if I'm working with this measure. Is there something I can add to that?

AVG = SUM(Batter[H])/sum(Batter[AB])

Thanks. I appreciate the help.

Here is some sample data

Name            AB  H
Gleyber Torres  546 152
Brett Gardner   491 123
Aaron Judge     378 103
Adam Ottavino   0   0
Aroldis Chapman 0   0

Body:
Unfortunately, it isn't directly possible. However, in the last step (the visualization of the data), you can convert the decimal number to text and format it as you want. For example, your measure could be like this:

AVG = FORMAT(SUM(Batter[H])/SUM(Batter[AB]), "#,###.00")

This will give you 2 decimal places (0 means that there will be a digit displayed at this position), but the digits before the decimal are optional (# means it will show a digit, but will omit the leading zeros) or here are some examples:


问:
Jpql and hibernate age difference
I want to write a method that searches for people at a given age with an interval of 5 years. That is, if the age is set to 30 years, then the method should bring all people from 25 to 35 years old.

```<code>  @Entity
@NamedQueries({
        @NamedQuery(name = "Person.findByNameUndSurname", query = "SELECT c FROM Person c WHERE c.name = ?1 and c.surname = ?1"),
        @NamedQuery(name = "Person.findByAge", query = "SELECT c FROM Person c WHERE c.age = ?1")
})
    Person{
    name,age und get,set
    }

public class PersonMenager extends AbstractRepository {

---
    public List findPersonByAge(int age){
            return entityManager.createQuery("SELECT c from Person c WHERE c.age = ?1 and c.age between age-5 and  age+5").getResultList();
        }
}
</code>```

I don’t understand how I can use the age input

答:
The query would be:

```<code>SELECT c from Person c WHERE c.age between :age -5 and  :age + 5
</code>```

Then you need to call query.setParameter("age", age).

For a more flexible query if would use:

```<code>SELECT c from Person c WHERE c.age between :startAge and  :endAge
</code>```

And to set de parameters:

```<code>query.setParameter("startAge", age - 5);
query.setParameter("endAge", age + 5);
</code>```

Title: Jpql and hibernate age difference

Body:
I want to write a method that searches for people at a given age with an interval of 5 years. That is, if the age is set to 30 years, then the method should bring all people from 25 to 35 years old.

  @Entity
@NamedQueries({
        @NamedQuery(name = "Person.findByNameUndSurname", query = "SELECT c FROM Person c WHERE c.name = ?1 and c.surname = ?1"),
        @NamedQuery(name = "Person.findByAge", query = "SELECT c FROM Person c WHERE c.age = ?1")
})
    Person{
    name,age und get,set
    }

public class PersonMenager extends AbstractRepository {

---
    public List findPersonByAge(int age){
            return entityManager.createQuery("SELECT c from Person c WHERE c.age = ?1 and c.age between age-5 and  age+5").getResultList();
        }
}

I don’t understand how I can use the age input

Body:
The query would be:

SELECT c from Person c WHERE c.age between :age -5 and  :age + 5

Then you need to call query.setParameter("age", age).

For a more flexible query if would use:

SELECT c from Person c WHERE c.age between :startAge and  :endAge

And to set de parameters:

query.setParameter("startAge", age - 5);
query.setParameter("endAge", age + 5);


问:
Regex Pattern for EMail
I searched a lot for a regex pattern which is convenient for me. I couldn't find any.

Here is my conditions,

```<code>1. email should not contain any space or special characters(excep @ and .)
2. email should not start with dot(.) or should not end with .(before @ symbot)
3. two dots should not come near.
4. @ symbol should not repeat.
</code>```

Here some valid and invalid email IDS,

```<code>firstname@gmail.com -- valid
firstname.@gmail.com -- invalid(dot and @ should not come closer)
firstname..lastname@gmail.com --invlid(two dots should not come closer)
firstname#lastname@gmail.com -- invalid(should not contain any special characters appart @ and .)
frist1991@gmail.com -- valid
first name@gmai.com -- invalie( should not allow any spaces)
.fristname@gmail.com --invalid(should not start with .)
</code>```

I found lot of regex pattern for email. but didn't satisfy my conditions

Thanks in advance,

Title: Regex Pattern for EMail

Body:
I searched a lot for a regex pattern which is convenient for me. I couldn't find any.

Here is my conditions,

1. email should not contain any space or special characters(excep @ and .)
2. email should not start with dot(.) or should not end with .(before @ symbot)
3. two dots should not come near.
4. @ symbol should not repeat.

Here some valid and invalid email IDS,

firstname@gmail.com -- valid
firstname.@gmail.com -- invalid(dot and @ should not come closer)
firstname..lastname@gmail.com --invlid(two dots should not come closer)
firstname#lastname@gmail.com -- invalid(should not contain any special characters appart @ and .)
frist1991@gmail.com -- valid
first name@gmai.com -- invalie( should not allow any spaces)
.fristname@gmail.com --invalid(should not start with .)

I found lot of regex pattern for email. but didn't satisfy my conditions

Thanks in advance,

Body:
This would work:

^[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*@[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*$

https://regex101.com/r/nen2SZ/1


问:
What will the code below output to the console and what is the reason?
This is an interview question and I'm very curious about the answer.</p>

```<code>var myObject = {
    foo: "bar",
    func: function() {
        var self = this;
        console.log("outer func:  this.foo = " + this.foo);
        console.log("outer func:  self.foo = " + self.foo);
        (function() {
            console.log("inner func:  this.foo = " + this.foo);
            console.log("inner func:  self.foo = " + self.foo);
        }());
    }
};
myObject.func();
</code>```

答:
Here's the console output:

```<code>outer func:  this.foo = bar
outer func:  self.foo = bar
inner func:  this.foo = undefined
inner func:  self.foo = bar
</code>```

This is a demonstration of a Javascript function closure, which is a very common question for coding interviews. The outer function has access to the object scope, which is referenced by this and assigned to the variable self. So both calls to access the property foo work as expected,

Then, an inner function is defined inside this function. This inner function does not have access to the object scope, but does have access to the scope of it's parent function, where the self variable was defined. This is the closure part of the closure so to speak. So when we try and access self.foo from the inner function we can access it - as it's been defined in the same lexical scope as the calling function. this.foo on the other hand exists in a different scope so cannot be accessed.

Body:
This is an interview question and I'm very curious about the answer.

var myObject = {
    foo: "bar",
    func: function() {
        var self = this;
        console.log("outer func:  this.foo = " + this.foo);
        console.log("outer func:  self.foo = " + self.foo);
        (function() {
            console.log("inner func:  this.foo = " + this.foo);
            console.log("inner func:  self.foo = " + self.foo);
        }());
    }
};
myObject.func();

Body:
Here's the console output:

outer func:  this.foo = bar
outer func:  self.foo = bar
inner func:  this.foo = undefined
inner func:  self.foo = bar

This is a demonstration of a Javascript function closure, which is a very common question for coding interviews. The outer function has access to the object scope, which is referenced by this and assigned to the variable self. So both calls to access the property foo work as expected,

Then, an inner function is defined inside this function. This inner function does not have access to the object scope, but does have access to the scope of it's parent function, where the self variable was defined. This is the closure part of the closure so to speak. So when we try and access self.foo from the inner function we can access it - as it's been defined in the same lexical scope as the calling function. this.foo on the other hand exists in a different scope so cannot be accessed.


问:
Restricting 3 figures after the decimal places is not working when copy paste value into the input field
I was successful in restricting the 3 figures after the decimal places however the fix is not working when i copy paste some random decimal figures into the text field.

$('.min-val').on('keyup', function(e) {
  $(this).val($(this).val().replace(/[^\d.]/g, ''));
  if ($(this).val().indexOf(".") > -1 && ($(this).val().split('.')[1].length > 3)) {
    $(this).val($(this).val().substring(0, $(this).val().length - 1));
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" placeholder="min val" class="min-val" /></code>```

How can i restrict the decimal figures to 3 even when i copy paste the data?

答:
You can achieve this with regex itself. I am not good at it though.

So below work around works.
You can determine the number of characters to trim and use that number

var charsToTrim = $(this).val().split('.')[1].length - 3;

$('.min-val').on('keyup', function(e) {
  $(this).val($(this).val().replace(/[^\d.]/g, ''));
  if ($(this).val().indexOf(".") > -1 && ($(this).val().split('.')[1].length > 3)) {
    var charsToTrim = $(this).val().split('.')[1].length - 3;
    $(this).val($(this).val().substring(0, $(this).val().length - charsToTrim));
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" placeholder="min val" class="min-val" /></code>```

Body:
I was successful in restricting the 3 figures after the decimal places however the fix is not working when i copy paste some random decimal figures into the text field.

$('.min-val').on('keyup', function(e) {
  $(this).val($(this).val().replace(/[^\d.]/g, ''));
  if ($(this).val().indexOf(".") > -1 && ($(this).val().split('.')[1].length > 3)) {
    $(this).val($(this).val().substring(0, $(this).val().length - 1));
  }
});

<input type="text" placeholder="min val" class="min-val" />

How can i restrict the decimal figures to 3 even when i copy paste the data?

Body:
You can achieve this with regex itself. I am not good at it though.

So below work around works.
You can determine the number of characters to trim and use that number

var charsToTrim = $(this).val().split('.')[1].length - 3;

$('.min-val').on('keyup', function(e) {
  $(this).val($(this).val().replace(/[^\d.]/g, ''));
  if ($(this).val().indexOf(".") > -1 && ($(this).val().split('.')[1].length > 3)) {
    var charsToTrim = $(this).val().split('.')[1].length - 3;
    $(this).val($(this).val().substring(0, $(this).val().length - charsToTrim));
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" placeholder="min val" class="min-val" />


问:
How to delete all the boxes in Hive Flutter?
I am developing an application using Flutter; it will store some data locally, so I decided to use Hive package which was really amazing package to store data. So now I will store all the data locally when the user press the sync button. After that, if the user clicks sync again, I have to delete all the boxes and store data which may or may not have the same box name.

I don't want to increase the application storage to increase if the sync button is clicked, I want to delete all the boxes and again I want to create the box.

答:
You didn't share any code so I will just give an example.

I would suggest you to open the boxes in your main function

```<code>void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Hive.initFlutter();
  Hive.registerAdapter(yourAdapter());
  await Hive.openBox('yourBoxName');
}
</code>```

When user wants to sync, you can do following;

```<code>// It will delete all the entry in the box
Hive.box('yourBoxName').clear();
yourSyncOperation();
</code>```

Body:
You didn't share any code so I will just give an example.

I would suggest you to open the boxes in your main function

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Hive.initFlutter();
  Hive.registerAdapter(yourAdapter());
  await Hive.openBox('yourBoxName');
}

When user wants to sync, you can do following;

// It will delete all the entry in the box
Hive.box('yourBoxName').clear();
yourSyncOperation();


问:
Which are the best alternatives to Lucene?
It may run on Unix and it will be used for email searching (Dovecot, Postfix and maildir).

Lucene is not a problem, I'm just analyzing some alternatives.

答: would need to know what problems you're having with Lucene, but Xapian is worth a look.</p>

OwnerDisplayName: Rui Carneiro

LastEditorDisplayName: Rui Carneiro

OwnerDisplayName: Paul Dixon

ContentLicense: CC BY-SA 2.5


问:
How to specify signature expressly in Alloy?
I'm learning Alloy modeling language, and I saw this code.

```<code>sig Person {
  partner: Person
}

fact partnerProperties {
  partner = ~partner
  no p: Person | p in p.partner
}
</code>```

This code express "Person's partner relation is mutual".

I can understand above code, but I think how to express partner is relation that wrote in Person expressly.
Because of readability.

I want to write like this.

```<code>fact partnerProperties {
  Person.partner = ~Person.partner
  no p: Person | p in p.partner
}
</code>```

I'm grad to help me.

答: Note that Person.partner doesn't mean what you think it means. It's a join of the set Person and the relation partner. To specify the relation partner belonging to the signature Person, you'd write Person <: partner, but that's not necessary here as Alloy infers it.

Body:
I'm learning Alloy modeling language, and I saw this code.

sig Person {
  partner: Person
}

fact partnerProperties {
  partner = ~partner
  no p: Person | p in p.partner
}

This code express "Person's partner relation is mutual".

I can understand above code, but I think how to express partner is relation that wrote in Person expressly.
Because of readability.

I want to write like this.

fact partnerProperties {
  Person.partner = ~Person.partner
  no p: Person | p in p.partner
}

I'm grad to help me.


问:
A question about local variable, range, for in Python
I am solving an algorithm problem in https://leetcode.com/problems/two-sum.

Here is my code:

```<code>class Solution:
    def twoSum(self, nums, target):
        list_length = len(nums)
        result = list()
        for i in range(0, list_length):
            for j in range(i+1, list_length):
                s = i + j
                if s == target:
                    result.append(i)
                    result.append(j)
                    return result

s = Solution()
ts = s.twoSum([2, 7, 11, 15], 9)
print(ts)
</code>```

The output is None.

I want to know why is it None rather than [0,1].

答:
When calculating s you are summing the indeces (i and j) you are iterating through rather than the elements at those indeces. This works:

```<code>class Solution:
    def twoSum(self, nums, target):
        list_length = len(nums)
        result = list()
        for i in range(list_length):
            for j in range(1, list_length):
                s = nums[i] + nums[j]
                if s == target:
                    result.append(i)
                    result.append(j)
                    return result
s = Solution()
ts = s.twoSum([2, 7, 11, 15], 27)
print(ts)
</code>```

Body:
I am solving an algorithm problem in https://leetcode.com/problems/two-sum.

Here is my code:

class Solution:
    def twoSum(self, nums, target):
        list_length = len(nums)
        result = list()
        for i in range(0, list_length):
            for j in range(i+1, list_length):
                s = i + j
                if s == target:
                    result.append(i)
                    result.append(j)
                    return result

s = Solution()
ts = s.twoSum([2, 7, 11, 15], 9)
print(ts)

The output is None.

I want to know why is it None rather than [0,1].

Body:
When calculating s you are summing the indeces (i and j) you are iterating through rather than the elements at those indeces. This works:

class Solution:
    def twoSum(self, nums, target):
        list_length = len(nums)
        result = list()
        for i in range(list_length):
            for j in range(1, list_length):
                s = nums[i] + nums[j]
                if s == target:
                    result.append(i)
                    result.append(j)
                    return result
s = Solution()
ts = s.twoSum([2, 7, 11, 15], 27)
print(ts)


问:
Clicking on input with keyup.enter.prevent form is submitted anyway
In  @vue/cli 4.1.1 app I use bootstrap-vue and I have a form with 2 tabs :
on 1st tab several fields and clicking Enter key on any
control my form is submitted as expected, but I have
the second tab with listing of meta keywords and single input control I want clicking
on this control

v-on:keyup.enter.prevent="addMetaKeyword()"
```
<p>to run update method, but without form submitted, but failed as my form is submitted.
I do like :</p>
<pre class="lang-html prettyprint-override"><code>    <template>
        <b-card class="backend_editor_container">
            <b-card-header>
                <h3 class="row_content_left_aligned p-2" v-show="is_page_loaded">
                    <i :class="'info_link '+getHeaderIcon('page')"></i>{{ getHeaderTitle }}
                </h3>
                <div v-show="!is_page_loaded">
                    <h3>
                        <b-spinner variant="success" label="Page loading"></b-spinner> Page loading...
                    </h3>
                </div>

            </b-card-header>

            <b-card-body v-show="is_page_loaded">

                <div>
                    <b-tabs content-class="mt-3" justified>

                        <b-tab
                                title="Details"
                        >

                            <ValidationObserver
                                    ref="pageObserverForm"
                                    v-slot="{handleSubmit}"
                            >
                                <b-form @submit.prevent="handleSubmit(onSubmit)">

                                    <b-row class="editor_row" v-if="!is_insert">
                                        <b-col md="4">
                                            <label for="id" class="pt-2 ">Id:</label>
                                        </b-col>
                                        <b-col md="8">
                                            <b-form-input
                                                    id="id"
                                                    v-model="pageForm.id"
                                                    readonly
                                                    class="text-right"
                                            ></b-form-input>
                                        </b-col>
                                    </b-row>
            ...
                        </b-tab>

                        <b-tab
                                title="Meta"
                                active
                        >
                            <fieldset class="bordered text-muted p-0 m-0 mb-4">

                                <legend class="bordered">Add meta keyword</legend>

                                <b-row class="editor_row">
                                    <b-col md="4">
                                        <label for="new_meta_keyword" class="pt-2 ">New meta keyword:</label>
                                    </b-col>
                                    <b-col md="8">
                                        <b-form-input
                                                id="id"
                                                v-model="new_meta_keyword"
                                                class="text-left"
                                                v-on:keyup.enter.prevent="addMetaKeyword()"
                                        ></b-form-input>
                                    </b-col>
                                </b-row>
                                <div class="buttons_container">
                                    <b-button type="button" variant="primary" size="sm" @click.prevent="addMetaKeyword()" class="m-1 ml-4">
                                        <i :class="'info_link '+getHeaderIcon('save')"></i>Add
                                    </b-button>
                                </div>

                            </fieldset>
</code>```

How correct ?

```<code>"bootstrap-vue": "^2.3.0",
"vue": "^2.6.11",
</code>```

Modified BLOCK #1 :

        addMetaKeyword() {
            this.new_meta_keyword = this.trim(this.new_meta_keyword)
            if (this.isEmpty(this.new_meta_keyword)) {
                this.showPopupMessage('Page editor', 'Meta keyword can not be empty !', 'warn')
                return
            }

            let l = this.metaKeywordsList.length
            for (let i = 0; i < l; i++) {
                if (this.metaKeywordsList[i] === this.new_meta_keyword) {
                    this.showPopupMessage('Page editor', 'This Meta keyword is already defined !', 'warn')
                    return
                }
            }

            this.metaKeywordsList[this.metaKeywordsList.length] = this.new_meta_keyword
            this.new_meta_keyword = null
            this.showPopupMessage("Page editor", 'You need to save changes in meta keyword mby clicking on "Update" button !', 'success');
        },
```

Thanks!

答:
The problem is that the keyup event is not preventable. Instead use the keydown event like so , this will run yourMethod without submitting the form.

new Vue({
 el: "#app",
 methods: {
  onSubmit() {
    console.log('Form submitted')
  },
  doOtherStuff(){
    console.log('Doing other stuff')
  }
 }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script>
<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>

<link href="https://unpkg.com/bootstrap@4.4.1/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://unpkg.com/bootstrap-vue@2.4.2/dist/bootstrap-vue.css" rel="stylesheet"/>

<div id='app'>
  <b-form @submit.prevent="onSubmit">
    <h1>This will submit your form</h1>
    <b-input></b-input>
    <h1>This wont submit your form</h1>
    <b-input @keydown.enter.prevent="doOtherStuff"></b-input>

    <!-- Needs the button to handle submit, I'm hiding it in this case -->
    <b-btn type="submit" class="d-none"></b-btn>
  </b-form>
</div></code>```

Body:
In  @vue/cli 4.1.1 app I use bootstrap-vue and I have a form with 2 tabs :
on 1st tab several fields and clicking Enter key on any
control my form is submitted as expected, but I have
the second tab with listing of meta keywords and single input control I want clicking
on this control

v-on:keyup.enter.prevent="addMetaKeyword()"

to run update method, but without form submitted, but failed as my form is submitted.
I do like :

    <template>

                    {{ getHeaderTitle }}

                         Page loading...

                            <ValidationObserver
                                    ref="pageObserverForm"
                                    v-slot="{handleSubmit}"
                            >

                                            Id:

            ...

                            <fieldset class="bordered text-muted p-0 m-0 mb-4">

                                <legend class="bordered">Add meta keyword</legend>

                                        New meta keyword:

                                        Add

                            </fieldset>

How correct ?

"bootstrap-vue": "^2.3.0",
"vue": "^2.6.11",

Modified BLOCK #1 :

        addMetaKeyword() {
            this.new_meta_keyword = this.trim(this.new_meta_keyword)
            if (this.isEmpty(this.new_meta_keyword)) {
                this.showPopupMessage('Page editor', 'Meta keyword can not be empty !', 'warn')
                return
            }

            let l = this.metaKeywordsList.length
            for (let i = 0; i < l; i++) {
                if (this.metaKeywordsList[i] === this.new_meta_keyword) {
                    this.showPopupMessage('Page editor', 'This Meta keyword is already defined !', 'warn')
                    return
                }
            }

            this.metaKeywordsList[this.metaKeywordsList.length] = this.new_meta_keyword
            this.new_meta_keyword = null
            this.showPopupMessage("Page editor", 'You need to save changes in meta keyword mby clicking on "Update" button !', 'success');
        },

Thanks!

Body:
The problem is that the keyup event is not preventable. Instead use the keydown event like so <b-input @keydown.enter.prevent="yourMethod"></b-input>, this will run yourMethod without submitting the form.

new Vue({
 el: "#app",
 methods: {
  onSubmit() {
    console.log('Form submitted')
  },
  doOtherStuff(){
    console.log('Doing other stuff')
  }
 }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script>
<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>

<link href="https://unpkg.com/bootstrap@4.4.1/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://unpkg.com/bootstrap-vue@2.4.2/dist/bootstrap-vue.css" rel="stylesheet"/>

<div id='app'>
  <b-form @submit.prevent="onSubmit">
    <h1>This will submit your form</h1>
    <b-input></b-input>
    <h1>This wont submit your form</h1>
    <b-input @keydown.enter.prevent="doOtherStuff"></b-input>

    <!-- Needs the button to handle submit, I'm hiding it in this case -->
    <b-btn type="submit" class="d-none"></b-btn>
  </b-form>
</div>


问:
Regex comma separated sub string within a string
I need to get key value pair from string using regex.

String is something like

```<code>country=xxx,state=yyy,city=zzz,
</code>```

then this regex

```<code>([^,=]+?)(=)([^,=]+?),
</code>```

gives me 3 different key value pairs but if I have multiple comma separated values then only first is selected.

For e.g.

```<code>country=xxx,state=yyy,city=zzz,pqr,
</code>```

then for city pqr is dropped. I want to have both zzz,pqr for the city.

答:
If you don't want to allow consecutive comma's ,, you might repeat matching a comma followed by any char except a , or =

You could ddd \r\n to the character class if you don't want to cross newlines.

```<code>([^,=]+)=([^,=]+(?:,[^,=]+)*),
</code>```

([^,=]+) Capture b, match any char except , or =

= Match literally

( Capture group 2

[^,=]+ Match 1+ times any char except , or =

(?:,[^,=]+)* Repeat 0+ times matching the , followed by any char except , or =

), Close group 2 and match trailing  ,

Regex demo

Note that you can omit the ? after [^,=]+? to make it non greedy as the negated character class can not match the following = in ([^,=]+?)(=)

Body:
I need to get key value pair from string using regex.

String is something like

country=xxx,state=yyy,city=zzz,

then this regex

([^,=]+?)(=)([^,=]+?),

gives me 3 different key value pairs but if I have multiple comma separated values then only first is selected.

For e.g.

country=xxx,state=yyy,city=zzz,pqr,

then for city pqr is dropped. I want to have both zzz,pqr for the city.

Body:
If you don't want to allow consecutive comma's ,, you might repeat matching a comma followed by any char except a , or =

You could ddd \r\n to the character class if you don't want to cross newlines.

([^,=]+)=([^,=]+(?:,[^,=]+)*),

([^,=]+) Capture b, match any char except , or =

= Match literally

( Capture group 2

[^,=]+ Match 1+ times any char except , or =

(?:,[^,=]+)* Repeat 0+ times matching the , followed by any char except , or =

), Close group 2 and match trailing  ,

Regex demo

Note that you can omit the ? after [^,=]+? to make it non greedy as the negated character class can not match the following = in ([^,=]+?)(=)


问:
Uploading images to S3
I'm working on a image hosting web site, and I'm in a bit of a pickle. I chose Amazon S3 beacuse it's fast, it scales and the pay-as-you-go model.

When I upload images from my web site, I need to process them on the server - creating 3 different sizes, inserting data into the DB, and then I'd be ready to upload to S3 (all 3 sizes of the image).

I'm currently using plupload for the uploading, and I set it all up now working with my DB as storage for the images - just for testing purposes. But I just realized - this uploading to my web server, processing and THEN uploading to S3 would mean double the upload time per image right?

Is there any smart way of handling this scenario?

答:
Of course you'll need more time saving images because you'll actually have two HTTP transfers. You can try to execute uploads in parallel with other operations, for example:

start uploading the original/largest image to S3

in the meantime, prepare the two other images

upload the two other images in parallel

I suspect that uploading the original/largest image takes more than generating the two smaller ones, so a parallel solution would work very well. Even if uploading takes less than generating the two other images, the upload is not stealing much CPU time, so in all cases you should see improvements.

Of course it's more complex, especially if you think about error handling.

Title: Uploading images to S3


问:
inline meaning in module interfaces
Consider the header file:

```<code>class T
{
private:
  int const ID;

public:
  explicit T(int const ID_) noexcept : ID(ID_) {}

  int GetID() const noexcept { return ID; }
};
</code>```

or, alternatively:

```<code>class T
{
private:
  int const ID;

public:
  explicit T(int const ID_) noexcept;

  int GetID() const noexcept;
};

inline T::T(int const ID_) noexcept : ID(ID_) {}

inline int T::GetID() const noexcept { return ID; }
</code>```

In a pre-modules world, these headers might be textually included in multiple TU without ODR violations. Furthermore, since the involved member functions are relatively small, the compiler would likely "inline" (avoid function calls when using) those functions, or even optimize away some instances of T altogether.

In a recent report on the meeting where C++20 was finished, I could read the following statement:

We clarified the meaning of inline in module interfaces: the intent is that bodies of functions that are not explicitly declared inline are not part of the ABI of a module, even if those function bodies appear in the module interface. In order to give module authors more control over their ABI, member functions defined in class bodies in module interfaces are no longer implicitly inline.

I'm not sure I'm not mistaken that. Does that mean that, in a modules world, for the compiler to be able to optimize away function calls we have to annotate them as inline even if they are defined in-class?

If so, would the following module interface be equivalent to the headers above?

```<code>export module M;

export
class T
{
private:
  int const ID;

public:
  inline explicit T(int const ID_) noexcept : ID(ID_) {}

  inline int GetID() const noexcept { return ID; }
};
</code>```

Even though I still don't have a compiler with modules support, I would like to start using inline like so when appropriate, to minimize future refactoring.

答:
This comes from P1779, just adopted in Prague a few days ago. From the proposal:

This paper proposes removing the implicit inline status from functions defined in a class definition attached to a (named) module. This allows classes to benefit from avoiding redundant declarations, maintaining the flexibility offered to module authors in declaring functions with or without inline. Moreover, it allows injected friends of class templates (which cannot be generically defined outside the class definition) to be non-inline at all. It also resolves NB comment US90.

The paper (among other things) removed the sentence:

A function defined within a class definition is an inline function.

and added the sentence:

In the global module, a function defined within a class definition is implicitly inline ([class.mfct], [class.friend]).

Your example with export module M would be the modular equivalent of the initial program. Note that compilers already do inline functions that aren't annotated inline, it's just that they additionally use the presence of the inline keyword in their heuristics.

Title: inline meaning in module interfaces

Body:
Consider the header file:

class T
{
private:
  int const ID;

public:
  explicit T(int const ID_) noexcept : ID(ID_) {}

  int GetID() const noexcept { return ID; }
};

or, alternatively:

class T
{
private:
  int const ID;

public:
  explicit T(int const ID_) noexcept;

  int GetID() const noexcept;
};

inline T::T(int const ID_) noexcept : ID(ID_) {}

inline int T::GetID() const noexcept { return ID; }

In a pre-modules world, these headers might be textually included in multiple TU without ODR violations. Furthermore, since the involved member functions are relatively small, the compiler would likely "inline" (avoid function calls when using) those functions, or even optimize away some instances of T altogether.

In a recent report on the meeting where C++20 was finished, I could read the following statement:

We clarified the meaning of inline in module interfaces: the intent is that bodies of functions that are not explicitly declared inline are not part of the ABI of a module, even if those function bodies appear in the module interface. In order to give module authors more control over their ABI, member functions defined in class bodies in module interfaces are no longer implicitly inline.

I'm not sure I'm not mistaken that. Does that mean that, in a modules world, for the compiler to be able to optimize away function calls we have to annotate them as inline even if they are defined in-class?

If so, would the following module interface be equivalent to the headers above?

export module M;

export
class T
{
private:
  int const ID;

public:
  inline explicit T(int const ID_) noexcept : ID(ID_) {}

  inline int GetID() const noexcept { return ID; }
};

Even though I still don't have a compiler with modules support, I would like to start using inline like so when appropriate, to minimize future refactoring.


问:
Convert INT to VARCHAR SQL
I am using Sybase and I am doing a select which returns me a column called "iftype", but its type is int and I need to convert into varchar. When I try to do the select without the convert function I get this error:

Error code 257, SQL state 37000: Implicit conversion from datatype 'VARCHAR' to 'INT' is not allowed.  Use the CONVERT function to run this query.

I dont know how to implement the function CONVERT. Can anyone help me, please ?

答:
Actually you don't need to use STR Or Convert. Just select 'xxx'+LTRIM(ColumnName) does the job.
Possibly, LTRIM uses Convert or STR under the hood.

LTRIM also removes need for providing length. It seems to be working for integer or float without worry of truncation.

```<code>SELECT LTRIM(ColumnName) FROM TableName
</code>```

also, LTRIM is better than STR as

```<code>SELECT STR(1234567890.123)
</code>```

gives 1234567890
whereas

```<code>SELECT LTRIM(1234567890.123)
</code>```

gives 1234567890.123

Title: Convert INT to VARCHAR SQL

Body:
Actually you don't need to use STR Or Convert. Just select 'xxx'+LTRIM(ColumnName) does the job.
Possibly, LTRIM uses Convert or STR under the hood.

LTRIM also removes need for providing length. It seems to be working for integer or float without worry of truncation.

SELECT LTRIM(ColumnName) FROM TableName

also, LTRIM is better than STR as

SELECT STR(1234567890.123)

gives 1234567890
whereas

SELECT LTRIM(1234567890.123)

gives 1234567890.123


问:
Zend project - mysql not fetching UTF8
I have one Zend project where I use mysql - my db connection collation is utf8_unicode_ci and my tables collation is utf8_unicode_ci. I have stored successfully some records which contain UTF8 characters but when I try to fetch them from the DB they're broken e.g.:

DVI•1500HD is fetched as DVIâ€¢1500HD

I've tried setting resources.db.params.charset = utf8 in application.ini but it doesn't fix the problem.

Any ideas?

答:
Try adding the following line to your config.

```<code>resource.db.params.driver_options.1002 = "SET NAMES utf8"
</code>```

Regarding to your Zend Framework version, this command is needed to change the transfer encoding of mysql. The given command is the first thing executet when intantiating the db adapter.

Title: Zend project - mysql not fetching UTF8

Body:
Try adding the following line to your config.

resource.db.params.driver_options.1002 = "SET NAMES utf8"

Regarding to your Zend Framework version, this command is needed to change the transfer encoding of mysql. The given command is the first thing executet when intantiating the db adapter.


问:
Calculate coordinates of a point after zooming in JavaScript
I have a requirement to make some annotations on an image. This image is scalable (can be zoomed in and out). Now the challenge is that the annotations should also move with the scaling. How can I achieve this? I understand that 'direction' of zooming depends on the point considered as 'centre' when zooming, so assuming that this 'centre' is the absolute centre of the iamge container (width/2, height/2), how do I get the coordinates of the same point on image after zooming?

As an example, consider the following two images:

Image-1 (Normal scale):

Image-2 (Zoomed-in):

If I know the coordinates of the red point in Image-1 (which is at normal scale), how do I get the coordinates (x,y) of the same red point in Image-2? Note that the image container's width and height will remain same throughout the zooming process.

答:
This function should return your new X and Y measured from the left top of the image.
Bear in mind, that the new coordinates can be outside of the width/height of your image, as the point you picked might be "zoomed off the edge"

/**
 * width: integer, width of image in px
 * height: integer, height of image in px;
 * x: integer, horizontal distance from left
 * y: integer, vertical distance from top
 * scale: float, scale factor (1,5 = 150%)
 */
const scaleCoordinates = (width, height, x, y, scale) =>{
 const centerX = width/2;
  const centerY = height/2;
  const relX = x - centerX;
  const relY = y - centerY;
  const scaledX = relX * scale;
  const scaledY= relY * scale;
  return {x: scaledX + centerX, y: scaledY + centerY};

}

console.log(scaleCoordinates(100,100,25,50, 1.2));```


问:
What is an eID in the context of TYPO3?
I have come across this term several times. Often the resources jump right into explaining how to do something but do not mention what this is or what it is for. Also, a bunch of resources are in German or not very clear.

So,

What is an eID?

Is this a TYPO3 specific thing or is it a general concept?

What can you do with it?

Is this still relevant for TYPO3 >= 9?

Examples resources:

Either build a plugin you can put on your site, or an eID that does not need a site to function.

https://stackoverflow.com/a/18593815/2444812

This resource actually explains it (though in German), but the code looks terribly outdated.

https://www.webmasterpro.de/coding/article/cms-typo3-eid-mechanismus.html

btw, there is a tag eID on Stack Overflow but it is for Electronic Identity Card :(

答:
The eID mechanism is an outdated approach to have a custom frontend request handler. The default request handling invokes the TypoScriptFrontendController to render pages and content as usual.

Compared to that an eID script can perform arbitary actions to generate output and is not bound to the regular rendering. In fact, eID scripts are executed with a very minimal environment so every dependency (e.g. parsed TypoScript setup) must be loaded manually. There is the EidUtility for common tasks.

Nowadays eID is not necessary anymore since PSR-15 (Middlewares) has been implemented in TYPO3v9. This provides a way cleaner API and makes it easy to inject custom logic anywhere in the frontend request handling, either to perform completely custom output or intercept and modify the default response generated by the TypoScriptFrontendController.

So if possible, middlewares should be used instead of eID scripts.

Title: What is an eID in the context of TYPO3?


问:
Android FlexboxLayoutManager recreating items
I am using FlexboxLayoutManager to display Recycler View items with dynamic width. The problem I'm facing is when the background of the item is changed it reanimates/redraw all the next items which are not very attractive/required.

The following screenshot shows the use case. Whenever there are two/more items with different width in a single row, selecting/unselecting views is recreating the next neighbors.

My code for the this:

```<code> val managerVal = FlexboxLayoutManager(context, FlexDirection.ROW)
// I have used these properties as well with other combinations showing here for reference
//            managerVal.alignItems = AlignItems.FLEX_START
//            managerVal.justifyContent = JustifyContent.CENTER
            itemView.rvFilterOptions.layoutManager = managerVal
val filterOptionAdapter = FilterOptionAdapter(
                context,
                record.values
            )
itemView.rvFilterOptions.adapter = filterOptionAdapter
</code>```

I have also tried changing values in Adapter

```<code>val lp = itemView.llFilterValue.getLayoutParams()
            if (lp is FlexboxLayoutManager.LayoutParams) {
               lp.flexGrow = 1.0f
               flexboxLp.flexShrink = 1f
               lp.alignSelf = AlignItems.FLEX_START

            }
</code>```

The code to change the background of the item in the adapter.

```<code>if (record.isSelected) {
                itemView.tvFilterValue.setTextColor(
                    AppCompatResources.getColorStateList(
                        context,
                        R.color.textWhite
                    )
                )
                itemView.ivFilterCheck.show()
                itemView.llFilterValue.background =
                    AppCompatResources.getDrawable(
                        context,
                        R.drawable.bg_dark_rectangle_circle_edge
                    )
            } else {
                itemView.tvFilterValue.setTextColor(
                    AppCompatResources.getColorStateList(
                        context,
                        R.color.textNormal
                    )
                )
                itemView.ivFilterCheck.invisible()
                itemView.llFilterValue.background =
                    AppCompatResources.getDrawable(
                        context,
                        R.drawable.bg_gray_rectangle_circle_edge
                    )
            }
</code>```

A gif to show the behavior:

Thank you for your time.

答:
So the fix ended up in my XML file.

Resoning: When you are using the flexbox with the flex-direction wrap you're allowing the flexbox library to handle the view sizes. Since my use case lies in nested recycler view one of my recycler view items was using match_parent property which was causing conflicts to adjust in view at the runtime (which caused confusion at library level).

The solution was to simply use wrap_content with flexbox to let the library take decisions for view measurements.

Body:
I am using FlexboxLayoutManager to display Recycler View items with dynamic width. The problem I'm facing is when the background of the item is changed it reanimates/redraw all the next items which are not very attractive/required.

The following screenshot shows the use case. Whenever there are two/more items with different width in a single row, selecting/unselecting views is recreating the next neighbors.

My code for the this:

 val managerVal = FlexboxLayoutManager(context, FlexDirection.ROW)
// I have used these properties as well with other combinations showing here for reference
//            managerVal.alignItems = AlignItems.FLEX_START
//            managerVal.justifyContent = JustifyContent.CENTER
            itemView.rvFilterOptions.layoutManager = managerVal
val filterOptionAdapter = FilterOptionAdapter(
                context,
                record.values
            )
itemView.rvFilterOptions.adapter = filterOptionAdapter

I have also tried changing values in Adapter

val lp = itemView.llFilterValue.getLayoutParams()
            if (lp is FlexboxLayoutManager.LayoutParams) {
               lp.flexGrow = 1.0f
               flexboxLp.flexShrink = 1f
               lp.alignSelf = AlignItems.FLEX_START

            }

The code to change the background of the item in the adapter.

if (record.isSelected) {
                itemView.tvFilterValue.setTextColor(
                    AppCompatResources.getColorStateList(
                        context,
                        R.color.textWhite
                    )
                )
                itemView.ivFilterCheck.show()
                itemView.llFilterValue.background =
                    AppCompatResources.getDrawable(
                        context,
                        R.drawable.bg_dark_rectangle_circle_edge
                    )
            } else {
                itemView.tvFilterValue.setTextColor(
                    AppCompatResources.getColorStateList(
                        context,
                        R.color.textNormal
                    )
                )
                itemView.ivFilterCheck.invisible()
                itemView.llFilterValue.background =
                    AppCompatResources.getDrawable(
                        context,
                        R.drawable.bg_gray_rectangle_circle_edge
                    )
            }

A gif to show the behavior:

Thank you for your time.


问:
How to show customised error page for forbidden url access in grails 3.3.9
My grails 3.3.9 application has different modules implemented with different ROLE based access using spring security.

AdminController accessed via ROLE_ADMIN.
If a non-admin user logged in and try to access Admin URL then grails show

[Image]Grails Error Message: Sorry, you're not authorized to view this page.

I want to show my custom message.

[Image: ]Custom Message: 403 Access Forbidden

application.groovy

```<code>grails.plugin.springsecurity.interceptUrlMap = [
        [pattern: '/user/**', access: ['IS_AUTHENTICATED_FULLY']],
        [pattern: '/role/**', access: ['ROLE_ADMIN']],
        [pattern: '/', access: ['IS_AUTHENTICATED_FULLY']],
        [pattern: '/admin/*', access: ['ROLE_ADMIN']]]
</code>```

URLMappings

```<code>"500"(controller: "error", action: "internalServerError")
"404"(controller: "error", action: "notFound")
"403" (controller: "error", action: "forbidden")
"403"(view: "/error/forbidden")
</code>```

I have individually for 403.

500 & 404 is working correctly.

答:
In URlMappings you can set a mapping to the response code and choose a controller or view to respond with - eg:

```<code>static mappings = {
    // ... other mappings ...
    // Send 403's to a controller if you'd like to do additional logic
    "403"(controller: "errors", action: "forbidden")
    // Or just render a static view under grails-app/views/errors/forbidden.gsp
    "403"(view: "/errors/forbidden")
}
</code>```

See: http://docs.grails.org/4.0.1/guide/single.html#mappingToResponseCodes

Body:
My grails 3.3.9 application has different modules implemented with different ROLE based access using spring security.

AdminController accessed via ROLE_ADMIN.
If a non-admin user logged in and try to access Admin URL then grails show

[Image]Grails Error Message: Sorry, you're not authorized to view this page.

I want to show my custom message.

[Image: ]Custom Message: 403 Access Forbidden

application.groovy

grails.plugin.springsecurity.interceptUrlMap = [
        [pattern: '/user/**', access: ['IS_AUTHENTICATED_FULLY']],
        [pattern: '/role/**', access: ['ROLE_ADMIN']],
        [pattern: '/', access: ['IS_AUTHENTICATED_FULLY']],
        [pattern: '/admin/*', access: ['ROLE_ADMIN']]]

URLMappings

"500"(controller: "error", action: "internalServerError")
"404"(controller: "error", action: "notFound")
"403" (controller: "error", action: "forbidden")
"403"(view: "/error/forbidden")

I have individually for 403.

500 & 404 is working correctly.

Body:
In URlMappings you can set a mapping to the response code and choose a controller or view to respond with - eg:

static mappings = {
    // ... other mappings ...
    // Send 403's to a controller if you'd like to do additional logic
    "403"(controller: "errors", action: "forbidden")
    // Or just render a static view under grails-app/views/errors/forbidden.gsp
    "403"(view: "/errors/forbidden")
}

See: http://docs.grails.org/4.0.1/guide/single.html#mappingToResponseCodes


问:
How to mock react custom hook returned value?
Here is my custom hook:

```<code>  export function useClientRect() {
    const [scrollH, setScrollH] = useState(0);
    const [clientH, setClientH] = useState(0);
    const ref = useCallback(node => {
      if (node !== null) {
        setScrollH(node.scrollHeight);
        setClientH(node.clientHeight);
      }
    }, []);
    return [scrollH, clientH, ref];
  }
}
</code>```

I want each time that it is called, it return my values. like:

```<code>jest.mock('useClientRect', () => [300, 200, () => {}]);
</code>```

How can I achieve this?

答:
Load the hook as a module. Then mock the module:

jest.mock('module_path/module_name', () => ({
    useClientRect: () => [300, 200, jest.fn()]
}));
```
<p>mock should be called on top of the file outside test fn. Therefore we are going to have only one array as the mocked value.</p>
<p>If you want to mock the hook with different values in different tests:</p>
<pre class="lang-js prettyprint-override"><code>import * as hooks from 'module_path/module_name'';

it('a test', () => {
    jest.spyOn(hooks, 'useClientRect').mockImplementation(() => ([100, 200, jest.fn()]));
    //rest of the test
});
</code>```

Body:
Here is my custom hook:

  export function useClientRect() {
    const [scrollH, setScrollH] = useState(0);
    const [clientH, setClientH] = useState(0);
    const ref = useCallback(node => {
      if (node !== null) {
        setScrollH(node.scrollHeight);
        setClientH(node.clientHeight);
      }
    }, []);
    return [scrollH, clientH, ref];
  }
}

I want each time that it is called, it return my values. like:

jest.mock('useClientRect', () => [300, 200, () => {}]);

How can I achieve this?

Body:
Load the hook as a module. Then mock the module:

jest.mock('module_path/module_name', () => ({
    useClientRect: () => [300, 200, jest.fn()]
}));

mock should be called on top of the file outside test fn. Therefore we are going to have only one array as the mocked value.

If you want to mock the hook with different values in different tests:

import * as hooks from 'module_path/module_name'';

it('a test', () => {
    jest.spyOn(hooks, 'useClientRect').mockImplementation(() => ([100, 200, jest.fn()]));
    //rest of the test
});


问:
Excel function to find nth to last non blank value in a row
I have a sheet filled with blood pressure (BP) data, arranged by month.

I am interested in storing the last three BP values in a range per patient, each of which is assigned a row. Note that there are months which do not have BP readings, so there are blanks in the dataset.

The range for the blood pressures is BB:BL.

I was able to find formulas for the last:

```<code>=LOOKUP(2,1/(ISNUMBER(BB3:BL3)),BB3:BL3)
</code>```

and second-to-last:

```<code>=LOOKUP(9.99E+307,BB3:INDEX(BB3:BL3,MATCH(9.99E+307,BB3:BL3)-1))
</code>```

But I am not able to modify the formula above to find the third-to-last non-blank BP value.

Any advice is appreciated!

答:
If one has the Dynamic Array Formula Filter then:

```<code>=INDEX(FILTER(1:1,1:1<>""),COUNTA(FILTER(1:1,1:1<>""))-2)
</code>```

Body:
I have a sheet filled with blood pressure (BP) data, arranged by month.

I am interested in storing the last three BP values in a range per patient, each of which is assigned a row. Note that there are months which do not have BP readings, so there are blanks in the dataset.

The range for the blood pressures is BB:BL.

I was able to find formulas for the last:

=LOOKUP(2,1/(ISNUMBER(BB3:BL3)),BB3:BL3)

and second-to-last:

=LOOKUP(9.99E+307,BB3:INDEX(BB3:BL3,MATCH(9.99E+307,BB3:BL3)-1))

But I am not able to modify the formula above to find the third-to-last non-blank BP value.

Any advice is appreciated!

Body:
If one has the Dynamic Array Formula Filter then:

=INDEX(FILTER(1:1,1:1<>""),COUNTA(FILTER(1:1,1:1<>""))-2)


问:
hashmap or hashset?
I have two list containing

```<code>List<MyObj>.
</code>```

and MyObj has a "String ID" member.

I need to iterate them from time to time and sometimes I need to find objects which are similar on both.

I want a quicker way than lists.  so I can know I can use  hashMap
(than ask contains (String ) when comparing )

should I use hashmap or hashset?

note: in a hashset - I need to do implement my equals and when I run contains() - i think it will be slower than hashmap where  upon inserting I put the string id in the key.
Am I correct?

答:
note: in a hashset - I need to do implement my equals and when I run contains() - i think it will be slower than hashmap where upon inserting I put the string id in the key. Am I correct?

I don't think you would notice any performance difference. HashSet<E> is implemented using a HashMap<E, E> under the hood. So the only difference would be calling MyObj.equals() (which supposedly calls String.equals()) vs calling String.equals() directly. And the JIT compiler is pretty good at inlining calls...

The bottom line is, you should (almost) never worry about micro-optimizations, rather focus on making your design simple and consistent. If your only concern is to avoid duplication and to check for containment, a Set is a more logical choice.

Title: hashmap or hashset?

Body:
I have two list containing

List<MyObj>.

and MyObj has a "String ID" member.

I need to iterate them from time to time and sometimes I need to find objects which are similar on both.

I want a quicker way than lists.  so I can know I can use  hashMap
(than ask contains (String ) when comparing )

should I use hashmap or hashset?

note: in a hashset - I need to do implement my equals and when I run contains() - i think it will be slower than hashmap where  upon inserting I put the string id in the key.
Am I correct?


问:
how to convert YYYYMMDD to MJD format using bash
How to convert javascript equivalent of algorithm to convert YYYYMMDD to MJD modified julan day to bash script here is the javascript code

```<code>function YMDtoMJD (year, month, day)
{

var year;
var monthi
var day;
var yr  = Math.floor (year);
var mn  = Math.floor (month);
var day = Math.floor (day);
var hr  = 0.0;                    // Hours are not valid
var L;
var julian;
var mjd;

// In leap years, -1 for Jan, Feb, else 0
L = Math.ceil ((mn - 14) / 12);

var p1 = day - 32075 + Math.floor (1461 * (yr + 4800 + L) / 4);
var p2 = Math.floor (367 * (mn - 2 - L * 12) / 12);
var p3 = 3 * Math.floor (Math.floor ((yr + 4900 + L) / 100) / 4);
julian = p1 + p2 - p3;
julian = julian + (hr / 24.0) - 0.5;

mjd = julian - 2400000.5;
return (mjd);
}
</code>```

I tried in bash script but stuck in middle

```<code>#!/bin/bash
#clear

mn=12
Yr=2014
Dd=23

L=`ceil $((($mn-14)/12))`

p1=$(($Dd-32075+`floor $(((1461*(($Yr+4800+$L)/4))))`))
</code>```

Please help me to convert it to bash
below is my floor and ceil function i am using

```<code>   floor_val=
    function floor() {
      float_in=$1
      floor_val=${float_in/.*}
   }
  float_val=$1
floor $float_val
echo $floor_val

ceil_val=
function ceiling() {
float_in=$1
ceil_val=${float_in/.*}
ceil_val=$((ceil_val+1))
}

float_val=$1
ceiling $float_val
echo $ceil_val
</code>```

Body:
How to convert javascript equivalent of algorithm to convert YYYYMMDD to MJD modified julan day to bash script here is the javascript code

function YMDtoMJD (year, month, day)
{

var year;
var monthi
var day;
var yr  = Math.floor (year);
var mn  = Math.floor (month);
var day = Math.floor (day);
var hr  = 0.0;                    // Hours are not valid
var L;
var julian;
var mjd;

// In leap years, -1 for Jan, Feb, else 0
L = Math.ceil ((mn - 14) / 12);

var p1 = day - 32075 + Math.floor (1461 * (yr + 4800 + L) / 4);
var p2 = Math.floor (367 * (mn - 2 - L * 12) / 12);
var p3 = 3 * Math.floor (Math.floor ((yr + 4900 + L) / 100) / 4);
julian = p1 + p2 - p3;
julian = julian + (hr / 24.0) - 0.5;

mjd = julian - 2400000.5;
return (mjd);
}

I tried in bash script but stuck in middle

#!/bin/bash
#clear

mn=12
Yr=2014
Dd=23

L=`ceil $((($mn-14)/12))`

p1=$(($Dd-32075+`floor $(((1461*(($Yr+4800+$L)/4))))`))

Please help me to convert it to bash
below is my floor and ceil function i am using

   floor_val=
    function floor() {
      float_in=$1
      floor_val=${float_in/.*}
   }
  float_val=$1
floor $float_val
echo $floor_val

ceil_val=
function ceiling() {
float_in=$1
ceil_val=${float_in/.*}
ceil_val=$((ceil_val+1))
}

float_val=$1
ceiling $float_val
echo $ceil_val

Body:
I use this:

DAY="20200101"
MJD=$(( ( $(date +%s -d "$DAY") / 86400 ) + 40588 ))
#echo $MJD
58849


问:
Xcode 10 Error: Multiple commands produce

error: Multiple commands produce '/Users/uesr/Library/Developer/Xcode/DerivedData/OptimalLive-fxatvygbofczeyhjsawtebkimvwx/Build/Products/Debug-iphoneos/OptimalLive.app/Info.plist':
1) Target 'OptimalLive' has copy command from '/Users/uesr/Desktop/workSpace/SEALIVE/SeaLive1.1/OptimalLive/Info.plist' to '/Users/uesr/Library/Developer/Xcode/DerivedData/OptimalLive-fxatvygbofczeyhjsawtebkimvwx/Build/Products/Debug-iphoneos/OptimalLive.app/Info.plist'
2) Target 'OptimalLive' has copy command from '/Users/uesr/Desktop/workSpace/SEALIVE/SeaLive1.1/OptimalLive/Server/Masonry/Info.plist' to '/Users/uesr/Library/Developer/Xcode/DerivedData/OptimalLive-fxatvygbofczeyhjsawtebkimvwx/Build/Products/Debug-iphoneos/OptimalLive.app/Info.plist'
3) Target 'OptimalLive' has process command with input '/Users/uesr/Desktop/workSpace/SEALIVE/SeaLive1.1/OptimalLive/Info.plist'

Running the code in Xcode 9 works, but there is an error in Xcode 10.

答:
My situation was similar to the Damo's one - some Products were added to the Pods project twice. The structure of my Podfile was:

```<code># platform :ios, '11.0'

def shared_pods
  use_frameworks!
  pod 'SharedPod1'
end

target 'Target1' do
  pod 'SomePod1'
  shared_pods
end

target 'Target2' do
  shared_pods
end
</code>```

and all shared pods were added twice. Uncommenting of first line and then pod install solved the problem.

Body:
My situation was similar to the Damo's one - some Products were added to the Pods project twice. The structure of my Podfile was:

# platform :ios, '11.0'

def shared_pods
  use_frameworks!
  pod 'SharedPod1'
end

target 'Target1' do
  pod 'SomePod1'
  shared_pods
end

target 'Target2' do
  shared_pods
end

and all shared pods were added twice. Uncommenting of first line and then pod install solved the problem.


问:
Unable to create Linux Function Apps (Consumption plan) and Linux App Service Plans and in the same Resource Group
I am unable to create an Azure Function App (hosted on Linux on a Consumption plan) in a Resource Group which already contains 2 App Services hosted on Linux. I am getting an Error (from the Azure portal) saying that the “Requested Feature is not available in the resource group”.
Are there any restrictions in having a dynamic and app service plan on Linux in the same RG?

This is the complete error:

{
    "Code": "BadRequest",
    "Message": "Requested feature is not available in resource group *******. Please try using a different resource group or create a new one.",
    "Target": null,
    "Details": [
        {
            "Message": "Requested feature is not available in resource group ********. Please try using a different resource group or create a new one."
        },
        {
            "Code": "BadRequest"
        },
        {
            "ErrorEntity": {
                "ExtendedCode": "59324",
                "MessageTemplate": "Requested feature is not available in resource group {0}. Please try using a different resource group or create a new one.",
                "Parameters": [
                    "************"
                ],
                "Code": "BadRequest",
                "Message": "Requested feature is not available in resource group *******. Please try using a different resource group or create a new one."
            }
        }
    ],
    "Innererror": null
}

I have also attached the screengrab of the Function App that I am trying to create:

答:
Did you find a solution?

I have the same issue when creating it via an ARM template.

There is one way to do it (tried on EU West though):

Create a new Resource Group

Create your function in the new RG

Move your function-plan, storage, and function to the desired RG

I hope it would be possible to create the same plan from ARM or via the interface. Let me know if someone has found a method. I would rather do it via ARM template and therefore can control the name of the plan..

Edit:

If you create a consumption plan first and then the app service plan, then it should work too.

From the interface: Just create a function app which is a linux version, then the plan should be created. Then add the linux app service plan.

From ARM: Just make the app service plan depend on the consumption plan.

I will update if we know more in the future..


问:
Regex strip all html tags excluding
 &
I am relatively new to regex but my aim is to strip all html tags from a string excluding
s and  tags with the class='user'. I want to user this regex to clean unwanted html garbage from contentedittable fields.

Hope one of you regex masters can help...

Here is an example to test on: http://gskinner.com/RegExr/?2tpai

I think I'm close, but the closing tag of the a class='user' is currently still being selected as garbage when it is required.

答:
I would suggest this to you:

```<code><(?!a class='user'|br|/a)[^>]+>
</code>```

i.e., you keep in your html all the  tags, which should not bother much.

This is pretty hacky, but the regex engine will immediately skip a chunk of text starting with class='user' and start looking for the next <...

In general, in my experience with transforming html through regexes, I found out that the only way to go safely is splitting the process in several intermediate steps, like first dealing with the class='user'..../a>s, then with the rest, but I can't see an easy way to do that in your case without transforming the class='user'..../a> into something different as an intermediate step.

Title:
Regex strip all html tags excluding
 &

Body:
I would suggest this to you:

<(?!a class='user'|br|/a)[^>]+>

i.e., you keep in your html all the </a> tags, which should not bother much.

This is pretty hacky, but the regex engine will immediately skip a chunk of text starting with <a class='user' and start looking for the next <...

In general, in my experience with transforming html through regexes, I found out that the only way to go safely is splitting the process in several intermediate steps, like first dealing with the <a class='user'..../a>s, then with the rest, but I can't see an easy way to do that in your case without transforming the <a class='user'..../a> into something different as an intermediate step.


问:
How to make VSCode to replace the word when accepting autocomplete hint?
JetBrains IDE platform have very useful feature, which I am using a lot and I find it a performance booster. When I have a word in editor, and I want to change or update that word, I do the following.

Place cursor in front of the word (or in middle, ex. when I want to change only last part.)

Start typing until I got autocomplete I want to use.

Press TAB or ENTER.

On TAB - Old word is completely replaced by new word. This is especially useful when I update some names, in which beginning of word is the same, but ending is different. For example, change getTimeInSeconds() to getTimeInMinutes() - I put cursor after getTimeIn, get autocomplete, and press TAB. Nothing left to delete, everything is replaced.

On ENTER - New word is replaced from the start of old word, but right part from the cursor stays on screen.

By default VSCode supports only "ENTER" use case. Does it support "TAB" use case? If so, how to enable it?

答: You can set this using the "editor.suggest.insertMode" setting. If you set this to "replace", it will behave as you want.


问:
ESRI : Failed to parse source map
I am getting this error in the Google chrome developer console.

Failed to parse SourceMap:
  http://localhost:15132/Scripts/_External/igniteui/css/themes/infragistics/infragistics.theme.css.map

How do I fix it?

答: Check if you're using some Chrome extension (Night mode or something else). Disable that and see if the 'inject' gone.</p>

Title: ESRI : Failed to parse source map