问:
Openlayers 3 remove drawn feature
I am adding "draw interaction" and drawing features on a map...

```<code> webMapValues.drawObj = new ol.interaction.Draw({
                            features: features,
                            type: /** @type {ol.geom.GeometryType} */ (webMapValues.drawType)

                        });
</code>```

I am catching the "drawend" event...

```<code> webMapValues.drawObj.on('drawend', function (e) {

                        //Here I am saving my feature to a data base
                          and displaying the saved vector...
                        control.UpdateObjects(e, "Draw");

                        //Here I would like to remove the vector that
                          draw interaction placed and just display the
                          vector from the db

                    });
</code>```

I can not figure out how to remove the vector that ol.interaction.Draw has placed so that only the vector from the data base shows after I save it?

I guess 'drawend' is not the place to do this...but I'm not sure how to achieve the functionality I need then...

any help is greatly appreciated!!

答:
I achieved this by listening to the "addfeature" event to immediately remove the added feature if the feature has the key "removeMe"</p>
```<code>  yourVectorSource.on("addfeature", (event) => {
    if (event.feature.get("removeMe")) {
      this.source.removeFeature(event.feature);
    }
  });
  webMapValues.drawObj.on('drawend', function (e) {
    control.UpdateObjects(e, "Draw");

    //add removeMe key now!
    e.feature.set("removeMe",true);
  });
</code>```

Title: Openlayers 3 remove drawn feature

Body:
I am adding "draw interaction" and drawing features on a map...

 webMapValues.drawObj = new ol.interaction.Draw({
                            features: features,
                            type: /** @type {ol.geom.GeometryType} */ (webMapValues.drawType)

                        });

I am catching the "drawend" event...

 webMapValues.drawObj.on('drawend', function (e) {

                        //Here I am saving my feature to a data base
                          and displaying the saved vector...
                        control.UpdateObjects(e, "Draw");

                        //Here I would like to remove the vector that
                          draw interaction placed and just display the
                          vector from the db

                    });

I can not figure out how to remove the vector that ol.interaction.Draw has placed so that only the vector from the data base shows after I save it?

I guess 'drawend' is not the place to do this...but I'm not sure how to achieve the functionality I need then...

any help is greatly appreciated!!

Body:
I achieved this by listening to the "addfeature" event to immediately remove the added feature if the feature has the key "removeMe"

  yourVectorSource.on("addfeature", (event) => {
    if (event.feature.get("removeMe")) {
      this.source.removeFeature(event.feature);
    }
  });
  webMapValues.drawObj.on('drawend', function (e) {
    control.UpdateObjects(e, "Draw");

    //add removeMe key now!
    e.feature.set("removeMe",true);
  });


来源: stackexchange

问:
Is there "LoadComplete" such an event in Windows Forms?
I want my windows form to be loaded first, render its children and all. After that load heavy data in it. This is why I am looking for any event which I could use just after form loading is complete.

Any thoughts on this?

答: Perhaps you're looking for the Form.Shown event. If you're doing a lot of intensive work though, perhaps you should be using a background thread anyway to avoid locking up the UI.</p>

ContentLicense: CC BY-SA 3.0


问:
How to insert data from R into Oracle table with identity column?
Assume I have a simple table in Oracle db

```<code>CREATE TABLE schema.d_test
(
    id_record integer GENERATED AS IDENTITY START WITH 95000 NOT NULL,
    DT DATE NOT NULL,
    var varchar(50),
    num float,
    PRIMARY KEY (ID_RECORD)
)
</code>```

And I have a dataframe in R

```<code>dt = c('2022-01-01', '2005-04-01', '2011-10-02')
var = c('sgdsg', 'hjhgjg', 'rurtur')
num = c(165, 1658.5, 8978.12354)

data = data.frame(dt, var, num)%>%
  mutate(dt = as.Date(dt))
</code>```

I'm trying to insert data into Oracle d_test table using the code

```<code>data %>%
  dbWriteTable(
    oracle_con,
    value = .,
    date = T,
    'D_TEST',
    append = T,
    row.names=F,
    overwrite = F
  )
</code>```

But the following error returned

```<code>Error in .oci.WriteTable(conn, name, value, row.names = row.names, overwrite = overwrite,  :
  Error in .oci.GetQuery(con, stmt, data = value) :
  ORA-00947: not enough values
</code>```

What's the problem?
How can I fix it?
Thank you.

答:
This is pure Oracle (I don't know R).

Sample table:

```<code>SQL> create table test_so (id number generated always as identity not null, name varchar2(20));

Table created.

SQL> insert into test_so(name) values ('Name 1');

1 row created.
</code>```

My initial idea was to suggest you to insert any value into the ID column, hoping that Oracle would discard it and generate its own value. However, that won't work.

```<code>SQL> insert into test_so (id, name) values (-100, 'Name 2');
insert into test_so (id, name) values (-100, 'Name 2')
                     *
ERROR at line 1:
ORA-32795: cannot insert into a generated always identity column
</code>```

But, if you can afford recreating the table so that it doesn't automatically generate the ID column's value but use a "workaround" (we used anyway, as identity columns are relatively new in Oracle) - a sequence and a trigger - you might be able to "fix" it.

```<code>SQL> drop table test_so;

Table dropped.

SQL> create table test_so (id number not null, name varchar2(20));

Table created.

SQL> create sequence seq_so;

Sequence created.

SQL> create or replace trigger trg_bi_so
  2    before insert on test_so
  3    for each row
  4  begin
  5    :new.id := seq_so.nextval;
  6  end;
  7  /

Trigger created.
</code>```

Inserting only name (Oracle will use a trigger to populate ID):

```<code>SQL> insert into test_so(name) values ('Name 1');

1 row created.
</code>```

This is what you'll do in your code - provide dummy ID value, just to avoid

ORA-00947: not enough values

error you have now. Trigger will discard it and use sequence anyway:

```<code>SQL> insert into test_so (id, name) values (-100, 'Name 2');

1 row created.

SQL> select * from test_so;

        ID NAME
---------- --------------------
         1 Name 1
         2 Name 2       --> this is a row which was supposed to have ID = -100

SQL>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Assume I have a simple table in Oracle db

CREATE TABLE schema.d_test
(
    id_record integer GENERATED AS IDENTITY START WITH 95000 NOT NULL,
    DT DATE NOT NULL,
    var varchar(50),
    num float,
    PRIMARY KEY (ID_RECORD)
)

And I have a dataframe in R

dt = c('2022-01-01', '2005-04-01', '2011-10-02')
var = c('sgdsg', 'hjhgjg', 'rurtur')
num = c(165, 1658.5, 8978.12354)

data = data.frame(dt, var, num)%>%
  mutate(dt = as.Date(dt))

I'm trying to insert data into Oracle d_test table using the code

data %>%
  dbWriteTable(
    oracle_con,
    value = .,
    date = T,
    'D_TEST',
    append = T,
    row.names=F,
    overwrite = F
  )

But the following error returned

Error in .oci.WriteTable(conn, name, value, row.names = row.names, overwrite = overwrite,  :
  Error in .oci.GetQuery(con, stmt, data = value) :
  ORA-00947: not enough values

What's the problem?
How can I fix it?
Thank you.

Body:
This is pure Oracle (I don't know R).

Sample table:

SQL> create table test_so (id number generated always as identity not null, name varchar2(20));

Table created.

SQL> insert into test_so(name) values ('Name 1');

1 row created.

My initial idea was to suggest you to insert any value into the ID column, hoping that Oracle would discard it and generate its own value. However, that won't work.

SQL> insert into test_so (id, name) values (-100, 'Name 2');
insert into test_so (id, name) values (-100, 'Name 2')
                     *
ERROR at line 1:
ORA-32795: cannot insert into a generated always identity column

But, if you can afford recreating the table so that it doesn't automatically generate the ID column's value but use a "workaround" (we used anyway, as identity columns are relatively new in Oracle) - a sequence and a trigger - you might be able to "fix" it.

SQL> drop table test_so;

Table dropped.

SQL> create table test_so (id number not null, name varchar2(20));

Table created.

SQL> create sequence seq_so;

Sequence created.

SQL> create or replace trigger trg_bi_so
  2    before insert on test_so
  3    for each row
  4  begin
  5    :new.id := seq_so.nextval;
  6  end;
  7  /

Trigger created.

Inserting only name (Oracle will use a trigger to populate ID):

SQL> insert into test_so(name) values ('Name 1');

1 row created.

This is what you'll do in your code - provide dummy ID value, just to avoid

ORA-00947: not enough values

error you have now. Trigger will discard it and use sequence anyway:

SQL> insert into test_so (id, name) values (-100, 'Name 2');

1 row created.

SQL> select * from test_so;

        ID NAME
---------- --------------------
         1 Name 1
         2 Name 2       --> this is a row which was supposed to have ID = -100

SQL>


问:
403 error with axios but works on postman and browser
I get Nfts on magic eden with this third party api.
http://api-mainnet.magiceden.io/rpc/getGlobalActivitiesByQuery?q=%7B%22%24match%22%3A%7B%22txType%22%3A%22initializeEscrow%22%2C%22blockTime%22%3A%7B%22%24gt%22%3A1643468983%7D%7D%2C%22%24sort%22%3A%7B%22blockTime%22%3A-1%7D%7D

It responses with results on postman and browser but causes 403 error with axios in node.js.

How can I get data in node.js?

```<code> const res = await axios.get(
    'http://api-mainnet.magiceden.io/rpc/getGlobalActivitiesByQuery?q=%7B%22%24match%22%3A%7B%22txType%22%3A%22initializeEscrow%22%2C%22blockTime%22%3A%7B%22%24gt%22%3A1643468983%7D%7D%2C%22%24sort%22%3A%7B%22blockTime%22%3A-1%7D%7D',
    {
      headers : {
        "Content-Type": "application/json",
        "Access-Control-Allow-Credentials": "*"
      }
    }
  );
  return res.data;
</code>```

答:
It can be because of CORS error.
You can use Cors proxy to fix it.
Try it,please.</p>
```
const CORS_PROXY_API = `https://cors.ryanking13.workers.dev/?u=`;
const magicedenAPI = `http://api-mainnet.magiceden.io/rpc/getGlobalActivitiesByQuery?q=%7B%22%24match%22%3A%7B%22txType%22%3A%22initializeEscrow%22%2C%22blockTime%22%3A%7B%22%24gt%22%3A1643468983%7D%7D%2C%22%24sort%22%3A%7B%22blockTime%22%3A-1%7D%7D`
const { data } = await axios({
  method: 'get',
  url: `${CORS_PROXY_API}${magicedenAPI}`
});
```

Body:
I get Nfts on magic eden with this third party api.
http://api-mainnet.magiceden.io/rpc/getGlobalActivitiesByQuery?q=%7B%22%24match%22%3A%7B%22txType%22%3A%22initializeEscrow%22%2C%22blockTime%22%3A%7B%22%24gt%22%3A1643468983%7D%7D%2C%22%24sort%22%3A%7B%22blockTime%22%3A-1%7D%7D

It responses with results on postman and browser but causes 403 error with axios in node.js.

How can I get data in node.js?

 const res = await axios.get(
    'http://api-mainnet.magiceden.io/rpc/getGlobalActivitiesByQuery?q=%7B%22%24match%22%3A%7B%22txType%22%3A%22initializeEscrow%22%2C%22blockTime%22%3A%7B%22%24gt%22%3A1643468983%7D%7D%2C%22%24sort%22%3A%7B%22blockTime%22%3A-1%7D%7D',
    {
      headers : {
        "Content-Type": "application/json",
        "Access-Control-Allow-Credentials": "*"
      }
    }
  );
  return res.data;

Body:
It can be because of CORS error.
You can use Cors proxy to fix it.
Try it,please.

const CORS_PROXY_API = `https://cors.ryanking13.workers.dev/?u=`;
const magicedenAPI = `http://api-mainnet.magiceden.io/rpc/getGlobalActivitiesByQuery?q=%7B%22%24match%22%3A%7B%22txType%22%3A%22initializeEscrow%22%2C%22blockTime%22%3A%7B%22%24gt%22%3A1643468983%7D%7D%2C%22%24sort%22%3A%7B%22blockTime%22%3A-1%7D%7D`
const { data } = await axios({
  method: 'get',
  url: `${CORS_PROXY_API}${magicedenAPI}`
});


问:
How to locate multiple widget of same type in widget hierarchy?
I am developing some intregration tests for one of my flutter-web application. I wanted to specifically locate the container(width: 50, height: 50) in the following below widget hierarchy tree considering top to bottom approach.
ParentWidget --> Row --> Text, SizedBox, Row --> Container(), Container(width: 50, height: 50), Container().
Note: Without key approach

I tried to locate using descendant of ParentWidget --> Row --> Row --> with index tried to select the 2nd container, but this isn't working, it fails with error "Bad state: No element".

```<code>import 'package:flutter/material.dart';

class ParentWidget extends StatelessWidget {
  const ParentWidget({Key? key});

  @override
  Widget build(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Text("Hello World..!!"),
        SizedBox(
          width: 20,
        ),
        Row(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Container(
              width: 20,
              height: 20,
              color: Colors.red,
            ),
            Container(
              width: 50,
              height: 50,
              color: Colors.red,
            ),
            Container(
              width: 20,
              height: 20,
              color: Colors.red,
            ),
          ],
        ),
      ],
    );
  }
}
</code>```
```<code>final container = tester.widget<Container>(find.descendant(
    of: find.descendant(
        of: find.byType(ParentWidget), matching: find.byType(Row)),
    matching: find.descendant(
        of: find.byType(Row), matching: find.byType(Container).at(1))));
</code>```

答:
If your widget tree is deep nested and you want to locate specific widget down the tree we can make use of something:
If sub-widget tree contains multiple widget of same type...try locating it via index...how the look up will going to work is, it iwll try to locate the 2nd Container down under the ParentWidget sub tree.

```<code>final container = (find
          .descendant(
              of: find.byType(ParentWidget),
              matching: find.byType(Container),
              matchRoot: true)
          .evaluate()
          .elementAt(1)
          .widget as Container);
</code>```

Body:
I am developing some intregration tests for one of my flutter-web application. I wanted to specifically locate the container(width: 50, height: 50) in the following below widget hierarchy tree considering top to bottom approach.
ParentWidget --> Row --> Text, SizedBox, Row --> Container(), Container(width: 50, height: 50), Container().
Note: Without key approach

I tried to locate using descendant of ParentWidget --> Row --> Row --> with index tried to select the 2nd container, but this isn't working, it fails with error "Bad state: No element".

import 'package:flutter/material.dart';

class ParentWidget extends StatelessWidget {
  const ParentWidget({Key? key});

  @override
  Widget build(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Text("Hello World..!!"),
        SizedBox(
          width: 20,
        ),
        Row(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Container(
              width: 20,
              height: 20,
              color: Colors.red,
            ),
            Container(
              width: 50,
              height: 50,
              color: Colors.red,
            ),
            Container(
              width: 20,
              height: 20,
              color: Colors.red,
            ),
          ],
        ),
      ],
    );
  }
}

final container = tester.widget<Container>(find.descendant(
    of: find.descendant(
        of: find.byType(ParentWidget), matching: find.byType(Row)),
    matching: find.descendant(
        of: find.byType(Row), matching: find.byType(Container).at(1))));

Body:
If your widget tree is deep nested and you want to locate specific widget down the tree we can make use of something:
If sub-widget tree contains multiple widget of same type...try locating it via index...how the look up will going to work is, it iwll try to locate the 2nd Container down under the ParentWidget sub tree.

final container = (find
          .descendant(
              of: find.byType(ParentWidget),
              matching: find.byType(Container),
              matchRoot: true)
          .evaluate()
          .elementAt(1)
          .widget as Container);


问:
Typescript: How to preserve length information when using .map

My current "working" approach is this:

const generateMainOrientations = <T extends readonly string[]>(
  mainOrientationsNames: T
): { [Index in keyof T]: Orientation } => {
  const temp: Orientation[] = mainOrientationsNames.map(
    mainOrientationName => ({
      name: mainOrientationName,
      getYear(date) {
        return date.getFullYear()
      },
      getRecordContent: getMainOrientationRecordContent
    })
  )

  return temp as unknown as { [Index in keyof T]: Orientation }
}

const mainOrientations = generateMainOrientations([
  "One",
  "Two",
  "Three"
] as const)
```
<p>However, I have to use <code>as unknown as { [Index in keyof T]: Orientation }</code>, which is not ideal, otherwise (even removing the type assertion from the <code>temp</code> variable) it will throw</p>
<pre class="lang-typescript prettyprint-override"><code>Type '{ name: string; getYear(date: any): any; getRecordContent: (values: number[]) => string[]; }[]' is not assignable to type '{ [Index in keyof T]: Orientation; }'.ts(2322)
</code>```

Still, { name: string; getYear(date: any): any; getRecordContent: (values: number[]) => string[]; } is the definition of Orientation

This shows that any length information is lost after map is used.

Is there a more organic way to achieve this, preferably without having to use type assertions at all, or at least without having to use as unknown. The objective would be to make mainOrientations a tuple of Orientation of the same length as the argument passed to generateMainOrientations, so [Orientation, Orientation, Orientation] in this case, (not Orientation[]).

Playground

答:
You can use temp as any

```<code>const generateMainOrientations = <T extends readonly string[]>(
  mainOrientationsNames: T
): { [Index in keyof T]: Orientation } => {
  const temp = mainOrientationsNames.map((mainOrientationName) => ({
    name: mainOrientationName,
    getYear(date: Date) {
      return date.getFullYear();
    },
    getRecordContent: getMainOrientationRecordContent
  }));

  return temp as any;
};
</code>```

Body:
My current "working" approach is this:

const generateMainOrientations = <T extends readonly string[]>(
  mainOrientationsNames: T
): { [Index in keyof T]: Orientation } => {
  const temp: Orientation[] = mainOrientationsNames.map(
    mainOrientationName => ({
      name: mainOrientationName,
      getYear(date) {
        return date.getFullYear()
      },
      getRecordContent: getMainOrientationRecordContent
    })
  )

  return temp as unknown as { [Index in keyof T]: Orientation }
}

const mainOrientations = generateMainOrientations([
  "One",
  "Two",
  "Three"
] as const)

However, I have to use as unknown as { [Index in keyof T]: Orientation }, which is not ideal, otherwise (even removing the type assertion from the temp variable) it will throw

Type '{ name: string; getYear(date: any): any; getRecordContent: (values: number[]) => string[]; }[]' is not assignable to type '{ [Index in keyof T]: Orientation; }'.ts(2322)

Still, { name: string; getYear(date: any): any; getRecordContent: (values: number[]) => string[]; } is the definition of Orientation

This shows that any length information is lost after map is used.

Is there a more organic way to achieve this, preferably without having to use type assertions at all, or at least without having to use as unknown. The objective would be to make mainOrientations a tuple of Orientation of the same length as the argument passed to generateMainOrientations, so [Orientation, Orientation, Orientation] in this case, (not Orientation[]).

<a href="https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgPJWBcczAPYjIDeAsAFDLIhwC2EAXMgM5gYgDmANOZexGAE0IcKAAoAJjgbIAIlICUjEAFcaAI2jcKyPmABKEBHijiAwgUjhRANzgAbZRCZLVGqAG0AuouatQ7L3IAX3JycUM7ERQYZRAEXAIdfgBZOFB0TGwEkAMjE3NwLDAbe0dnKldoLx8WNgDPULIjEBYkkGgpVPSMIpx8FuQAXmQAHgAVZAgAD0txJl86zmQx5QAHOxRp2fmxrwA+UR5kGjSQDN7spgA5WidGdwA6J5X1iAayHyJkdwBJEHCpshQMgANYQACeeBgyzWG08jHOWX6yCCQz2xCOzVakBoqwRPSRBC8Q2Op0RYD6BGutyYDxOq0O2koJ26mQp2RudDRyFEpCZlCot0YLLOBPZ-U5EC0AoFuiEIgkCgx-JlUH4yighEkkAeugAYso7HZ5WJ5EcZUFpTKkvpDMYzBYioxdF1RWzKTk7flHeBzSizdoA0c1WANYQcatkHB5rEQSA8AB3QjR4jfP4AoGEMGQ6EvOH493ZFHBRpYsCk1kXfrzYZ8dpQTpksUepiidxHABEqHaHatHbGCbwvc7YwAFmqIB3yN4gA" rel="nofollow noreferrer">Playground

Body:
You can use temp as any

const generateMainOrientations = <T extends readonly string[]>(
  mainOrientationsNames: T
): { [Index in keyof T]: Orientation } => {
  const temp = mainOrientationsNames.map((mainOrientationName) => ({
    name: mainOrientationName,
    getYear(date: Date) {
      return date.getFullYear();
    },
    getRecordContent: getMainOrientationRecordContent
  }));

  return temp as any;
};


问:
Why am I getting an error in C# when mixing explicit implementation and polymorphism?
I am getting this error:

type  Bar does not implement interface IFoo

From this code:

```<code>public interface IFoo
{
   void DoA();

   void DoB();
}

public class Foo:IFoo
{

    void IFoo.DoA()
    {

    }

    void IFoo.DoB()
    {

   }
}

public class Bar:Foo
{

     void IFoo.DoA()
      {
          base.doA();

      }

      void IFoo.DoB()
      {
          base.doB();

      }
  }
</code>```

I am using C# 2.0.

What am I doing wrong?

答:
I have run into this as well. what is 'worse', depending on how you look at it is you can't define the interface implementations to be virtual to be overridden in descendent classes. I have gotten into the habit of doing this:</p>

```<code>public class Foo:IFoo
{
     void IFoo.DoA()
     {
          DoACore();
     }
     void IFoo.DoB()
     {
          DoBCore();
     }
     protected virtual void DoACore()
     {
     }
     protected virtual void DoBCore()
     {
     }
}
public class Bar:Foo
{     protected override void DoACore()
      {
          base.DoACore();
      }
      protected override void DoBCore()
      {
          base.DoBCore();
      }
}
</code>```

OwnerDisplayName: Sasha

LastEditorDisplayName: Sasha

ContentLicense: CC BY-SA 2.5

Body:
I am getting this error:

type  Bar does not implement interface IFoo

From this code:

public interface IFoo
{
   void DoA();

   void DoB();
}

public class Foo:IFoo
{

    void IFoo.DoA()
    {

    }

    void IFoo.DoB()
    {

   }
}

public class Bar:Foo
{

     void IFoo.DoA()
      {
          base.doA();

      }

      void IFoo.DoB()
      {
          base.doB();

      }
  }

I am using C# 2.0.

What am I doing wrong?

Body:
I have run into this as well. what is 'worse', depending on how you look at it is you can't define the interface implementations to be virtual to be overridden in descendent classes. I have gotten into the habit of doing this:

public class Foo:IFoo
{
     void IFoo.DoA()
     {
          DoACore();
     }
     void IFoo.DoB()
     {
          DoBCore();
     }
     protected virtual void DoACore()
     {
     }
     protected virtual void DoBCore()
     {
     }
}
public class Bar:Foo
{     protected override void DoACore()
      {
          base.DoACore();
      }
      protected override void DoBCore()
      {
          base.DoBCore();
      }
}


问:
how to send text(objects) from my activity to android's mms.apk
Before, i used intents for same activity. I have sent some text to other class via implementing serializable both of class which is sending texts and other class which is taken texts.
I used them:
Text Sending Class Has::
intent.putExtra("text",text);
startActivity(intent);
Text Receiving Class Has:
 getIntent().getSerializableExtra("text").toString();
In my question for my new application, i have a listactivity which is stored some text. I want to send choosen text from list to send mms.apk's textfield. Is it possible to do that?
Then user choose person from telephone directory and send message.

Many Thanks.

答:
I'm think your asking how to send a SMS from within you activity with a specific string... if that is the case then to send an SMS from within your activity you create a sms intent:

```<code>i = new Intent(Intent.ACTION_SENDTO, Uri.parse("sms:"));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("sms_body", "your string here");
</code>```

See this question too: launch sms application with an intent

Body:
I'm think your asking how to send a SMS from within you activity with a specific string... if that is the case then to send an SMS from within your activity you create a sms intent:

i = new Intent(Intent.ACTION_SENDTO, Uri.parse("sms:"));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("sms_body", "your string here");

See this question too: launch sms application with an intent


问:
Close react button dropdown menu on clicking or hovering outside of menu area
In my react application one of the component is creating a button dropdown menu like below.

```<code><div class="dropdown">
    <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Dropdown Example
    <span class="caret"></span></button>
    <ul class="dropdown-menu">
      <li><a onClick=doSomething href="#">HTML</a></li>
      <li><a onClick=doSomething href="#">CSS</a></li>
      <li><a onClick=doSomething href="#">JavaScript</a></li>
    </ul>
</div>
</code>```

How can I close this menu if someone clicks/hovers anywhere outside of this menu area?

答:
onBlur = {() => console.log("Clicked outside")}

The above method is triggered when clicked outside the Dropdown. You can change the states etc to show or hide your div or react dropdown

Body:
In my react application one of the component is creating a button dropdown menu like below.

    <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Dropdown Example
    </button>

HTML

CSS

JavaScript

How can I close this menu if someone clicks/hovers anywhere outside of this menu area?


问:
How to build web component with styling library using vite and vue 3?
I am able to build vue web component and load it in other pages, but I can't find document how to correctly include a UI framework. It seems the web component is under shadowDOM and import css using style tag won't work.

(Add the CDN link in the template and style is applied)

Any hint on any framework,  Vuetify or Ant Design or Tailwind CSS will be appreciated.

Similar question: Vuetify build as Web component style not showing

答:
Using custom elements without Shadow DOM is trivial. Just add like the way you do traditionally. However, with Shadow DOM, things are tricky. Only inheritable CSS styles pass through the Shadow DOM. Everything else is blocked. No straight forward integration with existing design systems (Vuetify, Ant, etc.) is not directly possible if that library is only exposing global CSS.

If the design system or a component library is exposing styles i.e. css files for individual components, then you can that with some effort.

The best solution is to use constructable stylesheet. You can use a bundler like Webpack to load the stylesheet for individual component (if and only if it is provided) as a string and feed it to the stylesheet constructor method as illustrated here.

```<code>// Read SCSS file as a raw CSS text using Webpack/Rollup/Parcel
import styleText from './my-component.scss';

const sheet = new CSSStyleSheet();sheet.replaceSync(styleText);

// Use the sheet inside the web component constructor
shadowRoot.adoptedStyleSheets = [sheet];
</code>```

However, Firefox and Safari are yet to implement it.

If you need a fallback, then there are ways that are not so clean. Approach is same. Import the CSS/SCSS as a string and using the template literal, add it to the element's inner style tag.

```<code>import styleText from 'ant/button.css';

class FancyComponent extends HTMLElement {

  constructor() {
    super();

    const shadowRoot = this.attachShadow({ mode: 'open' });

    shadowRoot.innerHTML = `
      <!-- Styles are scoped -->
      <style>
        ${styleText}
      </style>
      <div>
        <p>Hello World</p>
      </div>
    `;
  }
}

customElements.define('fancy-comp', FacyComponent);
</code>```

This all relies on the assumption that ant/material/veutify is exposing styles as individual files instead of one global file.

Alternately, the browsers have started supporting the link tag inside the Shadow DOM. But again it is really useful if you have styles for individual components. Read more about that here.

Body:
Using custom elements without Shadow DOM is trivial. Just add like the way you do traditionally. However, with Shadow DOM, things are tricky. Only inheritable CSS styles pass through the Shadow DOM. Everything else is blocked. No straight forward integration with existing design systems (Vuetify, Ant, etc.) is not directly possible if that library is only exposing global CSS.

If the design system or a component library is exposing styles i.e. css files for individual components, then you can that with some effort.

The best solution is to use constructable stylesheet. You can use a bundler like Webpack to load the stylesheet for individual component (if and only if it is provided) as a string and feed it to the stylesheet constructor method as illustrated here.

// Read SCSS file as a raw CSS text using Webpack/Rollup/Parcel
import styleText from './my-component.scss';

const sheet = new CSSStyleSheet();sheet.replaceSync(styleText);

// Use the sheet inside the web component constructor
shadowRoot.adoptedStyleSheets = [sheet];

However, Firefox and Safari are yet to implement it.

If you need a fallback, then there are ways that are not so clean. Approach is same. Import the CSS/SCSS as a string and using the template literal, add it to the element's inner style tag.

import styleText from 'ant/button.css';

class FancyComponent extends HTMLElement {

  constructor() {
    super();

    const shadowRoot = this.attachShadow({ mode: 'open' });

    shadowRoot.innerHTML = `
      <!-- Styles are scoped -->
      <style>
        ${styleText}
      </style>
      <div>
        <p>Hello World</p>
      </div>
    `;
  }
}

customElements.define('fancy-comp', FacyComponent);

This all relies on the assumption that ant/material/veutify is exposing styles as individual files instead of one global file.

Alternately, the browsers have started supporting the link tag inside the Shadow DOM. But again it is really useful if you have styles for individual components. Read more about that here.


问:
CakePHP where can I put this code for reuse?
I have a model called PageMetaData that contains a title and a description. This is to be tied to any other model and to be used as the title tag and meta description for the page.

So I have a model called Brand. Brand has a field called page_meta_data_id and Brand belongsTo PageMetaData

Now on the view for Brand I can run this code:

```<code>if(!empty($data['PageMetaData']['title']))
{
    $this->set('title_for_layout', $data['PageMetaData']['title']);
}
else if(!empty($data['Brand']['name']))
{
    $this->set('title_for_layout', $data['Brand']['name']);
}
if(!empty($data['PageMetaData']['description']))
{
    echo $this->Html->meta('description', $data['PageMetaData']['description'],array('inline'=>false));
}
else if(!empty($data['Brand']['description']))
{
    echo $this->Html->meta('description', $data['Brand']['description'],array('inline'=>false));
}
</code>```

And if a PageMetaData has been associated to the current Brand and has a value for title, it will set that as the page title, otherwise if the brand has a field called name it will us that. Same for description.

The problem is I don't want to have to diplicate this code in every view for every model that uses PageMetaData.

I cannot figure out where I can abstract the code to, to avoid duplication.

I cannot put it in a Behavior or a Helper because you cannot set the title from either. I cannot put it in a Component because it cannot access the data found from the model.

Is there somewhere I can put this code for reuse?

答:
You can possibly use elements for this. have a look at the cookbook link:

http://book.cakephp.org/view/1081/Elements

Body:
I have a model called PageMetaData that contains a title and a description. This is to be tied to any other model and to be used as the title tag and meta description for the page.

So I have a model called Brand. Brand has a field called page_meta_data_id and Brand belongsTo PageMetaData

Now on the view for Brand I can run this code:

if(!empty($data['PageMetaData']['title']))
{
    $this->set('title_for_layout', $data['PageMetaData']['title']);
}
else if(!empty($data['Brand']['name']))
{
    $this->set('title_for_layout', $data['Brand']['name']);
}
if(!empty($data['PageMetaData']['description']))
{
    echo $this->Html->meta('description', $data['PageMetaData']['description'],array('inline'=>false));
}
else if(!empty($data['Brand']['description']))
{
    echo $this->Html->meta('description', $data['Brand']['description'],array('inline'=>false));
}

And if a PageMetaData has been associated to the current Brand and has a value for title, it will set that as the page title, otherwise if the brand has a field called name it will us that. Same for description.

The problem is I don't want to have to diplicate this code in every view for every model that uses PageMetaData.

I cannot figure out where I can abstract the code to, to avoid duplication.

I cannot put it in a Behavior or a Helper because you cannot set the title from either. I cannot put it in a Component because it cannot access the data found from the model.

Is there somewhere I can put this code for reuse?


问:
Finding Number of pages from the total number of digits used to number the pages
I am stuck in a problem where the user inputs the total number of digits used in numbering the pages and the program gives the total number of pages in the book.

(i.e. a book of 10 pages needs 11 digits to number because the numbers 1-9 are written with one digit and the number 10 is written with two digits; an 11 pages book requires 13 digits ...).

I tried it by using a while loop but it does not run as it exceeds the execution time.

My C code looks like this:

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

int main() {
    int n, pages = 9;
    scanf("%d", &n);

    if (n <= 9) {
        printf("%d",n);
    }
    else if (n % 2 == 0) {
        printf("Invalid input");
    }
    else {
        while (n < 9) {
            pages++;
            n -= 2;
        }
    }
    return 0;
}
</code>```

Can anyone please help me with this problem?

答:
```<code>else if(n%2==0)
{
    printf("Invalid input");
}
</code>```

Please note that there are books with more than 100 pages:

A book with 102 pages has 198 digits!

```<code> while(n!=0)
 {
     pages++;
     n-=2;
 }
</code>```

This loop will run forever:

Because n is initially an odd number, n-2 is also odd. So n will always be odd (maybe negative) if n-=2 is the only instruction that modifies n. n cannot become 0, so the loop will run forever.

You also have to consider that books with more than 100 pages or with more than 1000 pages may exist.

I would do it the other way round and count pages up from 1 to N. I would sum up the digits required for the given number of pages and stop when the number of digits is exceeded:

```<code>int n, pages=0, digits=0;
int realdigits=0, neededdigits, tooLarge;

/* "realdigits" is the number of digits required
 * by "pages" pages; loop until
 * "realdigits" >= "digits" */
while(realdigits < digits)
{
    pages++;
    /*
     * Add some code that calculates:
     * neededdigits = Number of digits required by
     *                the number "pages"
     */
    realdigits += neededdigits;
}
/* Case: "(pages-1)" pages need less digits
 * than "digits" but "pages" pages need more
 * digits... */
if(realdigits > digits)
{
    printf("Invalid number\n");
}
else
{
    printf("%d pages\n", pages);
}
</code>```

I would use a loop based on a condition to calculate the number of digits required by the number pages:

```<code>neededdigits = 1;
tooLarge = 10; /* Number that is too large for digits */
while(pages >= tooLarge)
{
    neededdigits++;
    tooLarge *= 10;
}
</code>```

Note that in "C-like" programming languages (C, C++, Java, C#, PHP ...) you may use the for keyword for "condition-based" loops ...

Body:
I am stuck in a problem where the user inputs the total number of digits used in numbering the pages and the program gives the total number of pages in the book.

(i.e. a book of 10 pages needs 11 digits to number because the numbers 1-9 are written with one digit and the number 10 is written with two digits; an 11 pages book requires 13 digits ...).

I tried it by using a while loop but it does not run as it exceeds the execution time.

My C code looks like this:

#include <stdio.h>

int main() {
    int n, pages = 9;
    scanf("%d", &n);

    if (n <= 9) {
        printf("%d",n);
    }
    else if (n % 2 == 0) {
        printf("Invalid input");
    }
    else {
        while (n < 9) {
            pages++;
            n -= 2;
        }
    }
    return 0;
}

Can anyone please help me with this problem?

Body:
else if(n%2==0)
{
    printf("Invalid input");
}

Please note that there are books with more than 100 pages:

A book with 102 pages has 198 digits!

 while(n!=0)
 {
     pages++;
     n-=2;
 }

This loop will run forever:

Because n is initially an odd number, n-2 is also odd. So n will always be odd (maybe negative) if n-=2 is the only instruction that modifies n. n cannot become 0, so the loop will run forever.

You also have to consider that books with more than 100 pages or with more than 1000 pages may exist.

I would do it the other way round and count pages up from 1 to N. I would sum up the digits required for the given number of pages and stop when the number of digits is exceeded:

int n, pages=0, digits=0;
int realdigits=0, neededdigits, tooLarge;

/* "realdigits" is the number of digits required
 * by "pages" pages; loop until
 * "realdigits" >= "digits" */
while(realdigits < digits)
{
    pages++;
    /*
     * Add some code that calculates:
     * neededdigits = Number of digits required by
     *                the number "pages"
     */
    realdigits += neededdigits;
}
/* Case: "(pages-1)" pages need less digits
 * than "digits" but "pages" pages need more
 * digits... */
if(realdigits > digits)
{
    printf("Invalid number\n");
}
else
{
    printf("%d pages\n", pages);
}

I would use a loop based on a condition to calculate the number of digits required by the number pages:

neededdigits = 1;
tooLarge = 10; /* Number that is too large for digits */
while(pages >= tooLarge)
{
    neededdigits++;
    tooLarge *= 10;
}

Note that in "C-like" programming languages (C, C++, Java, C#, PHP ...) you may use the for keyword for "condition-based" loops ...


问:
Intellij Maven dependency not resolved while following guide
I am currently trying to follow this guide and every time I try to run the test code I am getting this error:

[ERROR] Failed to execute goal on project MyBot: Could not resolve
dependencies for project org.example:MyBot:jar:1.0-SNAPSHOT:
org.javacord:javacord:jar:3.4.0 was not found in
https://repo.maven.apache.org/maven2 during a previous attempt. This
failure was cached in the local repository and resolution is not
reattempted until the update interval of central has elapsed or
updates are forced -> [Help 1]

pom.xml

答:
Maybe you have to load the dependencies you added to the pom.xml.

in IntelliJ you can right click on your pom.xml chose maven -> reload Project.
This loads all dependencies from pom.xml.
Check the console output for any errors.


问:
how to css link influence only to a "div" card?
I have a project and use more than 1 template I have problems with 2 css links from 2 different templates, I want the css link from templates to only affect a single html card without affecting the rest in file .cshtml . Please give me a solution.

I have the layout.cshtml file as follows and the css link in my 2nd templates in the last line

    <title>POU Education Category Bootstrap Responsive website Template | Home :: w3layouts</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="keywords" content="POU Responsive web template, Bootstrap Web Templates, Flat Web Templates, Android Compatible web template,
    SmartPhone Compatible web template, free WebDesigns for Nokia, Samsung, LG, Sony Ericsson, Motorola web design" />

    <link href="~/home/css/bootstrap.css" type="text/css" rel="stylesheet" media="all">

    <link href="~/home/css/shop.css" type="text/css" rel="stylesheet" media="all">
    <link href="~/home/css/style.css" type="text/css" rel="stylesheet" media="all">

    <link href="~/home/css/font-awesome.css" rel="stylesheet">

    <link href="//fonts.googleapis.com/css?family=Fredericka+the+Great" rel="stylesheet">

    <link href="//fonts.googleapis.com/css?family=Merriweather+Sans:300,300i,400,400i,700,700i,800,800i" rel="stylesheet">

    <link href="//fonts.googleapis.com/css?family=Roboto:100,100i,300,300i,400,400i,500,500i,700,700i,900,900i" rel="stylesheet">

        <link href="//fonts.googleapis.com/css2?family=Hind:wght@300;400;500;600&display=swap" rel="stylesheet">
    <link href="//fonts.googleapis.com/css2?family=Libre+Baskerville:wght@400;700&display=swap" rel="stylesheet">
    <link href="~/css/style-starter.css" type="text/css" rel="stylesheet">
```
</div>
</div>
</p>
<p>This is an index.cshtml file code that uses the layout above</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--end post-->
<div class="w3l-homeblock2 py-5">
    <div class="container py-lg-5 py-md-4">
        <!-- block -->
        <div class="row">
            <div class="col-lg-12">
                <h3 class="section-title-left mb-4"> Editor's Pick </h3>
                <div class="row">
                    <div class="col-lg-6 col-md-6 item">
                        <div class="card">
                            <div class="card-header p-0 position-relative">

                                    <img class="card-img-bottom d-block radius-image-full"
                                        src="assets/images/image1.jpg" alt="Card image cap">

                            </div>
                            <div class="card-body blog-details">
                                <span class="label-blue">Beauty</span>
                                The 3 Eyeshadow palettes I own & How to
                                    downsize your stash

                                <p>Lorem ipsum dolor sit amet consectetur ipsum adipisicing elit. Quis
                                    vitae sit.</p>
                                <div class="author align-items-center mt-3 mb-1">
                                    <img src="assets/images/a1.jpg" alt="" class="img-fluid rounded-circle" />
                                    <ul class="blog-meta">
                                        <li>
                                            Isabella ava </a>
                                        </li>
                                        <li class="meta-item blog-lesson">
                                            <span class="meta-value"> July 13, 2020 </span>. <span
                                                class="meta-value ml-2"><span class="fa fa-clock-o"></span> 1 min</span>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-6 col-md-6 mt-md-0 mt-sm-5 mt-4">
                        <div class="card">
                            <div class="card-header p-0 position-relative">

                                    <img class="card-img-bottom d-block radius-image-full"
                                        src="assets/images/image2.jpg" alt="Card image cap">

                            </div>
                            <div class="card-body blog-details">
                                <span class="label-blue">Fashion</span>
                                2 New outfit formulas to add to your
                                    Capsule Wardrobe

                                <p>Lorem ipsum dolor sit amet consectetur ipsum adipisicing elit. Quis
                                    vitae sit.</p>
                                <div class="author align-items-center mt-3 mb-1">
                                    <img src="assets/images/a2.jpg" alt="" class="img-fluid rounded-circle" />
                                    <ul class="blog-meta">
                                        <li>
                                            Charlotte mia </a>
                                        </li>
                                        <li class="meta-item blog-lesson">
                                            <span class="meta-value"> July 13, 2020 </span>. <span
                                                class="meta-value ml-2"><span class="fa fa-clock-o"></span> 1 min</span>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div></code>```

I would like to take the path css at the bottom of the layout.cshtml file (<link href="~/css/style-starter.css" type="text/css" rel="stylesheet">) only affects the card // in the first line (//) but other card components will not be usable  in the index file.cshtml

答:
What I understand is that you got 2-cards in 2-separate-html-files, now you want some global-css to be applied on one, but not in the other html-file or some card contained there.

Solution-1:

Add an extra class like .special-card and use this class in 1st-file to add CSS to the card selectively, based on this class. Now, when you don't have attach this class in the 2nd card, CSS will NOT be automatically applied there.

Solution-2:

In card, where you don't want the CSS to be applied, use Inline-CSS adding styles in the html-element directly to override CSS coming from global-CSS file.

Solution-3:

Keep the CSS that you want to partially apply in some separate test.css file, and attach it to only the card (externally), where you want to apply this. Just don't just attach this external .CSS file in your 2nd html file, so it won't take affect.

Body:
I have a project and use more than 1 template I have problems with 2 css links from 2 different templates, I want the css link from templates to only affect a single html card without affecting the rest in file .cshtml . Please give me a solution.

I have the layout.cshtml file as follows and the css link in my 2nd templates in the last line

    <title>POU Education Category Bootstrap Responsive website Template | Home :: w3layouts</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="keywords" content="POU Responsive web template, Bootstrap Web Templates, Flat Web Templates, Android Compatible web template,
    SmartPhone Compatible web template, free WebDesigns for Nokia, Samsung, LG, Sony Ericsson, Motorola web design" />

    <link href="~/home/css/bootstrap.css" type="text/css" rel="stylesheet" media="all">

    <link href="~/home/css/shop.css" type="text/css" rel="stylesheet" media="all">
    <link href="~/home/css/style.css" type="text/css" rel="stylesheet" media="all">

    <link href="~/home/css/font-awesome.css" rel="stylesheet">

    <link href="//fonts.googleapis.com/css?family=Fredericka+the+Great" rel="stylesheet">

    <link href="//fonts.googleapis.com/css?family=Merriweather+Sans:300,300i,400,400i,700,700i,800,800i" rel="stylesheet">

    <link href="//fonts.googleapis.com/css?family=Roboto:100,100i,300,300i,400,400i,500,500i,700,700i,900,900i" rel="stylesheet">

        <link href="//fonts.googleapis.com/css2?family=Hind:wght@300;400;500;600&display=swap" rel="stylesheet">
    <link href="//fonts.googleapis.com/css2?family=Libre+Baskerville:wght@400;700&display=swap" rel="stylesheet">
    <link href="~/css/style-starter.css" type="text/css" rel="stylesheet">

This is an index.cshtml file code that uses the layout above

 Editor's Pick

                                Beauty
                                The 3 Eyeshadow palettes I own & How to
                                    downsize your stash

Lorem ipsum dolor sit amet consectetur ipsum adipisicing elit. Quis
                                    vitae sit.

                                            Isabella ava

                                             July 13, 2020 .  1 min

                                Fashion
                                2 New outfit formulas to add to your
                                    Capsule Wardrobe

Lorem ipsum dolor sit amet consectetur ipsum adipisicing elit. Quis
                                    vitae sit.

                                            Charlotte mia

                                             July 13, 2020 .  1 min

I would like to take the path css at the bottom of the layout.cshtml file (<link href="~/css/style-starter.css" type="text/css" rel="stylesheet">) only affects the card // in the first line (//) but other card components will not be usable  in the index file.cshtml


问:
Amazon SES failure with smtp retcode 250
I try to send email with amazon SES API docs below, and python return the code 250 meaing OK but my email got a failure message. Could anyone kindly tell me what maybe the problem? thank you

python:

```<code>import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# https://us-east-2.console.aws.amazon.com/sesv2/home?region=us-east-2#/account
# https://console.aws.amazon.com/iam/home?#/s=SESHomeV4/us-east-2
mail_host = "email-smtp.us-east-2.amazonaws.com"
mail_user = "AKI....T7H"
mail_pass = "BHJ.....iS/x"

sender = 'thelou1s@...com'
receivers = 'thelou1s@...com'

msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receivers
msg['Subject'] = 'simple email in python'
message = 'here is the email'
msg.attach(MIMEText(message))

try:
    print("try smtplib.SMTP")
    smtp = smtplib.SMTP(mail_host, 587)
    smtp.set_debuglevel(True)

    print("try connect")
    smtp.ehlo()
    smtp.starttls()
    smtp.ehlo()
    # smtpObj.connect(mail_host, 465)

    print("try login")
    smtp.login(mail_user, mail_pass)
    print("try sendmail: " + msg.as_string())
    smtp.sendmail(sender, receivers, msg.as_string())
    print("Send Success")
    smtp.close()
except smtplib.SMTPException:
    print("Send Error")
</code>```

log (Is retcode 250 means success in code side or user side?):

```<code>reply: retcode (250); Msg: b'Ok 010f017d8f0f1703-d018f2a9-833e-428e-9010-5e45818e51e4-000000'
data: (250, b'Ok 010f017d8f0f1703-d018f2a9-833e-428e-9010-5e45818e51e4-000000')
Send Success
</code>```

emails from amazon:

```<code>Delivery Status Notification (Failure)
An error occurred while trying to deliver the mail to the following recipients:
thelou1s@...com
here is the email
</code>```

答: Just validate your email in amazon console</p>

Body:
I try to send email with amazon SES API docs below, and python return the code 250 meaing OK but my email got a failure message. Could anyone kindly tell me what maybe the problem? thank you

python:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# https://us-east-2.console.aws.amazon.com/sesv2/home?region=us-east-2#/account
# https://console.aws.amazon.com/iam/home?#/s=SESHomeV4/us-east-2
mail_host = "email-smtp.us-east-2.amazonaws.com"
mail_user = "AKI....T7H"
mail_pass = "BHJ.....iS/x"

sender = 'thelou1s@...com'
receivers = 'thelou1s@...com'

msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receivers
msg['Subject'] = 'simple email in python'
message = 'here is the email'
msg.attach(MIMEText(message))

try:
    print("try smtplib.SMTP")
    smtp = smtplib.SMTP(mail_host, 587)
    smtp.set_debuglevel(True)

    print("try connect")
    smtp.ehlo()
    smtp.starttls()
    smtp.ehlo()
    # smtpObj.connect(mail_host, 465)

    print("try login")
    smtp.login(mail_user, mail_pass)
    print("try sendmail: " + msg.as_string())
    smtp.sendmail(sender, receivers, msg.as_string())
    print("Send Success")
    smtp.close()
except smtplib.SMTPException:
    print("Send Error")

log (Is retcode 250 means success in code side or user side?):

reply: retcode (250); Msg: b'Ok 010f017d8f0f1703-d018f2a9-833e-428e-9010-5e45818e51e4-000000'
data: (250, b'Ok 010f017d8f0f1703-d018f2a9-833e-428e-9010-5e45818e51e4-000000')
Send Success

emails from amazon:

Delivery Status Notification (Failure)
An error occurred while trying to deliver the mail to the following recipients:
thelou1s@...com
here is the email


问:
Why does this simple 64-bit/32-bit division algorithm using 32-bit division work?
I was looking for a 64-bit/32-bit division algorithm preferably with a small code size for a 32-bit x86 machine. I found this surprisingly simple one, but couldn't see how it works.

The algorithm is as follows.

We are calculating x / y where x is 64-bit and y is 32-bit. Both are unsigned.

x.l is the lower bits of x, and x.h is the higher bits of x, assuming a little-endian machine.

h <- x.h / y

x.h <- x.h % y

x.l <- x / y, (x.h <- x % y); 64-bit/32-bit division only works when the quotient fits in 32 bits, which seems to be true in this case.

x.h <- h

return x

My math is just too short to easily get this algorithm. Could you help me to understand this algorithm?

This is a test program I wrote to see if it works.

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

typedef union {
    uint64_t q;
    struct {
        uint32_t l;
        uint32_t h;
    };
} uint64_u;

uint64_t div_(uint64_t _x, uint32_t y) {
    uint64_u x = {_x};
    uint32_t h = x.h / y;
    x.h = x.h % y;
    __asm__ (
        "div %2":
        "+a" (x.l),
        "+d" (x.h):
        "r" (y)
    );
    x.h = h;
    return x.q;
}

int main() {
    for (int i = 0; i < 1000000; ++i) {
        uint64_t x = (uint64_t)rand() << 32 | rand();
        uint32_t y = rand() % RAND_MAX + 1;
        uint64_t r0 = x / y;
        uint64_t r1 = div_(x, y);
        if (r0 != r1) {
            abort();
        }
    }
    return 0;
}
</code>```

答:
The algorithm is an adaptation of the classic long division method taught in high schools:

instead of base 10, use base 232

dividing a 64-bit dividend by a 32-bit divisor is akin to dividing a 2 digit number A:B by a one digit number C

take the first digit A and divide that by the dividend C: in A goes D times C, remainder E

take the next digit B: in E:B goes F times C, remainder G (ignored in the code, but could be returned via a pointer)

the result is D:F as constructed in the code.

The code uses a div instruction that takes a 64-bit operand EDX:EAX constructed as above from (x.h % y):(x.l).  See https://godbolt.org/z/7x9K8dzsf

A fully portable version, without assembly and using only 32-bit operations is more difficult to write efficiently.

Body:
I was looking for a 64-bit/32-bit division algorithm preferably with a small code size for a 32-bit x86 machine. I found this surprisingly simple one, but couldn't see how it works.

The algorithm is as follows.

We are calculating x / y where x is 64-bit and y is 32-bit. Both are unsigned.

x.l is the lower bits of x, and x.h is the higher bits of x, assuming a little-endian machine.

h <- x.h / y

x.h <- x.h % y

x.l <- x / y, (x.h <- x % y); 64-bit/32-bit division only works when the quotient fits in 32 bits, which seems to be true in this case.

x.h <- h

return x

My math is just too short to easily get this algorithm. Could you help me to understand this algorithm?

This is a test program I wrote to see if it works.

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

typedef union {
    uint64_t q;
    struct {
        uint32_t l;
        uint32_t h;
    };
} uint64_u;

uint64_t div_(uint64_t _x, uint32_t y) {
    uint64_u x = {_x};
    uint32_t h = x.h / y;
    x.h = x.h % y;
    __asm__ (
        "div %2":
        "+a" (x.l),
        "+d" (x.h):
        "r" (y)
    );
    x.h = h;
    return x.q;
}

int main() {
    for (int i = 0; i < 1000000; ++i) {
        uint64_t x = (uint64_t)rand() << 32 | rand();
        uint32_t y = rand() % RAND_MAX + 1;
        uint64_t r0 = x / y;
        uint64_t r1 = div_(x, y);
        if (r0 != r1) {
            abort();
        }
    }
    return 0;
}


问:
How to ignore a Task in F#?
If we have a function f that returns Async<something>, we can ignore the return value with do! f() |> Async.Ignore. Is there a similar construct for ignoring Tasks? Right now, I'm having to do something like this:

task {
    let! result = SomeOperation()
    result |> ignore
}
```

Technically I could do |> Async.AwaitTask |> Async.Ignore, but I'm not sure how wasteful it is to convert a task to async just to ignore it...

If it matters, I'm using task{} computation expressions from Ply.

答:
You can wait for a task to complete using the Result property:

```<code>let t =
    task {
        let! _ = SomeOperation()
        ()
    }
let _ = t.Result
</code>```

Title: How to ignore a Task in F#?

Body:
If we have a function f that returns Async<something>, we can ignore the return value with do! f() |> Async.Ignore. Is there a similar construct for ignoring Tasks? Right now, I'm having to do something like this:

task {
    let! result = SomeOperation()
    result |> ignore
}

Technically I could do |> Async.AwaitTask |> Async.Ignore, but I'm not sure how wasteful it is to convert a task to async just to ignore it...

If it matters, I'm using task{} computation expressions from Ply.

Body:
You can wait for a task to complete using the Result property:

let t =
    task {
        let! _ = SomeOperation()
        ()
    }
let _ = t.Result


问:
Dart - Call Named Constructor using super vs class name
```<code>class Person {
  late String name;
  late int age;
  Person();
  Person.ap(this.name, this.age);
}

class Employee extends Person {
  Employee(String name, int age) : super.ap(name, age); // This works

  // This is giving error. The method 'ap' isn't defined in a superclass of 'Employee'.
  Employee(String name, int age) {
    super.ap(name, age);
  }
}
</code>```

What's the difference of calling unnamed constructor using super or inside the parenthesis?

答:
You are making two same-named constructors. Do something like this</p>
```<code>class Employee extends Person {

Employee(String name, int age) : super.ap(name, age);

Employee.foo(String name, int age): super.ap(name, age);

}
</code>```

Body:
class Person {
  late String name;
  late int age;
  Person();
  Person.ap(this.name, this.age);
}

class Employee extends Person {
  Employee(String name, int age) : super.ap(name, age); // This works

  // This is giving error. The method 'ap' isn't defined in a superclass of 'Employee'.
  Employee(String name, int age) {
    super.ap(name, age);
  }
}

What's the difference of calling unnamed constructor using super or inside the parenthesis?

Body:
You are making two same-named constructors. Do something like this

class Employee extends Person {

Employee(String name, int age) : super.ap(name, age);

Employee.foo(String name, int age): super.ap(name, age);

}


问:
Query AzureADExtensionProperty from Graph api
When i run this command i get the extension property list.
Get-AzureADExtensionProperty

```<code>
7da33d44-be79-4325-bad6-768125698316 extension_33e0eb1e326c430ea21852abdc035ac7_Fin_Role    {User}
0b3ff694-6b8a-4b1a-9d54-062b475289f6 extension_33e0eb1e326c430ea21852abdc035ac7_Contributor {User}
1d421ded-a7ed-4d6d-8e82-5erf012543bc extension_33e0eb1e326c430ea21852abdc035ac7_Reader      {User}
</code>```

how can i get the same records using graph api.

i already tried using https://graph.microsoft.com/v1.0/applications/id/extensionProperties but i got an empty array.

答:
Could you please verify the application id you are using is correct?

You can get List of application id by running the URL-https://graph.microsoft.com/v1.0/applications/

Then enter the application Id to URL - https://graph.microsoft.com/v1.0/applications/{id}/extensionProperties and retry the operation.

Body:
When i run this command i get the extension property list.
Get-AzureADExtensionProperty

7da33d44-be79-4325-bad6-768125698316 extension_33e0eb1e326c430ea21852abdc035ac7_Fin_Role    {User}
0b3ff694-6b8a-4b1a-9d54-062b475289f6 extension_33e0eb1e326c430ea21852abdc035ac7_Contributor {User}
1d421ded-a7ed-4d6d-8e82-5erf012543bc extension_33e0eb1e326c430ea21852abdc035ac7_Reader      {User}

how can i get the same records using graph api.

i already tried using https://graph.microsoft.com/v1.0/applications/id/extensionProperties but i got an empty array.


问:
Test if an internet connection is present in python
I have the following code that checks if an internet connection is present.

```<code>import urllib2

def internet_on():
    try:
        response=urllib2.urlopen('http://74.125.228.100',timeout=20)
        return True
    except urllib2.URLError as err: pass
    return False
</code>```

This will test for an internet connection, but how effective is it?

I know internet varies in quality from person to person, so I'm looking for something that is most effective for the broad spectrum, and the above code seems like there might be loopholes where people could find bugs. For instance if someone just had a really slow connection, and took longer than 20 seconds to respond.

答:
I have another solution. We have cmd command for checking connection: For example "netsh wlan show interface " this command in cmd gives us connection in and out speed. So you can use that in python:

```<code>from subprocess import check_output
</code>```

output=check_output(['netsh','wlan','show','interface'])

```<code>output=str(output) #to convert byte to string
</code>```

and then you can see the state of internet in the line started as Result:

... \r\n State : connected\r\n

then we can split it by '\r\n' character to extract the information we need or we can use Regular expression.

Body:
I have the following code that checks if an internet connection is present.

import urllib2

def internet_on():
    try:
        response=urllib2.urlopen('http://74.125.228.100',timeout=20)
        return True
    except urllib2.URLError as err: pass
    return False

This will test for an internet connection, but how effective is it?

I know internet varies in quality from person to person, so I'm looking for something that is most effective for the broad spectrum, and the above code seems like there might be loopholes where people could find bugs. For instance if someone just had a really slow connection, and took longer than 20 seconds to respond.

Body:
I have another solution. We have cmd command for checking connection: For example "netsh wlan show interface " this command in cmd gives us connection in and out speed. So you can use that in python:

from subprocess import check_output

output=check_output(['netsh','wlan','show','interface'])

output=str(output) #to convert byte to string

and then you can see the state of internet in the line started as Result:

... \r\n State : connected\r\n

then we can split it by '\r\n' character to extract the information we need or we can use Regular expression.


问:
Compiling Simulink Model based on NI Veristand and error: The name cannot start or end with / character
When Compiling Simulink Model based on NI Veristand
, I get a Model error - Error: NI Veristand Error: Invaild character in ‘model path’, exiting code generation. The name cannot start or end with / character.Then I check the model in model of the path, but don’t find relative character.
Finally I need to do something to solve this problem.

答: Name of simulink model hides part. And Compiling Simulink Model is correct after deleting hidden part.</p>


问:
SUBSTRING with multiple CHARINDEX options in query
A column I'm trying to extract only the last name from has possible combinations like H.Naude or H. Naude or H Naude and I need just the Naude part. If I use the SUBSTRING method I'm able to get the characters after either the space or the point but how to test for all 3 possibilities? Unfortunately this data comes from an imported entry form so I have no control as to how the data is formatted. Currently I have the following which is only for the space character

```<code>SUBSTRING(H.PtsNonFemale, CHARINDEX('' '', H.PtsNonFemale) +1, DATALENGTH(H.PtsNonFemale) - CHARINDEX('' '', H.PtsNonFemale) +1 ) AS Female
</code>```

Any assistance is much appreciated.

答:
Assuming the data provided covers all use-cases then you can simply test for each case in descending length order of the of the component you want to remove and use the first match (longest) found in the substring.

```<code>SELECT H.PtsNonFemale
    , SUBSTRING(H.PtsNonFemale, COALESCE(NULLIF(I.A,0)+6,NULLIF(I.B,0)+2,NULLIF(I.C,0)+1,NULLIF(I.D,0)+1), LEN(H.PtsNonFemale)) AS Female
FROM (
    VALUES
    ('H.Naude'), ('H. Naude'), ('H Naude'), ('A. M. Someone')
) H (PtsNonFemale)
CROSS APPLY (
    VALUES
    (PATINDEX('_. _. %', H.PtsNonFemale), CHARINDEX('. ',H.PtsNonFemale,0), CHARINDEX('.',H.PtsNonFemale,0), CHARINDEX(' ',H.PtsNonFemale,0))
) I (A, B, C, D);
</code>```

Returns:

PtsNonFemale
Female

H.Naude
Naude

H. Naude
Naude

H Naude
Naude

A. M. Someone
Someone

Body:
A column I'm trying to extract only the last name from has possible combinations like H.Naude or H. Naude or H Naude and I need just the Naude part. If I use the SUBSTRING method I'm able to get the characters after either the space or the point but how to test for all 3 possibilities? Unfortunately this data comes from an imported entry form so I have no control as to how the data is formatted. Currently I have the following which is only for the space character

SUBSTRING(H.PtsNonFemale, CHARINDEX('' '', H.PtsNonFemale) +1, DATALENGTH(H.PtsNonFemale) - CHARINDEX('' '', H.PtsNonFemale) +1 ) AS Female

Any assistance is much appreciated.

Body:
Assuming the data provided covers all use-cases then you can simply test for each case in descending length order of the of the component you want to remove and use the first match (longest) found in the substring.

SELECT H.PtsNonFemale
    , SUBSTRING(H.PtsNonFemale, COALESCE(NULLIF(I.A,0)+6,NULLIF(I.B,0)+2,NULLIF(I.C,0)+1,NULLIF(I.D,0)+1), LEN(H.PtsNonFemale)) AS Female
FROM (
    VALUES
    ('H.Naude'), ('H. Naude'), ('H Naude'), ('A. M. Someone')
) H (PtsNonFemale)
CROSS APPLY (
    VALUES
    (PATINDEX('_. _. %', H.PtsNonFemale), CHARINDEX('. ',H.PtsNonFemale,0), CHARINDEX('.',H.PtsNonFemale,0), CHARINDEX(' ',H.PtsNonFemale,0))
) I (A, B, C, D);

Returns:

PtsNonFemale
Female

H.Naude
Naude

H. Naude
Naude

H Naude
Naude

A. M. Someone
Someone


问:
Is there any way to add metadata to MongoDB Aggregation Queries?
Having a lots of apps accessing the MongoDB cluster, slow queries are hard to track. especially when it's an aggregation pipeline.

We're using MongoDB Atlas, where we have a profiler which shows the executed queries which ran beyond a threshold, say 5000ms, and also shows the corresponding collection. We can look at the slow queries but it doesn't give any hint which app has called for it. It requires to do a "find" for the relevant piece of query - throughout the applications in the whole solution. Very time consuming!

At the moment I'm using MongoDB C# Driver.

Is there any way to insert/add any "metadata" in MongoDB queries, like "name" or "calling-application", etc., and get it back from the slow queries section, or from the query logs?

Below is a sample db log (credentials redacted, for reference purpose only)

```<code>[conn280813] command <database>.<collection> command: aggregate
{ aggregate: "<collection>", pipeline: [ { $match: { <collection>.
<property2>: "XXXXXXXXXXXX", <collection>.<property3>:
"XXXXXXXXXXXXXXXXX", <collection>.<property4>: "XXXXXXX",
<collection>.<property5>: "XX", <collection>.<property6>: { $gte: 1
}, <collection>.<property7>: { $gte: new Date(1636730882184) } } },
{ $group: { _id: "$<collection>.<property>", count: { $sum:
"$<collection>.<property>" }, <aggregate-field>: { $first:
"$<collection>.<property>" } } }, { $sort: { count: -1 } }, {
$lookup: { from: "<collection>", let: { <out-field>: "$<property>"
}, pipeline: [ { $match: { $expr: { $eq: [ "$_id", "$$<property>" ]
} } }, { $graphLookup: { from: "<collection>", startWith: "$_id",
connectFromField: "<property>", connectToField: "_id", as: "
<object>", depthField: "level" } }, { $unwind: "$<object>" }, {
$unwind: "$<object>.<property>" }, { $match: { <object>.<property>:
<value> } }, { $group: { _id: "$<object>.<property>", <property>: {
$push: "$<object>.<property>" }, protectionLevel: { $push:
"$<object>.<property>" } } }, { $project: { _id: 0, <property>:
"$_id", <property2>: { $in: [ true, "$<property>" ] }, <property>:
{ $in: [ 1, "$<property>" ] } } } ], as: "<out-property>" } }, {
$unwind: { path: "$<property>" } }, { $match: { <object>.
<property>: false } }, { $limit: 50 }, { $lookup: { from: "
<collection>", localField: "_id", foreignField: "_id", as: "<out-
object>" } }, { $unwind: { path: "$<property>" } }, { $project: {
<property>: "$_id", count: 1, <property2>: 1, <property3>:
"$<object>.<property>" } }, { $unwind: { path: "$<property>" } }, {
$match: { <object>.<property>: "<filter-value>", <object>.
<property>: <value>, <object>.<property>: { $gt: 0 } } }, {
$project: { <collection>.<property>: { $arrayElemAt: [ { $map: {
input: { $filter: { input: "$<object>.<property>", as: "version",
cond: { $eq: [ "$<object>.<property>", "$$<object>.<property>" ] }
} }, as: "v", in: "$$<property>" } }, 0 ] }, <out-field>:
"$<property>", <out-field>: "$_id", <out-field>: "$<property>",
_id: 0 } }, { $lookup: { from: "<collection>", localField: "
<collection>.<property>", foreignField: "_id", as: "<collection>" }
}, { $project: { <out-field>: { $arrayElemAt: [ "$<collection>.
<property>", 0 ] }, <out-field>: 1, <out-field>: 1, <out-field>: 1
} }, { $limit: 5 } ], allowDiskUse: false, cursor: {}, $db: "<db>",
lsid: { id: UUID("XXXXXXXX-XXXXX-XXXX") }, $clusterTime: {
clusterTime: Timestamp(1644506882, 1), signature: { hash:
BinData(0, XXXXXXXXXXXXXXXXXXXXXXXXXX), keyId: XXXXXXXXXXXXX } } }
planSummary: IXSCAN { <object>.<property>: 1, <object>.<property>:
1, <object>.<property>: 1 } keysExamined:12476 docsExamined:12475
hasSortStage:1 cursorExhausted:1 numYields:99 nreturned:5
reslen:1138 locks:{ Global: { acquireCount: { r: 193 } }, Database:
{ acquireCount: { r: 193 } }, Collection: { acquireCount: { r: 192
} } } storage:{ data: { bytesRead: 10641559, timeReadingMicros:
59687 } } protocol:op_msg 263ms
</code>```

Thanks in advance.

答:
You can see in the logs the connectionId : conn280813  , if you search by this id you will find the IP from where the connection was made and the user , best practice is to create user per application so by the user to identify which app is connecting ...

The ACCESS message looks as follow:

```<code> 2022-02-14T09:27:26.423+0100 I ACCESS   [conn2800813] Successfully authenticated as principal <the_user_name> on admin from client <CLIENT_IP_ADDRESS>:<CLIENT_PORT_NO>
</code>```

Body:
Having a lots of apps accessing the MongoDB cluster, slow queries are hard to track. especially when it's an aggregation pipeline.

We're using MongoDB Atlas, where we have a profiler which shows the executed queries which ran beyond a threshold, say 5000ms, and also shows the corresponding collection. We can look at the slow queries but it doesn't give any hint which app has called for it. It requires to do a "find" for the relevant piece of query - throughout the applications in the whole solution. Very time consuming!

At the moment I'm using MongoDB C# Driver.

Is there any way to insert/add any "metadata" in MongoDB queries, like "name" or "calling-application", etc., and get it back from the slow queries section, or from the query logs?

Below is a sample db log (credentials redacted, for reference purpose only)

[conn280813] command <database>.<collection> command: aggregate
{ aggregate: "<collection>", pipeline: [ { $match: { <collection>.
<property2>: "XXXXXXXXXXXX", <collection>.<property3>:
"XXXXXXXXXXXXXXXXX", <collection>.<property4>: "XXXXXXX",
<collection>.<property5>: "XX", <collection>.<property6>: { $gte: 1
}, <collection>.<property7>: { $gte: new Date(1636730882184) } } },
{ $group: { _id: "$<collection>.<property>", count: { $sum:
"$<collection>.<property>" }, <aggregate-field>: { $first:
"$<collection>.<property>" } } }, { $sort: { count: -1 } }, {
$lookup: { from: "<collection>", let: { <out-field>: "$<property>"
}, pipeline: [ { $match: { $expr: { $eq: [ "$_id", "$$<property>" ]
} } }, { $graphLookup: { from: "<collection>", startWith: "$_id",
connectFromField: "<property>", connectToField: "_id", as: "
<object>", depthField: "level" } }, { $unwind: "$<object>" }, {
$unwind: "$<object>.<property>" }, { $match: { <object>.<property>:
<value> } }, { $group: { _id: "$<object>.<property>", <property>: {
$push: "$<object>.<property>" }, protectionLevel: { $push:
"$<object>.<property>" } } }, { $project: { _id: 0, <property>:
"$_id", <property2>: { $in: [ true, "$<property>" ] }, <property>:
{ $in: [ 1, "$<property>" ] } } } ], as: "<out-property>" } }, {
$unwind: { path: "$<property>" } }, { $match: { <object>.
<property>: false } }, { $limit: 50 }, { $lookup: { from: "
<collection>", localField: "_id", foreignField: "_id", as: "<out-
object>" } }, { $unwind: { path: "$<property>" } }, { $project: {
<property>: "$_id", count: 1, <property2>: 1, <property3>:
"$<object>.<property>" } }, { $unwind: { path: "$<property>" } }, {
$match: { <object>.<property>: "<filter-value>", <object>.
<property>: <value>, <object>.<property>: { $gt: 0 } } }, {
$project: { <collection>.<property>: { $arrayElemAt: [ { $map: {
input: { $filter: { input: "$<object>.<property>", as: "version",
cond: { $eq: [ "$<object>.<property>", "$$<object>.<property>" ] }
} }, as: "v", in: "$$<property>" } }, 0 ] }, <out-field>:
"$<property>", <out-field>: "$_id", <out-field>: "$<property>",
_id: 0 } }, { $lookup: { from: "<collection>", localField: "
<collection>.<property>", foreignField: "_id", as: "<collection>" }
}, { $project: { <out-field>: { $arrayElemAt: [ "$<collection>.
<property>", 0 ] }, <out-field>: 1, <out-field>: 1, <out-field>: 1
} }, { $limit: 5 } ], allowDiskUse: false, cursor: {}, $db: "<db>",
lsid: { id: UUID("XXXXXXXX-XXXXX-XXXX") }, $clusterTime: {
clusterTime: Timestamp(1644506882, 1), signature: { hash:
BinData(0, XXXXXXXXXXXXXXXXXXXXXXXXXX), keyId: XXXXXXXXXXXXX } } }
planSummary: IXSCAN { <object>.<property>: 1, <object>.<property>:
1, <object>.<property>: 1 } keysExamined:12476 docsExamined:12475
hasSortStage:1 cursorExhausted:1 numYields:99 nreturned:5
reslen:1138 locks:{ Global: { acquireCount: { r: 193 } }, Database:
{ acquireCount: { r: 193 } }, Collection: { acquireCount: { r: 192
} } } storage:{ data: { bytesRead: 10641559, timeReadingMicros:
59687 } } protocol:op_msg 263ms

Thanks in advance.

Body:
You can see in the logs the connectionId : conn280813  , if you search by this id you will find the IP from where the connection was made and the user , best practice is to create user per application so by the user to identify which app is connecting ...

The ACCESS message looks as follow:

 2022-02-14T09:27:26.423+0100 I ACCESS   [conn2800813] Successfully authenticated as principal <the_user_name> on admin from client <CLIENT_IP_ADDRESS>:<CLIENT_PORT_NO>


问:
Argument of type 'User' is not assignable to parameter of type 'FirebaseOperation'
Currently, I am facing this problem and I don't know what is it about:

```<code>SetUserData(user) {
const userRef: AngularFireList<any> = this.firebase.list(`users/${user.uid}`);
const userData: User = {
  uid: user.uid,
  email: user.email,
  displayName: user.displayName,
  photoURL: user.photoURL,
  emailVerified: user.emailVerified
}
return userRef.set(userData, {
  merge: true
})
}
</code>```

And this is an error in console:

error TS2345: Argument of type 'User' is not assignable to parameter of type 'FirebaseOperation'.
Type 'User' is missing the following properties from type 'DataSnapshot': child, exists, exportVal,
forEach, and 8 more.

答:
This simple solution worked for me. You could return a new object based on the old object.

Add the 'Object.assign()' to return a new object. Mozilla - Object.assign()

```<code>Object.assign()
</code>```

Your code refactored

```<code>SetUserData(user) {
  const userRef: AngularFireList<any> =
  this.firebase.list(`users/${user.uid}`);
  const userData: User = Object.assign({
    uid: user.uid,
    email: user.email,
    displayName: user.displayName,
    photoURL: user.photoURL,
    emailVerified: user.emailVerified
  })
  return userRef.set(userData, {
    merge: true
  })
}
</code>```

You could refactor using the deconstruct method, see below

```<code>// Don't forget to import this line
import firebase from "firebase/compat";

SetUserData({ uid, email, displayName, photoURL, emailVerified }: firebase.User) {
  const userRef: AngularFireList<any> = this.firebase.list(`users/${uid}`);
  const userData = Object.assign({ uid, email, displayName, photoURL, emailVerified })
  return userRef.set(userData, { merge: true })
}
</code>```

Body:
Currently, I am facing this problem and I don't know what is it about:

SetUserData(user) {
const userRef: AngularFireList<any> = this.firebase.list(`users/${user.uid}`);
const userData: User = {
  uid: user.uid,
  email: user.email,
  displayName: user.displayName,
  photoURL: user.photoURL,
  emailVerified: user.emailVerified
}
return userRef.set(userData, {
  merge: true
})
}

And this is an error in console:

error TS2345: Argument of type 'User' is not assignable to parameter of type 'FirebaseOperation'.
Type 'User' is missing the following properties from type 'DataSnapshot': child, exists, exportVal,
forEach, and 8 more.

Body:
This simple solution worked for me. You could return a new object based on the old object.

Add the 'Object.assign()' to return a new object. Mozilla - Object.assign()

Object.assign()

Your code refactored

SetUserData(user) {
  const userRef: AngularFireList<any> =
  this.firebase.list(`users/${user.uid}`);
  const userData: User = Object.assign({
    uid: user.uid,
    email: user.email,
    displayName: user.displayName,
    photoURL: user.photoURL,
    emailVerified: user.emailVerified
  })
  return userRef.set(userData, {
    merge: true
  })
}

You could refactor using the deconstruct method, see below

// Don't forget to import this line
import firebase from "firebase/compat";

SetUserData({ uid, email, displayName, photoURL, emailVerified }: firebase.User) {
  const userRef: AngularFireList<any> = this.firebase.list(`users/${uid}`);
  const userData = Object.assign({ uid, email, displayName, photoURL, emailVerified })
  return userRef.set(userData, { merge: true })
}


问:
Lodash Merge not updating object with correct values
I am trying to merge these two objects using Lodash merge.

Server object:

```<code>[
  {
    "id": "74738",
    "customerId": "534430"
  },
  {
    "id": "74742",
    "customerId": "534429"
  }
]
</code>```

Local Object

```<code>[
  {
    "customerId": "534429"
    "name": "ABC"
  },
  {
    "customerId": "534430",
    "name": "XYZ"
  },
]
</code>```

I am using lodash merge to combine these two objects based on attributes, I am using this code below:

```<code>merge({}, serverObject, localObject);

// Output: [{"id":"74738","customerId":"534429","name":"ABC"},{"id":"74742","customerId":"534430","name":"XYZ"}]
</code>```

The object is not being updated based on the Customer Ids but instead by the sequence of local object.

Expected Output:

```<code>[{"id":"74738","customerId":"534430","name":"ABC"},{"id":"74742","customerId":"534429","name":"XYZ"}]
</code>```

答:
With lodash you can combine all arrays to a single one using _.flatten(), group by a predicate, and then map and merge each group to a single object.

Note: since your customerId is an integer, the items would be ordered by the numerical value.

const { map, groupBy, flatten, merge } = _

const fn = (predicate, ...arrs) => map(
  groupBy(flatten(arrs), predicate),
  group => merge({}, ...group)
)

const arr1 = [{"id":"74738","customerId":"534430"},{"id":"74742","customerId":"534429"}]
const arr2 = [{"customerId":"534429","name":"ABC"},{"customerId":"534430","name":"XYZ"}]

const result = fn('customerId', arr1, arr2)

console.log(result)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script></code>```

If you need to preserve the original order, flatten to a single array, and then reduce the items to a Map using the result of the predicate as the key. Merge each new item with the same key to the existing one in the Map. Convert  the Map's values back to an array using Array.from():

const fn = (predicate, ...arrs) => Array.from(arrs
  .flat()
  .reduce((acc, o) => {
    const key = predicate(o)

    return acc.set(key, { ...acc.get(key), ...o })
  }, new Map()).values()
)

const arr1 = [{"id":"74738","customerId":"534430"},{"id":"74742","customerId":"534429"}]
const arr2 = [{"customerId":"534429","name":"ABC"},{"customerId":"534430","name":"XYZ"}]

const result = fn(o => o.customerId, arr1, arr2)

console.log(result)```

Body:
I am trying to merge these two objects using Lodash merge.

Server object:

[
  {
    "id": "74738",
    "customerId": "534430"
  },
  {
    "id": "74742",
    "customerId": "534429"
  }
]

Local Object

[
  {
    "customerId": "534429"
    "name": "ABC"
  },
  {
    "customerId": "534430",
    "name": "XYZ"
  },
]

I am using lodash merge to combine these two objects based on attributes, I am using this code below:

merge({}, serverObject, localObject);

// Output: [{"id":"74738","customerId":"534429","name":"ABC"},{"id":"74742","customerId":"534430","name":"XYZ"}]

The object is not being updated based on the Customer Ids but instead by the sequence of local object.

Expected Output:

[{"id":"74738","customerId":"534430","name":"ABC"},{"id":"74742","customerId":"534429","name":"XYZ"}]

Body:
With lodash you can combine all arrays to a single one using _.flatten(), group by a predicate, and then map and merge each group to a single object.

Note: since your customerId is an integer, the items would be ordered by the numerical value.

const { map, groupBy, flatten, merge } = _

const fn = (predicate, ...arrs) => map(
  groupBy(flatten(arrs), predicate),
  group => merge({}, ...group)
)

const arr1 = [{"id":"74738","customerId":"534430"},{"id":"74742","customerId":"534429"}]
const arr2 = [{"customerId":"534429","name":"ABC"},{"customerId":"534430","name":"XYZ"}]

const result = fn('customerId', arr1, arr2)

console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

If you need to preserve the original order, flatten to a single array, and then reduce the items to a Map using the result of the predicate as the key. Merge each new item with the same key to the existing one in the Map. Convert  the Map's values back to an array using Array.from():

const fn = (predicate, ...arrs) => Array.from(arrs
  .flat()
  .reduce((acc, o) => {
    const key = predicate(o)

    return acc.set(key, { ...acc.get(key), ...o })
  }, new Map()).values()
)

const arr1 = [{"id":"74738","customerId":"534430"},{"id":"74742","customerId":"534429"}]
const arr2 = [{"customerId":"534429","name":"ABC"},{"customerId":"534430","name":"XYZ"}]

const result = fn(o => o.customerId, arr1, arr2)

console.log(result)


问:
CSS Style switcher in JavaScript on an Asp .Net server
I am trying to create a mobile website and can do it with just CSS, but the server master pages MUST be in their current locations, I am planning to use a Javascript "Style Switcher" to change the stylesheets but most mobile browsers don't have java support, so is there a way using java (or any other "language" that is either supported by mobile phones or can be run server-side) to run server-side that can also stop some of the page elements from loading (for mobile bandwidth issues) and change a few lines of the master code?

I was thinking of using this (with some edits):
How to Use JavaScript to Change a Cascading Style Sheet (CSS) Dynamically

I cannot use PHP as our hosting provider will not install it.

I do not have Asp .Net access (as a user) but do have FTP access.

答:
```<code>var isMobile = function() {
    var w = window.innerWidth || document.body.clientWidth;
    var o = 900;
    if(w < o) {
        return true;
    }
    else {
        return false;
    }
};
</code>```

and an init func

```<code>var init = function(){
  if(!isMobile()){
    // all your desktop stuff goes here
    var desktopcss = document.createElement('link');
    desktopcss.rel = 'stylesheet';desktopcss.type = 'text/css';
    desktopcss.href='/desktop.css';
    document.getElementsByTagName('head')[0].appendChild(desktopcss);
  }
  else{
    // all your mobile stuff goes here
    var mobilecss= document.createElement('link');
    mobilecss.rel = 'stylesheet';mobilecss.type = 'text/css';
    mobilecss.href='/mobile.css';
    document.getElementsByTagName('head')[0].appendChild(mobilecss);
  }
};
</code>```

and keep in mind that if you set something to

```<code>display:none;
</code>```

via css, it will not be loaded and it will not be displayed!

Body:
var isMobile = function() {
    var w = window.innerWidth || document.body.clientWidth;
    var o = 900;
    if(w < o) {
        return true;
    }
    else {
        return false;
    }
};

and an init func

var init = function(){
  if(!isMobile()){
    // all your desktop stuff goes here
    var desktopcss = document.createElement('link');
    desktopcss.rel = 'stylesheet';desktopcss.type = 'text/css';
    desktopcss.href='/desktop.css';
    document.getElementsByTagName('head')[0].appendChild(desktopcss);
  }
  else{
    // all your mobile stuff goes here
    var mobilecss= document.createElement('link');
    mobilecss.rel = 'stylesheet';mobilecss.type = 'text/css';
    mobilecss.href='/mobile.css';
    document.getElementsByTagName('head')[0].appendChild(mobilecss);
  }
};

and keep in mind that if you set something to

display:none;

via css, it will not be loaded and it will not be displayed!


问:
Can i expose multiple docker containers behind nat to be accessible from the web
I have a single static ip and want to know if it is possible to run several containers (lets say with ssh and apache) and let them be accessible from outside my local network by using my public ip. I tried it by using bind9 but dont think that works because i only have 1 ip address.

Some kind of router which connects based on a hostname or something for example?

I ended up using kubernetes with a clusterIP and nodePort service.

答:
Yes, you can do this by having a reverse proxy like nginx in front of your containers.

Nginx will then receive all the requests and route them to the correct container, based on the hostname.

More info here: http://nginx.org/en/docs/http/server_names.html


问:
How can I use string instead of char* buffer to read the file data into string?
I am using standard file-handler API to read the file , currently I have used a char* buffer to read the data, but I want to use string so I can avoid calloc() use. I tried to pass the string address to the ReadFile() function, but it's not working. Could you please help me???

```<code>l_FileHandle = CreateFileA(inputFilePath.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

l_FileSize = GetFileSize(l_FileHandle, NULL);

char * l_FileBuffer = NULL;

l_FileBuffer = (char *)calloc(l_FileSize, sizeof(char));

ReadFile(l_FileHandle,(void *)(l_FileBuffer), l_FileSize, &lpNumberOfBytesRead, lpOverlapped);
</code>```

答:
The proper use is std::vector.

```<code>l_FileSize = GetFileSize(l_FileHandle, NULL);
std::vector<char>  l_FileBuffer(l_FileSize);
ReadFile(l_FileHandle,l_FileBuffer.data(), l_FileSize, &lpNumberOfBytesRead, lpOverlapped);
</code>```

Since vector by the standard ensures that the items are stored continuously.

Note that even in this way you are still implicitly allocating memory, it's just that the vector will release it automatically on destruction. If the file is known to be very small then you can afford to load it on a stack-allocated buffer instead.

Body:
I am using standard file-handler API to read the file , currently I have used a char* buffer to read the data, but I want to use string so I can avoid calloc() use. I tried to pass the string address to the ReadFile() function, but it's not working. Could you please help me???

l_FileHandle = CreateFileA(inputFilePath.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

l_FileSize = GetFileSize(l_FileHandle, NULL);

char * l_FileBuffer = NULL;

l_FileBuffer = (char *)calloc(l_FileSize, sizeof(char));

ReadFile(l_FileHandle,(void *)(l_FileBuffer), l_FileSize, &lpNumberOfBytesRead, lpOverlapped);

Body:
The proper use is std::vector.

l_FileSize = GetFileSize(l_FileHandle, NULL);
std::vector<char>  l_FileBuffer(l_FileSize);
ReadFile(l_FileHandle,l_FileBuffer.data(), l_FileSize, &lpNumberOfBytesRead, lpOverlapped);

Since vector by the standard ensures that the items are stored continuously.

Note that even in this way you are still implicitly allocating memory, it's just that the vector will release it automatically on destruction. If the file is known to be very small then you can afford to load it on a stack-allocated buffer instead.


问:
How do I install Rails?
I am completely new to Ruby and need to use Ruby on Rails 2.3.5 on Windows. I have downloaded the zip from GitHub here: https://github.com/rails/rails/tree/v2.3.5

There was no gem file so I tried rake in the extracted directory. It took ages and seemed to have a lot of errors, but it did eventually complete.

There was no gem file created (is this even what rake is supposed to do?). And rails is not installed (typing rails at the command prompt doesnt work).

Any ideas what I am doing wrong?

EDIT: I cannot use gem install rails -v "2.3.5" as I am behind a firewall. I think I need to install it from local files.

Title: How do I install Rails?

Body: Install InstantRails: http://broadcast.oreilly.com/2008/12/installing-instant-rails-on-wi.html


问:
C# Datetime is increasing by 3 hours
My dates are being stored in sql server.

Windows server region and timezone are correct, but when I see the date in database it's increased by 3 hours, I think it is comming from some server configuration that is overriding, but don't know where else to look.

When I send date from local project to production database, it saves correctly, but when I use production website it doesn't.

Where else should I check to solve this?

答:
If you want to get advantage of your local machine timezone you can use myDateTime.ToUniversalTime() to get the UTC time from your local time or myDateTime.ToLocalTime() to convert the UTC time to the local machine's time.

```<code>// convert UTC time from the database to the machine's time
DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
var localTime = databaseUtcTime.ToLocalTime();

// convert local time to UTC for database save
var databaseUtcTime = localTime.ToUniversalTime();
</code>```

If you need to convert time from/to other timezones, you may use TimeZoneInfo.ConvertTime() or TimeZoneInfo.ConvertTimeFromUtc().

```<code>// convert UTC time from the database to japanese time
DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
var japaneseTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
var japaneseTime = TimeZoneInfo.ConvertTimeFromUtc(databaseUtcTime, japaneseTimeZone);

// convert japanese time to UTC for database save
var databaseUtcTime = TimeZoneInfo.ConvertTimeToUtc(japaneseTime, japaneseTimeZone);
</code>```

Title: C# Datetime is increasing by 3 hours

Body:
If you want to get advantage of your local machine timezone you can use myDateTime.ToUniversalTime() to get the UTC time from your local time or myDateTime.ToLocalTime() to convert the UTC time to the local machine's time.

// convert UTC time from the database to the machine's time
DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
var localTime = databaseUtcTime.ToLocalTime();

// convert local time to UTC for database save
var databaseUtcTime = localTime.ToUniversalTime();

If you need to convert time from/to other timezones, you may use TimeZoneInfo.ConvertTime() or TimeZoneInfo.ConvertTimeFromUtc().

// convert UTC time from the database to japanese time
DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
var japaneseTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
var japaneseTime = TimeZoneInfo.ConvertTimeFromUtc(databaseUtcTime, japaneseTimeZone);

// convert japanese time to UTC for database save
var databaseUtcTime = TimeZoneInfo.ConvertTimeToUtc(japaneseTime, japaneseTimeZone);


问:
iOS PWA Background Audio Support
While playing audio in Safari on iOS, it is possible to minimise Safari or lock the screen and the audio continues to play. However, if the site is installed to the HomeScreen as a PWA, minimising the PWA or locking the screen pauses the audio.

Is there any way to make playback continue in the background when in the iOS PWA?

The problem is described in detail here:
https://medium.com/prototyped/what-we-learned-about-pwas-and-audio-playback-10a01c6aecbd

答:
It seems to have been a bug fixed in iOS 15.4
https://twitter.com/othermaciej/status/1491500338305667072

I just tried it and it appears to work fine!

Title: iOS PWA Background Audio Support


问:
Having number above 60 in "ss" format
```<code>Global time As Date

Sub countdown()
time = Now()
time = DateAdd("s", 120, time)

Do Until time < Now()
DoEvents
oSh.TextFrame.TextRange = Format((time - Now()), "ss")
Loop
End Sub
</code>```

The timer starts from 60 and ends at 00. Then the same repeats. Is it possible to start the timer from 120 directly? How can we go about it?

答:
Format will simply read the seconds from a date value, there is no way to "force" it to calculate the total seconds. However, it is rather easy to calculate it manually:</p>
```<code>Dim delta as Date
delta = t - now
oSh.TextFrame.TextRange = Minute(d) * 60 + Second(d)
' or, if you want to have always 3 digits, eg 030
oSh.TextFrame.TextRange = Format(Minute(d) * 60 + Second(d), "000")
</code>```

Title: Having number above 60 in "ss" format

Body:
Global time As Date

Sub countdown()
time = Now()
time = DateAdd("s", 120, time)

Do Until time < Now()
DoEvents
oSh.TextFrame.TextRange = Format((time - Now()), "ss")
Loop
End Sub

The timer starts from 60 and ends at 00. Then the same repeats. Is it possible to start the timer from 120 directly? How can we go about it?

Body:
Format will simply read the seconds from a date value, there is no way to "force" it to calculate the total seconds. However, it is rather easy to calculate it manually:

Dim delta as Date
delta = t - now
oSh.TextFrame.TextRange = Minute(d) * 60 + Second(d)
' or, if you want to have always 3 digits, eg 030
oSh.TextFrame.TextRange = Format(Minute(d) * 60 + Second(d), "000")