问:
PHAsset (or ALAsset) cross-device identifier
I am actually creating an iOS app, and want to store some details about Photo Library pictures in an SQLite database. I also would like to be able to share this data across the different devices the user has (imagine someone wanted to reorganize pictures on his iPhone, and wants to retrieve the same order in his iPad).

I have searched across the Apple documentation, but did not find any PHAsset identifier that is shared across devices. I also tried to check if the PHImageFileURLKey, hashValue, or localIdentifier of the PHAsset where shared, but none of them are.

Has someone already done something like this?

答:
Since iOS 15 there is an identifier that is available across all devices: https://developer.apple.com/documentation/photokit/phcloudidentifier

The API is pretty simple. The idea is that you store and sync cloud identifiers and then use them to retrieve local identifiers, which you then can use with existing API's like you are used to. You can request the cloud identifiers in batches, like so:

let localIdentifiers = <your-list-of-local-identifiers>
let mappings: [String: Result<PHCloudIdentifier, Error>] =
  PHPhotoLibrary.shared().cloudIdentifierMappings(forLocalIdentifiers: localIdentifiers)
```
<p>You can store such identifiers by using the <code>stringValue</code> property.</p>
<p>Vice versa (say you have a list of <code>cloudIdentifiers</code> with the string values of the identifiers):</p>
<pre class="lang-swift prettyprint-override"><code>let localIdentifiers: [PHCloudIdentifier: Result<String, Error>]
   = PHPhotoLibrary
        .shared()
        .localIdentifierMappings(
          for: cloudIdentifiers.map(PHCloudIdentifier.init(stringValue:)))
</code>```

What errors can happen?

No identifier was found: Either you passed in an invalid identifier or the asset has been deleted

Multiple local identifiers for a cloud identifier where found (According to WWDC this happens if "Cloud state isn't in sync or the library relies on image content to find a match")
More info about the error handling here

Additional insights that i derived through experimentation:

You seem to be able to get cloud identifiers without internet, with iCloud disabled for your app even without being signed into an iCloud account at all.

Even though the doc states it's an expensive operation, the overhead for loading some hundreds of identifiers at once is not noticeable for me

Body:
Since iOS 15 there is an identifier that is available across all devices: https://developer.apple.com/documentation/photokit/phcloudidentifier

The API is pretty simple. The idea is that you store and sync cloud identifiers and then use them to retrieve local identifiers, which you then can use with existing API's like you are used to. You can request the cloud identifiers in batches, like so:

let localIdentifiers = <your-list-of-local-identifiers>
let mappings: [String: Result<PHCloudIdentifier, Error>] =
  PHPhotoLibrary.shared().cloudIdentifierMappings(forLocalIdentifiers: localIdentifiers)

You can store such identifiers by using the stringValue property.

Vice versa (say you have a list of cloudIdentifiers with the string values of the identifiers):

let localIdentifiers: [PHCloudIdentifier: Result<String, Error>]
   = PHPhotoLibrary
        .shared()
        .localIdentifierMappings(
          for: cloudIdentifiers.map(PHCloudIdentifier.init(stringValue:)))

What errors can happen?

No identifier was found: Either you passed in an invalid identifier or the asset has been deleted

Multiple local identifiers for a cloud identifier where found (According to WWDC this happens if "Cloud state isn't in sync or the library relies on image content to find a match")
More info about the error handling here

Additional insights that i derived through experimentation:

You seem to be able to get cloud identifiers without internet, with iCloud disabled for your app even without being signed into an iCloud account at all.

Even though the doc states it's an expensive operation, the overhead for loading some hundreds of identifiers at once is not noticeable for me


来源: stackexchange

问:
Security tokens with unreadable private keys?
I'd like to uniquely identify users by issuing security tokens to them. In order to guarantee non-repudiation I'd like to ensure that no one has access to the user's private key, not even the person who issues the tokens.

What's the cheapest/most-secure way to implement this?

答:
It would be relatively easy for compromised computers to steal the user's private key if it were stored as a soft public key (e.g., on the hard drive).  (APT (botnet) malware has been known to include functionality to do exactly this.)

But more fundamentally, nothing short of physically incapacitating the user will guarantee non-repudiation.  Non-repudiation is something the user chooses to do, opposing evidence notwithstanding, and to prove that a user didn't do something is impossible.  Ultimately, non-repudiation involves a legal (or at least a business) question: what level of confidence do you have that the user performed the action he is denying having performed and that his denial is dishonest?  Cryptosystems can only provide reasonable confidence of a user's involvement in an action; they cannot provide absolute proof.

PIV cards (and PIV-I cards) use a number of safeguards for signing certificates.  First, the private key is stored on the smart card, and there is no trivial way to extract it.  The card requires a numeric PIN to use the private signing key, and effectively destroys the key after a certain number of incorrect attempts.  The hardware cryptomodule must meet Level-2 standards and be tamper-resistant, and transport of the card requires Level-3 physical security (FIPS 201).  The certificate is signed by a trusted CA.  The PIN, if entered using a keyboard, must be sent directly to the card to avoid keylogger-type attacks.

These precautions are elaborate, intensive, and still do not guarantee non-repudiation.  (What if malware convinces the user to sign a different document than the one he is intending to sign?  Or the user is under duress?  Or an intelligence agency obtains the card in transit and uses a secret vulnerability to extract the private key before replacing the card?)

Security is not generally a question of cheapest/most secure, but rather of risk assessment, mitigation, and ultimately acceptance.  What are your significant risks?  If you assess the types of non-repudiation risks you face and implement effective compensating controls, you will be more likely to find a cost-effective solution than if you seek to eliminate risk altogether.

ContentLicense: CC BY-SA 3.0


问:
Extend QPixmap on the right side without modify the content
For a given QPixmap with 200x200 dimension, I want to extend it with 50px (transparent) on the right side, without scaling the existing content.

Is this possible on QPixmap or with any Qt helper class?

答:
Just paint the original pixmap onto a new, extended one...</p>
```<code>QPixmap original_pixmap = ...
QPixmap new_pixmap(original_pixmap.width() + 50, original_pixmap.height());
new_pixmap.fill(Qt::transparent);
QPainter painter(new_pixmap);
painter.drawPixmap(0, 0, original_pixmap);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Just paint the original pixmap onto a new, extended one...

QPixmap original_pixmap = ...
QPixmap new_pixmap(original_pixmap.width() + 50, original_pixmap.height());
new_pixmap.fill(Qt::transparent);
QPainter painter(new_pixmap);
painter.drawPixmap(0, 0, original_pixmap);


问:
11ty - How do I display post / page year?
I'm using Eleventy and using Posts. I have set the date in the meta data using the format

date: 2021-09-10.

I can display the full date using

{{ page.date | readableDate }}

But I want to display just the year (YYYY) within the post content. I'm using Nunjucks.

How do i do this?

I've tried

{{ page.date.getFullYear }}

This gives the following error:

function () { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return obj[val].apply(obj, args); }

Any help would be really appreciated - thanks!

答:
Add a filter to your .eleventy.js file

```<code>eleventyConfig.addFilter("justYear", (dateString) => {
  dateObj = new Date(dateString);
  return DateTime.fromJSDate(dateObj, { zone: 'utc' }).toFormat('yyyy');
});
</code>```

Then in your .njk file

```<code>{{ page.date | justYear }}
</code>```

Body:
Add a filter to your .eleventy.js file

eleventyConfig.addFilter("justYear", (dateString) => {
  dateObj = new Date(dateString);
  return DateTime.fromJSDate(dateObj, { zone: 'utc' }).toFormat('yyyy');
});

Then in your .njk file

{{ page.date | justYear }}


问:
not able to mute someone in discord.js - node.js
I want to mute someone manually in discord.js
by adding:

if(message.author == /*muted list*/){
message.delete();
return;
}
```
<p>and I need to extract the list from a json file (and I did)</p>
<pre class="lang-json prettyprint-override"><code>{
  "muted":[
    //someone's ID,
    //someone else's ID
    ]
}
</code>```

I got the the IDs in a variable.
and logged it into console to see if I did it correct
console output:

[  some id , some else id ]
```

so I put the variable in the /*muted list*/  in the js file.
but it did nothing.
help pls

答:
If you got JSON converted into list you can simply check string from the list with .includes()

if (yourlist.includes(message.author.id)) {

}
```

Body:
I want to mute someone manually in discord.js
by adding:

if(message.author == /*muted list*/){
message.delete();
return;
}

and I need to extract the list from a json file (and I did)

{
  "muted":[
    //someone's ID,
    //someone else's ID
    ]
}

I got the the IDs in a variable.
and logged it into console to see if I did it correct
console output:

[  some id , some else id ]

so I put the variable in the /*muted list*/  in the js file.
but it did nothing.
help pls


问:
SignalR: The remote certificate is invalid according to the validation procedure: RemoteCertificateNameMismatch
I have a Blazor server app in .Net 5 and it works fine. Newly I have added a SignalR HubConnection for notify messages, but I face with an exception due to SSL connection establishment in production sever as follows:

```<code>Workflow2.Common.DalException: The SSL connection could not be established, see inner exception.
 ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure: RemoteCertificateNameMismatch
   at System.Net.Security.SslStream.SendAuthResetSignal(ProtocolToken message, ExceptionDispatchInfo exception)
   at System.Net.Security.SslStream.ForceAuthenticationAsync[TIOAdapter](TIOAdapter adapter, Boolean receiveFirst, Byte[] reAuthenticationData, Boolean isApm)
   at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Boolean async, Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
[2022-01-26 13:07:30.970][ERR]: InnerException Message
System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure: RemoteCertificateNameMismatch
   at System.Net.Security.SslStream.SendAuthResetSignal(ProtocolToken message, ExceptionDispatchInfo exception)
   at System.Net.Security.SslStream.ForceAuthenticationAsync[TIOAdapter](TIOAdapter adapter, Boolean receiveFirst, Byte[] reAuthenticationData, Boolean isApm)
   at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Boolean async, Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
</code>```

The application works without any issues if it bounded with http and I can receive notifications correctly, the issue happens only for https binding.

Here is my code for starting HubConnection:

```<code>try
{
    string sHubUrl = NavManager.BaseUri;
    sHubUrl = sHubUrl.TrimEnd('/') + "/call";

    hubConnection = new HubConnectionBuilder()
        .WithUrl(sHubUrl, options => {
            options.UseDefaultCredentials = true;
        })
        .WithAutomaticReconnect()
        .Build();
    hubConnection.On<string, string>("NewMessage", ReceivedNotification);

    await hubConnection.StartAsync();
}
catch (Exception ex)
{
    LogBuilder.LogExecption(new DalException(ex));
}
</code>```

I tryed to test it with both self-signed certificate and a valid commercial certificate, but in both cases I face with the same result.

Are there any idea, what can I do to solve my Problem?

Now after some days, I set up VS remote debugging tools and with a break at
occured exception, I saw that exactly the same error has happen:

```<code>The remote certificate is invalid according to the validation procedure: RemoteCertificateNameMismatch

   at System.Net.Security.SslStream.SendAuthResetSignal(ProtocolToken message, ExceptionDispatchInfo exception)
   at System.Net.Security.SslStream.ForceAuthenticationAsync[TIOAdapter](TIOAdapter adapter, Boolean receiveFirst, Byte[] reAuthenticationData, Boolean isApm)
   at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Boolean async, Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
</code>```

答:
I could resolve my problem with bypassing certirficate:

```<code>    hubConnection = new HubConnectionBuilder()
        .WithUrl(sHubUrl, options => {
            options.UseDefaultCredentials = true;
            options.HttpMessageHandlerFactory = (msg) =>
            {
                if (msg is HttpClientHandler clientHandler)
                {
                    // bypass SSL certificate
                    clientHandler.ServerCertificateCustomValidationCallback +=
                        (sender, certificate, chain, sslPolicyErrors) => { return true; };
                }

                return msg;
            };
        })
        .WithAutomaticReconnect()
        .Build();
</code>```

and now SignalR HubConnection starts successfully if I open the page using an internal IP address in my private network for example https://10.0.0.36/call but if I want to open the page using a public IP address such as https://example.com/call, it throws an exception with an InnerException equal to null and StartAsync fails.

Body:
I have a Blazor server app in .Net 5 and it works fine. Newly I have added a SignalR HubConnection for notify messages, but I face with an exception due to SSL connection establishment in production sever as follows:

Workflow2.Common.DalException: The SSL connection could not be established, see inner exception.
 ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure: RemoteCertificateNameMismatch
   at System.Net.Security.SslStream.SendAuthResetSignal(ProtocolToken message, ExceptionDispatchInfo exception)
   at System.Net.Security.SslStream.ForceAuthenticationAsync[TIOAdapter](TIOAdapter adapter, Boolean receiveFirst, Byte[] reAuthenticationData, Boolean isApm)
   at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Boolean async, Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
[2022-01-26 13:07:30.970][ERR]: InnerException Message
System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure: RemoteCertificateNameMismatch
   at System.Net.Security.SslStream.SendAuthResetSignal(ProtocolToken message, ExceptionDispatchInfo exception)
   at System.Net.Security.SslStream.ForceAuthenticationAsync[TIOAdapter](TIOAdapter adapter, Boolean receiveFirst, Byte[] reAuthenticationData, Boolean isApm)
   at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Boolean async, Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)

The application works without any issues if it bounded with http and I can receive notifications correctly, the issue happens only for https binding.

Here is my code for starting HubConnection:

try
{
    string sHubUrl = NavManager.BaseUri;
    sHubUrl = sHubUrl.TrimEnd('/') + "/call";

    hubConnection = new HubConnectionBuilder()
        .WithUrl(sHubUrl, options => {
            options.UseDefaultCredentials = true;
        })
        .WithAutomaticReconnect()
        .Build();
    hubConnection.On<string, string>("NewMessage", ReceivedNotification);

    await hubConnection.StartAsync();
}
catch (Exception ex)
{
    LogBuilder.LogExecption(new DalException(ex));
}

I tryed to test it with both self-signed certificate and a valid commercial certificate, but in both cases I face with the same result.

Are there any idea, what can I do to solve my Problem?

Now after some days, I set up VS remote debugging tools and with a break at
occured exception, I saw that exactly the same error has happen:

The remote certificate is invalid according to the validation procedure: RemoteCertificateNameMismatch

   at System.Net.Security.SslStream.SendAuthResetSignal(ProtocolToken message, ExceptionDispatchInfo exception)
   at System.Net.Security.SslStream.ForceAuthenticationAsync[TIOAdapter](TIOAdapter adapter, Boolean receiveFirst, Byte[] reAuthenticationData, Boolean isApm)
   at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Boolean async, Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)

Body:
I could resolve my problem with bypassing certirficate:

    hubConnection = new HubConnectionBuilder()
        .WithUrl(sHubUrl, options => {
            options.UseDefaultCredentials = true;
            options.HttpMessageHandlerFactory = (msg) =>
            {
                if (msg is HttpClientHandler clientHandler)
                {
                    // bypass SSL certificate
                    clientHandler.ServerCertificateCustomValidationCallback +=
                        (sender, certificate, chain, sslPolicyErrors) => { return true; };
                }

                return msg;
            };
        })
        .WithAutomaticReconnect()
        .Build();

and now SignalR HubConnection starts successfully if I open the page using an internal IP address in my private network for example https://10.0.0.36/call but if I want to open the page using a public IP address such as https://example.com/call, it throws an exception with an InnerException equal to null and StartAsync fails.


问:
CurrentCulture and SecurityException
We write some winForms GUI application that uses the Invariant Culture. So in the beginning of the Main we have:

```<code>    [STAThread]
    static void Main()
    {
        CultureInfo culture = CultureInfo.InvariantCulture;
        System.Threading.Thread.CurrentThread.CurrentCulture = culture;
        ...
</code>```

The problem is that on some machines it works perfectly but on some machines on some configurations ( like Debug/AnyCPU fro x64 machines) it raises SequrityException

```<code>Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
</code>```

So what is the problem with it? And why it happens only on some conditions?

答:
Another post mentions security issues when using the invariant culture. Perhaps this is your issue?

Using the InvariantCulture Property

```<code>The InvariantCulture property represents neither a neutral nor a
</code>```

specific culture. It represents a third type of culture that is
  culture-insensitive. It is associated with the English language but
  not with a country or region. Your applications can use this property
  with almost any method in the System.Globalization namespace that
  requires a culture. However, an application should use the invariant
  culture only for processes that require culture-independent results,
  such as formatting and parsing data that is persisted to a file. In
  other cases, it produces results that might be linguistically
  incorrect or culturally inappropriate.

```<code>Security Considerations If a security decision will be made based
</code>```

on the result of a string comparison or case change, your application
  should use an ordinal comparison that ignores case instead of using
  InvariantCulture. The default implementations of methods such as
  Compare()()() and ToUpper use the CurrentCulture property. Code that
  performs culture-sensitive string operations can cause security
  vulnerabilities if CurrentCulture is changed or if the culture on the
  computer running the code differs from the culture used to test the
  code. The behavior that you expect when writing a string operation
  differs from the actual behavior of your code on the executing
  computer. In contrast, an ordinal comparison depends solely on the
  binary value of the compared characters.

```<code>String Operations If your application needs to perform a
</code>```

culture-sensitive string operation that is not affected by the value
  of CurrentCulture, it should use a method that accepts a CultureInfo
  parameter. The application should specify the value of the
  InvariantCulture property for this parameter. The application should
  use the property with methods such as Compare()()() and ToUpper to
  eliminate cultural variations and ensure consistent results. For more
  information about using the InvariantCulture property to perform
  culture-insensitive string operations, see Culture-Insensitive String
  Operations.

```<code>Persisting Data The InvariantCulture property is useful for
</code>```

storing data that will not be displayed directly to users. Storing
  data in a culture-independent format guarantees a known format that
  does not change. When users from different cultures access the data,
  it can be formatted appropriately based on specific user. For example,
  if your application stores DateTime types in a text file, formatted
  for the invariant culture, the application should use the
  InvariantCulture property when calling ToString to store the strings
  and the Parse method to retrieve the strings. This technique ensures
  that the underlying values of the DateTime types do not change when
  the data is read or written by users from different cultures.

Title: CurrentCulture and SecurityException

Body:
We write some winForms GUI application that uses the Invariant Culture. So in the beginning of the Main we have:

    [STAThread]
    static void Main()
    {
        CultureInfo culture = CultureInfo.InvariantCulture;
        System.Threading.Thread.CurrentThread.CurrentCulture = culture;
        ...

The problem is that on some machines it works perfectly but on some machines on some configurations ( like Debug/AnyCPU fro x64 machines) it raises SequrityException

Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

So what is the problem with it? And why it happens only on some conditions?

Body:
Another post mentions security issues when using the invariant culture. Perhaps this is your issue?

Using the InvariantCulture Property

The InvariantCulture property represents neither a neutral nor a

specific culture. It represents a third type of culture that is
  culture-insensitive. It is associated with the English language but
  not with a country or region. Your applications can use this property
  with almost any method in the System.Globalization namespace that
  requires a culture. However, an application should use the invariant
  culture only for processes that require culture-independent results,
  such as formatting and parsing data that is persisted to a file. In
  other cases, it produces results that might be linguistically
  incorrect or culturally inappropriate.

Security Considerations If a security decision will be made based

on the result of a string comparison or case change, your application
  should use an ordinal comparison that ignores case instead of using
  InvariantCulture. The default implementations of methods such as
  Compare()()() and ToUpper use the CurrentCulture property. Code that
  performs culture-sensitive string operations can cause security
  vulnerabilities if CurrentCulture is changed or if the culture on the
  computer running the code differs from the culture used to test the
  code. The behavior that you expect when writing a string operation
  differs from the actual behavior of your code on the executing
  computer. In contrast, an ordinal comparison depends solely on the
  binary value of the compared characters.

String Operations If your application needs to perform a

culture-sensitive string operation that is not affected by the value
  of CurrentCulture, it should use a method that accepts a CultureInfo
  parameter. The application should specify the value of the
  InvariantCulture property for this parameter. The application should
  use the property with methods such as Compare()()() and ToUpper to
  eliminate cultural variations and ensure consistent results. For more
  information about using the InvariantCulture property to perform
  culture-insensitive string operations, see Culture-Insensitive String
  Operations.

Persisting Data The InvariantCulture property is useful for

storing data that will not be displayed directly to users. Storing
  data in a culture-independent format guarantees a known format that
  does not change. When users from different cultures access the data,
  it can be formatted appropriately based on specific user. For example,
  if your application stores DateTime types in a text file, formatted
  for the invariant culture, the application should use the
  InvariantCulture property when calling ToString to store the strings
  and the Parse method to retrieve the strings. This technique ensures
  that the underlying values of the DateTime types do not change when
  the data is read or written by users from different cultures.


问:
How to get sum and count in MongoDB?

I want to list Names, loan amount and number of loans that are Completed.

Thanks alot!!! Appreciate it.

答:
try

https://mongoplayground.net/p/rA5T1PAxU9_

for results only from loans with Completed status

status isn't added to response, since it will always be 'Completed' from the input

```<code>db.collection.aggregate([
  {
    $match: {
      status: "Completed"
    }
  },
  {
    $group: {
      _id: null,
      total_amount_from_completed_loans: {
        $sum: "$loan_amount"
      },
      "names_from_completed_loans": {
        $push: "$name"
      }
    }
  },
  {
    $project: {
      _id: 0
    }
  }
])
</code>```

sample response:

```<code>[
  {
    "names_from_completed_loans": [
      "Yuyu Lee",
      "Joseph Lee"
    ],
    "total_amount_from_completed_loans": 1.836544e+06
  }
]
</code>```

Title: How to get sum and count in MongoDB?

Body:
try

https://mongoplayground.net/p/rA5T1PAxU9_

for results only from loans with Completed status

status isn't added to response, since it will always be 'Completed' from the input

db.collection.aggregate([
  {
    $match: {
      status: "Completed"
    }
  },
  {
    $group: {
      _id: null,
      total_amount_from_completed_loans: {
        $sum: "$loan_amount"
      },
      "names_from_completed_loans": {
        $push: "$name"
      }
    }
  },
  {
    $project: {
      _id: 0
    }
  }
])

sample response:

[
  {
    "names_from_completed_loans": [
      "Yuyu Lee",
      "Joseph Lee"
    ],
    "total_amount_from_completed_loans": 1.836544e+06
  }
]


问:
Read data directly from REST Api with Kafka
Is such a situation even possible ? :

There is an application "XYZ" (in which there is no Kafka) that exposes a REST api. It is a SpringBoot application with which Angular application communicates.

A new application (SpringBoot) is created which wants to use Kafka and needs to fetch data from "XYZ" application. And it wants to do this using Kafka.

The "XYZ" application has an example endpoint [GET] api/message/all  which displays all messages.

Is there a way to "connect" Kafka directly to this endpoint and read data from it ? In short, the idea is for Kafka to consume data directly from the EP. Communication between two microservices, where one microservice does not have a kafka.

What suggestions do you have for solving this situation. Because I guess this option is not possible. Is it necessary to add a publisher in application XYZ which will send data to the queue and only then will they be available for consumption by a new application ??

答:
Getting them via the REST-Interface might not be a very good idea.
Simply put, in the messaging world, message delivery guarantees are a big topic and the standard ways to solve that with Kafka are usually

Producing messages from your service using the Producer-API to a Kafka topic.

Using Kafka-Connect to read from an outbox-table.

Since you most likely have a database already attached to your API-Service, there might arise the problem of dual writes if you choose to produce the messages directly to a topic. What this means, is that writes to a database might fail while it might be successfully written to Kafka/vice-versa. So you can end up with inconsistent states. Depending on your use case this might be a problem or not.

Nevertheless, to overcome that, the outbox pattern can come in handy.

Via the outbox pattern, you'd basically write your messages to a table, a so-called outbox-table, and then you'd use Kafka-Connect to poll this table of the database. Kafka Connect is basically a cluster of workers that consume this database table and forward the entries of the table to a Kafka topic. You might want to look at confluent cloud, they offer a fully managed Kafka-Connect service. Like this you don't have to manage the cluster of workers yourself. Once you have the messages in a Kafka topic, you can consume them with the standard Kafka Consumer-API/ Stream-API.

What you're looking for is a Source-Connector.
A source connector for a specific database. E.g. MongoDB

E.g. https://www.confluent.io/hub/mongodb/kafka-connect-mongodb

For now, most source-connectors produce in an at-least-once fashion. This means that the topic you configure the connector to write to might contain a message twice. So make sure that if you need them to be consumed exactly once, you think about deduplicating these messages.


问:
Datatype for indexing vector
I just started to learn Rust. I understand that Rust's for loop indices and vector indices must be of type usize, hence I have written the following code. The computation of j within the for loop requires i to be type u32, so I convert it. Now, I have to change the type of i and j again to get the vector items.

I would like to avoid this constant back-and-forth conversion, is there an alternate way to do this in Rust? Thank you for your help.

```<code>fn compute(dots: Vec, N: u32) -> f32 {

    let mut j: u32;
    let mut value: f32 = 0.0;

    for i in 0..N {
        j = (i as u32 + 1) % N;
        value += dots[i as usize].a * dots[j as usize].b;
        value -= dots[i as usize].b * dots[j as usize].a;
    }

    return value
}
</code>```

答:
Either change the function signature to use N: usize, or, if you can't do that, just let M = N as usize and loop over 0..M (the loop variable will then have type usize).

Be aware that in real code, you need to be sure that usize is at least as wide as u32 if you opt for the conversion. If you cannot assure that, use try_into instead of as to convert.

Title: Datatype for indexing vector

Body:
I just started to learn Rust. I understand that Rust's for loop indices and vector indices must be of type usize, hence I have written the following code. The computation of j within the for loop requires i to be type u32, so I convert it. Now, I have to change the type of i and j again to get the vector items.

I would like to avoid this constant back-and-forth conversion, is there an alternate way to do this in Rust? Thank you for your help.

fn compute(dots: Vec, N: u32) -> f32 {

    let mut j: u32;
    let mut value: f32 = 0.0;

    for i in 0..N {
        j = (i as u32 + 1) % N;
        value += dots[i as usize].a * dots[j as usize].b;
        value -= dots[i as usize].b * dots[j as usize].a;
    }

    return value
}


问:
ctx.req is undefined Next.js
ctx.req is undefined Next.js. This code is inside _document.js file.

static async getInitialProps(ctx) {
        const props = await Document.getInitialProps(ctx);
        const userData = await getServerSideToken(ctx.req);
        return { ...userData, ...props }
    }
```

I am trying to pass ctx.req to getServerSideToken, but it is displaying an error saying that ctx.req is undefined

答:
To make ctx.req contain the expected payload, you must invoke getServerSideProps further down the Next.js tree, for example, in pages/index.js. Then ctx.req in _document will no longer be undefined.

I don't understand so many people complaining about application logic in this file. This is literally where you need to access server-side cookies and add a classname or two to the body element. Same for other css-in-js logic as well.

Title: ctx.req is undefined Next.js

Body:
ctx.req is undefined Next.js. This code is inside _document.js file.

static async getInitialProps(ctx) {
        const props = await Document.getInitialProps(ctx);
        const userData = await getServerSideToken(ctx.req);
        return { ...userData, ...props }
    }

I am trying to pass ctx.req to getServerSideToken, but it is displaying an error saying that ctx.req is undefined


问:
Can this prime sieve code be further simplified in Haskell?
The code works well

```<code>primes = next [2 ..]
  where
    next (p : ps) = p : next ts
      where
        ts = filter (\x -> mod x p /= 0) ps
</code>```

Just GHCI think there is a incomplete patter in next.

Well, this is correct from a grammatical point of view.

But obviously the input of 'next' cannot be empty.

So is there a solution other than adding the declaration
({-# OPTIONS_GHC -Wno-incomplete-patterns #-})?

答:
You've already got a proper answer to your question. For completeness, the other option is just to add the unneeded clause that we know will never be called:

```<code>primes = next [2 ..]
  where
  next (p : xs) =
       p : next [x | x <- xs, mod x p > 0]
  next _ = undefined
</code>```

Another, more "old-style" solution, is to analyze the argument by explicit calls  to head and tail (very much not recommended, in general):

```<code>primes = next [2 ..]
  where
  next xs = let { p = head xs } in
       p : next [x | x <- tail xs, mod x p > 0]
</code>```

This could perhaps count as a simplification.

On an unrelated note, you write that it "works well". Unfortunately, while indeed producing the correct results, it does so very slowly. Because of always taking only one element at a time off the input list, its time complexity is quadratic in the number n of primes produced. In other words, primes !! n takes time quadratic in n. Empirically,

```<code>> primes !! 1000
7927     -- (0.27 secs, 102987392 bytes)
> primes !! 2000
17393    -- (1.00 secs, 413106616 bytes)
> primes !! 3000
27457    -- (2.23 secs, 952005872 bytes)

> logBase (2/1) (1.00 / 0.27)
1.8889686876112561                -- n^1.9
> logBase (3/2) (2.23 / 1.00)
1.9779792870810489                -- n^2.0
</code>```

In fact the whole bunch of the elements may be taken from the input at once, up to the square of the current prime, with the code thus taking only about ~ n1.5 time, give or take a log factor:

```<code>{-# LANGUAGE ViewPatterns #-}

primes_ = 2 : next primes_ [3 ..]
  where
  next (p : ps) (span (< p*p) -> (h, xs)) =
      h ++ next ps [x | x <- xs, mod x p > 0]
  next _ _ = undefined
</code>```

Empirically, again, we get

```<code>> primes !! 3000
27457     -- (0.08 secs,   29980864 bytes)
> primes !! 30000
350381    -- (1.81 secs,  668764336 bytes)
> primes !! 60000
746777    -- (4.74 secs, 1785785848 bytes)
> primes !! 100000
1299721   -- (9.87 secs, 3633306112 bytes)

> logBase (6/3)  (4.74 / 1.81)
1.388897361815054                 -- n^1.4
> logBase (10/6) (9.87 / 4.74)
1.4358377567888103                -- n^1.45
</code>```

As we can see here, the complexity advantage expresses itself as an enormous speedup in absolute terms as well.

So then this sieve is equivalent to the optimal trial division, unlike the one in the question. Of course when it was first proposed in 1976, Haskell had no view patterns yet, and in fact there was yet no Haskell itself.

Body:
The code works well

primes = next [2 ..]
  where
    next (p : ps) = p : next ts
      where
        ts = filter (\x -> mod x p /= 0) ps

Just GHCI think there is a incomplete patter in next.

Well, this is correct from a grammatical point of view.

But obviously the input of 'next' cannot be empty.

So is there a solution other than adding the declaration
({-# OPTIONS_GHC -Wno-incomplete-patterns #-})?

Body:
You've already got a proper answer to your question. For completeness, the other option is just to add the unneeded clause that we know will never be called:

primes = next [2 ..]
  where
  next (p : xs) =
       p : next [x | x <- xs, mod x p > 0]
  next _ = undefined

Another, more "old-style" solution, is to analyze the argument by explicit calls  to head and tail (very much not recommended, in general):

primes = next [2 ..]
  where
  next xs = let { p = head xs } in
       p : next [x | x <- tail xs, mod x p > 0]

This could perhaps count as a simplification.

On an unrelated note, you write that it "works well". Unfortunately, while indeed producing the correct results, it does so very slowly. Because of always taking only one element at a time off the input list, its time complexity is quadratic in the number n of primes produced. In other words, primes !! n takes time quadratic in n. Empirically,

> primes !! 1000
7927     -- (0.27 secs, 102987392 bytes)
> primes !! 2000
17393    -- (1.00 secs, 413106616 bytes)
> primes !! 3000
27457    -- (2.23 secs, 952005872 bytes)

> logBase (2/1) (1.00 / 0.27)
1.8889686876112561                -- n^1.9
> logBase (3/2) (2.23 / 1.00)
1.9779792870810489                -- n^2.0

In fact the whole bunch of the elements may be taken from the input at once, up to the square of the current prime, with the code thus taking only about ~ n1.5 time, give or take a log factor:

{-# LANGUAGE ViewPatterns #-}

primes_ = 2 : next primes_ [3 ..]
  where
  next (p : ps) (span (< p*p) -> (h, xs)) =
      h ++ next ps [x | x <- xs, mod x p > 0]
  next _ _ = undefined

Empirically, again, we get

> primes !! 3000
27457     -- (0.08 secs,   29980864 bytes)
> primes !! 30000
350381    -- (1.81 secs,  668764336 bytes)
> primes !! 60000
746777    -- (4.74 secs, 1785785848 bytes)
> primes !! 100000
1299721   -- (9.87 secs, 3633306112 bytes)

> logBase (6/3)  (4.74 / 1.81)
1.388897361815054                 -- n^1.4
> logBase (10/6) (9.87 / 4.74)
1.4358377567888103                -- n^1.45

As we can see here, the complexity advantage expresses itself as an enormous speedup in absolute terms as well.

So then this sieve is equivalent to the optimal trial division, unlike the one in the question. Of course when it was first proposed in 1976, Haskell had no view patterns yet, and in fact there was yet no Haskell itself.


问:
nested array object property return undefined typeError in react redux
i want to show the post detail in frontend. my api is showing the postdetail like below captured in postman:

```<code>"message": "Posts fetched successfully!",
    "posts": {
        "_id": "61f05f676793d49f466e7aaa",
        "title": "Liberal Arts Student Sample",
        "content": "The three-page.",
        "creator": {
            "_id": "61cd99efa0b8d616a7a53ce1",
            "createdAt": "2021-12-30T11:37:19.041Z",
            "updatedAt": "2022-01-06T14:35:48.801Z",
            "__v": 0,
            "bio": "user bio",
            "name": "username"
        },
        "Comments": [],
        "created": "2022-01-25T20:36:55.095Z",
        "createdAt": "2022-01-25T20:36:55.096Z",
        "updatedAt": "2022-01-25T20:36:55.096Z",
        "__v": 0
    }
}
</code>```

i want to exhibit this post detail in frontend and here is the code:

```<code>export default function PostDetail() {
    const { postId } = useParams();
    const post = useSelector((state) => state.post)
    const dispatch = useDispatch();
    const { title, content,creator, created } = post;
    const fetchPostDetail = async (id) => {
        const response = await axios.get(`http://localhost:5000/api/articles/post/${id}`, { post })
            .catch(err => {
                console.log(err);
            })
        dispatch(selectedPost(response.data.posts));
              }

    useEffect(() => {
        fetchPostDetail(postId)
    }, [])

    return (
        <div>
            <h1>Post Detail</h1>
            <div>
                <h2>{title}</h2>
                <i>posted in {created}</i>
                 <li>Created by {creator.map((m,i)=>(
<b key={i}>{m.name}</b>
                 ))}</li>
                <p>{content}</p>
            </div>
        </div>
    );
}
</code>```

There are three errors:

Uncaught TypeError: creator is undefined

The above error occurred in the  component:

Uncaught TypeError: creator is undefined

if i mute the

Created by {creator.map((m,i)=>(
{m.name}
                 ))}
 then it shows the post detail without post author name. but i want to show the author name.

how can i solve that?
thank you in advance

答: make sure the post object contains the "creator" key, and you don't need map() if the state looks exactly like the API response. If you could show how the state looks that will reveal more of the issue.</p>

Body:
i want to show the post detail in frontend. my api is showing the postdetail like below captured in postman:

"message": "Posts fetched successfully!",
    "posts": {
        "_id": "61f05f676793d49f466e7aaa",
        "title": "Liberal Arts Student Sample",
        "content": "The three-page.",
        "creator": {
            "_id": "61cd99efa0b8d616a7a53ce1",
            "createdAt": "2021-12-30T11:37:19.041Z",
            "updatedAt": "2022-01-06T14:35:48.801Z",
            "__v": 0,
            "bio": "user bio",
            "name": "username"
        },
        "Comments": [],
        "created": "2022-01-25T20:36:55.095Z",
        "createdAt": "2022-01-25T20:36:55.096Z",
        "updatedAt": "2022-01-25T20:36:55.096Z",
        "__v": 0
    }
}

i want to exhibit this post detail in frontend and here is the code:

export default function PostDetail() {
    const { postId } = useParams();
    const post = useSelector((state) => state.post)
    const dispatch = useDispatch();
    const { title, content,creator, created } = post;
    const fetchPostDetail = async (id) => {
        const response = await axios.get(`http://localhost:5000/api/articles/post/${id}`, { post })
            .catch(err => {
                console.log(err);
            })
        dispatch(selectedPost(response.data.posts));
              }

    useEffect(() => {
        fetchPostDetail(postId)
    }, [])

    return (

Post Detail

{title}

                posted in {created}

Created by {creator.map((m,i)=>(
{m.name}
                 ))}

{content}

    );
}

There are three errors:

Uncaught TypeError: creator is undefined

The above error occurred in the  component:

Uncaught TypeError: creator is undefined

if i mute the

Created by {creator.map((m,i)=>(
{m.name}
                 ))}
 then it shows the post detail without post author name. but i want to show the author name.

how can i solve that?
thank you in advance


问:
Column text color when row takes focus (is clicked)
I use jquery and jgrid for create a grid in php.
I have modified the color of a column of my grid, using:

```$grid[“loadComplete”] = "function(ids) { onloadFunction(ids)";```

The onloadFunction function is as follows:

```<code>function onloadFunction(ids) {

   var ids = $(“#lstStudents”).jqGrid(‘getDataIDs’);

   for (var z=0;z<ids.length;z++) {

      var id=ids[z];

      $(“#lstStudents”).jqGrid(‘setCell’,id, ‘quarter1’,”, {‘background’:’rgb(250, 250, 250)’});
      $(“#lstStudents”).jqGrid(‘setCell’,id, ‘quarter1’,”, {‘color’:’rgb(0, 0, 0)’});

   }
}
</code>```

When selecting a row, the column whose color I modified in the onLoadFunction function remains with the established color, that is, it does not take the defined color of a selected row. How would I make the modified column also have the background color and text color of the rest of the columns?

Image to clarify better: https://imgur.com/Uhr2sb3

Thank you very much for the help.

答:
This is little bit tricky.

You know that the inline style (the style of the table cell) has higher priority than the css. Moreover the highlight class is added to the row while the custom class is added to the child table cell.

This mean that to solve the problem we need to redefine the cell class within  the highlight class.

In your application do :

```<code>td.mycolor {
    background:rgb(250, 250, 250);
    color : rgb(100, 200, 300);
}
</code>```

Add this class to the cell using the setCell method

```<code>$("#grid").jqGrid("setCell", rowid, "colname", "", "mycolor" );
</code>```

Below the definition of mycolor class do:

```<code>.ui-widget-content .ui-state-highlight > td.mycolor {
    background-color: inherit !important;
    color : inherit !important;
}
</code>```

in case of Bootstrap this maybe should be

```<code>.table-success > td.mycolor {
    background-color: inherit !important;
    color : inherit !important;
}
</code>```

(check the docs to be a sure which class is added when the row is selected)

This way the mycolor will inherit the colors of the parent class when we add the class to the row.

Body:
I use jquery and jgrid for create a grid in php.
I have modified the color of a column of my grid, using:

$grid[“loadComplete”] = "function(ids) { onloadFunction(ids)";

The onloadFunction function is as follows:

function onloadFunction(ids) {

   var ids = $(“#lstStudents”).jqGrid(‘getDataIDs’);

   for (var z=0;z<ids.length;z++) {

      var id=ids[z];

      $(“#lstStudents”).jqGrid(‘setCell’,id, ‘quarter1’,”, {‘background’:’rgb(250, 250, 250)’});
      $(“#lstStudents”).jqGrid(‘setCell’,id, ‘quarter1’,”, {‘color’:’rgb(0, 0, 0)’});

   }
}

When selecting a row, the column whose color I modified in the onLoadFunction function remains with the established color, that is, it does not take the defined color of a selected row. How would I make the modified column also have the background color and text color of the rest of the columns?

Image to clarify better: https://imgur.com/Uhr2sb3

Thank you very much for the help.

Body:
This is little bit tricky.

You know that the inline style (the style of the table cell) has higher priority than the css. Moreover the highlight class is added to the row while the custom class is added to the child table cell.

This mean that to solve the problem we need to redefine the cell class within  the highlight class.

In your application do :

td.mycolor {
    background:rgb(250, 250, 250);
    color : rgb(100, 200, 300);
}

Add this class to the cell using the setCell method

$("#grid").jqGrid("setCell", rowid, "colname", "", "mycolor" );

Below the definition of mycolor class do:

.ui-widget-content .ui-state-highlight > td.mycolor {
    background-color: inherit !important;
    color : inherit !important;
}

in case of Bootstrap this maybe should be

.table-success > td.mycolor {
    background-color: inherit !important;
    color : inherit !important;
}

(check the docs to be a sure which class is added when the row is selected)

This way the mycolor will inherit the colors of the parent class when we add the class to the row.


问:
jest with log4js console appender appends "console.log" and a dummy stack
When I run my jest tests which use log4js's console appender, each output line is littered with console: and a small stack trace (output and code below), which make it harder to follow the log flow.

Question: How do I get rid of these text additions?

Current solution: Replace type to type: 'stdout' solves this. [Edit] But then, when running the code not through jest, the log output doesn't appear under vscode's "Debug Console"

Notes:

This does not happen when running just node code - only within jest.

Adding enableCallStack: false to the category - doesn't change anything

Adding layout to the appender affects the line ([2021-12-28T13:12:20.334] [INFO] default - myinfo), but the surrounding lines remain.

Versions: Node.js v14.18.1, jest@26.6.3, log4js@6.3.0

Output

```<code>PS > node --experimental-vm-modules .\node_modules\jest\bin\jest
(node:21824) ExperimentalWarning: VM Modules is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
 PASS  ./test.spec.js
  √ testname (13 ms)

  console.log                   <<<<<< want to get rid of this
    [2021-12-28T13:12:20.334] [INFO] default - myinfo     <<<<<< want to keep only this

      at node_modules/log4js/lib/appenders/console.js:6:5   <<<<<< want to get rid of this
          at Array.forEach (<anonymous>)   <<<<<< want to get rid of this
          at Array.forEach (<anonymous>)   <<<<<< want to get rid of this

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.366 s
</code>```

Code

```<code>import log4js from 'log4js';
log4js.configure({
    appenders: { console: { type: 'console' } },
    categories: { default: { appenders: [ 'console' ], level: 'trace' } }
  });

let logger = log4js.getLogger();

test('testname', () => {
    logger.info("myinfo");
});

// my actual code
function myActualCode
</code>```

答:
As @jonrsharpe noted, this is by design in jest. For reference: This is implemented in node_modules\@jest\console\build\getConsoleOutput.js

My solution: Detect whether running under jest, and if so switch to stdout:

```<code>log4js.configure(
    {
        appenders: {
            myAppender: {
                type: (process.env.JEST_WORKER_ID) ? 'stdout' : 'console',
                layout: ...
</code>```

Body:
When I run my jest tests which use log4js's console appender, each output line is littered with console: and a small stack trace (output and code below), which make it harder to follow the log flow.

Question: How do I get rid of these text additions?

Current solution: Replace type to type: 'stdout' solves this. [Edit] But then, when running the code not through jest, the log output doesn't appear under vscode's "Debug Console"

Notes:

This does not happen when running just node code - only within jest.

Adding enableCallStack: false to the category - doesn't change anything

Adding layout to the appender affects the line ([2021-12-28T13:12:20.334] [INFO] default - myinfo), but the surrounding lines remain.

Versions: Node.js v14.18.1, jest@26.6.3, log4js@6.3.0

Output

PS > node --experimental-vm-modules .\node_modules\jest\bin\jest
(node:21824) ExperimentalWarning: VM Modules is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
 PASS  ./test.spec.js
  √ testname (13 ms)

  console.log                   <<<<<< want to get rid of this
    [2021-12-28T13:12:20.334] [INFO] default - myinfo     <<<<<< want to keep only this

      at node_modules/log4js/lib/appenders/console.js:6:5   <<<<<< want to get rid of this
          at Array.forEach (<anonymous>)   <<<<<< want to get rid of this
          at Array.forEach (<anonymous>)   <<<<<< want to get rid of this

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.366 s

Code

import log4js from 'log4js';
log4js.configure({
    appenders: { console: { type: 'console' } },
    categories: { default: { appenders: [ 'console' ], level: 'trace' } }
  });

let logger = log4js.getLogger();

test('testname', () => {
    logger.info("myinfo");
});

// my actual code
function myActualCode

Body:
As @jonrsharpe noted, this is by design in jest. For reference: This is implemented in node_modules\@jest\console\build\getConsoleOutput.js

My solution: Detect whether running under jest, and if so switch to stdout:

log4js.configure(
    {
        appenders: {
            myAppender: {
                type: (process.env.JEST_WORKER_ID) ? 'stdout' : 'console',
                layout: ...


问:
Prevent jekyll for loop from skipping future posts
I have a jekyll website with a blog section that has this:

```<code>{% for post in site.posts %}
  ... display post ...
{% endfor %}
</code>```

This blog section correctly skips posts that are dated in the future.

In another part of my website I want to be able list posts that have a specific "Event" tag, regardless of the date of the post (so even posts in the future should be shown). I have something like this for now:

```<code>{% for post in site.posts %}
  {% if post.tag contains "Event" %}
    ... display post ...
  {% endif %}
{% endfor %}
</code>```

However this loop skips the posts that have a date in the future. How can I prevent this (only for this loop)? Solutions like setting published: true would not work because the blog section would start showing those posts as well.

答:
Unfortunately, the future option is a build configuration option. This means you will have to set it to true, otherwise future posts are skipped from the site.posts collection during build.

Here's a workaround:

After you have set future: true in the _config.yml file, in your blog section, filter the posts like this:

```<code>{% assign filtered_posts = site.posts | where_exp: "post", "post.date <= site.time" %}
{% assign sorted_posts = filtered_posts | sort: 'post.date' %}

{% for post in sorted_posts %}
  ... display post ...
{% endfor %}
</code>```

In your other section, you should then be able to list all posts with the Event tag including the future ones using the second code block in your question above.

Body:
I have a jekyll website with a blog section that has this:

{% for post in site.posts %}
  ... display post ...
{% endfor %}

This blog section correctly skips posts that are dated in the future.

In another part of my website I want to be able list posts that have a specific "Event" tag, regardless of the date of the post (so even posts in the future should be shown). I have something like this for now:

{% for post in site.posts %}
  {% if post.tag contains "Event" %}
    ... display post ...
  {% endif %}
{% endfor %}

However this loop skips the posts that have a date in the future. How can I prevent this (only for this loop)? Solutions like setting published: true would not work because the blog section would start showing those posts as well.

Body:
Unfortunately, the future option is a build configuration option. This means you will have to set it to true, otherwise future posts are skipped from the site.posts collection during build.

Here's a workaround:

After you have set future: true in the _config.yml file, in your blog section, filter the posts like this:

{% assign filtered_posts = site.posts | where_exp: "post", "post.date <= site.time" %}
{% assign sorted_posts = filtered_posts | sort: 'post.date' %}

{% for post in sorted_posts %}
  ... display post ...
{% endfor %}

In your other section, you should then be able to list all posts with the Event tag including the future ones using the second code block in your question above.


问:
Very slow join query on large table (machine = Xeon 2.4 GHz, 16 core, 64 GB RAM)
Here is my query :

```<code>SELECT  email_data.id, email_data.source_file, email_data.report_id,
        email_data.filePath, email_data.fileName, email_data.size,
        email_data.emailID, email_data.msgID, email_data.cus, email_data.subject,
        email_data.sentto, email_data.emailFrom, email_data.hdrs, email_data.cc,
        email_data.bcc, email_data.extracted, email_data.DateTime,
        email_data.TimeStamp, email_data.OriginalDateTime, email_data.ParentID,
        email_data.reply_to, email_data.MD5Hash, email_data.duplicated,
        email_data.TimeZone, email_data.AttachName, email_data.fqdn,
        attach_data.id, attach_data.source_file, attach_data.report_id,
        attach_data.filePath, attach_data.fileName, attach_data.size, attach_data.ext,
        attach_data.emailID, attach_data.cus, attach_data.extracted,
        attach_data.MD5Hash, attach_data.duplicated
FROM email_data
LEFT JOIN attach_data
ON (email_data.emailID = attach_data.emailID);
</code>```

Combination of both of the table has 50k + records (email_data have 22k records and other have 30K + records).

Above query takes over 90 mins and still not finished.

This one :

```<code>SELECT email_data.id, attach_data.id
FROM email_data
LEFT JOIN attach_data
ON (email_data.emailID = attach_data.emailID);
</code>```

takes 2 mins 22 sec:

What am I doing wrong? It seems that MySQL do not using enough memory to speed things up, and it only uses 1 core out of 16 cores.

How can I configure it to use all available resources?

Or should I query IDs (as in 2nd query) and loop + select each of them back in my code? Will it cause same result?

I needs all those fields and all the row, I am converting them into Custom CSV-Like format so it can be exported to other software.

Columns :

```<code>mysql> show columns from email_data;
+------------------+----------+------+-----+---------+----------------+
| Field            | Type     | Null | Key | Default | Extra          |
+------------------+----------+------+-----+---------+----------------+
| id               | int(11)  | NO   | PRI | NULL    | auto_increment |
| source_file      | longtext | YES  |     | NULL    |                |
| report_id        | int(11)  | YES  |     | NULL    |                |
| filePath         | longtext | YES  |     | NULL    |                |
| fileName         | longtext | YES  |     | NULL    |                |
| size             | int(11)  | YES  |     | NULL    |                |
| emailID          | longtext | YES  |     | NULL    |                |
| msgID            | longtext | YES  |     | NULL    |                |
| cus              | longtext | YES  |     | NULL    |                |
| subject          | longtext | YES  |     | NULL    |                |
| sentto           | longtext | YES  |     | NULL    |                |
| emailFrom        | longtext | YES  |     | NULL    |                |
| hdrs             | longtext | YES  |     | NULL    |                |
| cc               | longtext | YES  |     | NULL    |                |
| bcc              | longtext | YES  |     | NULL    |                |
| extracted        | longtext | YES  |     | NULL    |                |
| DateTime         | char(1)  | YES  |     | NULL    |                |
| TimeStamp        | int(11)  | YES  |     | NULL    |                |
| OriginalDateTime | char(1)  | YES  |     | NULL    |                |
| ParentID         | longtext | YES  |     | NULL    |                |
| reply_to         | longtext | YES  |     | NULL    |                |
| MD5Hash          | longtext | YES  |     | NULL    |                |
| duplicated       | char(1)  | YES  |     | NULL    |                |
| TimeZone         | char(1)  | YES  |     | NULL    |                |
| AttachName       | longtext | YES  |     | NULL    |                |
| fqdn             | longtext | YES  |     | NULL    |                |
+------------------+----------+------+-----+---------+----------------+
</code>```

Almost same for attach_data

答:
First, a single query will never use multiple cores (AFAIK mysql and most other RDBMS).

Your second query shows mysql is able to use an index (or utilize a big cache), that's good.

If your disk is slow and the longtexts contain much data, just pulling all of it to memory may be slow and trash your in memory index pages.

If it is a serious app I would switch to PostgreSQL or another DB as a long term solution. In my experience mysql is only fast for trivial tasks.

Body:
Here is my query :

SELECT  email_data.id, email_data.source_file, email_data.report_id,
        email_data.filePath, email_data.fileName, email_data.size,
        email_data.emailID, email_data.msgID, email_data.cus, email_data.subject,
        email_data.sentto, email_data.emailFrom, email_data.hdrs, email_data.cc,
        email_data.bcc, email_data.extracted, email_data.DateTime,
        email_data.TimeStamp, email_data.OriginalDateTime, email_data.ParentID,
        email_data.reply_to, email_data.MD5Hash, email_data.duplicated,
        email_data.TimeZone, email_data.AttachName, email_data.fqdn,
        attach_data.id, attach_data.source_file, attach_data.report_id,
        attach_data.filePath, attach_data.fileName, attach_data.size, attach_data.ext,
        attach_data.emailID, attach_data.cus, attach_data.extracted,
        attach_data.MD5Hash, attach_data.duplicated
FROM email_data
LEFT JOIN attach_data
ON (email_data.emailID = attach_data.emailID);

Combination of both of the table has 50k + records (email_data have 22k records and other have 30K + records).

Above query takes over 90 mins and still not finished.

This one :

SELECT email_data.id, attach_data.id
FROM email_data
LEFT JOIN attach_data
ON (email_data.emailID = attach_data.emailID);

takes 2 mins 22 sec:

What am I doing wrong? It seems that MySQL do not using enough memory to speed things up, and it only uses 1 core out of 16 cores.

How can I configure it to use all available resources?

Or should I query IDs (as in 2nd query) and loop + select each of them back in my code? Will it cause same result?

I needs all those fields and all the row, I am converting them into Custom CSV-Like format so it can be exported to other software.

Columns :

mysql> show columns from email_data;
+------------------+----------+------+-----+---------+----------------+
| Field            | Type     | Null | Key | Default | Extra          |
+------------------+----------+------+-----+---------+----------------+
| id               | int(11)  | NO   | PRI | NULL    | auto_increment |
| source_file      | longtext | YES  |     | NULL    |                |
| report_id        | int(11)  | YES  |     | NULL    |                |
| filePath         | longtext | YES  |     | NULL    |                |
| fileName         | longtext | YES  |     | NULL    |                |
| size             | int(11)  | YES  |     | NULL    |                |
| emailID          | longtext | YES  |     | NULL    |                |
| msgID            | longtext | YES  |     | NULL    |                |
| cus              | longtext | YES  |     | NULL    |                |
| subject          | longtext | YES  |     | NULL    |                |
| sentto           | longtext | YES  |     | NULL    |                |
| emailFrom        | longtext | YES  |     | NULL    |                |
| hdrs             | longtext | YES  |     | NULL    |                |
| cc               | longtext | YES  |     | NULL    |                |
| bcc              | longtext | YES  |     | NULL    |                |
| extracted        | longtext | YES  |     | NULL    |                |
| DateTime         | char(1)  | YES  |     | NULL    |                |
| TimeStamp        | int(11)  | YES  |     | NULL    |                |
| OriginalDateTime | char(1)  | YES  |     | NULL    |                |
| ParentID         | longtext | YES  |     | NULL    |                |
| reply_to         | longtext | YES  |     | NULL    |                |
| MD5Hash          | longtext | YES  |     | NULL    |                |
| duplicated       | char(1)  | YES  |     | NULL    |                |
| TimeZone         | char(1)  | YES  |     | NULL    |                |
| AttachName       | longtext | YES  |     | NULL    |                |
| fqdn             | longtext | YES  |     | NULL    |                |
+------------------+----------+------+-----+---------+----------------+

Almost same for attach_data


问:
How do I approach a DynamoDB single table design?
I'm learning more about DynamoDB and I'm building a full serverless project using it as my main database.
The project is a simple Poll app, where a user can create and vote in polls.

The data model for a SQL database is quite simple in fact this is all that it looks like

But with DynamoDB I need to think about access patterns and this is where it becomes a little bit confusing for me.

After watching a few courses on DynamoDB not specifically related to data modeling I was able to come up with this aggregate view, following the Single Table Design.

This was done in the NoSQL Workbench app

There are the same 3 entities within the same table but I have a question

These are the access patterns I need for my app, at least the ones I can think for now

[Put, Delete, Get] User by userId
[Get] All Users by pollId (who voted in what)
[Put, Delete, Get] Poll by pollId
[Put, Delete, Get] All Polls by userId
[Put, Delete, Get] All Polls by visibility
[Create, Get] Poll Votes by pollId
```

Are Global Secondary Indexes all I need to satisfy these access patterns?

Are there any pitfalls in the way that I designed the data?

Are there any other tips you might recommend?

答:
You are correct that using a GSI will be helpful to design a good access pattern here, but in your NoSQL Workbench screenshot you are not showing GSIs. Instead you are showing a batch write (or transact write) operation for each vote operation. 1. pk: user Id, sk: poll id, 2. pk: poll id, sk: user Id.

This is less efficient if you want to enforce a rule that no user can vote in the same poll twice. To enforce this with the current key structure you will need to use the transact write API call, which is more expensive.

Instead you can try to use a single write for a vote, keep attributes needed for condition checks in the pk or sk, and use a GSI to offer alternative access patterns.

Alternative Pattern:
Model: Vote
pk: pollId,
sk: userId
gsi1pk: userId,
gsi1sk: pollId

Model: User
pk: userId,
sk: userId

Model: Poll
pk: pollId
sk: pollId

This has a tradeoff in that either 'Get all Poles (votes) by UserId' or 'Get all Users by PollId' will require 2 read operations. Choose the Vote pk and sk to favour the read operation which will see more traffic.

This design also suggests you may want to denormalise some data from the Poll model to the Vote model.

If you application is massively read heavy, your original model could be the correct choice. But consider that a query can read an extra data item for 0.5 RRU, and 1 on-demand RRU costs $0.25/million, whereas a transact write operation costs 2 WRU per item, and 1 on-demand WRU costs $1.25/million. This implies that unless your query 'Get all polls for a user' gets at least 20x the traffic of 'create vote', it is better to use a GSI (GSI costs an extra 1 WRU, but 3 transact write items costs 6 WRU).

Even using a read then batch-write to enforce uniqueness still causes an extra 1 WRU + 1 RRU in consumption for each vote..

Body:
I'm learning more about DynamoDB and I'm building a full serverless project using it as my main database.
The project is a simple Poll app, where a user can create and vote in polls.

The data model for a SQL database is quite simple in fact this is all that it looks like

But with DynamoDB I need to think about access patterns and this is where it becomes a little bit confusing for me.

After watching a few courses on DynamoDB not specifically related to data modeling I was able to come up with this aggregate view, following the Single Table Design.

This was done in the NoSQL Workbench app

There are the same 3 entities within the same table but I have a question

These are the access patterns I need for my app, at least the ones I can think for now

[Put, Delete, Get] User by userId
[Get] All Users by pollId (who voted in what)
[Put, Delete, Get] Poll by pollId
[Put, Delete, Get] All Polls by userId
[Put, Delete, Get] All Polls by visibility
[Create, Get] Poll Votes by pollId

Are Global Secondary Indexes all I need to satisfy these access patterns?

Are there any pitfalls in the way that I designed the data?

Are there any other tips you might recommend?


问:
how to access second span tag under class in xpath
I am trying to access data from XPath for the below data. I wanted to get the Hostname - 192.81.xx.xx and ISP - Random

```<code><div class="left">
 <p class="information">
    <span>Hostname</span>
    <span>192.81.xx.xx</span>
 </p>
 <p class="information">
    <span>ISP</span>
    <span>Random</span>
 </p>
</div>
</code>```

Xpath I've Tried - //div[@class="left"]//p[@class="information"]//span[contains(text(), "Hostname:")]

答:
this xpath

```<code>//div[@class="left"]//p[@class="information"]//span
</code>```

will return 4 nodes.

```<code><span>Hostname</span>
<span>192.81.xx.xx</span>
<span>ISP</span>
<span>Random</span>
</code>```

based on the HTML that you've shared.

you should use find_elements that will return list of web elements.

Also, if you use the above XPath with find_element it will always fetch the first matching node which is Hostname

to get specific node:

to get 192.81.xx.xx use the below XPath:

```<code>//div[@class="left"]//p[@class="information"]//span[1]
</code>```

for random:

```<code>//div[@class="left"]//p[2][@class="information"]//span[2]
</code>```

Body:
I am trying to access data from XPath for the below data. I wanted to get the Hostname - 192.81.xx.xx and ISP - Random

    Hostname
    192.81.xx.xx

    ISP
    Random

Xpath I've Tried - //div[@class="left"]//p[@class="information"]//span[contains(text(), "Hostname:")]

Body:
this xpath

//div[@class="left"]//p[@class="information"]//span

will return 4 nodes.

<span>Hostname</span>
<span>192.81.xx.xx</span>
<span>ISP</span>
<span>Random</span>

based on the HTML that you've shared.

you should use find_elements that will return list of web elements.

Also, if you use the above XPath with find_element it will always fetch the first matching node which is <span>Hostname</span>

to get specific node:

to get 192.81.xx.xx use the below XPath:

//div[@class="left"]//p[@class="information"]//span[1]

for random:

//div[@class="left"]//p[2][@class="information"]//span[2]


问:
Can Chart.js Horizontal bar work with time series data?
I am trying to develop a stacked bar graph based on time series data. The data is representing the running of a machine logged to Influx.

Looking about I have not seen this done and cannot seem to get my data to line up correctly to make the stacked bar chart. Essentially I want to show one color for running and one for not running. This isn't an issue as this can be changed programmatically.

However, the issue I seem to be facing is possible more of a configuration issue. I would expect the time series adaptor to automatically align my data up with how it would correspond in my dataset.

See my example so far. To clarify, I am using the latest Chart.js at time of writing 3.7

const data = {
  labels: ["Label 1"],
  datasets: [{
    label: "Testing",
    data: [{
        x:  moment().valueOf(),
      y: moment().valueOf()
    }],
    backgroundColor: "red"
  },
  {
    label: "Testing",
    data: [{
        x:  moment().add(1, 'day').valueOf(),
            y: moment().add(1, 'day').valueOf()

    }],
    backgroundColor: "blue"
  }]
};
const config = {
  type: 'bar',
  data,
  options: {
    indexAxis: 'y',
    scales: {
      x: {
        ticks: {
                beginAtZero: true
            },
        stacked: true,
        type: 'time',
        time: {
            unit: 'day',
          unitStepSize: 6
        }
      },
      y: {
        stacked: true
      }
    }
  }
};

new Chart("myChart", config)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment@^2"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@^1"></script>

<canvas id="myChart"></canvas></code>```

Any point in the correct direction would be most beneficial. I will also answer any queries to clarify my though process on the config also.

答:
The problem is that Date represents milliseconds since 1 January 1970 UTC. Therefore you need to define the start date to see only the period of interest. This can be done by adding the min option to the x-axis as follows:

```<code>min: moment().startOf('day').subtract(1, 'day')
</code>```

You should also use moment().startOf('day') when defining your data. That way, the ticks on the x-axis will be correctly positioned.

Please take a look at your amended code below and see how it works.

const data = {
  datasets: [{
      label: "Testing",
      data: [{
        x: moment().startOf('day'),
        y: 0
      }],
      backgroundColor: "red"
    },
    {
      label: "Testing",
      data: [{
        x: moment().startOf('day').add(1, 'day'),
        y: 0
      }],
      backgroundColor: "blue"
    }
  ]
};
const config = {
  type: 'bar',
  data,
  options: {
    plugins: {
      tooltip: {
        callbacks: {
          title: () => ''
        }
      }
    },
    indexAxis: 'y',
    scales: {
      x: {
        stacked: true,
        type: 'time',
        time: {
          unit: 'day'
        },
        min: moment().startOf('day').subtract(1, 'day')
      },
      y: {
        stacked: true
      }
    }
  }
};

new Chart("myChart", config)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment@^2"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@^1"></script>

<canvas id="myChart" height="90"></canvas></code>```

Body:
I am trying to develop a stacked bar graph based on time series data. The data is representing the running of a machine logged to Influx.

Looking about I have not seen this done and cannot seem to get my data to line up correctly to make the stacked bar chart. Essentially I want to show one color for running and one for not running. This isn't an issue as this can be changed programmatically.

However, the issue I seem to be facing is possible more of a configuration issue. I would expect the time series adaptor to automatically align my data up with how it would correspond in my dataset.

See my example so far. To clarify, I am using the latest Chart.js at time of writing 3.7

const data = {
  labels: ["Label 1"],
  datasets: [{
    label: "Testing",
    data: [{
        x:  moment().valueOf(),
      y: moment().valueOf()
    }],
    backgroundColor: "red"
  },
  {
    label: "Testing",
    data: [{
        x:  moment().add(1, 'day').valueOf(),
            y: moment().add(1, 'day').valueOf()

    }],
    backgroundColor: "blue"
  }]
};
const config = {
  type: 'bar',
  data,
  options: {
    indexAxis: 'y',
    scales: {
      x: {
        ticks: {
                beginAtZero: true
            },
        stacked: true,
        type: 'time',
        time: {
            unit: 'day',
          unitStepSize: 6
        }
      },
      y: {
        stacked: true
      }
    }
  }
};

new Chart("myChart", config)

<canvas id="myChart"></canvas>

Any point in the correct direction would be most beneficial. I will also answer any queries to clarify my though process on the config also.

Body:
The problem is that Date represents milliseconds since 1 January 1970 UTC. Therefore you need to define the start date to see only the period of interest. This can be done by adding the min option to the x-axis as follows:

min: moment().startOf('day').subtract(1, 'day')

You should also use moment().startOf('day') when defining your data. That way, the ticks on the x-axis will be correctly positioned.

Please take a look at your amended code below and see how it works.

const data = {
  datasets: [{
      label: "Testing",
      data: [{
        x: moment().startOf('day'),
        y: 0
      }],
      backgroundColor: "red"
    },
    {
      label: "Testing",
      data: [{
        x: moment().startOf('day').add(1, 'day'),
        y: 0
      }],
      backgroundColor: "blue"
    }
  ]
};
const config = {
  type: 'bar',
  data,
  options: {
    plugins: {
      tooltip: {
        callbacks: {
          title: () => ''
        }
      }
    },
    indexAxis: 'y',
    scales: {
      x: {
        stacked: true,
        type: 'time',
        time: {
          unit: 'day'
        },
        min: moment().startOf('day').subtract(1, 'day')
      },
      y: {
        stacked: true
      }
    }
  }
};

new Chart("myChart", config)

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment@^2"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@^1"></script>

<canvas id="myChart" height="90"></canvas>


问:
Encode and Decode a String using the repetition of characters along the string
I've been trying to tackle this problem but I haven't got any luck so far :( so any guidance would be awesome, especially since I'm just learning Python, so the problem is this:

Given a certain string, first you'll have to encode it using the following algorithm:

For every letter, strip the consecutive repetitions, if any, and add a number with the number of times it appears consecutively, including the first time.

After you've completed the encoding you'll have to create a function to decode it using the same criteria/assumptions.

Some examples of how it should work:

“Goooooooooddddd” => “G1o9d5”

“Oooo” => “O1o3”

“anagram” => “a1n1a1g1r1a1m1”

So far I have the following code for the encoding:

```<code>def encode(s) :

    i = 0
    while( i < len(s) - 1) :
        count = 1
        while s[i] == s[i + 1] :
            i += 1
            count += 1

            if i + 1 == len(s):
                break
        print(str(s[i]) + str(count),
                          end = "")
        i += 1
    print()

# Code for the driver
if __name__ == "__main__" :

    encode("Goooooooooddddd")
    encode("Oooo")
</code>```

With this I'm getting the needed output for the encoding part at least.

But I'm unable to actually do the "decoding" part by using this encoding as a starting point.

I know this question is quite silly/basic but I really can't get my head over it
Thanks in advance for the guidance/tips for this challenge problem

答:
Decoding in pseudo code would involve:

Scan encoded string character by character

If character is alphabetic then add it to the decoded result

Sub scan encoded string for numeric sequence of 1 or more characters till next alphabetic character or end of string.

Repeat the last decoded string character this many times minus one.

Resume from step 1 till encoded string is entirely consumed.

Body:
I've been trying to tackle this problem but I haven't got any luck so far :( so any guidance would be awesome, especially since I'm just learning Python, so the problem is this:

Given a certain string, first you'll have to encode it using the following algorithm:

For every letter, strip the consecutive repetitions, if any, and add a number with the number of times it appears consecutively, including the first time.

After you've completed the encoding you'll have to create a function to decode it using the same criteria/assumptions.

Some examples of how it should work:

“Goooooooooddddd” => “G1o9d5”

“Oooo” => “O1o3”

“anagram” => “a1n1a1g1r1a1m1”

So far I have the following code for the encoding:

def encode(s) :

    i = 0
    while( i < len(s) - 1) :
        count = 1
        while s[i] == s[i + 1] :
            i += 1
            count += 1

            if i + 1 == len(s):
                break
        print(str(s[i]) + str(count),
                          end = "")
        i += 1
    print()

# Code for the driver
if __name__ == "__main__" :

    encode("Goooooooooddddd")
    encode("Oooo")

With this I'm getting the needed output for the encoding part at least.

But I'm unable to actually do the "decoding" part by using this encoding as a starting point.

I know this question is quite silly/basic but I really can't get my head over it
Thanks in advance for the guidance/tips for this challenge problem


问:
R function select value in vector via input value and between values other vector
I am not sure if I explain this correctly... but I have a function with 3 vectors and a value input, where the value of vector 3 (val_3) needs to be selected based on the input value which is between the values in vector 1 (val_1) and 2 (val_2)... How do I do this?

```<code>val <- 235412

select <- function(val){

  val_1 <- c(1, 10, 100, 10000, 100000)
  val_2 <- c(10, 100, 10000, 100000, 1000000)
  val_3 <- c(2:6)

  for (i in length(val_1)) {

    if (val > val_1[i] && val < val_2[i]){
      select_var = val_3[i]
    }
  }
}
</code>```

答:
Assuming your example is over-simplified and the vectors involved aren't always powers of 10, you can avoid a loop altogether by using the fact that R is vectorized:

select <- function(val) {

  val_1 <- c(1, 10, 100, 10000, 100000)
  val_2 <- c(10, 100, 10000, 100000, 1000000)
  val_3 <- c(2:6)

  val_3[which(val_1 < val & val_2 > val)]

}

select(235412)
#> [1] 6
```
<p>If your variables inside the function never change, you could even shorten the function to:</p>
<pre class="lang-r prettyprint-override"><code>select <- function(val) (2:6)[tail(which(log(val, 10) > (0:6)[-4]), 1)]

select(235412)
#> [1] 6
</code>```

But this is difficult to read and hence would be difficult to debug.

As a side-note here, it would be best not to call your function select, as there are already commonly used functions called select that this would over-write.

Body:
I am not sure if I explain this correctly... but I have a function with 3 vectors and a value input, where the value of vector 3 (val_3) needs to be selected based on the input value which is between the values in vector 1 (val_1) and 2 (val_2)... How do I do this?

val <- 235412

select <- function(val){

  val_1 <- c(1, 10, 100, 10000, 100000)
  val_2 <- c(10, 100, 10000, 100000, 1000000)
  val_3 <- c(2:6)

  for (i in length(val_1)) {

    if (val > val_1[i] && val < val_2[i]){
      select_var = val_3[i]
    }
  }
}

Body:
Assuming your example is over-simplified and the vectors involved aren't always powers of 10, you can avoid a loop altogether by using the fact that R is vectorized:

select <- function(val) {

  val_1 <- c(1, 10, 100, 10000, 100000)
  val_2 <- c(10, 100, 10000, 100000, 1000000)
  val_3 <- c(2:6)

  val_3[which(val_1 < val & val_2 > val)]

}

select(235412)
#> [1] 6

If your variables inside the function never change, you could even shorten the function to:

select <- function(val) (2:6)[tail(which(log(val, 10) > (0:6)[-4]), 1)]

select(235412)
#> [1] 6

But this is difficult to read and hence would be difficult to debug.

As a side-note here, it would be best not to call your function select, as there are already commonly used functions called select that this would over-write.


问:
Property 'initializeOnMount' required in type 'MoralisProviderInitializedProps'
I was getting an error due to the following code snippet:

Type '{ children: Element; appId: string | undefined; serverUrl: string | undefined; }'
is not assignable to type 'IntrinsicAttributes & MoralisProviderProps'.
Property 'initializeOnMount' is missing in type '{ children: Element; appId: string |
undefined; serverUrl: string | undefined; }' but required in type
'MoralisProviderInitializedProps'.ts(2322)
MoralisProvider.d.ts(19, 5): 'initializeOnMount' is declared here.

Here's my _app.jsx

```<code>import "../styles/globals.css";
import { MoralisProvider } from "react-moralis";

function MyApp({ Component, pageProps }:any) {

return (

 < MoralisProvider
   appId={process.env.NEXT_PUBLIC_APP_ID}
   serverUrl={process.env.NEXT_PUBLIC_SERVER_URL} >

 <Component {...pageProps} />

 </MoralisProvider>

        );
 }

 export default MyApp;
</code>```

Even deploying on vercel gave this same error:

答:
Just to further elaborate on my comment: the error you're getting informs you that the prop initializeOnMount is missing from your <MoralisProvider> component, as the typing indicates as such. It does appear to be an inconsistency with their documentation, as their example clearly leaves out the prop.

However, it seems like this can be fixed by simply setting initializeOnMount={false} on the component itself:

```<code><MoralisProvider
  appId={process.env.NEXT_PUBLIC_APP_ID}
  serverUrl={process.env.NEXT_PUBLIC_SERVER_URL}
  initializeOnMount={false}>
  <Component {...pageProps} />
</MoralisProvider>
</code>```

Body:
I was getting an error due to the following code snippet:

Type '{ children: Element; appId: string | undefined; serverUrl: string | undefined; }'
is not assignable to type 'IntrinsicAttributes & MoralisProviderProps'.
Property 'initializeOnMount' is missing in type '{ children: Element; appId: string |
undefined; serverUrl: string | undefined; }' but required in type
'MoralisProviderInitializedProps'.ts(2322)
MoralisProvider.d.ts(19, 5): 'initializeOnMount' is declared here.

Here's my _app.jsx

import "../styles/globals.css";
import { MoralisProvider } from "react-moralis";

function MyApp({ Component, pageProps }:any) {

return (

 < MoralisProvider
   appId={process.env.NEXT_PUBLIC_APP_ID}
   serverUrl={process.env.NEXT_PUBLIC_SERVER_URL} >

 <Component {...pageProps} />

 </MoralisProvider>

        );
 }

 export default MyApp;

Even deploying on vercel gave this same error:

Body:
Just to further elaborate on my comment: the error you're getting informs you that the prop initializeOnMount is missing from your <MoralisProvider> component, as the typing indicates as such. It does appear to be an inconsistency with their documentation, as their example clearly leaves out the prop.

However, it seems like this can be fixed by simply setting initializeOnMount={false} on the component itself:

<MoralisProvider
  appId={process.env.NEXT_PUBLIC_APP_ID}
  serverUrl={process.env.NEXT_PUBLIC_SERVER_URL}
  initializeOnMount={false}>
  <Component {...pageProps} />
</MoralisProvider>


问:
Javascript errors from Google Adsense
On several of my adsense running sites, I have been getting the following errors:

Unable to post message to [http://]googleads.g.doubleclick.net.
  Recipient has origin
  http://www.anekdotz.com.

Unsafe JavaScript attempt to access
  frame with URL
  [http://]www.anekdotz.com/ from frame
  with URL
  [http://]googleads.g.doubleclick.net/pagead/ads?client=ca-pub-9099580055602120&output=html&h=250&slotname=9210181593&w=300&flash=10.0.42&url=http%3A%2F%2Fwww.anekdotz.com%2F&dt=1269901036429&correlator=1269901036438&frm=0&ga_vid=711000587.1269901037&ga_sid=1269901037&ga_hid=654061172&ga_fc=0&u_tz=-240&u_his=2&u_java=1&u_h=900&u_w=1440&u_ah=878&u_aw=1436&u_cd=24&u_nplug=10&u_nmime=101&biw=1365&bih=806&eid=44901212&fu=0&ifi=1&dtd=153&xpc=Xkfk1oufPQ&p=http%3A//www.anekdotz.com.
  Domains, protocols and ports must match.

(from the Chrome javascript console)

The ads seem to show properly and it doesn't affect my native javascript code.  However sometimes these errors seem to slow down page loading.  How can I fix this problem?

(I modified the URLs to let me post this as I'm a new user)

答:
This seems to be a case of the error message masking the real cause. The real cause is probably some kind of Adsense misconfiguration; unfortunately Adsense doesn't seem to do sufficient checks to give a more relevant error message.

I had this error myself and came to this conclusion after researching the forums, where some people reported it was fixed after verifying their bank account or whatever. In my case, my server-side environment was messing with the google_ad_client parameter, so the real problem was that parameter being null. Once I fixed that, ads were showing and no more error message.

So in practice, it's really nothing to do with same-origin policy. Now that the adsense code is correct, I'm even now able to show ads when running on localhost, as well as on the server.

ContentLicense: CC BY-SA 2.5

Title: Javascript errors from Google Adsense

Body:
On several of my adsense running sites, I have been getting the following errors:

Unable to post message to [http://]googleads.g.doubleclick.net.
  Recipient has origin
  http://www.anekdotz.com.

Unsafe JavaScript attempt to access
  frame with URL
  [http://]www.anekdotz.com/ from frame
  with URL
  [<a href="http://]googleads.g.doubleclick.net/pagead/ads?client=ca-pub-9099580055602120&output=html&h=250&slotname=9210181593&w=300&flash=10.0.42&url=http%3A%2F%2Fwww.anekdotz.com%2F&dt=1269901036429&correlator=1269901036438&frm=0&ga_vid=711000587.1269901037&ga_sid=1269901037&ga_hid=654061172&ga_fc=0&u_tz=-240&u_his=2&u_java=1&u_h=900&u_w=1440&u_ah=878&u_aw=1436&u_cd=24&u_nplug=10&u_nmime=101&biw=1365&bih=806&eid=44901212&fu=0&ifi=1&dtd=153&xpc=Xkfk1oufPQ&p=http%3A//www.anekdotz.com" rel="noreferrer">http://]googleads.g.doubleclick.net/pagead/ads?client=ca-pub-9099580055602120&output=html&h=250&slotname=9210181593&w=300&flash=10.0.42&url=http%3A%2F%2Fwww.anekdotz.com%2F&dt=1269901036429&correlator=1269901036438&frm=0&ga_vid=711000587.1269901037&ga_sid=1269901037&ga_hid=654061172&ga_fc=0&u_tz=-240&u_his=2&u_java=1&u_h=900&u_w=1440&u_ah=878&u_aw=1436&u_cd=24&u_nplug=10&u_nmime=101&biw=1365&bih=806&eid=44901212&fu=0&ifi=1&dtd=153&xpc=Xkfk1oufPQ&p=http%3A//www.anekdotz.com.
  Domains, protocols and ports must match.

(from the Chrome javascript console)

The ads seem to show properly and it doesn't affect my native javascript code.  However sometimes these errors seem to slow down page loading.  How can I fix this problem?

(I modified the URLs to let me post this as I'm a new user)


问:
Can typescript not infer the type of unique symbol passed directly into a function?
I'm trying to make a utility like ts-action but with symbol as action type instead of string.

Typescript infers the symbol correctly when symbol is first declared as const. When symbol is passed directly into the function, typescript fails to infer the type. Is there something I do not know?

interface Action<T extends symbol> {
    type: T;
}

function action<T extends symbol>(type: T): () => Action<T> {
    return () => ({ type });
}

const SOME_ACTION_TYPE = Symbol('some action type');
const actionBuilder = action(SOME_ACTION_TYPE);
type actionBuilderType = typeof actionBuilder;
// expected: () => Action<typeof SOME_ACTION_TYPE>
// actual: () => Action<typeof SOME_ACTION_TYPE>

const actionBuilder2 = action(Symbol('another action type'));
type actionBuilder2Type = typeof actionBuilder2
// expected: () => Action<typeof Symbol('another action type')>
// actual: () => Action<symbol>
```
<p>Here's the string version that works perfectly:</p>
<pre class="lang-js prettyprint-override"><code>interface Action<T extends string> {
    type: T;
}

function action<T extends string>(type: T): () => Action<T> {
    return () => ({ type });
}

const SOME_ACTION_TYPE = 'some action type';
const actionBuilder = action(SOME_ACTION_TYPE);
type actionBuilderType = typeof actionBuilder;
// expected: () => Action<'some action type'>
// actual: () => Action<'some action type'>

const actionBuilder2 = action('another action type');
type actionBuilder2Type = typeof actionBuilder2
// expected: () => Action<'another action type'>
// actual: () => Action<'another action type'>
</code>```

答:
This is because 'another action type' in Symbol('another action type') is not being infered, because Symbol constructor is not parametrized, I mean it does not have generic parameter.

Please see the type signature of SymbolConstructor:

interface SymbolConstructor {
    /**
     * A reference to the prototype.
     */
    readonly prototype: Symbol;

    /**
     * Returns a new unique Symbol value.
     * @param  description Description of the new Symbol object.
     */
    (description?: string | number): symbol;

    /**
     * Returns a Symbol object from the global symbol registry matching the given key if found.
     * Otherwise, returns a new symbol with this key.
     * @param key key to search for.
     */
    for(key: string): symbol;

    /**
     * Returns a key from the global symbol registry matching the given Symbol if found.
     * Otherwise, returns a undefined.
     * @param sym Symbol to find the key for.
     */
    keyFor(sym: symbol): string | undefined;
}

```
<p><code>description</code> parameter is always infered as a <code>string | number</code>. Further more, <code>symbol</code> type is a primitive type and cant be parametrized. However, if you want to parametrize it - you can.</p>
<p>First of all we need to declare own <code>SymbolConstructor</code> signature.</p>
<pre class="lang-js prettyprint-override"><code>interface SymbolConstructor {
    <T extends string>(description: T): symbol & { tag?: T };
}

declare var Symbol: SymbolConstructor;
</code>```

TypeScript will automaticaly merge it with existing one (see declaration merging).
You probably have noticed that I have added { tag?: T } to return type. It help use to unfer description and distinguish our special symbol from other symbols.

Lets test it:

interface Action<T extends symbol> {
    type: T;
}

interface SymbolConstructor {
    <T extends string>(description: T): symbol & { tag?: T };
}

declare var Symbol: SymbolConstructor;

function action<T extends symbol>(type: T): () => Action<T> {
    return () => ({ type });
}

const actionBuilder2 = action(Symbol('another action type'))

// () => Action<symbol & {
//     tag?: "another action type" | undefined;
// }>
type actionBuilder2Type = typeof actionBuilder2
```

Playground

If you want to infer string part, you should separate it from Symbol.

Body:
I'm trying to make a utility like ts-action but with symbol as action type instead of string.

Typescript infers the symbol correctly when symbol is first declared as const. When symbol is passed directly into the function, typescript fails to infer the type. Is there something I do not know?

interface Action<T extends symbol> {
    type: T;
}

function action<T extends symbol>(type: T): () => Action<T> {
    return () => ({ type });
}

const SOME_ACTION_TYPE = Symbol('some action type');
const actionBuilder = action(SOME_ACTION_TYPE);
type actionBuilderType = typeof actionBuilder;
// expected: () => Action<typeof SOME_ACTION_TYPE>
// actual: () => Action<typeof SOME_ACTION_TYPE>

const actionBuilder2 = action(Symbol('another action type'));
type actionBuilder2Type = typeof actionBuilder2
// expected: () => Action<typeof Symbol('another action type')>
// actual: () => Action<symbol>

Here's the string version that works perfectly:

interface Action<T extends string> {
    type: T;
}

function action<T extends string>(type: T): () => Action<T> {
    return () => ({ type });
}

const SOME_ACTION_TYPE = 'some action type';
const actionBuilder = action(SOME_ACTION_TYPE);
type actionBuilderType = typeof actionBuilder;
// expected: () => Action<'some action type'>
// actual: () => Action<'some action type'>

const actionBuilder2 = action('another action type');
type actionBuilder2Type = typeof actionBuilder2
// expected: () => Action<'another action type'>
// actual: () => Action<'another action type'>

Body:
This is because 'another action type' in Symbol('another action type') is not being infered, because Symbol constructor is not parametrized, I mean it does not have generic parameter.

Please see the type signature of SymbolConstructor:

interface SymbolConstructor {
    /**
     * A reference to the prototype.
     */
    readonly prototype: Symbol;

    /**
     * Returns a new unique Symbol value.
     * @param  description Description of the new Symbol object.
     */
    (description?: string | number): symbol;

    /**
     * Returns a Symbol object from the global symbol registry matching the given key if found.
     * Otherwise, returns a new symbol with this key.
     * @param key key to search for.
     */
    for(key: string): symbol;

    /**
     * Returns a key from the global symbol registry matching the given Symbol if found.
     * Otherwise, returns a undefined.
     * @param sym Symbol to find the key for.
     */
    keyFor(sym: symbol): string | undefined;
}

description parameter is always infered as a string | number. Further more, symbol type is a primitive type and cant be parametrized. However, if you want to parametrize it - you can.

First of all we need to declare own SymbolConstructor signature.

interface SymbolConstructor {
    <T extends string>(description: T): symbol & { tag?: T };
}

declare var Symbol: SymbolConstructor;

TypeScript will automaticaly merge it with existing one (see declaration merging).
You probably have noticed that I have added { tag?: T } to return type. It help use to unfer description and distinguish our special symbol from other symbols.

Lets test it:

interface Action<T extends symbol> {
    type: T;
}

interface SymbolConstructor {
    <T extends string>(description: T): symbol & { tag?: T };
}

declare var Symbol: SymbolConstructor;

function action<T extends symbol>(type: T): () => Action<T> {
    return () => ({ type });
}

const actionBuilder2 = action(Symbol('another action type'))

// () => Action<symbol & {
//     tag?: "another action type" | undefined;
// }>
type actionBuilder2Type = typeof actionBuilder2

Playground

If you want to infer string part, you should separate it from Symbol.