问:
How to pad a number with leading zero in a SAS Macro loop counter?
So I have a range of datasets in a specific library. These datasets are named in the format DATASET_YYYYMM, with one dataset for each month. I am trying to append a range of these datasets based on user input for the date range. i.e. If start_date is 01NOV2019 and the end_date is 31JAN2020, I want to append the three datasets: LIBRARY.DATASET_201911, LIBRARY.DATASET_201912 and LIBRARY.DATASET_202001.

The range is obviously variable, so I can't simply name the datasets manually in a set function. Since I need to loop through the years and months in the date range, I believe a macro is the best way to do this. I'm using a loop within the SET statement to append all the datasets. I have copied my example code below. It does work in theory. But in practice, only if we are looping over the months of November and December. As the format of the dataset name has a two digit month, for Jan-Sept it will be 01-09. The month function returns 1-9 however, and of course a 'File DATASET_NAME does not exist' error is thrown.
Problem is I cannot figure out a way to get it to interpret the month with leading 0, without ruining functionality of another part of the loop/macro.

I have tried numerous approaches to format the number as z2, cannot get any to work.
i.e. Including PUTN functions in the DO line for quote_month as follows, it ignores the leading zero when generating the dataset name in the line below.

```<code>%DO quote_month = %SYSFUNC(IFN(&quote_year. = &start_year.,%SYSFUNC(PUTN(&start_month.,z2.)),1,.)) %TO %SYSFUNC(IFN(&quote_year. = &end_year.,%SYSFUNC(PUTN(&end_month.,z2.)),12,.));
</code>```

Below is example code (without any attempt to reformat it to z2) - it will throw an error because it cannot find 'dataset_20201' because it is actually called 'dataset_202001'. The dataset called dataset_combined_example produces the desired output of the code by manually referencing the dataset names which it will be unable to do in practice. Does anyone know how to go about this?

```<code>DATA _NULL_;
    FORMAT start_date end_date DATE9.;
    start_date = '01NOV2019'd;
    end_date = '31JAN2020'd;
    CALL symput('start_date',start_date);
    CALL symput('end_date',end_date);
RUN;

DATA dataset_201911;
   input name $;
   datalines;
Nov1
Nov2
;
RUN;
DATA dataset_201912;
   input name $;
   datalines;
Dec1
Dec2
;
RUN;
DATA dataset_202001;
   input name $;
   datalines;
Jan1
Jan2
;
RUN;

DATA dataset_combined_example;
    SET dataset_201911 dataset_201912 dataset_202001;
RUN;

%MACRO get_table(start_date, end_date);
    %LET start_year = %SYSFUNC(year(&start_date.));
    %LET end_year = %SYSFUNC(year(&end_date.));
    %LET start_month = %SYSFUNC(month(&start_date.));
    %LET end_month = %SYSFUNC(month(&end_date.));
    DATA dataset_combined;
        SET
            %DO quote_year = &start_year. %TO &end_year.;
                %DO quote_month = %SYSFUNC(IFN(&quote_year. = &start_year.,&start_month.,1,.)) %TO %SYSFUNC(IFN(&quote_year. = &end_year.,&end_month.,12,.));
                    dataset_&quote_year.&quote_month.
                %END;
            %END;
        ;
    RUN;
%MEND;
%get_table(&start_date.,&end_date.);
</code>```

答:
In a macro

Use INTNX to compute the bounds for a loop over date values.  Within the loop:

Compute the candidate data set name according to specified lib, prefix and desired date value format.  <yyyy><mm> is output by format yymmn6.

Use EXIST to check candidate data sets for existence.

Alternatively, do not check, but make sure to set OPTIONS NODSNFERR prior to combining.  The setting will prevent errors when specifying a non-existent data set.

Update the loop index to the end of the month so the next increment takes the index to the start of the next month.

```<code>%macro names_by_month(lib=work, prefix=data_, start_date=today(), end_date=today(), format=yymmn6.);

  %local index name;

  %* loop over first-of-the-month date values;
  %do index = %sysfunc(intnx(month, &start_date, 0)) %to %sysfunc(intnx(month, &end_date, 0));

    %* compute month dependent name;
    %let name = &lib..&prefix.%sysfunc(putn(&index,&format));

    %* emit name if it exists;
    %if %sysfunc(exist(&name)) or %sysfunc(exist(&name,VIEW)) %then %str(&name);

    %* prepare index for loop +1 increment so it goes to start of next month;
    %let index = %sysfunc(intnx(month, &index, 0, E));
  %end;

%mend;

* example usage:

data combined_imports(label="nov2019 to jan2020");
  set
    %names_by_month(
      prefix=import_,
      start_date='01NOV2019'd,
      end_date = '31JAN2020'd
    )
  ;
run;
</code>```

Body:
So I have a range of datasets in a specific library. These datasets are named in the format DATASET_YYYYMM, with one dataset for each month. I am trying to append a range of these datasets based on user input for the date range. i.e. If start_date is 01NOV2019 and the end_date is 31JAN2020, I want to append the three datasets: LIBRARY.DATASET_201911, LIBRARY.DATASET_201912 and LIBRARY.DATASET_202001.

The range is obviously variable, so I can't simply name the datasets manually in a set function. Since I need to loop through the years and months in the date range, I believe a macro is the best way to do this. I'm using a loop within the SET statement to append all the datasets. I have copied my example code below. It does work in theory. But in practice, only if we are looping over the months of November and December. As the format of the dataset name has a two digit month, for Jan-Sept it will be 01-09. The month function returns 1-9 however, and of course a 'File DATASET_NAME does not exist' error is thrown.
Problem is I cannot figure out a way to get it to interpret the month with leading 0, without ruining functionality of another part of the loop/macro.

I have tried numerous approaches to format the number as z2, cannot get any to work.
i.e. Including PUTN functions in the DO line for quote_month as follows, it ignores the leading zero when generating the dataset name in the line below.

%DO quote_month = %SYSFUNC(IFN(&quote_year. = &start_year.,%SYSFUNC(PUTN(&start_month.,z2.)),1,.)) %TO %SYSFUNC(IFN(&quote_year. = &end_year.,%SYSFUNC(PUTN(&end_month.,z2.)),12,.));

Below is example code (without any attempt to reformat it to z2) - it will throw an error because it cannot find 'dataset_20201' because it is actually called 'dataset_202001'. The dataset called dataset_combined_example produces the desired output of the code by manually referencing the dataset names which it will be unable to do in practice. Does anyone know how to go about this?

DATA _NULL_;
    FORMAT start_date end_date DATE9.;
    start_date = '01NOV2019'd;
    end_date = '31JAN2020'd;
    CALL symput('start_date',start_date);
    CALL symput('end_date',end_date);
RUN;

DATA dataset_201911;
   input name $;
   datalines;
Nov1
Nov2
;
RUN;
DATA dataset_201912;
   input name $;
   datalines;
Dec1
Dec2
;
RUN;
DATA dataset_202001;
   input name $;
   datalines;
Jan1
Jan2
;
RUN;

DATA dataset_combined_example;
    SET dataset_201911 dataset_201912 dataset_202001;
RUN;

%MACRO get_table(start_date, end_date);
    %LET start_year = %SYSFUNC(year(&start_date.));
    %LET end_year = %SYSFUNC(year(&end_date.));
    %LET start_month = %SYSFUNC(month(&start_date.));
    %LET end_month = %SYSFUNC(month(&end_date.));
    DATA dataset_combined;
        SET
            %DO quote_year = &start_year. %TO &end_year.;
                %DO quote_month = %SYSFUNC(IFN(&quote_year. = &start_year.,&start_month.,1,.)) %TO %SYSFUNC(IFN(&quote_year. = &end_year.,&end_month.,12,.));
                    dataset_&quote_year.&quote_month.
                %END;
            %END;
        ;
    RUN;
%MEND;
%get_table(&start_date.,&end_date.);

Body:
In a macro

Use INTNX to compute the bounds for a loop over date values.  Within the loop:

Compute the candidate data set name according to specified lib, prefix and desired date value format.  <yyyy><mm> is output by format yymmn6.

Use EXIST to check candidate data sets for existence.

Alternatively, do not check, but make sure to set OPTIONS NODSNFERR prior to combining.  The setting will prevent errors when specifying a non-existent data set.

Update the loop index to the end of the month so the next increment takes the index to the start of the next month.

%macro names_by_month(lib=work, prefix=data_, start_date=today(), end_date=today(), format=yymmn6.);

  %local index name;

  %* loop over first-of-the-month date values;
  %do index = %sysfunc(intnx(month, &start_date, 0)) %to %sysfunc(intnx(month, &end_date, 0));

    %* compute month dependent name;
    %let name = &lib..&prefix.%sysfunc(putn(&index,&format));

    %* emit name if it exists;
    %if %sysfunc(exist(&name)) or %sysfunc(exist(&name,VIEW)) %then %str(&name);

    %* prepare index for loop +1 increment so it goes to start of next month;
    %let index = %sysfunc(intnx(month, &index, 0, E));
  %end;

%mend;

* example usage:

data combined_imports(label="nov2019 to jan2020");
  set
    %names_by_month(
      prefix=import_,
      start_date='01NOV2019'd,
      end_date = '31JAN2020'd
    )
  ;
run;


来源: stackexchange

问:
Retweet via Twitter API fails in Flash
I am using the Tweetr AS3 library in Flash.

Authentication, timeline retrieval and posting to Twitter all work fine.

For some reason the Retweet function works only a small part of the time and fails most of the times - I get a Stream Error #2032 . When checking in Firebug I see that the call is made (https://api.twitter.com/1/statuses/retweet/[STATUSID].xml) but it returns a404 error. I can't see any difference between the times that it works and the times it doesn't.

Are there any known issues with Twitter's Retweet API that may cause this problem? Any suggestions on how to tackle this?

答:
I managed to overcome this problem by changing the URL to the Twitter API from https:// to http://.
Still not sure why this problem was happening, but for the time being this will do the job for me.
Thanks.</p>

ContentLicense: CC BY-SA 3.0

Title: Retweet via Twitter API fails in Flash


问:
React - toggle class: useState hook form several button
I have some buttons and I'm trying to add active class for clicked button. But when I click one of the buttons, all buttons are getting active class.

```<code>const { useState } = React;
const { render } = ReactDOM;
const node = document.getElementById("root");

const Button = ({ message }) => {
  const [condition, setCondition] = useState(false);
  return (
    <div>
    {
    Object.keys(res).map((data) => (
    <Button className={condition ? "button toggled" : "button"} onClick=.
     {() => {
      setCondition(!condition)}
     }}
     ))
      }
    </div>
  );
   //Updated
   Object.keys(res).map((data) => (
    <Button className={condition ? "button toggled" : "button"} onClick=.
     {() => {
      setCondition(condition === "off" ? "on" : "off")}
     }}
     ))
      }
    </div>
  ); //This can be modified to work for button clicked. Because active class is added to all buttons, if one of them is clicked
};
render(<Button message="Click me if you dare!" />, node);
</code>```

This is working if I click the first button, but if I click again the same button, this active class should be removed

答:
maybe you want to check this.

https://codesandbox.io/embed/import-css-file-react-vs488?fontsize=14&hidenavigation=1&theme=dark

ContentLicense: CC BY-SA 4.0

Body:
I have some buttons and I'm trying to add active class for clicked button. But when I click one of the buttons, all buttons are getting active class.

const { useState } = React;
const { render } = ReactDOM;
const node = document.getElementById("root");

const Button = ({ message }) => {
  const [condition, setCondition] = useState(false);
  return (

    {
    Object.keys(res).map((data) => (
    <Button className={condition ? "button toggled" : "button"} onClick=.
     {() => {
      setCondition(!condition)}
     }}
     ))
      }

  );
   //Updated
   Object.keys(res).map((data) => (
    <Button className={condition ? "button toggled" : "button"} onClick=.
     {() => {
      setCondition(condition === "off" ? "on" : "off")}
     }}
     ))
      }

  ); //This can be modified to work for button clicked. Because active class is added to all buttons, if one of them is clicked
};
render(<Button message="Click me if you dare!" />, node);

This is working if I click the first button, but if I click again the same button, this active class should be removed


问:
Adding quotations around words preceding a colon in Python
I am learning Python (python3) and am working with a text file containing semi-JSON format. It is not full JSON because the "keys" are not surrounded by quotes. I am looking to programmatically add quotes around all of these key names. My plan was to "open" this file and parse each "line" as an individual string.

From:

key_name: { another_key: "somevalue", second_key: "anotherval" }

Into:

"key_name": { "another_key": "somevalue", "second_key": "anotherval" }

I'm sure regex would be the ideal way to do this - for the sake of learning I have been using arrays...

I have some code that works partially, but not all of the keys get parentheses placed around them.

```<code>str = "this is: a string: testing testing: blah blah more: test: hereis: test:"

cp_str = list(str[::-1])

skip = False
find_end = False
for step in range(len(cp_str) - 1):
  if skip:
    skip = False
    continue

  if cp_str[step] == ':':
    cp_str.insert(step + 1, '"')
    skip = True
    find_end = True

  if not skip and find_end and not(ord(cp_str[step].lower()) > 95 and ord(cp_str[step].lower()) < 95+26):
    cp_str.insert(step, '"')
    skip = True
    find_end = False

print(''.join(cp_str[::-1]))
</code>```

Outputs:

this is: a string": testing "testing": blah blah "more":
  "test": "hereis": "test":

Any tips or help on the best ways to tackle this would be appreciated.

答:
While the pattern ([{,]\s*)([^"]*?)(\s*:\s*) isn't going to cover all corner cases, it should work fine for basic JSON content.

Example usage:

```<code>>>> import re
>>> data = '{ another_key: "somevalue", second_key: "anotherval" }'
>>> repl_fn = lambda x: f'{x.group(1)}"{x.group(2)}"{x.group(3)}'
>>> re.sub(r'([{,]\s*)([^"]*?)(\s*:\s*)', repl_fn, data)
'{ "another_key": "somevalue", "second_key": "anotherval" }'
</code>```

Body:
I am learning Python (python3) and am working with a text file containing semi-JSON format. It is not full JSON because the "keys" are not surrounded by quotes. I am looking to programmatically add quotes around all of these key names. My plan was to "open" this file and parse each "line" as an individual string.

From:

key_name: { another_key: "somevalue", second_key: "anotherval" }

Into:

"key_name": { "another_key": "somevalue", "second_key": "anotherval" }

I'm sure regex would be the ideal way to do this - for the sake of learning I have been using arrays...

I have some code that works partially, but not all of the keys get parentheses placed around them.

str = "this is: a string: testing testing: blah blah more: test: hereis: test:"

cp_str = list(str[::-1])

skip = False
find_end = False
for step in range(len(cp_str) - 1):
  if skip:
    skip = False
    continue

  if cp_str[step] == ':':
    cp_str.insert(step + 1, '"')
    skip = True
    find_end = True

  if not skip and find_end and not(ord(cp_str[step].lower()) > 95 and ord(cp_str[step].lower()) < 95+26):
    cp_str.insert(step, '"')
    skip = True
    find_end = False

print(''.join(cp_str[::-1]))

Outputs:

this is: a string": testing "testing": blah blah "more":
  "test": "hereis": "test":

Any tips or help on the best ways to tackle this would be appreciated.

Body:
While the pattern ([{,]\s*)([^"]*?)(\s*:\s*) isn't going to cover all corner cases, it should work fine for basic JSON content.

Example usage:

>>> import re
>>> data = '{ another_key: "somevalue", second_key: "anotherval" }'
>>> repl_fn = lambda x: f'{x.group(1)}"{x.group(2)}"{x.group(3)}'
>>> re.sub(r'([{,]\s*)([^"]*?)(\s*:\s*)', repl_fn, data)
'{ "another_key": "somevalue", "second_key": "anotherval" }'


问:
How to Do Sigma Sum Notation in Python?
How can I pass the expression as argument into the function and then execute it in Python?

def f(variable, function):
    # here calculate the function (unknown part)

f(3, 2 * variable)
```

The result should be 6. (f(x) = 2 * x; x = 3)

How can I do that?

答:
```<code>def sigma_sum(start, end, expression):
    return sum(expression(i) for i in range(start, end))
</code>```

Example usage using a lambda function

```<code>>>> sigma_sum(1, 10, lambda i: i**2)
285
</code>```

or using a named function

```<code>def square(i):
    return i**2

>>> sigma_sum(1, 10, square)
285
</code>```

Title: How to Do Sigma Sum Notation in Python?

Body:
How can I pass the expression as argument into the function and then execute it in Python?

def f(variable, function):
    # here calculate the function (unknown part)

f(3, 2 * variable)

The result should be 6. (f(x) = 2 * x; x = 3)

How can I do that?

Body:
def sigma_sum(start, end, expression):
    return sum(expression(i) for i in range(start, end))

Example usage using a lambda function

>>> sigma_sum(1, 10, lambda i: i**2)
285

or using a named function

def square(i):
    return i**2

>>> sigma_sum(1, 10, square)
285


问:
The problem with the word display if I have too many blank lines
I did not want to repeat the other question, I solved a problem in which I post the most common word in the text, but I have a problem, it does not work if I have more blank lines, how can I solve it?
I tried other ways of stackoverflow, but failed.
This is my code.

```<code>import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
    Map < String, Integer > map = new LinkedHashMap < String, Integer > ();
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(System.in));
        String currentLine = reader.readLine();
        while (currentLine != null) {
            String[] input = currentLine.replaceAll("[^a-zA-Z-\"\\n\\n\", \"\\n\"]", " ").toLowerCase().split(" ");
            for (int i = 0; i < input.length; i++) {
                if (map.containsKey(input[i])) {
                    int count = map.get(input[i]);
                    map.put(input[i], count + 1);

                } else {
                    map.put(input[i], 1);
                }
            }
            currentLine = reader.readLine();
        }
        String mostRepeatedWord = null;
        int count = 0;
        for (Map.Entry < String, Integer > m: map.entrySet()) {
            if (m.getValue() > count) {
                mostRepeatedWord = m.getKey();
                count = m.getValue();
            } else if (m.getValue() == count) {
                String key = m.getKey();
                if (key.compareTo(mostRepeatedWord) < 0) {
                    mostRepeatedWord = key;
                }
            }
        }
        System.out.println(mostRepeatedWord);

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

}

答:
Modify your for loop so that you're not adding to your map on a blank line.

```<code>for (int i = 0; i < input.length; i++) {
  // Skip the blank lines
  if (!input[i].trim().equals("")) {

    if (map.containsKey(input[i])) {
      int count = map.get(input[i]);
      map.put(input[i], count + 1);
    } else {
      map.put(input[i], 1);
    }
  }
}
</code>```

Body:
I did not want to repeat the other question, I solved a problem in which I post the most common word in the text, but I have a problem, it does not work if I have more blank lines, how can I solve it?
I tried other ways of stackoverflow, but failed.
This is my code.

import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
    Map < String, Integer > map = new LinkedHashMap < String, Integer > ();
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(System.in));
        String currentLine = reader.readLine();
        while (currentLine != null) {
            String[] input = currentLine.replaceAll("[^a-zA-Z-\"\\n\\n\", \"\\n\"]", " ").toLowerCase().split(" ");
            for (int i = 0; i < input.length; i++) {
                if (map.containsKey(input[i])) {
                    int count = map.get(input[i]);
                    map.put(input[i], count + 1);

                } else {
                    map.put(input[i], 1);
                }
            }
            currentLine = reader.readLine();
        }
        String mostRepeatedWord = null;
        int count = 0;
        for (Map.Entry < String, Integer > m: map.entrySet()) {
            if (m.getValue() > count) {
                mostRepeatedWord = m.getKey();
                count = m.getValue();
            } else if (m.getValue() == count) {
                String key = m.getKey();
                if (key.compareTo(mostRepeatedWord) < 0) {
                    mostRepeatedWord = key;
                }
            }
        }
        System.out.println(mostRepeatedWord);

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

}

Body:
Modify your for loop so that you're not adding to your map on a blank line.

for (int i = 0; i < input.length; i++) {
  // Skip the blank lines
  if (!input[i].trim().equals("")) {

    if (map.containsKey(input[i])) {
      int count = map.get(input[i]);
      map.put(input[i], count + 1);
    } else {
      map.put(input[i], 1);
    }
  }
}


问:
How to update multiple rows with values of two arrays in Postgres?
I need to update a set of records in the x table with values stored in arrays. Anyone know how I could do it?

```<code>IDS_NEW_SPONSORS INTEGER[] := ARRAY[]::INTEGER[]; --possible values [1,2,3,4,5,6]
IDS_DEBTORS  INTEGER[] := ARRAY[]::INTEGER[]; --possible values [20,21,22,23,24,25]
-- the arrays will be the same size--
UPDATE x
SET id_sponsor = [IDS_NEW_SPONSORS],-- HOW ADD
id_sponsor_historial = [IDS_DEBTORS], -- HOW ADD
id_patron = 5 -- ALWAYS SAME
WHERE id_sponsor = ANY(IDS_DEBTORS); -- this line working!!! loop each row
</code>```

I'm working with postgres 11...

After update. the table would look like this:

```<code>id_sponsor | id_sponsor_historial | id_patron
1            20                     5
2            21                     5
3            22                     5
4            23                     5
5            24                     5
6            25                     5
</code>```

答:
You can use a function to do that. Here is an example:

```<code>create table x(
    id_sponsor int primary key,
    id_sponsor_historial int,
    id_patron int);

CREATE OR REPLACE FUNCTION update_x(
    integer,
    integer[],
    integer[])
  RETURNS integer AS
$BODY$
DECLARE

in_pat    ALIAS FOR $1;
in_sp_arr  ALIAS FOR $2;
in_sp_hi_arr ALIAS FOR $3;

BEGIN

IF in_sp_arr ISNULL
THEN
RETURN 0;
END IF;

IF array_lower(in_sp_arr,1) ISNULL
   OR array_upper(in_sp_arr,1) ISNULL
THEN
RETURN 0;
END IF;

FOR index IN array_lower(in_sp_arr,1) .. array_upper(in_sp_arr,1) LOOP
    BEGIN
    INSERT INTO x(id_sponsor, id_sponsor_historial, id_patron )
    VALUES ( in_sp_arr[index], in_sp_hi_arr[index], in_pat);
    --EXCEPTION WHEN unique_violation THEN
    --do nothing ?
    END;
END LOOP;
RETURN 1;
END;
$BODY$
LANGUAGE plpgsql ;

select update_x(5, ARRAY[1,2,3,4,5,6],ARRAY[20,21,22,23,24,25]);
</code>```

This would probably need more error checking: It assumes for example, that the arrays are of the same size, have the same bounds and all the elements are defined.

Body:
I need to update a set of records in the x table with values stored in arrays. Anyone know how I could do it?

IDS_NEW_SPONSORS INTEGER[] := ARRAY[]::INTEGER[]; --possible values [1,2,3,4,5,6]
IDS_DEBTORS  INTEGER[] := ARRAY[]::INTEGER[]; --possible values [20,21,22,23,24,25]
-- the arrays will be the same size--
UPDATE x
SET id_sponsor = [IDS_NEW_SPONSORS],-- HOW ADD
id_sponsor_historial = [IDS_DEBTORS], -- HOW ADD
id_patron = 5 -- ALWAYS SAME
WHERE id_sponsor = ANY(IDS_DEBTORS); -- this line working!!! loop each row

I'm working with postgres 11...

After update. the table would look like this:

id_sponsor | id_sponsor_historial | id_patron
1            20                     5
2            21                     5
3            22                     5
4            23                     5
5            24                     5
6            25                     5

Body:
You can use a function to do that. Here is an example:

create table x(
    id_sponsor int primary key,
    id_sponsor_historial int,
    id_patron int);

CREATE OR REPLACE FUNCTION update_x(
    integer,
    integer[],
    integer[])
  RETURNS integer AS
$BODY$
DECLARE

in_pat    ALIAS FOR $1;
in_sp_arr  ALIAS FOR $2;
in_sp_hi_arr ALIAS FOR $3;

BEGIN

IF in_sp_arr ISNULL
THEN
RETURN 0;
END IF;

IF array_lower(in_sp_arr,1) ISNULL
   OR array_upper(in_sp_arr,1) ISNULL
THEN
RETURN 0;
END IF;

FOR index IN array_lower(in_sp_arr,1) .. array_upper(in_sp_arr,1) LOOP
    BEGIN
    INSERT INTO x(id_sponsor, id_sponsor_historial, id_patron )
    VALUES ( in_sp_arr[index], in_sp_hi_arr[index], in_pat);
    --EXCEPTION WHEN unique_violation THEN
    --do nothing ?
    END;
END LOOP;
RETURN 1;
END;
$BODY$
LANGUAGE plpgsql ;

select update_x(5, ARRAY[1,2,3,4,5,6],ARRAY[20,21,22,23,24,25]);

This would probably need more error checking: It assumes for example, that the arrays are of the same size, have the same bounds and all the elements are defined.


问:
Adding comma Separators for a value after a calculation
The calculation , i have setup 2 input fields where multiplication will take place. The text boxes will accept number input , while displaying comma separation to the value.Before the multiplication, i remove the commas and then pass the result to text box 3. How can i show the answer to the end user with comma separation for below instance ? Appreciate your great help.

function calculate() {

  var E1 =   $("#E1").val().split(",").join("");
  var E2 =   $("#E2").val().split(",").join("");

  var result = E1*E2;
  $("#E3").val(result);

}

//For comma seperation
$('input.number').keyup(function(event) {

  // skip for arrow keys
  if(event.which >= 37 && event.which <= 40) return;

  // format number
  $(this).val(function(index, value) {
    return value
    .replace(/\D/g, "")
    .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
    ;
  });
});```
<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>

<div class="form-group">
    <label>Value 01</label>
    <input class="form-control number" type="tel" id="E1" required oninput="calculate()" />
</div>

<div class="form-group">
    <label>Value 02</label>
    <input class="form-control number" type="tel" id="E2" required oninput="calculate()" />
</div>

<div class="form-group">
    <label>Value 03 (Result)</label>
    <input class="form-control number" type="tel" id="E3"  />
</div></code>```

答:
Just added digits function this function return make comma for every three digits. Hope this help you.

function calculate() {

  var E1 = $("#E1").val().split(",").join("");
  var E2 = $("#E2").val().split(",").join("");

  var result = E1 * E2;
  $("#E3").val(result);
  $("#E3").digits();

}

$.fn.digits = function() {
  return this.each(function() {
    $(this).val($(this).val().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"));
  })
}
//For comma seperation
$('input.number').keyup(function(event) {

  // skip for arrow keys
  if (event.which >= 37 && event.which <= 40) return;

  // format number
  $(this).val(function(index, value) {
    return value
      .replace(/\D/g, "")
      .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  });
});```
<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>
<div class="form-group">
  <label>Value 01</label>
  <input class="form-control number" type="tel" id="E1" required oninput="calculate()" />
</div>

<div class="form-group">
  <label>Value 02</label>
  <input class="form-control number" type="tel" id="E2" required oninput="calculate()" />
</div>

<div class="form-group">
  <label>Value 03 (Result)</label>
  <input class="form-control number" type="tel" id="E3" />
</div></code>```

Body:
The calculation , i have setup 2 input fields where multiplication will take place. The text boxes will accept number input , while displaying comma separation to the value.Before the multiplication, i remove the commas and then pass the result to text box 3. How can i show the answer to the end user with comma separation for below instance ? Appreciate your great help.

function calculate() {

  var E1 =   $("#E1").val().split(",").join("");
  var E2 =   $("#E2").val().split(",").join("");

  var result = E1*E2;
  $("#E3").val(result);

}

//For comma seperation
$('input.number').keyup(function(event) {

  // skip for arrow keys
  if(event.which >= 37 && event.which <= 40) return;

  // format number
  $(this).val(function(index, value) {
    return value
    .replace(/\D/g, "")
    .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
    ;
  });
});

    Value 01
    <input class="form-control number" type="tel" id="E1" required oninput="calculate()" />

    Value 02
    <input class="form-control number" type="tel" id="E2" required oninput="calculate()" />

    Value 03 (Result)
    <input class="form-control number" type="tel" id="E3"  />

Body:
Just added digits function this function return make comma for every three digits. Hope this help you.

function calculate() {

  var E1 = $("#E1").val().split(",").join("");
  var E2 = $("#E2").val().split(",").join("");

  var result = E1 * E2;
  $("#E3").val(result);
  $("#E3").digits();

}

$.fn.digits = function() {
  return this.each(function() {
    $(this).val($(this).val().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"));
  })
}
//For comma seperation
$('input.number').keyup(function(event) {

  // skip for arrow keys
  if (event.which >= 37 && event.which <= 40) return;

  // format number
  $(this).val(function(index, value) {
    return value
      .replace(/\D/g, "")
      .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
  <label>Value 01</label>
  <input class="form-control number" type="tel" id="E1" required oninput="calculate()" />
</div>

<div class="form-group">
  <label>Value 02</label>
  <input class="form-control number" type="tel" id="E2" required oninput="calculate()" />
</div>

<div class="form-group">
  <label>Value 03 (Result)</label>
  <input class="form-control number" type="tel" id="E3" />
</div>


问:
Playing Video in Xamarin Forms - Can't Play Video
I'm using Android's Video View to play a video in my app. It works fine when I put source as a web-link but I keep getting a "Can't play this video" message and a black screen in the Xamarin Android Player when I choose file from Local Resource. I have followed sample from Here. I have googled the issue some say the issue is may be because of

Unsupported file format

Unsupported android version

I Don't think this could be in my case as the sample project is running fine on same device .Moreover in my project video from URL are also played. I believe I might be missing a piece to fix this.
Xaml :-

```<code>  <StackLayout VerticalOptions="FillAndExpand">

    <video:VideoPlayer   AutoPlay="True"  x:Name="xvideoPlayer" WidthRequest="200" HeightRequest="200"  />
    <Button Clicked="Button_Clicked" ></Button>
</StackLayout>
</code>```

Cs:

```<code> public VideoPlayerPage(string url)
    {

        InitializeComponent();
        BindingContext = videoPlayerPageViewModel = new VideoPlayerPageViewModel();
        NavigationPage.SetHasNavigationBar(this, false);

    }
private async void Button_Clicked(object sender, EventArgs e)
    {
        Button btn = (Button)sender;
        btn.IsEnabled = false;
        var FileOperations = DependencyService.Get<IFileOperations>();

        //string pLocalPath = FileOperations.GetFilePath(url, "ErpwebChat");
        string pLocalPath = "content://com.android.externalstorage.documents/document/primary%3ADocument%2FErpwebChat%2F1aecb317-8d56-46c4-b29a-182d2e61093c.mp4";
        //DownloadVideo(url, "videos");

        if (!String.IsNullOrWhiteSpace(pLocalPath))
        {
            xvideoPlayer.Source = new FileVideoSource
            {
                File = pLocalPath
            };
        }
        btn.IsEnabled = true;
    }
</code>```

VideoPlayerRenderer.droid class:-

```<code>  public class VideoPlayerRenderer : ViewRenderer<VideoPlayer, ARelativeLayout>
{
    VideoView videoView;
    MediaController mediaController;    // Used to display transport controls
    bool isPrepared;

    public VideoPlayerRenderer(Context context) : base(context)
    {
    }

    protected override void OnElementChanged(ElementChangedEventArgs<VideoPlayer> args)
    {
        base.OnElementChanged(args);

        if (args.NewElement != null)
        {
            if (Control == null)
            {
                // Save the VideoView for future reference
                videoView = new VideoView(Context);

                // Put the VideoView in a RelativeLayout
                ARelativeLayout relativeLayout = new ARelativeLayout(Context);
                relativeLayout.AddView(videoView);

                // Center the VideoView in the RelativeLayout
                ARelativeLayout.LayoutParams layoutParams =
                    new ARelativeLayout.LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent);
                layoutParams.AddRule(LayoutRules.CenterInParent);
                videoView.LayoutParameters = layoutParams;

                // Handle a VideoView event
                videoView.Prepared += OnVideoViewPrepared;

                SetNativeControl(relativeLayout);
            }

            SetAreTransportControlsEnabled();
            SetSource();

            args.NewElement.UpdateStatus += OnUpdateStatus;
            args.NewElement.PlayRequested += OnPlayRequested;
            args.NewElement.PauseRequested += OnPauseRequested;
            args.NewElement.StopRequested += OnStopRequested;
        }

        if (args.OldElement != null)
        {
            args.OldElement.UpdateStatus -= OnUpdateStatus;
            args.OldElement.PlayRequested -= OnPlayRequested;
            args.OldElement.PauseRequested -= OnPauseRequested;
            args.OldElement.StopRequested -= OnStopRequested;
        }
    }

    protected override void Dispose(bool disposing)
    {
        if (Control != null && videoView != null)
        {
            videoView.Prepared -= OnVideoViewPrepared;
        }
        if (Element != null)
        {
            Element.UpdateStatus -= OnUpdateStatus;
        }

        base.Dispose(disposing);
    }

    void OnVideoViewPrepared(object sender, EventArgs args)
    {
        isPrepared = true;
        ((IVideoPlayerController)Element).Duration = TimeSpan.FromMilliseconds(videoView.Duration);
    }

    protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs args)
    {
        base.OnElementPropertyChanged(sender, args);
        if (args.PropertyName == VideoPlayer.AreTransportControlsEnabledProperty.PropertyName)
        {
            SetAreTransportControlsEnabled();
        }
        else if (args.PropertyName == VideoPlayer.SourceProperty.PropertyName)
        {
            SetSource();
        }
        else if (args.PropertyName == VideoPlayer.PositionProperty.PropertyName)
        {
            if (Math.Abs(videoView.CurrentPosition - Element.Position.TotalMilliseconds) > 1000)
            {
                videoView.SeekTo((int)Element.Position.TotalMilliseconds);
            }
        }
    }

    void SetAreTransportControlsEnabled()
    {
        if (Element.AreTransportControlsEnabled)
        {
            mediaController = new MediaController(Context);
            mediaController.SetMediaPlayer(videoView);
            videoView.SetMediaController(mediaController);
        }
        else
        {
            videoView.SetMediaController(null);

            if (mediaController != null)
            {
                mediaController.SetMediaPlayer(null);
                mediaController = null;
            }
        }
    }

    void SetSource()
    {
        isPrepared = false;
        bool hasSetSource = false;

        if (Element.Source is UriVideoSource)
        {
            string uri = (Element.Source as UriVideoSource).Uri;

            if (!String.IsNullOrWhiteSpace(uri))
            {
                videoView.SetVideoURI(Android.Net.Uri.Parse(uri));
                hasSetSource = true;
            }
        }
        else if (Element.Source is FileVideoSource)
        {
            string filename = (Element.Source as FileVideoSource).File;

            if (!String.IsNullOrWhiteSpace(filename))
            {
                videoView.SetVideoPath(filename);
                hasSetSource = true;
            }
        }
        else if (Element.Source is ResourceVideoSource)
        {
            string package = Context.PackageName;
            string path = (Element.Source as ResourceVideoSource).Path;

            if (!String.IsNullOrWhiteSpace(path))
            {
                string filename = Path.GetFileNameWithoutExtension(path).ToLowerInvariant();
                string uri = "android.resource://" + package + "/raw/" + filename;
                videoView.SetVideoURI(Android.Net.Uri.Parse(uri));
                hasSetSource = true;
            }
        }

        if (hasSetSource && Element.AutoPlay)
        {
            videoView.Start();
        }
    }

    // Event handler to update status
    void OnUpdateStatus(object sender, EventArgs args)
    {
        VideoStatus status = VideoStatus.NotReady;

        if (isPrepared)
        {
            status = videoView.IsPlaying ? VideoStatus.Playing : VideoStatus.Paused;
        }

        ((IVideoPlayerController)Element).Status = status;

        // Set Position property
        TimeSpan timeSpan = TimeSpan.FromMilliseconds(videoView.CurrentPosition);
        ((IElementController)Element).SetValueFromRenderer(VideoPlayer.PositionProperty, timeSpan);
    }

    // Event handlers to implement methods
    void OnPlayRequested(object sender, EventArgs args)
    {
        videoView.Start();
    }

    void OnPauseRequested(object sender, EventArgs args)
    {
        videoView.Pause();
    }

    void OnStopRequested(object sender, EventArgs args)
    {
        videoView.StopPlayback();
    }
}
</code>```

I am using .mp4 format
Rest all classes are same as in the sample app Here
Any help will be appreciated . !

Edit - Device log(From Button Click to Cant play Error)
Here

答:
Try taking the video player out of the StackLayout, I've been running through Xamarins own video player sample, copied system files and class structures, nothing but blank screen..
Took it out of the stack and bingo</p>

Body:
I'm using Android's Video View to play a video in my app. It works fine when I put source as a web-link but I keep getting a "Can't play this video" message and a black screen in the Xamarin Android Player when I choose file from Local Resource. I have followed sample from Here. I have googled the issue some say the issue is may be because of

Unsupported file format

Unsupported android version

I Don't think this could be in my case as the sample project is running fine on same device .Moreover in my project video from URL are also played. I believe I might be missing a piece to fix this.
Xaml :-

  <StackLayout VerticalOptions="FillAndExpand">

    <video:VideoPlayer   AutoPlay="True"  x:Name="xvideoPlayer" WidthRequest="200" HeightRequest="200"  />
    <Button Clicked="Button_Clicked" ></Button>
</StackLayout>

Cs:

 public VideoPlayerPage(string url)
    {

        InitializeComponent();
        BindingContext = videoPlayerPageViewModel = new VideoPlayerPageViewModel();
        NavigationPage.SetHasNavigationBar(this, false);

    }
private async void Button_Clicked(object sender, EventArgs e)
    {
        Button btn = (Button)sender;
        btn.IsEnabled = false;
        var FileOperations = DependencyService.Get<IFileOperations>();

        //string pLocalPath = FileOperations.GetFilePath(url, "ErpwebChat");
        string pLocalPath = "content://com.android.externalstorage.documents/document/primary%3ADocument%2FErpwebChat%2F1aecb317-8d56-46c4-b29a-182d2e61093c.mp4";
        //DownloadVideo(url, "videos");

        if (!String.IsNullOrWhiteSpace(pLocalPath))
        {
            xvideoPlayer.Source = new FileVideoSource
            {
                File = pLocalPath
            };
        }
        btn.IsEnabled = true;
    }

VideoPlayerRenderer.droid class:-

  public class VideoPlayerRenderer : ViewRenderer<VideoPlayer, ARelativeLayout>
{
    VideoView videoView;
    MediaController mediaController;    // Used to display transport controls
    bool isPrepared;

    public VideoPlayerRenderer(Context context) : base(context)
    {
    }

    protected override void OnElementChanged(ElementChangedEventArgs<VideoPlayer> args)
    {
        base.OnElementChanged(args);

        if (args.NewElement != null)
        {
            if (Control == null)
            {
                // Save the VideoView for future reference
                videoView = new VideoView(Context);

                // Put the VideoView in a RelativeLayout
                ARelativeLayout relativeLayout = new ARelativeLayout(Context);
                relativeLayout.AddView(videoView);

                // Center the VideoView in the RelativeLayout
                ARelativeLayout.LayoutParams layoutParams =
                    new ARelativeLayout.LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent);
                layoutParams.AddRule(LayoutRules.CenterInParent);
                videoView.LayoutParameters = layoutParams;

                // Handle a VideoView event
                videoView.Prepared += OnVideoViewPrepared;

                SetNativeControl(relativeLayout);
            }

            SetAreTransportControlsEnabled();
            SetSource();

            args.NewElement.UpdateStatus += OnUpdateStatus;
            args.NewElement.PlayRequested += OnPlayRequested;
            args.NewElement.PauseRequested += OnPauseRequested;
            args.NewElement.StopRequested += OnStopRequested;
        }

        if (args.OldElement != null)
        {
            args.OldElement.UpdateStatus -= OnUpdateStatus;
            args.OldElement.PlayRequested -= OnPlayRequested;
            args.OldElement.PauseRequested -= OnPauseRequested;
            args.OldElement.StopRequested -= OnStopRequested;
        }
    }

    protected override void Dispose(bool disposing)
    {
        if (Control != null && videoView != null)
        {
            videoView.Prepared -= OnVideoViewPrepared;
        }
        if (Element != null)
        {
            Element.UpdateStatus -= OnUpdateStatus;
        }

        base.Dispose(disposing);
    }

    void OnVideoViewPrepared(object sender, EventArgs args)
    {
        isPrepared = true;
        ((IVideoPlayerController)Element).Duration = TimeSpan.FromMilliseconds(videoView.Duration);
    }

    protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs args)
    {
        base.OnElementPropertyChanged(sender, args);
        if (args.PropertyName == VideoPlayer.AreTransportControlsEnabledProperty.PropertyName)
        {
            SetAreTransportControlsEnabled();
        }
        else if (args.PropertyName == VideoPlayer.SourceProperty.PropertyName)
        {
            SetSource();
        }
        else if (args.PropertyName == VideoPlayer.PositionProperty.PropertyName)
        {
            if (Math.Abs(videoView.CurrentPosition - Element.Position.TotalMilliseconds) > 1000)
            {
                videoView.SeekTo((int)Element.Position.TotalMilliseconds);
            }
        }
    }

    void SetAreTransportControlsEnabled()
    {
        if (Element.AreTransportControlsEnabled)
        {
            mediaController = new MediaController(Context);
            mediaController.SetMediaPlayer(videoView);
            videoView.SetMediaController(mediaController);
        }
        else
        {
            videoView.SetMediaController(null);

            if (mediaController != null)
            {
                mediaController.SetMediaPlayer(null);
                mediaController = null;
            }
        }
    }

    void SetSource()
    {
        isPrepared = false;
        bool hasSetSource = false;

        if (Element.Source is UriVideoSource)
        {
            string uri = (Element.Source as UriVideoSource).Uri;

            if (!String.IsNullOrWhiteSpace(uri))
            {
                videoView.SetVideoURI(Android.Net.Uri.Parse(uri));
                hasSetSource = true;
            }
        }
        else if (Element.Source is FileVideoSource)
        {
            string filename = (Element.Source as FileVideoSource).File;

            if (!String.IsNullOrWhiteSpace(filename))
            {
                videoView.SetVideoPath(filename);
                hasSetSource = true;
            }
        }
        else if (Element.Source is ResourceVideoSource)
        {
            string package = Context.PackageName;
            string path = (Element.Source as ResourceVideoSource).Path;

            if (!String.IsNullOrWhiteSpace(path))
            {
                string filename = Path.GetFileNameWithoutExtension(path).ToLowerInvariant();
                string uri = "android.resource://" + package + "/raw/" + filename;
                videoView.SetVideoURI(Android.Net.Uri.Parse(uri));
                hasSetSource = true;
            }
        }

        if (hasSetSource && Element.AutoPlay)
        {
            videoView.Start();
        }
    }

    // Event handler to update status
    void OnUpdateStatus(object sender, EventArgs args)
    {
        VideoStatus status = VideoStatus.NotReady;

        if (isPrepared)
        {
            status = videoView.IsPlaying ? VideoStatus.Playing : VideoStatus.Paused;
        }

        ((IVideoPlayerController)Element).Status = status;

        // Set Position property
        TimeSpan timeSpan = TimeSpan.FromMilliseconds(videoView.CurrentPosition);
        ((IElementController)Element).SetValueFromRenderer(VideoPlayer.PositionProperty, timeSpan);
    }

    // Event handlers to implement methods
    void OnPlayRequested(object sender, EventArgs args)
    {
        videoView.Start();
    }

    void OnPauseRequested(object sender, EventArgs args)
    {
        videoView.Pause();
    }

    void OnStopRequested(object sender, EventArgs args)
    {
        videoView.StopPlayback();
    }
}

I am using .mp4 format
Rest all classes are same as in the sample app Here
Any help will be appreciated . !

Edit - Device log(From Button Click to Cant play Error)
Here


问:
What is the default styling for html in components like JLabel
Swing has a nice feature where some components allow text to be specified using html.  For example, the JLabel component can use html formatting simply using:

JLabel jl = new JLabel("
Hello World
");
```

I find this feature to be really convenient and I am using it in several places in my app.

I would like to know what the default styling is when I use this feature.  I know that I can easily override these by adding my own style attributes, but I would like to know what the starting set is, because it is different than most browser defaults.

Where can I find out the default styling (font, line spacing, etc)?  I have not seen anything in the documentation.  I tried to browse through the source code, but I was unable to see where the  tag gets parsed and the styling gets applied.

Can someone give me a pointer as to where to look for this information, possibly in the OpenJDK source?

答:
The default style sheet is default.css, which can be found in resources.jar under the directory javax/swing/text/html/default.css.

You can also obtain the styles programmatically:

```<code>StyleSheet sheet = new HTMLEditorKit().getStyleSheet();
</code>```

Body:
Swing has a nice feature where some components allow text to be specified using html.  For example, the JLabel component can use html formatting simply using:

JLabel jl = new JLabel("
Hello World
");

I find this feature to be really convenient and I am using it in several places in my app.

I would like to know what the default styling is when I use this feature.  I know that I can easily override these by adding my own style attributes, but I would like to know what the starting set is, because it is different than most browser defaults.

Where can I find out the default styling (font, line spacing, etc)?  I have not seen anything in the documentation.  I tried to browse through the source code, but I was unable to see where the  tag gets parsed and the styling gets applied.

Can someone give me a pointer as to where to look for this information, possibly in the OpenJDK source?

Body:
The default style sheet is default.css, which can be found in resources.jar under the directory javax/swing/text/html/default.css.

You can also obtain the styles programmatically:

StyleSheet sheet = new HTMLEditorKit().getStyleSheet();


问:
How to decrease MySQL container memory usage?
Problem:

MySQL is taking over 350MB on idle, as shown in docker stats

Tried:

Tweaking the configuration file as suggested in posts like this one.

Added these lines to the file:  /etc/mysql/my.cnf

```<code>innodb_buffer_pool_size=64M
innodb_log_buffer_size=256K
max_connections=5
key_buffer_size=8
thread_cache_size=0
host_cache_size=0
innodb_ft_cache_size=1600000
innodb_ft_total_cache_size=32000000
thread_stack=131072
sort_buffer_size=32K
read_buffer_size=8200
read_rnd_buffer_size=8200
max_heap_table_size=16K
tmp_table_size=1K
bulk_insert_buffer_size=0
join_buffer_size=128
net_buffer_length=1K
innodb_sort_buffer_size=64K
</code>```

Dockerfile

```<code>FROM mysql
COPY my.cnf /etc/mysql/
</code>```

Actual:

I made sure my.cnf changes were in the container, however its still taking over 350MB idle, is it possible to get it below that or am I trying something just not possible?

答:
You can try and appropriately reduce footage.

https://github.com/major/MySQLTuner-perl

Body:
Problem:

MySQL is taking over 350MB on idle, as shown in docker stats

Tried:

Tweaking the configuration file as suggested in posts like this one.

Added these lines to the file:  /etc/mysql/my.cnf

innodb_buffer_pool_size=64M
innodb_log_buffer_size=256K
max_connections=5
key_buffer_size=8
thread_cache_size=0
host_cache_size=0
innodb_ft_cache_size=1600000
innodb_ft_total_cache_size=32000000
thread_stack=131072
sort_buffer_size=32K
read_buffer_size=8200
read_rnd_buffer_size=8200
max_heap_table_size=16K
tmp_table_size=1K
bulk_insert_buffer_size=0
join_buffer_size=128
net_buffer_length=1K
innodb_sort_buffer_size=64K

Dockerfile

FROM mysql
COPY my.cnf /etc/mysql/

Actual:

I made sure my.cnf changes were in the container, however its still taking over 350MB idle, is it possible to get it below that or am I trying something just not possible?


问:
Grep with regex expression
I need the content between the fourth and fifth "|" on all lines starting with FHEAD. The goal is to apply the regular expression in grep to read files.

I have this expression that returns all content between "|"

```<code>(?<=\|)(.*?)(?=\|)
</code>```

The goal in the example below would be to return

1047

  8401-

```<code>FHEAD|1|PRMPC|20200217103050|1047|S
TMBPE|FHEAD|2|MOD
FHEAD|3|8401|230008|8401-|8401-Dcto|8401-Dcto 10FHEAD|1|235211|20190206000001|20190402235959|2||1||8||
TPGRP|4|240184
TGLIST|5|235213||||FHEAD
TLITM|6|101029605
TLITM|7|FHEAD101052978
</code>```

Someone can help me?

Thanks in advance

答:
To print the content of the fifth field (non-empty) on lines starting with FHEAD:

```<code>awk -F'|' '$1=="FHEAD" && $5!=""{print $5}' file
</code>```

Title: Grep with regex expression

Body:
I need the content between the fourth and fifth "|" on all lines starting with FHEAD. The goal is to apply the regular expression in grep to read files.

I have this expression that returns all content between "|"

(?<=\|)(.*?)(?=\|)

The goal in the example below would be to return

1047

  8401-

FHEAD|1|PRMPC|20200217103050|1047|S
TMBPE|FHEAD|2|MOD
FHEAD|3|8401|230008|8401-|8401-Dcto|8401-Dcto 10FHEAD|1|235211|20190206000001|20190402235959|2||1||8||
TPGRP|4|240184
TGLIST|5|235213||||FHEAD
TLITM|6|101029605
TLITM|7|FHEAD101052978

Someone can help me?

Thanks in advance

Body:
To print the content of the fifth field (non-empty) on lines starting with FHEAD:

awk -F'|' '$1=="FHEAD" && $5!=""{print $5}' file


问:
How to add an onClick function to a dynamically-filled div?
I have bootstrap navbar with dropdown:

```<code><ul class="navbar-nav mr-auto">
  <li class="nav-item dropdown">
   <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria haspopup="true" aria-expanded="false">GANRES</a>
   <div class="dropdown-menu"></div>
  </li>
</ul>
</code>```

And I have function that fills them with genres with the TMDb API:

```<code>async function getGenres() {
    let url = "https://api.themoviedb.org/3/genre/movie/list?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US";
    let response = await fetch(url);
    let genres = await response.json();
    let navbar = document.getElementsByClassName("nav-item dropdown");
    navbar.innerHTML += `<div class="dropdown-menu">`;
    let nav = document.getElementsByClassName("dropdown-menu");
    for (let i = 0; i < genres.genres.length; i++) {
        nav[0].innerHTML += `<a class="dropdown-item" href="#">` + genres.genres[i].name + `</a>`;
    }

//This part should add separately to each element, but it does not work
//Here is error: Cannot set property 'click' of undefined at getGenres

    for (let i = 0; i < genres.genres.length; i++) {
    document.getElementsByClassName("dropdown-menu")[i].click = function () {
        getmovies("discover/movie?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-us&sort_by=popularity.desc&include_adult=false&include_video=false&page=1&with_genres=" + genres.genres[i].id);
    };
};
}
</code>```

The items themselves are created normally.GenresThe onClick function just doesn't work.

I tried to load this function as onload in body, but it didn't work

答:
You can easily do it, here is rough example. So just add event listener inside your for loop

function generateLinks() {
  var container = document.getElementById("containter");
  var textNode;
  var node;

  [1,2,3,4,5].forEach(function(i) {
    node = document.createElement("li");
    node.setAttribute("id", i);
    textNode = document.createTextNode("Hello" + i);
    node.appendChild(textNode);

    node.addEventListener("click", function() {
        console.log("hello " + i)
    });

    container.appendChild(node);
  });

}

generateLinks();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="containter">

</div></code>```

Body:
I have bootstrap navbar with dropdown:

   GANRES

And I have function that fills them with genres with the TMDb API:

async function getGenres() {
    let url = "https://api.themoviedb.org/3/genre/movie/list?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US";
    let response = await fetch(url);
    let genres = await response.json();
    let navbar = document.getElementsByClassName("nav-item dropdown");
    navbar.innerHTML += `<div class="dropdown-menu">`;
    let nav = document.getElementsByClassName("dropdown-menu");
    for (let i = 0; i < genres.genres.length; i++) {
        nav[0].innerHTML += `<a class="dropdown-item" href="#">` + genres.genres[i].name + `</a>`;
    }

//This part should add separately to each element, but it does not work
//Here is error: Cannot set property 'click' of undefined at getGenres

    for (let i = 0; i < genres.genres.length; i++) {
    document.getElementsByClassName("dropdown-menu")[i].click = function () {
        getmovies("discover/movie?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-us&sort_by=popularity.desc&include_adult=false&include_video=false&page=1&with_genres=" + genres.genres[i].id);
    };
};
}

The items themselves are created normally.GenresThe onClick function just doesn't work.

I tried to load this function as onload in body, but it didn't work

Body:
You can easily do it, here is rough example. So just add event listener inside your for loop

function generateLinks() {
  var container = document.getElementById("containter");
  var textNode;
  var node;

  [1,2,3,4,5].forEach(function(i) {
    node = document.createElement("li");
    node.setAttribute("id", i);
    textNode = document.createTextNode("Hello" + i);
    node.appendChild(textNode);

    node.addEventListener("click", function() {
        console.log("hello " + i)
    });

    container.appendChild(node);
  });

}

generateLinks();

<div id="containter">

</div>


问:
How to insert values to a nested array
I am having one report array of objects which is used to show report data on the dashboard as below,

```<code>    report = [
              {id: "id01", code: "C001", name: "apples", type: "fruits", intime:[], quantity:[]},
              {id: "id01", code: "C001", name: "grapes", type: "fruits", intime:[], quantity:[]},
              {id: "id01", code: "C002", name: "apples", type: "fruits", intime:[], quantity:[]},
              {id: "id01", code: "C002", name: "grapes", type: "fruits", intime:[], quantity:[]}
             ]
</code>```

And below array as input,

```<code>record = [
    {code: "C001",
    records :[{intime: "15:32:12", apples: "30", grapes: "80"},
            {intime: "15:32:13", apples: "34", grapes: "50"}]
    },
    {code: "C002",
    records :[{intime: "15:32:12", apples: "56", grapes: "100"},
            {intime: "15:32:13", apples: "75", grapes: "38"}]
    },
]
</code>```

I want to put these values to arrays of report array as per matching condition so that report array should look like,

```<code>report = [
  {id: "id01", code: "C001", name: "apples", type: "fruits", intime:["15:32:12","15:32:13"], quantity:[30,34]},
  {id: "id01", code: "C001", name: "grapes", type: "fruits", intime:["15:32:12","15:32:13"], quantity:[80,50]},
  {id: "id01", code: "C002", name: "apples", type: "fruits", intime:["15:32:12","15:32:13"], quantity:[56,75]},
  {id: "id01", code: "C002", name: "grapes", type: "fruits", intime:["15:32:12","15:32:13"], quantity:[100,38]}
]
</code>```

I think , this can be achieved through array filter method in loop but that method does not seems efficient when record array is big in size.  Please suggest me some better and efficient way to put values in such way.

答:
Create an object that uses code as the keys to find all the related report objects. Then use nested loops to insert the times in all the intime arrays.

var report = [
  {id: "id01", code: "C001", name: "apples", type: "fruits", intime:[], quantity:[]},
  {id: "id01", code: "C001", name: "grapes", type: "fruits", intime:[], quantity:[]},
  {id: "id01", code: "C002", name: "apples", type: "fruits", intime:[], quantity:[]},
  {id: "id01", code: "C002", name: "grapes", type: "fruits", intime:[], quantity:[]}
];

record = [
    {code: "C001",
    records :[{intime: "15:32:12", apples: "30", grapes: "80"},
            {intime: "15:32:13", apples: "34", grapes: "50"}]
    },
    {code: "C002",
    records :[{intime: "15:32:12", apples: "56", grapes: "100"},
            {intime: "15:32:13", apples: "75", grapes: "38"}]
    },
];

var report_by_code = report.reduce((o, r) => {
    if (o[r.code]) {
        o[r.code].push(r);
    } else {
        o[r.code] = [r];
    }
    return o;
}, {});
record.forEach(({code, records}) => records.forEach(({intime}) =>
    report_by_code[code].forEach(r => r.intime.push(intime))));

console.log(report);```

Title: How to insert values to a nested array

Body:
I am having one report array of objects which is used to show report data on the dashboard as below,

    report = [
              {id: "id01", code: "C001", name: "apples", type: "fruits", intime:[], quantity:[]},
              {id: "id01", code: "C001", name: "grapes", type: "fruits", intime:[], quantity:[]},
              {id: "id01", code: "C002", name: "apples", type: "fruits", intime:[], quantity:[]},
              {id: "id01", code: "C002", name: "grapes", type: "fruits", intime:[], quantity:[]}
             ]

And below array as input,

record = [
    {code: "C001",
    records :[{intime: "15:32:12", apples: "30", grapes: "80"},
            {intime: "15:32:13", apples: "34", grapes: "50"}]
    },
    {code: "C002",
    records :[{intime: "15:32:12", apples: "56", grapes: "100"},
            {intime: "15:32:13", apples: "75", grapes: "38"}]
    },
]

I want to put these values to arrays of report array as per matching condition so that report array should look like,

report = [
  {id: "id01", code: "C001", name: "apples", type: "fruits", intime:["15:32:12","15:32:13"], quantity:[30,34]},
  {id: "id01", code: "C001", name: "grapes", type: "fruits", intime:["15:32:12","15:32:13"], quantity:[80,50]},
  {id: "id01", code: "C002", name: "apples", type: "fruits", intime:["15:32:12","15:32:13"], quantity:[56,75]},
  {id: "id01", code: "C002", name: "grapes", type: "fruits", intime:["15:32:12","15:32:13"], quantity:[100,38]}
]

I think , this can be achieved through array filter method in loop but that method does not seems efficient when record array is big in size.  Please suggest me some better and efficient way to put values in such way.


答:
```<code>function calculate() {

  var E1 =   $("#E1").val().split(",").join("");
  var E2 =   $("#E2").val().split(",").join("");

  var result = E1*E2;
  $("#E3").val(result);
  formatNumber($("#E3"))

}

function formatNumber(input) {
  // format number
  input.val(function(index, value) {
    return value
    .replace(/\D/g, "")
    .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
    ;
  });

//For comma seperation
$('input.number').keyup(function(event) {

  // skip for arrow keys
  if(event.which >= 37 && event.which <= 40) return;

  formatNumber($(this))
});
</code>```

Title: Adding comma Separators for a value after a calculation


问:
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?

答: Maybe the content you get from the database is UTF8, but it goes wrong in your presentation. Do you send the correct content-type header when presenting in a webpage? And is that page also saved as UTF8 document?</p>

Title: Zend project - mysql not fetching UTF8


问:
Method inside class is not getting executed in unit test
I have a class which contains methods.Now after initializing the class i want to invoke the methods but my test flow is not to the method and getting error like Uncaught error outside test suite.Below is my code

```<code>describe('Test Stu positive', () => {
it("Test Stu positive", (done) => {
    const stuDetails = new masterDetails(getdetails);
    expect(stuDetails.retrieveStudent(res => {
        console.log(res);
        done()
    }))
});
});
</code>```

Now, in the above code i am not able to print console.log(res);. What i am doing wrong?

答:
I believe that you are using Mocha as your testing framework and looks like the error is not being handled by mocha, because is an asynchronous operation and you are not passing the error to the done callback method as described in the mocha documentation

it is really hard to tell how your function works, if it returns a promise or if it just uses a callback and the error is handled inside the function, so I can't provide you a code example on how to accomplish this. if you mind providing your function declaration I can update my answer with an example solution.

Body:
I have a class which contains methods.Now after initializing the class i want to invoke the methods but my test flow is not to the method and getting error like Uncaught error outside test suite.Below is my code

describe('Test Stu positive', () => {
it("Test Stu positive", (done) => {
    const stuDetails = new masterDetails(getdetails);
    expect(stuDetails.retrieveStudent(res => {
        console.log(res);
        done()
    }))
});
});

Now, in the above code i am not able to print console.log(res);. What i am doing wrong?


问:
Mapbox Examples - how to begin?
I'd like to begin loading mapbox examples in AndroidStudio. I followed guides, but I'm struggling with dependencies problems.
Can someone help me, please?
I downloaded examples from github and loaded it in my AndroidStudio.
I follow all explanations, dependencies.... repositories... ecc

I syncronized Gradle and it is ok.

I Cleared Cache and.. nothings!

But example don't works !

for example in this: import com.mapbox.mapboxandroiddemo.R; I have this error: error: cannot find symbol class R

Naturally I followed this guide https://docs.mapbox.com/help/tutorials/first-steps-android-sdk/

Is there any example that simply I can download and works?
Help me please. Thank you very mutch.

答:
Try swapping import com.mapbox.mapboxandroiddemo.R with your app'spackage name. You can find the app's package in the manifest file

import PACKAGE_NAME.R

Title: Mapbox Examples - how to begin?


问:
Unity + Firebase: is it possible to append data to a keys value, or do I have to retrieve keys data every time?
I'm a bit worried that I will reach the free data limits of Firebase in a student project.
Basically my question is:
is it possible to append to the end of the string instead of retrieving key and value, appending and uploading again.
What I want to achieve:
I have to create statistics of user right/wrong answers for particular questions.
I want to have a kvp:
answers: 1r/5w/3r
Where number is the number of users guesses and r/w means right wrong. Whenever the guessing session ends I want to add /numberOfGuesses+RightOrWrongAnswer and the end.

I'm using Unity 2018.

Thank you in advance for all the help!

答:
I don't know how your game is architected or how many people are playing, but I'd be surprised if you hit your free limit on a student project (you can store 1GB and download 10GB). That string is 8 bytes, let's assume worst case scenario: as a UTF32 string, that would be 32 bytes of data - you'd have to pull that down 312 million times to hit a cap (there'll be some overhead, but I can't imagine it being a hugely impactful). If you're afraid of being charged, you can opt to not have a credit card on file to be doubly sure you stay on a student budget.

If you want to reduce the amount of reading/writing though, I might suggest that instead of:
key: <value_string> (so, instead of session_id: "1r/5w/3r")

you structure more like:

```<code>key:
 - wrong: 5
 - right: 3
</code>```

So have two more values nested under your key. One for all the wrong answers, just an incrementing integer. Then one for all the right answers: just an incrementing integer.

The mechanism to "append" would be a transaction, and you should use these whether you're mutating a string or counter. Firebase tries to be smart with data usage and offline caching, but you don't get much more control other than that.

If order really matters, you might want to get cleverer. You'll generally want to work with the abstractions Realtime Database gives you though to maximize any inherent optimizations (it likes to think in terms of JSON documents, so think about your data layout similarly). This may not be as data optimal, but you may want to consider instead using a ledger of some kind (perhaps using ServerValue.Timestamp to record a single right or wrong answer, and having a cloud function listening to sum up the results in the background after a game - this would be especially useful if you plan on having a lot of users trying to write the same key at the same time).

Body:
I don't know how your game is architected or how many people are playing, but I'd be surprised if you hit your free limit on a student project (you can store 1GB and download 10GB). That string is 8 bytes, let's assume worst case scenario: as a UTF32 string, that would be 32 bytes of data - you'd have to pull that down 312 million times to hit a cap (there'll be some overhead, but I can't imagine it being a hugely impactful). If you're afraid of being charged, you can opt to not have a credit card on file to be doubly sure you stay on a student budget.

If you want to reduce the amount of reading/writing though, I might suggest that instead of:
key: <value_string> (so, instead of session_id: "1r/5w/3r")

you structure more like:

key:
 - wrong: 5
 - right: 3

So have two more values nested under your key. One for all the wrong answers, just an incrementing integer. Then one for all the right answers: just an incrementing integer.

The mechanism to "append" would be a transaction, and you should use these whether you're mutating a string or counter. Firebase tries to be smart with data usage and offline caching, but you don't get much more control other than that.

If order really matters, you might want to get cleverer. You'll generally want to work with the abstractions Realtime Database gives you though to maximize any inherent optimizations (it likes to think in terms of JSON documents, so think about your data layout similarly). This may not be as data optimal, but you may want to consider instead using a ledger of some kind (perhaps using ServerValue.Timestamp to record a single right or wrong answer, and having a cloud function listening to sum up the results in the background after a game - this would be especially useful if you plan on having a lot of users trying to write the same key at the same time).


问:
Azure Kusto Data Explorer: combine rows by column
I am looking to update/extend column Process such that it reflects whether or not the Process has ended.

For example, table below should return:

```<code>Id  Process
1   Completed
1   Completed
1   Completed   //Id 1: because the last Process state was End
2   InProgress
2   InProgress  //Id 2: because the last Process state was not End
3   InProgress
3   InProgress
3   InProgress
3   InProgress  //Id 3: because the last Process state was not End
</code>```

Table:

```<code>datatable(Id:int, Process:string, UpdateTime: datetime))
[
    1, "Initiate", datetime(2020-02-02 12:00:00),
    1, "Start", datetime(2020-02-02 13:00:00),
    1, "End", datetime(2020-02-02 14:00:00),
    2, "Initiate", datetime(2020-02-02 12:00:00),
    2, "Start", datetime(2020-02-02 13:00:00),
    3  "Initiate", datetime(2020-02-02 12:00:00),
    3, "Start", datetime(2020-02-02 13:00:00),
    3, "End", datetime(2020-02-02 14:00:00),
    3, "Reopen", datetime(2020-02-02 15:00:00),
]
</code>```

答:
you could try something along the following lines:

```<code>datatable(Id:int, Process:string, UpdateTime: datetime)
[
    1, "Initiate", datetime(2020-02-02 12:00:00),
    1, "Start", datetime(2020-02-02 13:00:00),
    1, "End", datetime(2020-02-02 14:00:00),
    2, "Initiate", datetime(2020-02-02 12:00:00),
    2, "Start", datetime(2020-02-02 13:00:00),
    3, "Initiate", datetime(2020-02-02 12:00:00),
    3, "Start", datetime(2020-02-02 13:00:00),
    3, "End", datetime(2020-02-02 14:00:00),
    3, "Reopen", datetime(2020-02-02 15:00:00),
]
| order by Id asc, UpdateTime asc
| extend session_start = row_window_session(UpdateTime, 365d, 365d, Id != prev(Id))
| as hint.materialized = true T
| lookup (
    T
    | summarize arg_max(UpdateTime, Process) by session_start, Id
    | project Id, LastProcess = Process
) on Id
| project Id, Process = case(LastProcess == "End", "Completed", "InProgress")
</code>```

which returns:

```<code>| Id | Process    |
|----|------------|
| 1  | Completed  |
| 1  | Completed  |
| 1  | Completed  |
| 2  | InProgress |
| 2  | InProgress |
| 3  | InProgress |
| 3  | InProgress |
| 3  | InProgress |
| 3  | InProgress |
</code>```

Body:
I am looking to update/extend column Process such that it reflects whether or not the Process has ended.

For example, table below should return:

Id  Process
1   Completed
1   Completed
1   Completed   //Id 1: because the last Process state was End
2   InProgress
2   InProgress  //Id 2: because the last Process state was not End
3   InProgress
3   InProgress
3   InProgress
3   InProgress  //Id 3: because the last Process state was not End

Table:

datatable(Id:int, Process:string, UpdateTime: datetime))
[
    1, "Initiate", datetime(2020-02-02 12:00:00),
    1, "Start", datetime(2020-02-02 13:00:00),
    1, "End", datetime(2020-02-02 14:00:00),
    2, "Initiate", datetime(2020-02-02 12:00:00),
    2, "Start", datetime(2020-02-02 13:00:00),
    3  "Initiate", datetime(2020-02-02 12:00:00),
    3, "Start", datetime(2020-02-02 13:00:00),
    3, "End", datetime(2020-02-02 14:00:00),
    3, "Reopen", datetime(2020-02-02 15:00:00),
]

Body:
you could try something along the following lines:

datatable(Id:int, Process:string, UpdateTime: datetime)
[
    1, "Initiate", datetime(2020-02-02 12:00:00),
    1, "Start", datetime(2020-02-02 13:00:00),
    1, "End", datetime(2020-02-02 14:00:00),
    2, "Initiate", datetime(2020-02-02 12:00:00),
    2, "Start", datetime(2020-02-02 13:00:00),
    3, "Initiate", datetime(2020-02-02 12:00:00),
    3, "Start", datetime(2020-02-02 13:00:00),
    3, "End", datetime(2020-02-02 14:00:00),
    3, "Reopen", datetime(2020-02-02 15:00:00),
]
| order by Id asc, UpdateTime asc
| extend session_start = row_window_session(UpdateTime, 365d, 365d, Id != prev(Id))
| as hint.materialized = true T
| lookup (
    T
    | summarize arg_max(UpdateTime, Process) by session_start, Id
    | project Id, LastProcess = Process
) on Id
| project Id, Process = case(LastProcess == "End", "Completed", "InProgress")

which returns:

| Id | Process    |
|----|------------|
| 1  | Completed  |
| 1  | Completed  |
| 1  | Completed  |
| 2  | InProgress |
| 2  | InProgress |
| 3  | InProgress |
| 3  | InProgress |
| 3  | InProgress |
| 3  | InProgress |


问:
Swagger UI Freeze/Crash - Asp.Net Core 3.1. Any fix?
I use swashbuckle in my ASP.Net Core 3.1 with swagger UI.
When I click on a model, the whole webpage crashes/freezes.
I use a lot (100 approx) Entity Framework Core entities (7000 lines of JSON).

I switched to Nswag to see if it would be better. No more crashes but still quite slow (10 seconds when you click on a model, 20 on a method)

Should I make DTOs or is there a solution for my problem?

I also tried adding this to my startup but it does not help at all.

```<code>     services.AddControllers().AddNewtonsoftJson(x =>
        {
            x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        });
</code>```

答:
From what you are reporting it seems that your swashbuckle is using an old version of the swagger-ui, there should not be any significant difference from Nswag and swashbuckle if they have the same version of swagger-ui.

But this issue has been discussed on the project, complex nested models when fully expanded are huge, here is some data I collected a while back:

https://github.com/swagger-api/swagger-ui/issues/4411#issuecomment-380168870

```<code>| Schema                                                     | SchemaSize | ExampleSize | ModelSize  |
|------------------------------------------------------------|------------|-------------|------------|
| http://swagger-net-test.azurewebsites.net/api/NestedSwag/2 | 1,368      | 10,578      | 262,519    |
| http://swagger-net-test.azurewebsites.net/api/NestedSwag/3 | 1,662      | 59,703      | 1,321,999  |
| http://swagger-net-test.azurewebsites.net/api/NestedSwag/4 | 1,956      | 332,828     | 6,640,079  |
| http://swagger-net-test.azurewebsites.net/api/NestedSwag/5 | 2,250      | 1,835,953   | 33,305,772 |
</code>```

As you can see expanding those complex models can be a costly task on the browser.

Body:
I use swashbuckle in my ASP.Net Core 3.1 with swagger UI.
When I click on a model, the whole webpage crashes/freezes.
I use a lot (100 approx) Entity Framework Core entities (7000 lines of JSON).

I switched to Nswag to see if it would be better. No more crashes but still quite slow (10 seconds when you click on a model, 20 on a method)

Should I make DTOs or is there a solution for my problem?

I also tried adding this to my startup but it does not help at all.

     services.AddControllers().AddNewtonsoftJson(x =>
        {
            x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        });

Body:
From what you are reporting it seems that your swashbuckle is using an old version of the swagger-ui, there should not be any significant difference from Nswag and swashbuckle if they have the same version of swagger-ui.

But this issue has been discussed on the project, complex nested models when fully expanded are huge, here is some data I collected a while back:

https://github.com/swagger-api/swagger-ui/issues/4411#issuecomment-380168870

| Schema                                                     | SchemaSize | ExampleSize | ModelSize  |
|------------------------------------------------------------|------------|-------------|------------|
| http://swagger-net-test.azurewebsites.net/api/NestedSwag/2 | 1,368      | 10,578      | 262,519    |
| http://swagger-net-test.azurewebsites.net/api/NestedSwag/3 | 1,662      | 59,703      | 1,321,999  |
| http://swagger-net-test.azurewebsites.net/api/NestedSwag/4 | 1,956      | 332,828     | 6,640,079  |
| http://swagger-net-test.azurewebsites.net/api/NestedSwag/5 | 2,250      | 1,835,953   | 33,305,772 |

As you can see expanding those complex models can be a costly task on the browser.


问:
JavaScript - Math.random() - parameter
What changes adding the parameter in Math.random()?

For example:

```<code>Math.random() == Math.random(1234)
</code>```

答: It will just ignore the passed parameter.</p>

Title: JavaScript - Math.random() - parameter

Body:
What changes adding the parameter in Math.random()?

For example:

Math.random() == Math.random(1234)


问:
How to "preselect" UIActivityViewController Icon?
I would like to redirect the user to an app that could be selected in UIActivityViewController.

For example, the "Message" app is often shown in UIActivityViewController. How could I,in advance, directly redirect the user to this app without showing the UIActivityViewController?

I would be glad to know if someone can help me out.

答:
Try this one!</p>

```<code>@IBAction func openMessagesApp(sender: UIButton){
   let sms = "sms:\(number)&body=\(message or link)"
   let url = URL(string:sms)!
   let shared = UIApplication.shared

    if(shared.canOpenURL(url)){
       shared.openURL(url)
     } else{
       print("unable to send message")
     }
}
</code>```

Body:
Try this one!

@IBAction func openMessagesApp(sender: UIButton){
   let sms = "sms:\(number)&body=\(message or link)"
   let url = URL(string:sms)!
   let shared = UIApplication.shared

    if(shared.canOpenURL(url)){
       shared.openURL(url)
     } else{
       print("unable to send message")
     }
}


问:
groupsumClump Problem
Im struggling to get the below problem right for a quite a while sometime.

Given an array of ints, is it possible to choose a group of some of the ints, such that the group sums to the given target, with this additional constraint: if there are numbers in the array that are adjacent and the identical value, they must either all be chosen, or none of them chosen. For example, with the array {1, 2, 2, 2, 5, 2}, either all three 2's in the middle must be chosen or not, all as a group. (one loop can be used to find the extent of the identical values).

```<code>  groupSumClump(0, {8, 2, 2, 1}, 9) → true
  groupSumClump(0, {2, 4, 4, 8}, 14) → false
</code>```

The code is at http://ideone.com/Udk5q

Failing test case scenarios:

```<code> groupSumClump(0, {2, 4, 4, 8}, 14) → false -->NegativeArraySizeException
 groupSumClump(0, {8, 2, 2, 1}, 9) → true false --> X
</code>```

i have really tried my best to make it work but alas its failing always.
Please Need your help SO experts to resolve this problem
I will be highly obliged and thankful to you,if you can spare a few minutes to look into my problem as well and help me in acheieving the desired solution.

答:
Method "summate" logic is realy messed up.
It should look something like function "f" here:
Algorithm to find which numbers from a list of size n sum to another number

Quick and dirty fix for your code:

```<code>class Demo {
public static void main(String args[]) {
    Demo.groupSumClump(0, new int[] { 2, 4, 4, 8 }, 14);
    Demo.groupSumClump(0, new int[] {8, 2, 2, 1}, 9);
}

public static void groupSumClump(int start, int[] nums, int target) {
    start = 0;

    nums = adjacents(start, nums);

    for (int a_number = 0; a_number < nums.length; a_number++) {
        System.out.println("Array is " + nums[a_number]);
    }
    summate(nums, 0, 0, target);
    System.out.println(false);
}

public static int[] adjacents(int start, int[] nums) {
    int sum = 0;
    for (int i = 0; i < nums.length - 1; i++) {
        if (nums[i] == nums[i + 1]) {
            sum += nums[i] + nums[i + 1];
            nums[i] = sum;
            nums[i + 1] = 0;
        }
    }
    return nums;
}

static void check(int sum, int target) {
    if (sum == target) {
        System.out.println(true);
        System.exit(0);
    }
}

static void summate(int[] numbers, int index, int sum, int target) {
    check(sum, target);
    if (index == numbers.length) {
        return;
    }
    summate(numbers, index + 1, sum + numbers[index], target);
    check(sum, target);
    summate(numbers, index + 1, sum, target);
    check(sum, target);
}
}
</code>```

Title: groupsumClump Problem

Body:
Im struggling to get the below problem right for a quite a while sometime.

Given an array of ints, is it possible to choose a group of some of the ints, such that the group sums to the given target, with this additional constraint: if there are numbers in the array that are adjacent and the identical value, they must either all be chosen, or none of them chosen. For example, with the array {1, 2, 2, 2, 5, 2}, either all three 2's in the middle must be chosen or not, all as a group. (one loop can be used to find the extent of the identical values).

  groupSumClump(0, {8, 2, 2, 1}, 9) → true
  groupSumClump(0, {2, 4, 4, 8}, 14) → false

The code is at http://ideone.com/Udk5q

Failing test case scenarios:

 groupSumClump(0, {2, 4, 4, 8}, 14) → false -->NegativeArraySizeException
 groupSumClump(0, {8, 2, 2, 1}, 9) → true false --> X

i have really tried my best to make it work but alas its failing always.
Please Need your help SO experts to resolve this problem
I will be highly obliged and thankful to you,if you can spare a few minutes to look into my problem as well and help me in acheieving the desired solution.

Body:
Method "summate" logic is realy messed up.
It should look something like function "f" here:
Algorithm to find which numbers from a list of size n sum to another number

Quick and dirty fix for your code:

class Demo {
public static void main(String args[]) {
    Demo.groupSumClump(0, new int[] { 2, 4, 4, 8 }, 14);
    Demo.groupSumClump(0, new int[] {8, 2, 2, 1}, 9);
}

public static void groupSumClump(int start, int[] nums, int target) {
    start = 0;

    nums = adjacents(start, nums);

    for (int a_number = 0; a_number < nums.length; a_number++) {
        System.out.println("Array is " + nums[a_number]);
    }
    summate(nums, 0, 0, target);
    System.out.println(false);
}

public static int[] adjacents(int start, int[] nums) {
    int sum = 0;
    for (int i = 0; i < nums.length - 1; i++) {
        if (nums[i] == nums[i + 1]) {
            sum += nums[i] + nums[i + 1];
            nums[i] = sum;
            nums[i + 1] = 0;
        }
    }
    return nums;
}

static void check(int sum, int target) {
    if (sum == target) {
        System.out.println(true);
        System.exit(0);
    }
}

static void summate(int[] numbers, int index, int sum, int target) {
    check(sum, target);
    if (index == numbers.length) {
        return;
    }
    summate(numbers, index + 1, sum + numbers[index], target);
    check(sum, target);
    summate(numbers, index + 1, sum, target);
    check(sum, target);
}
}


问:
SQL MATCH ... AGAINST limits result to current year
I'm stumped by this:

Two commands:

SELECT Date,Sentence FROM exampletable;
```

<pre class="lang-sh prettyprint-override"><code>SELECT Date,Sentence FROM exampletable WHERE MATCH (Sentence) AGAINST ("South" IN NATURAL LANGUAGE MODE );
</code>```

The first gives me results for the entire database, beginning in 2013. I see that there's an entry sometime in 2018 that contains the word "South", so using a match against in the second command I know I should get at least one result pre 2020. However, the first result is from 2020-01-28 onwards.

This happens in all examples I try. Simply adding a match against limits my returned results to > 2020. Is there some database setting that I'm not aware of? Or just something plainly obvious?

Any help would be appreciated! (I'm using MySQL 5.7)

答:
Your query has no order by.  Have you tried something like this?

```<code>SELECT Date, Sentence
FROM exampletable
WHERE MATCH (Sentence) AGAINST ("South" IN NATURAL LANGUAGE MODE )
ORDER BY date;
</code>```

Perhaps the earlier dates are just later in the result set.

Body:
I'm stumped by this:

Two commands:

SELECT Date,Sentence FROM exampletable;

SELECT Date,Sentence FROM exampletable WHERE MATCH (Sentence) AGAINST ("South" IN NATURAL LANGUAGE MODE );

The first gives me results for the entire database, beginning in 2013. I see that there's an entry sometime in 2018 that contains the word "South", so using a match against in the second command I know I should get at least one result pre 2020. However, the first result is from 2020-01-28 onwards.

This happens in all examples I try. Simply adding a match against limits my returned results to > 2020. Is there some database setting that I'm not aware of? Or just something plainly obvious?

Any help would be appreciated! (I'm using MySQL 5.7)

Body:
Your query has no order by.  Have you tried something like this?

SELECT Date, Sentence
FROM exampletable
WHERE MATCH (Sentence) AGAINST ("South" IN NATURAL LANGUAGE MODE )
ORDER BY date;

Perhaps the earlier dates are just later in the result set.


问:
How to hide Tab conditionally in react-navigation?
I want to hide one of my tabs conditionally if user login,

So I have 5 Tabs If user login\register I get a boolean from a redux store,
if this user login i want to how a "Library tab" if not login, i don't want to show this tab "Library" with others and just keep 4 tabs in the App

Code

```<code>import {createAppContainer} from 'react-navigation';
import {createBottomTabNavigator} from 'react-navigation-tabs';

let {isLogin} = store.getState().user;

const TabHome = createBottomTabNavigator(
  {
    Home: {
      screen: Home,
      navigationOptions: {
        tabBarLabel: 'Home',
      },
    },
    Browse: {
      screen: Browse,
      navigationOptions: {
        tabBarLabel: 'Browse',
      },
    },
    Search: {
      screen: Search,
      navigationOptions: {
        tabBarLabel: 'Search',
        headerShown: false,
      },
    },
    Radio: {
      screen: Radio,
      navigationOptions: {
        tabBarLabel: 'Radio',
      },
    },
    Library: isLogin ? (
      {
        screen: YourLibrary,
        navigationOptions: {
          tabBarLabel: 'Library',
        },
      }
    ) : (
      <View /> // Or :null => Not work and got the under error msg
    ),
    // Library: {
    //   screen: YourLibrary,
    // },
  },
)

export default createAppContainer(TabHome);
</code>```

Error: The component for route 'Library' must be a React component.
  For example:

import MyScreen from './MyScreen'; ... Library: MyScreen, }

You can also use a navigator:

import MyNavigator from './MyNavigator'; ... Library: MyNavigator, }

答:
You'd know that you can override the Tabbar Component and add your own logic for it?
Maybe this gives you an Idea about that: https://stackoverflow.com/a/58520533/1256697

Maybe this way, you can set conditional styles to show or hide single items of your TabBar.

Body:
I want to hide one of my tabs conditionally if user login,

So I have 5 Tabs If user login\register I get a boolean from a redux store,
if this user login i want to how a "Library tab" if not login, i don't want to show this tab "Library" with others and just keep 4 tabs in the App

Code

import {createAppContainer} from 'react-navigation';
import {createBottomTabNavigator} from 'react-navigation-tabs';

let {isLogin} = store.getState().user;

const TabHome = createBottomTabNavigator(
  {
    Home: {
      screen: Home,
      navigationOptions: {
        tabBarLabel: 'Home',
      },
    },
    Browse: {
      screen: Browse,
      navigationOptions: {
        tabBarLabel: 'Browse',
      },
    },
    Search: {
      screen: Search,
      navigationOptions: {
        tabBarLabel: 'Search',
        headerShown: false,
      },
    },
    Radio: {
      screen: Radio,
      navigationOptions: {
        tabBarLabel: 'Radio',
      },
    },
    Library: isLogin ? (
      {
        screen: YourLibrary,
        navigationOptions: {
          tabBarLabel: 'Library',
        },
      }
    ) : (
      <View /> // Or :null => Not work and got the under error msg
    ),
    // Library: {
    //   screen: YourLibrary,
    // },
  },
)

export default createAppContainer(TabHome);

Error: The component for route 'Library' must be a React component.
  For example:

import MyScreen from './MyScreen'; ... Library: MyScreen, }

You can also use a navigator:

import MyNavigator from './MyNavigator'; ... Library: MyNavigator, }


问:
Issues Installing pdftotext on MacOS using Anaconda
I am newer to programming and am having trouble installing pdftotext in Anaconda, using Mac OS Mojave 10.14.6 and Python 3.6.7. I have installed all the dependencies recommended (https://github.com/jalan/pdftotext) but have not been able to successfully install pdftotext. </p>

<p>Errors include: </p>

```<code>ERROR: Command errored out with exit status 1:
 command: /anaconda3/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/3_/T/pip-install-ak3q4wz7/pdftotext/setup.py'"'"'; __file__='"'"'/private/var/folders/3_/T/pip-install-ak3q4wz7/pdftotext/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/3_/T/pip-install-ak3q4wz7/pdftotext/pip-egg-info
     cwd: /private/var/folders/3_//T/pip-install-ak3q4wz7/pdftotext/
Complete output (3 lines):
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ModuleNotFoundError: No module named 'setuptools'
----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
</code>```

答:
I ended up using pdftotext from poppler instead of the package listed above. This required the installation of poppler using conda-forge in Anaconda.

For Mac:

```<code>conda create -n envname python=3.7
conda activate envname
conda config --add channels conda-forge
conda install poppler
</code>```

Body:
I am newer to programming and am having trouble installing pdftotext in Anaconda, using Mac OS Mojave 10.14.6 and Python 3.6.7. I have installed all the dependencies recommended (https://github.com/jalan/pdftotext) but have not been able to successfully install pdftotext.

Errors include:

ERROR: Command errored out with exit status 1:
 command: /anaconda3/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/3_/T/pip-install-ak3q4wz7/pdftotext/setup.py'"'"'; __file__='"'"'/private/var/folders/3_/T/pip-install-ak3q4wz7/pdftotext/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/3_/T/pip-install-ak3q4wz7/pdftotext/pip-egg-info
     cwd: /private/var/folders/3_//T/pip-install-ak3q4wz7/pdftotext/
Complete output (3 lines):
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ModuleNotFoundError: No module named 'setuptools'
----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

Body:
I ended up using pdftotext from poppler instead of the package listed above. This required the installation of poppler using conda-forge in Anaconda.

For Mac:

conda create -n envname python=3.7
conda activate envname
conda config --add channels conda-forge
conda install poppler


问:
Ember 3.16 Octane - Component not displaying in Application.hbs
I used ember generate to create a header component for a youtube video I am following. I have a few questions -

When I ran ember generate component header, the terminal responded with creating the header.hbs file in  app>components, but then skips header.js in app/components. I manually created a header.js file in that directory and if I do an alert() in the js file it works.

I have the following code in my header.hbs file.

```<code><h1>Hello There!</h1>

{{yield}}
</code>```

In my application.hbs file :

```<code><Header/>

{{outlet}}
</code>```

thoughts, suggestions? Thank you for any help in advance!

答:
Let me try to explain this a bit. Basically there are 4 kinds of components in ember.

without a .js file:

When you invoke a component ember will first look up the component class. When it does not find such a class the behavior depends on the optional feature template-only-glimmer-components. This is by default enabled for new octane apps.

If it is enabled ember will look up the component template based on some standard rules and use it, but there will be no backing class. That is pretty nice. This is also basically what you get in a octane app when you do ember g component my-component.

When template-only-glimmer-components is disabled then an implicit classic component class will automagically be created and used together with the correct template. You don't want this behavior. If you still have it you can migrate away from it by 1) creating a .js file for every component and then 2) enabling template-only-glimmer-components.

with a .js file

When a js file is found ember will get the default export of that module. Then it will look up the correct component manager. This actually depends on that export: setComponentManager should have been called on it. This is usually done in a base class as @ember/component or @glimmer/component.
But you can also write your own custom component manager.

Basically ember will then also look up the template based on that component. A public API for this is proposed in this RFC, but currently a private API is used for the so called template co-location where you place your .hbs file next to your .js file with the same name and just a different extension. This is the default in octant. Here a ember internal build-step in ember-cli basically adds your template to the .js file and uses that API. You can also see the result in a browser debugger. So when there is no default export then ember can not find your template.

Body:
I used ember generate to create a header component for a youtube video I am following. I have a few questions -

When I ran ember generate component header, the terminal responded with creating the header.hbs file in  app>components, but then skips header.js in app/components. I manually created a header.js file in that directory and if I do an alert() in the js file it works.

I have the following code in my header.hbs file.

Hello There!

{{yield}}

In my application.hbs file :

{{outlet}}

thoughts, suggestions? Thank you for any help in advance!