问:
Visual Studio 2019 Stopped Pushing to Git
I have VS Community 2019 and everything was working fine with my Git repo on Azure DevOps.  However VS updated this morning and now for some reason it won't push to Git.  It seems like that must be the issue because that's the only thing that changed since the last time I pushed.  Now when I try to push my commits I get this:

```<code>> Pushing develop Error encountered while pushing to the remote
> repository: Git failed with a fatal error. unable to access
> '<<my repo>>':
> error setting certificate verify locations:   CAfile: c:/program files
> (x86)/microsoft visual
> studio/2019/community/common7/ide/commonextensions/microsoft/teamfoundation/team
> explorer/Git/mingw32/bin/curl-ca-bundle.crt   CApath: none Pushing to
> <<my repo>>
</code>```

The really odd part is if I just do a git bash at the repo directory and use git push it works...

How can I fix this?

答:
I faced the same issue in Visual Studio 2022, but Git started functioning normally, after I re-reinstalled Git in my machine (leaving link below). For me, the path displayed in error did not exist and when I opened the path C:/Program Files/Git, it was empty. This was happening after I uninstalled Git in my machine, so that prompted me to re-install it.

Link for git download: https://git-scm.com/download/win

Body:
I have VS Community 2019 and everything was working fine with my Git repo on Azure DevOps.  However VS updated this morning and now for some reason it won't push to Git.  It seems like that must be the issue because that's the only thing that changed since the last time I pushed.  Now when I try to push my commits I get this:

> Pushing develop Error encountered while pushing to the remote
> repository: Git failed with a fatal error. unable to access
> '<<my repo>>':
> error setting certificate verify locations:   CAfile: c:/program files
> (x86)/microsoft visual
> studio/2019/community/common7/ide/commonextensions/microsoft/teamfoundation/team
> explorer/Git/mingw32/bin/curl-ca-bundle.crt   CApath: none Pushing to
> <<my repo>>

The really odd part is if I just do a git bash at the repo directory and use git push it works...

How can I fix this?


来源: stackexchange

问:
How to validate date as characters are entered in js
There is an input where the user must enter a date in the format dd.mm.yyyy., And I need to check that he does not write letters and other unnecessary characters. The Internet is full of examples for a ready-made date, in my case it is necessary to check as you enter. For example, the user pressed the key 2 - it appeared in the input, pressed z - nothing changed in the input. Pressed 3 - ok, pressed / - nothing has changed. I tried to write a regular expression,

```<code>((0[1-9]{0,1})|([1-2][0-9]{0,1})|(3[0-1]{0,1}))\.{ 0.1}
</code>```

but I can't figure out how to check the data after the dot. Need your advice.

Here is a small example

答:
Just updated you tags on question, as your linked example was using React, and how you do this in plain JS would be slightly different.

Rather than regEx, a slightly easier option might be to use lookups, you could then check what valid chars are available at each char position.

Below is an example.

ps. It won't catch everything, eg. 31 days in Feb, & 29/28 for leap years etc.  So ideally you should check again after date fully entered.

const {useState} = React;

const anynum = '01234567890';
const num01 = '01';
const num31 = '0123';
const dot = '.';

const posValid = [
  num31,    //3
  anynum,   //1
  dot,      //.
  num01,    //1
  anynum,   //2
  dot,      //.
  anynum,   //2
  anynum,   //0
  anynum,   //2
  anynum    //2
]

function partsValid(s) {
  if (s.length > posValid.length) return false;
  //simple num check at pos
  for (let l = 0; l < s.length; l += 1) {
    const c = s[l];
    if (!posValid[l].includes(c)) return false;
  }
  //check day
  if (s.length > 1) {
    const day = parseInt(s.slice(0, 2), 10);
    if (!(day >= 1 && day <= 31)) return false;
  }
  //check month
  if (s.length > 4) {
    const month = parseInt(s.slice(3, 5), 10);
    if (!(month >= 1 && month <= 12)) return false;
  }
  return true;
}

function App() {
  const [value, setValue] = useState("");
  const onchange = (e) => {
    const nv = e.target.value;
    if (partsValid(nv)) setValue(nv);
  };
  return (

      <input onChange={onchange} value={value} placeholder="dd.mm.yyyy" />

  );
}

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

<div id="mount"></div></code>```

ContentLicense: CC BY-SA 4.0

Body:
There is an input where the user must enter a date in the format dd.mm.yyyy., And I need to check that he does not write letters and other unnecessary characters. The Internet is full of examples for a ready-made date, in my case it is necessary to check as you enter. For example, the user pressed the key 2 - it appeared in the input, pressed z - nothing changed in the input. Pressed 3 - ok, pressed / - nothing has changed. I tried to write a regular expression,

((0[1-9]{0,1})|([1-2][0-9]{0,1})|(3[0-1]{0,1}))\.{ 0.1}

but I can't figure out how to check the data after the dot. Need your advice.

Here is a small example

Body:
Just updated you tags on question, as your linked example was using React, and how you do this in plain JS would be slightly different.

Rather than regEx, a slightly easier option might be to use lookups, you could then check what valid chars are available at each char position.

Below is an example.

ps. It won't catch everything, eg. 31 days in Feb, & 29/28 for leap years etc.  So ideally you should check again after date fully entered.

const {useState} = React;

const anynum = '01234567890';
const num01 = '01';
const num31 = '0123';
const dot = '.';

const posValid = [
  num31,    //3
  anynum,   //1
  dot,      //.
  num01,    //1
  anynum,   //2
  dot,      //.
  anynum,   //2
  anynum,   //0
  anynum,   //2
  anynum    //2
]

function partsValid(s) {
  if (s.length > posValid.length) return false;
  //simple num check at pos
  for (let l = 0; l < s.length; l += 1) {
    const c = s[l];
    if (!posValid[l].includes(c)) return false;
  }
  //check day
  if (s.length > 1) {
    const day = parseInt(s.slice(0, 2), 10);
    if (!(day >= 1 && day <= 31)) return false;
  }
  //check month
  if (s.length > 4) {
    const month = parseInt(s.slice(3, 5), 10);
    if (!(month >= 1 && month <= 12)) return false;
  }
  return true;
}

function App() {
  const [value, setValue] = useState("");
  const onchange = (e) => {
    const nv = e.target.value;
    if (partsValid(nv)) setValue(nv);
  };
  return (
    <div>
      <input onChange={onchange} value={value} placeholder="dd.mm.yyyy" />
    </div>
  );
}

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

<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

<div id="mount"></div>


问:
SmtpException: Unable to read data from the transport connection: net_io_connectionclosed
I am using the SmtpClient library to send emails using the following:

```<code>SmtpClient client = new SmtpClient();
client.Host = "hostname";
client.Port = 465;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.EnableSsl = true;
client.Credentials = new NetworkCredential("User", "Pass);
client.Send("from@hostname", "to@hostname", "Subject", "Body");
</code>```

The code works fine in my test environment, but when I use production SMTP servers, the code fails with an SmtpException "Failure sending mail." with an inner IOException "Unable to read data from the transport connection: net_io_connectionclosed".

I've confirmed that firewalls are not an issue. The port opens just fine between the client and the server. I'm not sure what else could throw this error.

答:
Putting this at the beginning of my method fixed this for me</p>
```<code>System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using the SmtpClient library to send emails using the following:

SmtpClient client = new SmtpClient();
client.Host = "hostname";
client.Port = 465;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.EnableSsl = true;
client.Credentials = new NetworkCredential("User", "Pass);
client.Send("from@hostname", "to@hostname", "Subject", "Body");

The code works fine in my test environment, but when I use production SMTP servers, the code fails with an SmtpException "Failure sending mail." with an inner IOException "Unable to read data from the transport connection: net_io_connectionclosed".

I've confirmed that firewalls are not an issue. The port opens just fine between the client and the server. I'm not sure what else could throw this error.

Body:
Putting this at the beginning of my method fixed this for me

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12


问:
MYSQL ERROR 1248 (42000): Every derived table must have its own alias
I cant for the life of me figure out why this is erroring</p>

```<code>SELECT * FROM
SELECT
c.city_id,
p.prop_ynow_id,
p.propertyid,
p.prop_add_value,
p.name,
picture,
ifnull(p.address,'') as`location`,
ifnull(city,'')as`city`,
ifnull(ShortCut,'') as `state`,
ifnull(p.zip,'') as `zip`,
min(if(pr.minrent = 0,99999999,pr.minrent)) as minrent,
max(pr.maxrent) as maxrent,
'' as service,
hood_id,
ifnull(p.phone,'') as `phone`,
latitude,
longitude,
min(CAST(pu.fullBath AS UNSIGNED)) as`minbath`,
max(CAST(pu.fullBath AS UNSIGNED)) as`maxbath`,
min(CAST(pu.Bed AS UNSIGNED)) as`minbed` ,
max(CAST(pu.Bed AS UNSIGNED)) as`maxbed`,
'' as url,
'' as source_id,
'' as source_name,
'' as addresscode,
'' as citycode,
'' as ctime,
'' as paid,
'' as similar_url,
'' as created_at,
'' as updated_at,
'' as city_name,
'' as service_listing_id

FROM
wiki_city_list c join propertyinfo p on c.city_id=p.city
join ynow_rentwiki.Property_Unitlayout pu on p.prop_ynow_id=pu.P_Ident
join (SELECT CAST(substring_index(if(Rent >0 ,Rent,RentLow),'.',1) AS UNSIGNED) as minrent, CAST(substring_index(if(Rent >0,Rent,Renthigh),'.',1) AS UNSIGNED) as maxrent,PRE_Ident,P_Ident,UNL_Ident,RTY_Ident from ynow_rentwiki.Property_rents where P_Ident in (3958, 4576, 4577) and (Rent!='' or (Rentlow!='' and Renthigh!='')) )  as pr on pu.UNL_Ident=pr.UNL_Ident
join state s on (p.state = s.stateid OR p.state = s.ShortCut )
WHERE
pu.Status='Active'
and p.delete_date='0000-00-00'

GROUP BY
c.city_id, p.prop_ynow_id

UNION
SELECT
c.city_id,
p.prop_ynow_id,
p.propertyid,
p.prop_add_value,
p.name,
picture,
ifnull(p.address,'') as`location`,
ifnull(city,'')as`city`,
ifnull(ShortCut,'') as `state`,
ifnull(p.zip,'') as `zip`,
min(if(pr.minrent = 0,99999999,pr.minrent)) as minrent,
max(pr.maxrent) as maxrent,
'' as service,
hood_id,
ifnull(p.phone,'') as `phone`,
latitude,
longitude,
min(CAST(pu.fullBath AS UNSIGNED)) as`minbath`,
max(CAST(pu.fullBath AS UNSIGNED)) as`maxbath`,
min(CAST(pu.Bed AS UNSIGNED)) as`minbed` ,
max(CAST(pu.Bed AS UNSIGNED)) as`maxbed`,
'' as url,
'' as source_id,
'' as source_name,
'' as addresscode,
'' as citycode,
'' as ctime,
'' as paid,
'' as similar_url,
'' as created_at,
'' as updated_at,
'' as city_name,
'' as service_listing_id

FROM
wiki_city_list c join propertyinfo p on c.city_id=p.city
join ynow_rentwiki.Property_Unitlayout pu on p.prop_ynow_id=pu.P_Ident
join (SELECT CAST(substring_index(if(Rent >0 ,Rent,RentLow),'.',1) AS UNSIGNED) as minrent, CAST(substring_index(if(Rent >0,Rent,Renthigh),'.',1) AS UNSIGNED) as maxrent,PRE_Ident,P_Ident,UNL_Ident,RTY_Ident from ynow_rentwiki.Property_rents where P_Ident in (9744) and (Rent!='' or (Rentlow!='' and Renthigh!='')) )  as pr on pu.UNL_Ident=pr.UNL_Ident
join state s on (p.state = s.stateid OR p.state = s.ShortCut )
WHERE
pu.Status='Active'
and p.delete_date='0000-00-00'

GROUP BY
c.city_id, p.prop_ynow_id

UNION
SELECT
'' as prop_ynow_id,
id as propertyid,
0 as prop_add_value,
t.name as name,
'' as picture,
t.address as location,
t.city as city,
s.ShortCut as state,
t.zip as zip,
CAST(REPLACE(REPLACE(t.price,'$',''),',','') as UNSIGNED) as minrent,
'' as maxrent,
t.service as service,
'' as hood_id,
'' as phone,
t.latitude as latitude,
t.longitude as longitude,
t.bathrooms as minbath,
'' as maxbath,
t.bedrooms as minbed,
'' as maxbed,
t.url as url,
t.source_id as source_id,
t.source_name as source_name,
t.addresscode as addresscode,
t.citycode as citycode,
t.ctime as ctime,
t.paid as paid,
t.similar_url as similar_url,
t.created_at as created_at,
t.updated_at as updated_at,
SUBSTRING_INDEX(c.city_name,'_',1) as city_name,
t.service_listing_id as service_listing_id

FROM LBCPrimary.third_party_properties as t, LBCPrimary.wiki_city_list as c, LBCPrimary.state as s
WHERE
t.city in ( '230' )
and
address <> '' and
t.city = c.city_id and
c.city_state = s.stateid

order by t.ctime
desc
limit 46 as a limit 0,50
</code>```

答:
SELECT h. hacker_id,
h. name,
COUNT (c. challenge_id) AS total
FROM hackers h,
challenges c
WHERE h.hacker_id,
h. name
HAVING COUNT (c. challenge_id) IN (SELECT MAX (total)
FROM (SELECT COUNT () AS total FROM challenge GROUP BY hacker_id))
OR COUNT (c. challenge_id) IN
(SELECT total
FROM
(SELECT COUNT () AS total
FROM challenges
GROUP BY hacker_id)
GROUP BY total
HAVING COUNT (total)=1)
ORDER BY COUNT (c. challenge_id) DESC, h. hacker_id;

ContentLicense: CC BY-SA 2.5

Body:
I cant for the life of me figure out why this is erroring

SELECT * FROM
SELECT
c.city_id,
p.prop_ynow_id,
p.propertyid,
p.prop_add_value,
p.name,
picture,
ifnull(p.address,'') as`location`,
ifnull(city,'')as`city`,
ifnull(ShortCut,'') as `state`,
ifnull(p.zip,'') as `zip`,
min(if(pr.minrent = 0,99999999,pr.minrent)) as minrent,
max(pr.maxrent) as maxrent,
'' as service,
hood_id,
ifnull(p.phone,'') as `phone`,
latitude,
longitude,
min(CAST(pu.fullBath AS UNSIGNED)) as`minbath`,
max(CAST(pu.fullBath AS UNSIGNED)) as`maxbath`,
min(CAST(pu.Bed AS UNSIGNED)) as`minbed` ,
max(CAST(pu.Bed AS UNSIGNED)) as`maxbed`,
'' as url,
'' as source_id,
'' as source_name,
'' as addresscode,
'' as citycode,
'' as ctime,
'' as paid,
'' as similar_url,
'' as created_at,
'' as updated_at,
'' as city_name,
'' as service_listing_id

FROM
wiki_city_list c join propertyinfo p on c.city_id=p.city
join ynow_rentwiki.Property_Unitlayout pu on p.prop_ynow_id=pu.P_Ident
join (SELECT CAST(substring_index(if(Rent >0 ,Rent,RentLow),'.',1) AS UNSIGNED) as minrent, CAST(substring_index(if(Rent >0,Rent,Renthigh),'.',1) AS UNSIGNED) as maxrent,PRE_Ident,P_Ident,UNL_Ident,RTY_Ident from ynow_rentwiki.Property_rents where P_Ident in (3958, 4576, 4577) and (Rent!='' or (Rentlow!='' and Renthigh!='')) )  as pr on pu.UNL_Ident=pr.UNL_Ident
join state s on (p.state = s.stateid OR p.state = s.ShortCut )
WHERE
pu.Status='Active'
and p.delete_date='0000-00-00'

GROUP BY
c.city_id, p.prop_ynow_id

UNION
SELECT
c.city_id,
p.prop_ynow_id,
p.propertyid,
p.prop_add_value,
p.name,
picture,
ifnull(p.address,'') as`location`,
ifnull(city,'')as`city`,
ifnull(ShortCut,'') as `state`,
ifnull(p.zip,'') as `zip`,
min(if(pr.minrent = 0,99999999,pr.minrent)) as minrent,
max(pr.maxrent) as maxrent,
'' as service,
hood_id,
ifnull(p.phone,'') as `phone`,
latitude,
longitude,
min(CAST(pu.fullBath AS UNSIGNED)) as`minbath`,
max(CAST(pu.fullBath AS UNSIGNED)) as`maxbath`,
min(CAST(pu.Bed AS UNSIGNED)) as`minbed` ,
max(CAST(pu.Bed AS UNSIGNED)) as`maxbed`,
'' as url,
'' as source_id,
'' as source_name,
'' as addresscode,
'' as citycode,
'' as ctime,
'' as paid,
'' as similar_url,
'' as created_at,
'' as updated_at,
'' as city_name,
'' as service_listing_id

FROM
wiki_city_list c join propertyinfo p on c.city_id=p.city
join ynow_rentwiki.Property_Unitlayout pu on p.prop_ynow_id=pu.P_Ident
join (SELECT CAST(substring_index(if(Rent >0 ,Rent,RentLow),'.',1) AS UNSIGNED) as minrent, CAST(substring_index(if(Rent >0,Rent,Renthigh),'.',1) AS UNSIGNED) as maxrent,PRE_Ident,P_Ident,UNL_Ident,RTY_Ident from ynow_rentwiki.Property_rents where P_Ident in (9744) and (Rent!='' or (Rentlow!='' and Renthigh!='')) )  as pr on pu.UNL_Ident=pr.UNL_Ident
join state s on (p.state = s.stateid OR p.state = s.ShortCut )
WHERE
pu.Status='Active'
and p.delete_date='0000-00-00'

GROUP BY
c.city_id, p.prop_ynow_id

UNION
SELECT
'' as prop_ynow_id,
id as propertyid,
0 as prop_add_value,
t.name as name,
'' as picture,
t.address as location,
t.city as city,
s.ShortCut as state,
t.zip as zip,
CAST(REPLACE(REPLACE(t.price,'$',''),',','') as UNSIGNED) as minrent,
'' as maxrent,
t.service as service,
'' as hood_id,
'' as phone,
t.latitude as latitude,
t.longitude as longitude,
t.bathrooms as minbath,
'' as maxbath,
t.bedrooms as minbed,
'' as maxbed,
t.url as url,
t.source_id as source_id,
t.source_name as source_name,
t.addresscode as addresscode,
t.citycode as citycode,
t.ctime as ctime,
t.paid as paid,
t.similar_url as similar_url,
t.created_at as created_at,
t.updated_at as updated_at,
SUBSTRING_INDEX(c.city_name,'_',1) as city_name,
t.service_listing_id as service_listing_id

FROM LBCPrimary.third_party_properties as t, LBCPrimary.wiki_city_list as c, LBCPrimary.state as s
WHERE
t.city in ( '230' )
and
address <> '' and
t.city = c.city_id and
c.city_state = s.stateid

order by t.ctime
desc
limit 46 as a limit 0,50


问:
Is there R syntax to delete rows with specific, multiple NAs in columns?
Hello coding community,

If my data frame looks like:

```<code>ID     Col1 Col2 Col3 Col4
Per1   1    2    3    4
Per2   2    NA   NA   NA
Per3   NA   NA   5    NA
</code>```

Is there any syntax to delete the row associated with ID = Per2, on the basis that Col2, Col3, AND Col4 = NA? I am hoping for code that will allow me to delete a row on the basis that three specific columns (Col2, Col3, and Col4) ALL are NA. This code would NOT delete the row ID = Per3, even though there are three NAs.

Please note that I know how to delete a specific row, but my data frame is big so I do not want to manually sort through all rows/columns.

Big thanks!

答:
You can use if_all

library(dplyr)
filter(df, !if_all(c(Col2, Col3, Col4), ~ is.na(.)))

#     ID Col1 Col2 Col3 Col4
# 1 Per1    1    2    3    4
# 2 Per3   NA   NA    5   NA
```
<p><strong>data</strong></p>
<pre class="lang-r prettyprint-override"><code>df <- structure(list(ID = c("Per1", "Per2", "Per3"), Col1 = c(1L, 2L,
NA), Col2 = c(2L, NA, NA), Col3 = c(3L, NA, 5L), Col4 = c(4L,
NA, NA)), class = "data.frame", row.names = c(NA, -3L))
</code>```

Body:
Hello coding community,

If my data frame looks like:

ID     Col1 Col2 Col3 Col4
Per1   1    2    3    4
Per2   2    NA   NA   NA
Per3   NA   NA   5    NA

Is there any syntax to delete the row associated with ID = Per2, on the basis that Col2, Col3, AND Col4 = NA? I am hoping for code that will allow me to delete a row on the basis that three specific columns (Col2, Col3, and Col4) ALL are NA. This code would NOT delete the row ID = Per3, even though there are three NAs.

Please note that I know how to delete a specific row, but my data frame is big so I do not want to manually sort through all rows/columns.

Big thanks!

Body:
You can use if_all

library(dplyr)
filter(df, !if_all(c(Col2, Col3, Col4), ~ is.na(.)))

#     ID Col1 Col2 Col3 Col4
# 1 Per1    1    2    3    4
# 2 Per3   NA   NA    5   NA

data

df <- structure(list(ID = c("Per1", "Per2", "Per3"), Col1 = c(1L, 2L,
NA), Col2 = c(2L, NA, NA), Col3 = c(3L, NA, 5L), Col4 = c(4L,
NA, NA)), class = "data.frame", row.names = c(NA, -3L))


问:
Turtle graphics - framerate?
Using Turtle Graphics and Python -- I have a group of 10 basic graphic elements on the screen at the same time and it runs sluggish.  As soon as some of the elements "leave" the graphic window, it speeds up considerably.  Is there a way to maintain the same frame-rate, regardless of the number of graphic elements?</p>

答:
You should say:

```<code>screen = turtle.Screen()
screen.tracer("I recommend you do 0") # Make sure you do this at the beginning.
</code>```

By using screen.tracer() you can control the frame rate

Title: Turtle graphics - framerate?

Body:
You should say:

screen = turtle.Screen()
screen.tracer("I recommend you do 0") # Make sure you do this at the beginning.

By using screen.tracer() you can control the frame rate


问:
How to view on delete / on update constraints?
I have some tables in a PostgreSQL database, and they have foreign keys with constraints on them (e.g. add constraint "table_column_fkey" foreign key ("otherTableId") references public."otherTable"(id) on delete cascade on update cascade).
Some may have on delete no action, some on delete cascade, others on delete set null.

How do I view for a specific constraint what it's on delete or on update set to?

答:
You can find out within the PostgreSQL catalog (eg information_schema):

```<code>SELECT
    constraint_schema,
    constraint_name,
    unique_constraint_name,
    update_rule,
    delete_rule
FROM
    information_schema.referential_constraints rc

</code>```

Body:
You can find out within the PostgreSQL catalog (eg information_schema):

SELECT
    constraint_schema,
    constraint_name,
    unique_constraint_name,
    update_rule,
    delete_rule
FROM
    information_schema.referential_constraints rc


问:
C# .NET StreamWriter: How to skip lines when writing file using StreamWriter?
I read in a text file using StreamReader.
I want to write out this same text file EXCEPT its first 4 lines and its last 6 lines.

How do I do this? Thanks.

答:
Doesn't appear to be the shortest way... but it works for me... Hope it provides some insight.</p>

```<code>        System.IO.StreamReader input = new System.IO.StreamReader(@"originalFile.txt");
        System.IO.StreamWriter output = new System.IO.StreamWriter(@"outputFile.txt");

        String[] allLines = input.ReadToEnd().Split("\n".ToCharArray());

        int numOfLines = allLines.Length;
        int lastLineWeWant = numOfLines - (6);                  //The last index we want.

        for (int x = 0; x < numOfLines; x++)
        {
            if (x > 4 - 1 && x < lastLineWeWant)  //Index has to be greater than num to skip @ start and below the total length - num to skip at end.
            {
                output.WriteLine(allLines[x].Trim());  //Trim to remove any \r characters.
            }
        }

        input.Close();
        output.Close();
</code>```

Body:
Doesn't appear to be the shortest way... but it works for me... Hope it provides some insight.

        System.IO.StreamReader input = new System.IO.StreamReader(@"originalFile.txt");
        System.IO.StreamWriter output = new System.IO.StreamWriter(@"outputFile.txt");

        String[] allLines = input.ReadToEnd().Split("\n".ToCharArray());

        int numOfLines = allLines.Length;
        int lastLineWeWant = numOfLines - (6);                  //The last index we want.

        for (int x = 0; x < numOfLines; x++)
        {
            if (x > 4 - 1 && x < lastLineWeWant)  //Index has to be greater than num to skip @ start and below the total length - num to skip at end.
            {
                output.WriteLine(allLines[x].Trim());  //Trim to remove any \r characters.
            }
        }

        input.Close();
        output.Close();


问:
What are all possible permissions taken by apps?
There are two types of app permissions in case of android apps

Install time permissions- apps take permission while being installed (run at startup, install shortcuts, run in background etc.)

Run time permissions- Users give permission to the app (gallery, camera, contacts etc.)

Can you please give me the separate lists of all the permissions?
Also, how to know which permissions are taken by an app?

答: For permission list go through this page do some digging you will find required info</p>


问:
how to focus input element when page renders in React
```<code>export const InputComponent = () => {
  const inputRef = useRef<HTMLInputElement | undefined>();

  useEffect(() => {
    inputRef.current.focus();
  }, [inputRef]);

  return(<input type="text" ref={inputRef})
}
</code>```

whats wrong in my code. Please help me.

答:
```<code>

export const InputComponent = () => {
  const inputRef = useRef<HTMLInputElement | undefined>(null);

  useEffect(() => {
    inputRef.current.focus();
  }, [inputRef]);

  return(<input type="text" ref={inputRef})
}
</code>```

Try using this code .
check this codesandbox

Body:
export const InputComponent = () => {
  const inputRef = useRef<HTMLInputElement | undefined>();

  useEffect(() => {
    inputRef.current.focus();
  }, [inputRef]);

  return(<input type="text" ref={inputRef})
}

whats wrong in my code. Please help me.

Body:
export const InputComponent = () => {
  const inputRef = useRef<HTMLInputElement | undefined>(null);

  useEffect(() => {
    inputRef.current.focus();
  }, [inputRef]);

  return(<input type="text" ref={inputRef})
}

Try using this code .
check this codesandbox


问:
How do I add two numbers and them multiply it with the 3rd number and show the total in a disabled input in a html form with javascript?
```<code>This is the html code:
</code>```

the id's are : num1, num2, num3 and the total input is "total"
I want the calc function to be (num1+num2)*num3

```<code><div class="row">
    <div class="col">
    <label> Tarif Colet</label>
      <input type="num1" onfocus="calculare()" onkeyup="calculare()" onclick="calculare()" onblur="calculare()"  value="0" id="tarifcolet" id="num1"  class="form-control" placeholder="Tarif Colet">

    </div>
<div class="col">
      <label>Alte Taxe</label>
      <input type="num2" value="0" onfocus="calculare()" onkeyup="calculare()" onclick="calculare()" onblur="calculare()" id="num2"  class="form-control" placeholder="Alte Taxe">
    </div>
<div class="col">
    <label>Tva</label>
      <input type="percent" name="num3" id="num3" value="19%"  class="form-control" placeholder="TVA">
</div>
    <div class="col">
    <label>Total</label>
      <input type="number" name="total" disabled="disabled" id="total" class="form-control" placeholder="total">
    </div>
</code>```

答:
Use return method.

```<code>function myFunction(a, b, c) {
 return (a+b)*c;
}
</code>```

And then add in a button onclick event (you can use in other events too).

```<code><div class="row">
    <div class="col">
    <label> Tarif Colet</label>
      <input type="num1" onfocus="calculare()" onkeyup="calculare()" onclick="calculare()" onblur="calculare()"  value="0" id="tarifcolet" id="num1"  class="form-control" placeholder="Tarif Colet">

    </div>
<div class="col">
      <label>Alte Taxe</label>
      <input type="num2" value="0" onfocus="calculare()" onkeyup="calculare()" onclick="calculare()" onblur="calculare()" id="num2"  class="form-control" placeholder="Alte Taxe">
    </div>
<div class="col">
    <label>Tva</label>
      <input type="percent" name="num3" id="num3" value="19%"  class="form-control" placeholder="TVA">
</div>
    <div class="col">
    <label>Total</label>
      <input type="number" name="total" disabled="disabled" id="total" class="form-control" placeholder="total">
    </div>
<button type="button" onclick="getValue() ">
</code>```
```<code>function getValue(){
 var num1 = document.getElementById("num1").value;
var num2 = document.getElementById("num2").value;
var num3 = document.getElementById("num3").value;
var displayResult = document.getElementById("total");
var result = myFunction(num1, num2, num3);

displayResult.value = result;
}
</code>```

I hope this works

Body:
This is the html code:

the id's are : num1, num2, num3 and the total input is "total"
I want the calc function to be (num1+num2)*num3

     Tarif Colet
      <input type="num1" onfocus="calculare()" onkeyup="calculare()" onclick="calculare()" onblur="calculare()"  value="0" id="tarifcolet" id="num1"  class="form-control" placeholder="Tarif Colet">

      Alte Taxe
      <input type="num2" value="0" onfocus="calculare()" onkeyup="calculare()" onclick="calculare()" onblur="calculare()" id="num2"  class="form-control" placeholder="Alte Taxe">

    Tva
      <input type="percent" name="num3" id="num3" value="19%"  class="form-control" placeholder="TVA">

    Total
      <input type="number" name="total" disabled="disabled" id="total" class="form-control" placeholder="total">

Body:
Use return method.

function myFunction(a, b, c) {
 return (a+b)*c;
}

And then add in a button onclick event (you can use in other events too).

<div class="row">
    <div class="col">
    <label> Tarif Colet</label>
      <input type="num1" onfocus="calculare()" onkeyup="calculare()" onclick="calculare()" onblur="calculare()"  value="0" id="tarifcolet" id="num1"  class="form-control" placeholder="Tarif Colet">

    </div>
<div class="col">
      <label>Alte Taxe</label>
      <input type="num2" value="0" onfocus="calculare()" onkeyup="calculare()" onclick="calculare()" onblur="calculare()" id="num2"  class="form-control" placeholder="Alte Taxe">
    </div>
<div class="col">
    <label>Tva</label>
      <input type="percent" name="num3" id="num3" value="19%"  class="form-control" placeholder="TVA">
</div>
    <div class="col">
    <label>Total</label>
      <input type="number" name="total" disabled="disabled" id="total" class="form-control" placeholder="total">
    </div>
<button type="button" onclick="getValue() ">

function getValue(){
 var num1 = document.getElementById("num1").value;
var num2 = document.getElementById("num2").value;
var num3 = document.getElementById("num3").value;
var displayResult = document.getElementById("total");
var result = myFunction(num1, num2, num3);

displayResult.value = result;
}

I hope this works


问:
How do I download a file with Angular2 or greater
I have a WebApi / MVC app for which I am developing an angular2 client (to replace MVC). I am having some troubles understanding how Angular saves a file.

The request is ok (works fine with MVC, and we can log the data received) but I can't figure out how to save the downloaded data (I am mostly following the same logic as in this post). I am sure it is stupidly simple, but so far I am simply not grasping it.

The code of the component function is below. I've tried different alternatives, the blob way should be the way to go as far as I understood, but there is no function createObjectURL in URL. I can't even find the definition of URL in window, but apparently it exists. If I use the FileSaver.js module I get the same error. So I guess this is something that changed recently or is not yet implemented. How can I trigger the file save in A2?

downloadfile(type: string){

    let thefile = {};
    this.pservice.downloadfile(this.rundata.name, type)
        .subscribe(data => thefile = new Blob([data], { type: "application/octet-stream" }), //console.log(data),
                    error => console.log("Error downloading the file."),
                    () => console.log('Completed file download.'));

    let url = window.URL.createObjectURL(thefile);
    window.open(url);
}
```

<p>For the sake of completeness, the service that fetches the data is below, but the only thing it does is to issue the request and pass on the data without mapping if it succeeds:</p>

<pre class="lang-typescript prettyprint-override"><code>downloadfile(runname: string, type: string){
   return this.authHttp.get( this.files_api + this.title +"/"+ runname + "/?file="+ type)
            .catch(this.logAndPassOn);
}
</code>```

答:
Although the question is old, none of the answers are that viable.
As far as I saw all the files are first loaded in memory and saved after that.
This way we:

Cause a lag, for which a custom loading must be implemented.

Load the file in memory, which means for big files the browser will crash.

Do not use the implemented browser download function.

The front end side is simple enough (Angular 12):

```<code>downloadFile(url: string, fileName: string): void {
   const downloadLink = document.createElement('a');
   downloadLink.download = fileName;
   downloadLink.href = url;
   downloadLink.click();
}
</code>```

On the back end (.NET 6) we need to work with streams and write to the response body:

```<code>public void Get(string fileId)
{
    var fileName = fileService.GetFileName(fileId);
    var fileContentType = fileService.GetFileContentType(fileId);
    this.Response.Headers.Add(HeaderNames.ContentType, fileContentType);
    this.Response.Headers.Add(HeaderNames.ContentDisposition, $"attachment; filename=\"{fileName}\"");
    fileService.GetFile(Response.Body, fileId);
}
</code>```

File content type and name can be retrieved from either the DB (if you save file info in there) or the file system.
Content type is parsed from the extension.

I write to the stream like this:

```<code>public void GetFile(Stream writeStream, string fileId)
{
    var file = GetFileInfo(fileId);
    try
    {
        var fileStream = File.OpenRead(file.FullName);
        byte[] buffer = new byte[32768];
        int read;
        while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            writeStream.Write(buffer, 0, read);
        }
        writeStream.Flush();
    }
    catch (Exception e)
    {
        throw new CustomException($"Error occured while reading the file. Inner Exception Message: ({e.Message}) Stack Trace: ({e.StackTrace})", ErrorCode.FileReadFailure, e);
    }
}
</code>```

Keep in mind I have simplified my implementation for presentation purposes, so it has not been tested.

Body:
I have a WebApi / MVC app for which I am developing an angular2 client (to replace MVC). I am having some troubles understanding how Angular saves a file.

The request is ok (works fine with MVC, and we can log the data received) but I can't figure out how to save the downloaded data (I am mostly following the same logic as in this post). I am sure it is stupidly simple, but so far I am simply not grasping it.

The code of the component function is below. I've tried different alternatives, the blob way should be the way to go as far as I understood, but there is no function createObjectURL in URL. I can't even find the definition of URL in window, but apparently it exists. If I use the FileSaver.js module I get the same error. So I guess this is something that changed recently or is not yet implemented. How can I trigger the file save in A2?

downloadfile(type: string){

    let thefile = {};
    this.pservice.downloadfile(this.rundata.name, type)
        .subscribe(data => thefile = new Blob([data], { type: "application/octet-stream" }), //console.log(data),
                    error => console.log("Error downloading the file."),
                    () => console.log('Completed file download.'));

    let url = window.URL.createObjectURL(thefile);
    window.open(url);
}

For the sake of completeness, the service that fetches the data is below, but the only thing it does is to issue the request and pass on the data without mapping if it succeeds:

downloadfile(runname: string, type: string){
   return this.authHttp.get( this.files_api + this.title +"/"+ runname + "/?file="+ type)
            .catch(this.logAndPassOn);
}

Body:
Although the question is old, none of the answers are that viable.
As far as I saw all the files are first loaded in memory and saved after that.
This way we:

Cause a lag, for which a custom loading must be implemented.

Load the file in memory, which means for big files the browser will crash.

Do not use the implemented browser download function.

The front end side is simple enough (Angular 12):

downloadFile(url: string, fileName: string): void {
   const downloadLink = document.createElement('a');
   downloadLink.download = fileName;
   downloadLink.href = url;
   downloadLink.click();
}

On the back end (.NET 6) we need to work with streams and write to the response body:

public void Get(string fileId)
{
    var fileName = fileService.GetFileName(fileId);
    var fileContentType = fileService.GetFileContentType(fileId);
    this.Response.Headers.Add(HeaderNames.ContentType, fileContentType);
    this.Response.Headers.Add(HeaderNames.ContentDisposition, $"attachment; filename=\"{fileName}\"");
    fileService.GetFile(Response.Body, fileId);
}

File content type and name can be retrieved from either the DB (if you save file info in there) or the file system.
Content type is parsed from the extension.

I write to the stream like this:

public void GetFile(Stream writeStream, string fileId)
{
    var file = GetFileInfo(fileId);
    try
    {
        var fileStream = File.OpenRead(file.FullName);
        byte[] buffer = new byte[32768];
        int read;
        while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            writeStream.Write(buffer, 0, read);
        }
        writeStream.Flush();
    }
    catch (Exception e)
    {
        throw new CustomException($"Error occured while reading the file. Inner Exception Message: ({e.Message}) Stack Trace: ({e.StackTrace})", ErrorCode.FileReadFailure, e);
    }
}

Keep in mind I have simplified my implementation for presentation purposes, so it has not been tested.


问:
How to define a component as default value for a prop in React?
How can I do something like this correctly in React?

import Bar from './Bar.jsx'

const Foo = ({ icon = <Bar />}) => {
  // ...
}

export default Foo
```

Right now using icon = <Bar /> will simple give parsing error.

答:
Don't include the <>'s, just assign it however it's imported (so Bar in this case).

You'll need to make the icon prop have a capital I, then you can use <Icon /> to call any component passed to it.

If Bar has any props, add them to Icon and they'll be passed through to Bar.

```<code>import Bar from './Bar.jsx'

const Foo = ({ Icon = Bar }) => {
  return (
    <Icon />
  )
}

export default Foo
</code>```

Body:
How can I do something like this correctly in React?

import Bar from './Bar.jsx'

const Foo = ({ icon = <Bar />}) => {
  // ...
}

export default Foo

Right now using icon = <Bar /> will simple give parsing error.

Body:
Don't include the <>'s, just assign it however it's imported (so Bar in this case).

You'll need to make the icon prop have a capital I, then you can use <Icon /> to call any component passed to it.

If Bar has any props, add them to Icon and they'll be passed through to Bar.

import Bar from './Bar.jsx'

const Foo = ({ Icon = Bar }) => {
  return (
    <Icon />
  )
}

export default Foo


问:
In Solr, why is 'built' not being stemmed to 'build' but 'building' is?
I'm trying to figure out two things in this posting:

Why is 'built' NOT being stemmed to 'build' even though the
field type definition has a stemmer defined. However, 'building' is
being stemmed to 'build'

How to use Luke to examine the index to see which words got stemmed
and to what. I wasn't able to see 'building' being stemmed 'build'
in Luke. I know Lucene is stemming it because I am able to
successfully retrieve the row with 'building' by searching for
'build'.

This link was pretty helpful but didn't answer my questions.

For reference, here is the schema.xml portions.

```<code><fieldType name="text_en" class="solr.TextField" positionIncrementGap="100">
  <analyzer type="index">
    <tokenizer class="solr.StandardTokenizerFactory"/>
    <!-- in this example, we will only use synonyms at query time
    <filter class="solr.SynonymFilterFactory" synonyms="index_synonyms.txt" ignoreCase="true" expand="false"/>
    -->
    <!-- Case insensitive stop word removal.
      add enablePositionIncrements=true in both the index and query
      analyzers to leave a 'gap' for more accurate phrase queries.
    -->
    <filter class="solr.StopFilterFactory"
            ignoreCase="true"
            words="stopwords_en.txt"
            enablePositionIncrements="true"
            />
    <filter class="solr.LowerCaseFilterFactory"/>
    <filter class="solr.EnglishPossessiveFilterFactory"/>
    <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
    <!-- Optionally you may want to use this less aggressive stemmer instead of PorterStemFilterFactory:
    <filter class="solr.EnglishMinimalStemFilterFactory"/>
    -->
    <filter class="solr.PorterStemFilterFactory"/>
  </analyzer>
  <analyzer type="query">
    <tokenizer class="solr.StandardTokenizerFactory"/>
    <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
    <filter class="solr.StopFilterFactory"
            ignoreCase="true"
            words="stopwords_en.txt"
            enablePositionIncrements="true"
            />
    <filter class="solr.LowerCaseFilterFactory"/>
    <filter class="solr.EnglishPossessiveFilterFactory"/>
    <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
    <!-- Optionally you may want to use this less aggressive stemmer instead of PorterStemFilterFactory:
    <filter class="solr.EnglishMinimalStemFilterFactory"/>
    -->
    <filter class="solr.PorterStemFilterFactory"/>
  </analyzer>
</fieldType>
</code>```

and the field definition is

```<code><field name="features" type="text_en" indexed="true" stored="true" multiValued="true"/>
</code>```

The data set consists of multiple documents, 1 document has 'building' in the features field, 1 documents has 'built' in the same field, and 1 document has 'Built-in' in the features field:

file : hd.xml:

```<code><field name="features">building NoiseGuard, SilentSeek technology, Fluid Dynamic Bearing (FDB) motor</field>
</code>```

file ipod_video.xml:

```<code><field name="features">Notes, Calendar, Phone book, Hold button, Date display, Photo wallet, Built-in games, JPEG photo playback, Upgradeable firmware, USB 2.0 compatibility, Playback speed control, Rechargeable capability, Battery level indication</field>
</code>```

file sd500.xml:

```<code> <field name="features">built in flash, red-eye reduction</field>
</code>```

Using Lukeall-3.3.0, This is the result I get from searching for 'features:build'. Notice that I get back 1 (instead of the expected 3 documents)

Even within that one document, I don't see the stemming, ie, I only see the original word, 'building' as shown:

and, again in Luke, searching for 'features:built', returns two documents:

Selecting one of them, shows the original 'built' but not 'build'.

答: For exceptional cases like this, you can tune the stemming algorithm with StemmerOverrideFilter</p>

Body:
I'm trying to figure out two things in this posting:

Why is 'built' NOT being stemmed to 'build' even though the
field type definition has a stemmer defined. However, 'building' is
being stemmed to 'build'

How to use Luke to examine the index to see which words got stemmed
and to what. I wasn't able to see 'building' being stemmed 'build'
in Luke. I know Lucene is stemming it because I am able to
successfully retrieve the row with 'building' by searching for
'build'.

This link was pretty helpful but didn't answer my questions.

For reference, here is the schema.xml portions.

<fieldType name="text_en" class="solr.TextField" positionIncrementGap="100">
  <analyzer type="index">
    <tokenizer class="solr.StandardTokenizerFactory"/>

    <filter class="solr.StopFilterFactory"
            ignoreCase="true"
            words="stopwords_en.txt"
            enablePositionIncrements="true"
            />
    <filter class="solr.LowerCaseFilterFactory"/>
    <filter class="solr.EnglishPossessiveFilterFactory"/>
    <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>

    <filter class="solr.PorterStemFilterFactory"/>
  </analyzer>
  <analyzer type="query">
    <tokenizer class="solr.StandardTokenizerFactory"/>
    <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
    <filter class="solr.StopFilterFactory"
            ignoreCase="true"
            words="stopwords_en.txt"
            enablePositionIncrements="true"
            />
    <filter class="solr.LowerCaseFilterFactory"/>
    <filter class="solr.EnglishPossessiveFilterFactory"/>
    <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>

    <filter class="solr.PorterStemFilterFactory"/>
  </analyzer>
</fieldType>

and the field definition is

<field name="features" type="text_en" indexed="true" stored="true" multiValued="true"/>

The data set consists of multiple documents, 1 document has 'building' in the features field, 1 documents has 'built' in the same field, and 1 document has 'Built-in' in the features field:

file : hd.xml:

<field name="features">building NoiseGuard, SilentSeek technology, Fluid Dynamic Bearing (FDB) motor</field>

file ipod_video.xml:

<field name="features">Notes, Calendar, Phone book, Hold button, Date display, Photo wallet, Built-in games, JPEG photo playback, Upgradeable firmware, USB 2.0 compatibility, Playback speed control, Rechargeable capability, Battery level indication</field>

file sd500.xml:

 <field name="features">built in flash, red-eye reduction</field>

Using Lukeall-3.3.0, This is the result I get from searching for 'features:build'. Notice that I get back 1 (instead of the expected 3 documents)

Even within that one document, I don't see the stemming, ie, I only see the original word, 'building' as shown:

and, again in Luke, searching for 'features:built', returns two documents:

Selecting one of them, shows the original 'built' but not 'build'.


问:
How to manage DI with a service that needs a component?
I manage an Angular project using this architecture:

```<code>  ├── media
  └── src
      ├── app
      │   ├── core <-- services folder inside
      │   ├── data
      │   ├── layout
      │   ├── module
      │   └── shared
      └── styles
</code>```

I got my services inside core folder, and my components divided in modules inside module folder. However, I created a new service, that is opening an emergency modal. It requires a component inside module folder. Therefore, it creates a DI because I inject external dependencies inside the core folder (which needs to remain like this without depending on extra folder).
How can I manage this DI? Do I insert the module inside the core folder?

Here is my service code:

```<code>@Injectable({
  providedIn: 'root'
})
export class EmergencyService {
  constructor(private modalService: NgbModal) {}

  onOpenModal(): void {
    this.modalService.open(EmergencyComponent);
  }
}
</code>```

Thanks,

Architecture from link

答:
Could you post the code of your service?

I use a similar architecture with multiple module and I have a service for my modals too. In my case using:

@Injectable({ providedIn: 'root' })

on top of my service works fine, but all my shared component are defined in root module, also basic modal opened by modal service

Body:
I manage an Angular project using this architecture:

  ├── media
  └── src
      ├── app
      │   ├── core <-- services folder inside
      │   ├── data
      │   ├── layout
      │   ├── module
      │   └── shared
      └── styles

I got my services inside core folder, and my components divided in modules inside module folder. However, I created a new service, that is opening an emergency modal. It requires a component inside module folder. Therefore, it creates a DI because I inject external dependencies inside the core folder (which needs to remain like this without depending on extra folder).
How can I manage this DI? Do I insert the module inside the core folder?

Here is my service code:

@Injectable({
  providedIn: 'root'
})
export class EmergencyService {
  constructor(private modalService: NgbModal) {}

  onOpenModal(): void {
    this.modalService.open(EmergencyComponent);
  }
}

Thanks,

Architecture from link


问:
Zero-pad digits in string
I need to cast single figures (1 to 9) to (01 to 09). I can think of a way but its big and ugly and cumbersome. I'm sure there must be some concise way. Any Suggestions</p>

答:
Here is my solution to handle both positive and negative numbers

<?php

// add zeros to a number at left or right side.
function add_zeros_to_number( $number, $number_of_zeros, $zeros_position="left"){
    // check if number is negative
    $is_negative = FALSE;
    if ( strpos($number , '-') !== FALSE ){
        $is_negative = TRUE;
        $number = substr($number, 1);
    }
    if($zeros_position == "right"){
        $r = str_pad($number, $number_of_zeros, "0", STR_PAD_RIGHT);
    }else{
        $r = str_pad($number, $number_of_zeros, "0", STR_PAD_LEFT);
    }
    if( $is_negative ){
        return "-".$r;
    }else{
        return $r;
    }
}

// how to use
$number = -333;   // Desire number
$number_of_zeros = 4;  // number of zeros [ your number length + zeros ]
$position = "right";  // left or right . default left
echo $result = add_zeros_to_number($number, $number_of_zeros, $position);

// output
// -333 => -3330    left
// -333 => -0333    right

```

OwnerDisplayName: Giles

LastEditorDisplayName: scunliffe

Title: Zero-pad digits in string


问:
Select everything inside spaces keyboard shortcut
Is there any keyboard shortcut to select everything separated by space?

For example:

And I want to click anywhere inside classname press shortcut and it selects classname="header__logo", is that possible?

答:
It depends on your code editor. In this question, for example, works in eclipse but not in a few other editors.

In VSCode I often use CTRL + SHIFT + [LEFT OR RIGHT ARROW] to select words quickly.


问:
R losing levels when importing csv file
I have one data frame with 3686 rows and 34 columns. When I save this data.frame with write.csv2(data, file = folder/data.csv2) and than load it into R again with read.csv2(folder/data.csv2), it also has the same number of rows (3686); but, when I ask for the number of species (Factor) with unique(data$Species), the data table in the Environment has 708 Levels and the one I imported showed only 554 Levels.

```<code>str(imported_dataframe$Species)
</code>```

Output: Factor w/ 554 levels

```<code>str(Data_in_Environment$Species)
</code>```

Output: Factor w/ 708 levels

Can anyone help me?

答:
Alternatively, you can use csvy library and export csv file with yaml header containing factor levels:

```<code># library load
library(csvy)
library(dplyr)

# relevel factos
iris_releveled = iris %>% mutate(Species = relevel(Species, "virginica","setosa","versicolor"))
# write csv file
write.csv2(iris_releveled,"iris_releveled.csv")
# load exported dataset
iris_relevel_loaded = read.csv2("iris_releveled.csv",stringsAsFactors = T)
# now factor levels are lost
iris_relevel_loaded$Species %>% levels()

# write CSVy file from dataset with releveled factors
write_csvy(iris_releveled,  file = "iris_releveled.csvy")
# read csv file with original factor levels
iris_relevel_loaded = read_csvy("iris_releveled.csvy", stringsAsFactors = T)
# now factor levels are kept
iris_relevel_loaded$Species %>% levels()
</code>```

Title: R losing levels when importing csv file

Body:
I have one data frame with 3686 rows and 34 columns. When I save this data.frame with write.csv2(data, file = folder/data.csv2) and than load it into R again with read.csv2(folder/data.csv2), it also has the same number of rows (3686); but, when I ask for the number of species (Factor) with unique(data$Species), the data table in the Environment has 708 Levels and the one I imported showed only 554 Levels.

str(imported_dataframe$Species)

Output: Factor w/ 554 levels

str(Data_in_Environment$Species)

Output: Factor w/ 708 levels

Can anyone help me?

Body:
Alternatively, you can use csvy library and export csv file with yaml header containing factor levels:

# library load
library(csvy)
library(dplyr)

# relevel factos
iris_releveled = iris %>% mutate(Species = relevel(Species, "virginica","setosa","versicolor"))
# write csv file
write.csv2(iris_releveled,"iris_releveled.csv")
# load exported dataset
iris_relevel_loaded = read.csv2("iris_releveled.csv",stringsAsFactors = T)
# now factor levels are lost
iris_relevel_loaded$Species %>% levels()

# write CSVy file from dataset with releveled factors
write_csvy(iris_releveled,  file = "iris_releveled.csvy")
# read csv file with original factor levels
iris_relevel_loaded = read_csvy("iris_releveled.csvy", stringsAsFactors = T)
# now factor levels are kept
iris_relevel_loaded$Species %>% levels()


问:
set_language not changing language in certain cases (django)
I have the following menu to change languages in my site:

```<code><div class="btn-group navbar-right language menu">
    <button class="btn btn-secondary btn-sm dropdown-toggle language-btn" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        {% get_language_info for LANGUAGE_CODE as lang %}
        {{ lang.name_local }} ({{ lang.code }})
    </button>
    <div class="dropdown-menu" aria-labelledby="dropdownMenu2">

        {% get_current_language as LANGUAGE_CODE %}
        {% get_available_languages as LANGUAGES %}
        {% get_language_info_list for LANGUAGES as languages %}

        {% for language in languages %}
            <ul class="language-item">
              <form action="{% url 'set_language' %}" method="post">
                {% csrf_token %}
                <input name="next" type="hidden" value="{{ request.get_full_path }}" />
                <input name="language" type="hidden" value="{{ language.code }}" />
                <input type="submit" value="{{ language.name_local }} ({{ language.code }})" /> <span>{% if language.code == LANGUAGE_CODE %}✓{% endif %}</span>
              </form>
            </ul>
        {% endfor %}
    </div>
</div>
</code>```

Being shown like

This works the same than the form suggested by Django docs but avoiding the "Go" button to switch languages.

It usually switches languages properly, except in certain cases, as I found out after a user reported the problem.

If the user gets to my site via www.mydomain.com, it will be redirected to www.mydomain.com/en/ (or /es/ or /de/) and as far as I know, changing languages works as expected.

However, if the user gets to my site via www.mydomain.com/es/, then when trying to change the language through the menu, www.mydomain.com/es/ is loaded again. The same behavior occurs with www.mydomain.com/de/.

Strange enough, when entering my site via www.mydomain.com/en/, changing languages works properly. Maybe because it is the default language?

I am able to replicate the issue consistently if entering the site through an incognito window. If I do it through a normal window, it is a similar behavior, but not always consistent. For instance, sometimes entering via www.mydomain.com/en/ will not let me change the language either. This makes me think it might have something to do with cookies. But this is as far as I got.

I checked for similar problems during hours and the only similar thing I found is the Django ticket In some cases i18n set_language does not change url language. Its conclusion is:

...I recreated the issue: we set a language (once) then try to reverse
  a URL from the old language when setting the language again.

This obviously fails.

Workarounds:

keeping track of the old language and falling back to try that if the lookup with the current language fails.

Signalling across browser tabs that we already changed the language and adjusting accordingly (???).

Both of these are out of scope for the in-built i18n. (The first would
  be possible on a project level — reimplementing e.g. set_language — if
  it was deemed cost effective.)

I'm going to close this on that basis.

I am not sure if it is the same case, as I don't understand why it "obviously fails". As I see it, the obvious behavior should be to change the language.

I am surprised that such a basic feature does not work, so probably I am missing something.

Why is it not working in the cases described?
Any help would be appreciated.

Edit 1:

Previously I was using translated URLs instead of the form, as suggested here. However, this was taking 1 second to render due to the translation of the slug. This is why I decided to change

答:
Solved the issue by removing the language code from the "next" input (slice the current language code from the url)

Next input:
<input name="next" type="hidden" value="{{ request.get_full_path|slice:"3:" }}">

Whole dropdown:

```<code><form action="{% url 'set_language' %}" method="post">
  {% csrf_token %}
  <div class="row g-2">
    <div class="col col-sm-12 col-lg-3 col-md-4">
      <div class="form-floating">
        <input name="next" type="hidden" value="{{ request.get_full_path|slice:"3:" }}">
        <select class="form-select" name="language" onchange="this.form.submit()" id="language">
          {% get_current_language as LANGUAGE_CODE %}
          {% get_available_languages as LANGUAGES %}
          {% get_language_info_list for LANGUAGES as languages %}
          {% for language in languages %}
            <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}>
              {{ language.name_local }} ({{ language.code }})
            </option>
          {% endfor %}
        </select>
        <label for="language">Language</label>
      </div>
    </div>
  </div>
</form>
</code>```

Body:
I have the following menu to change languages in my site:

    <button class="btn btn-secondary btn-sm dropdown-toggle language-btn" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        {% get_language_info for LANGUAGE_CODE as lang %}
        {{ lang.name_local }} ({{ lang.code }})
    </button>

        {% get_current_language as LANGUAGE_CODE %}
        {% get_available_languages as LANGUAGES %}
        {% get_language_info_list for LANGUAGES as languages %}

        {% for language in languages %}

              <form action="{% url 'set_language' %}" method="post">
                {% csrf_token %}
                <input name="next" type="hidden" value="{{ request.get_full_path }}" />
                <input name="language" type="hidden" value="{{ language.code }}" />
                <input type="submit" value="{{ language.name_local }} ({{ language.code }})" /> {% if language.code == LANGUAGE_CODE %}✓{% endif %}
              </form>

        {% endfor %}

Being shown like

This works the same than the form suggested by Django docs but avoiding the "Go" button to switch languages.

It usually switches languages properly, except in certain cases, as I found out after a user reported the problem.

If the user gets to my site via www.mydomain.com, it will be redirected to www.mydomain.com/en/ (or /es/ or /de/) and as far as I know, changing languages works as expected.

However, if the user gets to my site via www.mydomain.com/es/, then when trying to change the language through the menu, www.mydomain.com/es/ is loaded again. The same behavior occurs with www.mydomain.com/de/.

Strange enough, when entering my site via www.mydomain.com/en/, changing languages works properly. Maybe because it is the default language?

I am able to replicate the issue consistently if entering the site through an incognito window. If I do it through a normal window, it is a similar behavior, but not always consistent. For instance, sometimes entering via www.mydomain.com/en/ will not let me change the language either. This makes me think it might have something to do with cookies. But this is as far as I got.

I checked for similar problems during hours and the only similar thing I found is the Django ticket In some cases i18n set_language does not change url language. Its conclusion is:

...I recreated the issue: we set a language (once) then try to reverse
  a URL from the old language when setting the language again.

This obviously fails.

Workarounds:

keeping track of the old language and falling back to try that if the lookup with the current language fails.

Signalling across browser tabs that we already changed the language and adjusting accordingly (???).

Both of these are out of scope for the in-built i18n. (The first would
  be possible on a project level — reimplementing e.g. set_language — if
  it was deemed cost effective.)

I'm going to close this on that basis.

I am not sure if it is the same case, as I don't understand why it "obviously fails". As I see it, the obvious behavior should be to change the language.

I am surprised that such a basic feature does not work, so probably I am missing something.

Why is it not working in the cases described?
Any help would be appreciated.

Edit 1:

Previously I was using translated URLs instead of the form, as suggested here. However, this was taking 1 second to render due to the translation of the slug. This is why I decided to change

Body:
Solved the issue by removing the language code from the "next" input (slice the current language code from the url)

Next input:
<input name="next" type="hidden" value="{{ request.get_full_path|slice:"3:" }}">

Whole dropdown:

<form action="{% url 'set_language' %}" method="post">
  {% csrf_token %}
  <div class="row g-2">
    <div class="col col-sm-12 col-lg-3 col-md-4">
      <div class="form-floating">
        <input name="next" type="hidden" value="{{ request.get_full_path|slice:"3:" }}">
        <select class="form-select" name="language" onchange="this.form.submit()" id="language">
          {% get_current_language as LANGUAGE_CODE %}
          {% get_available_languages as LANGUAGES %}
          {% get_language_info_list for LANGUAGES as languages %}
          {% for language in languages %}
            <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}>
              {{ language.name_local }} ({{ language.code }})
            </option>
          {% endfor %}
        </select>
        <label for="language">Language</label>
      </div>
    </div>
  </div>
</form>


问:
How do I make my query return one another property inside dictionary
Below query returns ItemNo's of children and grandchildren in an array of dictionaries, so that relationship is maintained.

```<code>    public async Task<List<KeyValuePair<string, IEnumerable<string>>>> GetChild(string parentItemNo)
    {
               var childDetails = await DbContext.Items
                    .Where(x => x.ItemNo== parentItemNo)
                    .SelectMany(x => x.Children.Select(c => new
                    {
                        c.ItemNo, // I can select c.ItemName as well
                        // how do I select ItemName below, tried Select(gc => new { gc.ItemNo, gc.ItemName})
                        GrandChildItemNos = c.Children.Select(gc => gc.ItemNo)
                    })).ToListAsync();

                var dictionary = childDetails.ToDictionary(d => d.ItemNo, d => d.GrandChildItemNos).ToList();  // how do i set ItemName here

                return dictionary;

    }
</code>```

Query returns children(key) and grandchild(value), like below

```<code> [{"Key":"A","Value":["AQ11", AH45]},{"Key":"C","Value":["CN22", "CL33", "CG24"]}]
</code>```

how do I to return 'ItemName' as well for each children and grandchildren.

答:
You should write:

```<code>public async Task<List<Child>> GetChild(string parentItemNo)
{
               return await DbContext.Items
                    .Where(x => x.ItemNo== parentItemNo)
                    .SelectMany(x => x.Children.Select(c => new Child
                        {
                            ItemNo = c.ItemNo,
                            ItemName = c.ItemName,
                            GrandChildItemNos = c.Children.Select(gc =>
                               new GrandChild
                               {
                                  ItemNo = gc.ItemNo,
                                  ItemName = gc.ItemName
                               })
                        })).ToListAsync();

 }
</code>```

Using this class

```<code>public class GrandChild
{
    public string ItemNo {get;set;}
    public strng ItemName {get;set;}
}

public class Child
{
    public string ItemNo {get;set;}
    public string ItemName {get;set;}
    public IEnumerable<GrandChild> GrandChildItemNos {get;set;}
}
</code>```

Body:
Below query returns ItemNo's of children and grandchildren in an array of dictionaries, so that relationship is maintained.

    public async Task<List<KeyValuePair<string, IEnumerable<string>>>> GetChild(string parentItemNo)
    {
               var childDetails = await DbContext.Items
                    .Where(x => x.ItemNo== parentItemNo)
                    .SelectMany(x => x.Children.Select(c => new
                    {
                        c.ItemNo, // I can select c.ItemName as well
                        // how do I select ItemName below, tried Select(gc => new { gc.ItemNo, gc.ItemName})
                        GrandChildItemNos = c.Children.Select(gc => gc.ItemNo)
                    })).ToListAsync();

                var dictionary = childDetails.ToDictionary(d => d.ItemNo, d => d.GrandChildItemNos).ToList();  // how do i set ItemName here

                return dictionary;

    }

Query returns children(key) and grandchild(value), like below

 [{"Key":"A","Value":["AQ11", AH45]},{"Key":"C","Value":["CN22", "CL33", "CG24"]}]

how do I to return 'ItemName' as well for each children and grandchildren.

Body:
You should write:

public async Task<List<Child>> GetChild(string parentItemNo)
{
               return await DbContext.Items
                    .Where(x => x.ItemNo== parentItemNo)
                    .SelectMany(x => x.Children.Select(c => new Child
                        {
                            ItemNo = c.ItemNo,
                            ItemName = c.ItemName,
                            GrandChildItemNos = c.Children.Select(gc =>
                               new GrandChild
                               {
                                  ItemNo = gc.ItemNo,
                                  ItemName = gc.ItemName
                               })
                        })).ToListAsync();

 }

Using this class

public class GrandChild
{
    public string ItemNo {get;set;}
    public strng ItemName {get;set;}
}

public class Child
{
    public string ItemNo {get;set;}
    public string ItemName {get;set;}
    public IEnumerable<GrandChild> GrandChildItemNos {get;set;}
}


问:
Deploy Strapi with HTTPS on Azure
I have deployed my Strapi application on a VM on Azure but I would like to expose it on port 443 in https. I could see that it was recommended to use nginx as a reverse proxy but is there another way? Could you tell me how you would do it? Do you know a complete tutorial on this subject?
Thanks</p>

答:
We can Deploy Strapi with HTTPS on Azure by following the below steps:

Install all the pre-requisites as mentioned in this document like creating VM and setting inbound rules which we want to allow.

Next, Logging in and installing Strapi dependencies by following this steps here.

Then Creating or cloning our Strapi Project.

Title: Deploy Strapi with HTTPS on Azure


问:
how to exclude digits using regular expression in VBA
Hello I need to exclude sequence of digits from 890000 till 890001;

890002 to 899999 is acceptable

Is it possible doing using regular expression?

答:
No need for regex.

If Value >= 890002 And Value <= 899999 Then
    ' Accept
End If
```


问:
Unit testing a custom exception in Java
Pretty new to Java and trying to practice writing unit tests. I have a few similar custom exceptions to the below and wondering what way I can write a test to cover this.</p>
```<code>public class ExampleException extends RuntimeException{
    public ExampleException(String message, Throwable e) {
        super(message, e);
    }
}
</code>```

答: Testing exceptions in JUnit 5 is done through Assertions.assertThrows. You give it an exception type and an action that should throw exceptions of this type. If it doesn't the assertion fails. If it does it returns the thrown exception, which allows you to perform more assertions on the exception itself.

Title: Unit testing a custom exception in Java

Body:
Pretty new to Java and trying to practice writing unit tests. I have a few similar custom exceptions to the below and wondering what way I can write a test to cover this.

public class ExampleException extends RuntimeException{
    public ExampleException(String message, Throwable e) {
        super(message, e);
    }
}


问:
What makes repeated base64 and base36 encoding so slow? and how to make it faster?
I was trying out some different encodings and as I tried to encode some text repeatedly in base64/base32 (which one is used depends on a semi-random boolean list) I noticed that it was ridiculously slow which I didn't understand because I thought that they were particularly fast. I can't really figure out why it's so slow, it'd be cool if you could help me.

This is the part of the code concerned :

from base64 import b64encode, b32encode
from random import random as rn

big_number = int(input("The number of encoding layers : "))
bool_list = [True if rn() < 0.5 else False for _ in range(big_number)]
sample_text = bytes("lorem ipsum", "utf8")
for curr_bool in bool_list:
    temp = b64encode(sample_text) if curr_bool else b32encode(sample_text)
    sample_text = temp
```

答:
Memory and time expensive operations. The answer is based on pivotal comment (by Wups):

If you encode bytes with base64, the result is longer than the
input. If you take this result and encode it again in a loop, you have
exponential growth.

The following modified script shows growing ratio for base64 and base32 encodings:

```<code>from base64 import b64encode, b32encode
from random import random as rn
ii = 0
big_number = int(input("The number of encoding layers : "))
30
bool_list = [True if rn() < 0.5 else False for _ in range(big_number)]
sample_text = bytes("lorem ipsum", "utf8")
sample_len = len( sample_text )
current_len = sample_len
for curr_bool in bool_list:
    sample_text = b64encode(sample_text) if curr_bool else b32encode(sample_text)
    print( ii, curr_bool, len(sample_text), (len( sample_text )/current_len))
    current_len = len( sample_text )
    ii += 1
</code>```

** Sample output** (truncated): python .\SO\71009943.py

```<code>The number of encoding layers : 30
…
24 True 172320 1.3333333333333333
25 False 275712 1.6
26 True 367616 1.3333333333333333
27 False 588192 1.600017409470752
28 True 784256 1.3333333333333333
29 False 1254816 1.6000081606006202
</code>```

So resultant length is roughly somewhere between Compound interest for base64's 4/3 and base32's 1.6:

```<code>big_number = 30
round( sample_len * (4/3) ** big_number)
# 61596
round( sample_len * 1.6 ** big_number)
# 14621508
</code>```

and for a bigger numbers:

```<code>big_number = 50
round( sample_len * (4/3) ** big_number)
# 19423591
round( sample_len * 1.6 ** big_number)
# 176763184868
</code>```

and

```<code>big_number = 99
round( sample_len * (4/3) ** big_number)
# 25723354884215
round( sample_len * 1.6 ** big_number)
# 1775296791184759324672
</code>```

Body:
Memory and time expensive operations. The answer is based on pivotal comment (by Wups):

If you encode bytes with base64, the result is longer than the
input. If you take this result and encode it again in a loop, you have
exponential growth.

The following modified script shows growing ratio for base64 and base32 encodings:

from base64 import b64encode, b32encode
from random import random as rn
ii = 0
big_number = int(input("The number of encoding layers : "))
30
bool_list = [True if rn() < 0.5 else False for _ in range(big_number)]
sample_text = bytes("lorem ipsum", "utf8")
sample_len = len( sample_text )
current_len = sample_len
for curr_bool in bool_list:
    sample_text = b64encode(sample_text) if curr_bool else b32encode(sample_text)
    print( ii, curr_bool, len(sample_text), (len( sample_text )/current_len))
    current_len = len( sample_text )
    ii += 1

** Sample output** (truncated): python .\SO\71009943.py

The number of encoding layers : 30
…
24 True 172320 1.3333333333333333
25 False 275712 1.6
26 True 367616 1.3333333333333333
27 False 588192 1.600017409470752
28 True 784256 1.3333333333333333
29 False 1254816 1.6000081606006202

So resultant length is roughly somewhere between Compound interest for base64's 4/3 and base32's 1.6:

big_number = 30
round( sample_len * (4/3) ** big_number)
# 61596
round( sample_len * 1.6 ** big_number)
# 14621508

and for a bigger numbers:

big_number = 50
round( sample_len * (4/3) ** big_number)
# 19423591
round( sample_len * 1.6 ** big_number)
# 176763184868

and

big_number = 99
round( sample_len * (4/3) ** big_number)
# 25723354884215
round( sample_len * 1.6 ** big_number)
# 1775296791184759324672


问:
Spring batch job step up defenition
Im developing a Spring Batch application, technology which by the way I'm new to.

I have made some tutoriais, and read some docs in order to prepare myself to this development.
Im already "confortable" with some of the most common APIs (ItemRead, ItemProcessor, ItemWriter, Setps, Tasklets, Jobs, Parameters...)

My requirement is simple.

1 - Read some data from CSV file.

2 - Fetch an Entity from database by each line of the CSV file.

3 - Update the state of the Entity.

4 - Export a new CSV file with some generated data from each Entity.

My problem is not how to fetch, how to update or how to export a csv file, but more conceptualy how to setup my JOB.

The way I see it I like to end up with a Job something like

1 - ItemRead            -> to read the whole csv file.

2 - ItemProcessor   -> to update the entity.

3 - ItemWriter          -> to persist the entity.

4 - ItemWriter          -> to export the new CSV file based on the entity state.

Does it make sense? There's a better way. Am I missisng some pitfalls?

答:
updating line by line might not be best idea. Instead I suggest

Job 1

Read entire file

Write it to the tmp table

Here write update query that join original table and tmp table based on primary key.

After query execution, call second job

Job 2

Read records from table

Write it to the file

Finally clear tmp table for next Job sequence.

This Ans is based on my thought process. there might be other best approaches as well.

Title: Spring batch job step up defenition


问:
hudson.remoting.ProxyException: net.sf.json.JSONException: Invalid JSON String
Facing below error while trying to parse the json file in Jenkins

```<code>def appconfig="./appSettings.json"
def testconfig= readJSON file: appconfig;
</code>```

Json File

```<code>{
  "Configuration": {
    "ConnectionString": "",
    "ConnectionString2": "",
    "UnProcessedHeaderFilePath": "\\\\edisilon01\\prod\\Reporting\\GET\\Header-{0:yyyyMMddHHmmss}.txt",
    "UnProcessedDetailFilePath": "\\\\edisilon01\\prod\\Reporting\\GET\\Detail-{0:yyyyMMddHHmmss}.txt",
    "ApplicationTriggerFile": "\\\\edisilon01\\PROD\\Reporting\\InputFiles\\Factor\\DR\\Factor.txt",
    "DB2ConnectionString": ""
  },
  "Serilog": {
    "Using": [ "Serilog.Sinks.Console" ],
    "MinimumLevel": "Information",
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "File",
        "Args": {
          "path": "\\\\ECPCICS\\Files\\Generator\\log\\log-.txt",
          "rollingInterval": "Day",
          "outputTemplate": "{Timestamp:dd-MMM-yyyy HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
        }
      }
    ]
  }
}
</code>```

Error

hudson.remoting.ProxyException: net.sf.json.JSONException:
  Invalid JSON String   at
  net.sf.json.JSONSerializer.toJSON(JSONSerializer.java:143)    at
  net.sf.json.JSONSerializer.toJSON(JSONSerializer.java:103)    at
  net.sf.json.JSONSerializer.toJSON(JSONSerializer.java:84)     at
  org.jenkinsci.plugins.pipeline.utility.steps.json.ReadJSONStepExecution.doRun(ReadJSONStepExecution.java:77)
    at
  org.jenkinsci.plugins.pipeline.utility.steps.AbstractFileOrTextStepExecution.run(AbstractFileOrTextStepExecution.java:32)
    at
  org.jenkinsci.plugins.workflow.steps.SynchronousNonBlockingStepExecution.lambda$start$0(SynchronousNonBlockingStepExecution.java:47)
    at
  java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)     at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

答:
In addition to other answers regarding leading/trailing whitespace, this can also be caused by a byte order mark at the start of the file.

I changed the encoding of my file from UTF-8 with BOM to UTF-8 and it fixed the problem.

Body:
Facing below error while trying to parse the json file in Jenkins

def appconfig="./appSettings.json"
def testconfig= readJSON file: appconfig;

Json File

{
  "Configuration": {
    "ConnectionString": "",
    "ConnectionString2": "",
    "UnProcessedHeaderFilePath": "\\\\edisilon01\\prod\\Reporting\\GET\\Header-{0:yyyyMMddHHmmss}.txt",
    "UnProcessedDetailFilePath": "\\\\edisilon01\\prod\\Reporting\\GET\\Detail-{0:yyyyMMddHHmmss}.txt",
    "ApplicationTriggerFile": "\\\\edisilon01\\PROD\\Reporting\\InputFiles\\Factor\\DR\\Factor.txt",
    "DB2ConnectionString": ""
  },
  "Serilog": {
    "Using": [ "Serilog.Sinks.Console" ],
    "MinimumLevel": "Information",
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "File",
        "Args": {
          "path": "\\\\ECPCICS\\Files\\Generator\\log\\log-.txt",
          "rollingInterval": "Day",
          "outputTemplate": "{Timestamp:dd-MMM-yyyy HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
        }
      }
    ]
  }
}

Error

hudson.remoting.ProxyException: net.sf.json.JSONException:
  Invalid JSON String   at
  net.sf.json.JSONSerializer.toJSON(JSONSerializer.java:143)    at
  net.sf.json.JSONSerializer.toJSON(JSONSerializer.java:103)    at
  net.sf.json.JSONSerializer.toJSON(JSONSerializer.java:84)     at
  org.jenkinsci.plugins.pipeline.utility.steps.json.ReadJSONStepExecution.doRun(ReadJSONStepExecution.java:77)
    at
  org.jenkinsci.plugins.pipeline.utility.steps.AbstractFileOrTextStepExecution.run(AbstractFileOrTextStepExecution.java:32)
    at
  org.jenkinsci.plugins.workflow.steps.SynchronousNonBlockingStepExecution.lambda$start$0(SynchronousNonBlockingStepExecution.java:47)
    at
  java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)     at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)


问:
Android studio new version BumbleBee show error when run old project in IOS Device/Simulator in Flutter
It Will shows Error like this:-

```<code>After updating the Android studio it's throwing the error in IOS run

Warning: CocoaPods not installed. Skipping pod install.
  CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side.
  Without CocoaPods, plugins will not work on iOS or macOS.
  For more info, see https://flutter.dev/platform-plugins
To install see https://guides.cocoapods.org/using/getting-started.html#installation for instructions.

CocoaPods not installed or not in valid state.
Error launching application on iPhone 13 Pro Max.
</code>```

It's run easily in android device and when we run through terminal its runs easily.

答:
Upgrade with the new version of Bumblebee resolve the issue for me

Version: Android Studio Bumblebee | 2021.1.1 Patch 1

Body:
It Will shows Error like this:-

After updating the Android studio it's throwing the error in IOS run

Warning: CocoaPods not installed. Skipping pod install.
  CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side.
  Without CocoaPods, plugins will not work on iOS or macOS.
  For more info, see https://flutter.dev/platform-plugins
To install see https://guides.cocoapods.org/using/getting-started.html#installation for instructions.

CocoaPods not installed or not in valid state.
Error launching application on iPhone 13 Pro Max.

It's run easily in android device and when we run through terminal its runs easily.


问:
Immediate function using JavaScript ES6 arrow functions
Does anyone know how to write an immediate function using ES6 arrow syntax?

Here's the ES3/5 way of doing it:

```<code>(function () {
   //...
}());
</code>```

I've tried the following but get an unexpected token error on the last line.

```<code>(() => {
  //...
}());
</code>```

You can test this here: http://www.es6fiddle.net/hsb8bgu4/

答:
Here's a simple example.

To define an arrow function:

const temp = (x)=> {return x+" world";}

// call it as a function
temp("hello") // output: hello world
```
<p>To make an arrow function immediately invoke:</p>
<pre class="lang-js prettyprint-override"><code>const temp = ((x)=> {return x+" world";})("hello")

// use it as a variable:
console.log(temp); // output: hello world

// a self-invoking function without params:
const temp = (()=> {return "world";})()
</code>```

Body:
Does anyone know how to write an immediate function using ES6 arrow syntax?

Here's the ES3/5 way of doing it:

(function () {
   //...
}());

I've tried the following but get an unexpected token error on the last line.

(() => {
  //...
}());

You can test this here: http://www.es6fiddle.net/hsb8bgu4/

Body:
Here's a simple example.

To define an arrow function:

const temp = (x)=> {return x+" world";}

// call it as a function
temp("hello") // output: hello world

To make an arrow function immediately invoke:

const temp = ((x)=> {return x+" world";})("hello")

// use it as a variable:
console.log(temp); // output: hello world

// a self-invoking function without params:
const temp = (()=> {return "world";})()