问:
Find and Return found string in an array
I am looking for a function that suits the following situation.

What the script does:
It retrieves the server.log from a minecraft server, and breaks it into sections from user chats, to server notifications etc.

I have an array containing the users information, it is set by another file called users.yml
and it is converted to an array like so

```<code>$userconfig = array(
    'TruDan'    => array(
        'prefix'    => '&3',
        'suffix'    => '&e',
    ),
    'TruGaming' => array(
        'prefix'    => '&c',
        'suffix'    => '&f',
    ),
    'PancakeMiner'  => array(
        'prefix'    => '&c',
        'suffix'    => '&f',
    ),
    'Teddybear952'  => array(
        'prefix'    => '&b',
        'suffix'    => '&f',
    ),
);
</code>```

What i want to do, is search the $line from server.log (it loops through lines) for a username above (array key) and return the array. so i can then parse $ret['prefix'] and $ret['suffix']

mc.php (the file) http://pastebin.com/9geyfuup
server.log (partial, the actual thing is 12,000 lines long, so i took a few lines from it) http://pastebin.com/DKz8YfgK

答:
If you're using preg_match() to search each line for a username, make sure you first sort the list of usernames in reverse order using rsort():

```<code>$users = array_map('preg_quote', array_keys($userconfig));
rsort($users);
$pattern = '/' . implode('|', $users); . '/';
if preg_match($pattern, $line, $matches) {
    return matches[0];
}
else {
    return array();
}
</code>```

If you search a line for the pattern "/TruDan|TruDan123/" the search will match a line containing "TruDan123" to the shorter version "TruDan" because it was specified first in the pattern. Sorting the user list in reverse order ensures that the pattern will be "/TruDan123|TruDan/" and so give preference to the longer match.

Body:
I am looking for a function that suits the following situation.

What the script does:
It retrieves the server.log from a minecraft server, and breaks it into sections from user chats, to server notifications etc.

I have an array containing the users information, it is set by another file called users.yml
and it is converted to an array like so

$userconfig = array(
    'TruDan'    => array(
        'prefix'    => '&3',
        'suffix'    => '&e',
    ),
    'TruGaming' => array(
        'prefix'    => '&c',
        'suffix'    => '&f',
    ),
    'PancakeMiner'  => array(
        'prefix'    => '&c',
        'suffix'    => '&f',
    ),
    'Teddybear952'  => array(
        'prefix'    => '&b',
        'suffix'    => '&f',
    ),
);

What i want to do, is search the $line from server.log (it loops through lines) for a username above (array key) and return the array. so i can then parse $ret['prefix'] and $ret['suffix']

mc.php (the file) http://pastebin.com/9geyfuup
server.log (partial, the actual thing is 12,000 lines long, so i took a few lines from it) http://pastebin.com/DKz8YfgK

Body:
If you're using preg_match() to search each line for a username, make sure you first sort the list of usernames in reverse order using rsort():

$users = array_map('preg_quote', array_keys($userconfig));
rsort($users);
$pattern = '/' . implode('|', $users); . '/';
if preg_match($pattern, $line, $matches) {
    return matches[0];
}
else {
    return array();
}

If you search a line for the pattern "/TruDan|TruDan123/" the search will match a line containing "TruDan123" to the shorter version "TruDan" because it was specified first in the pattern. Sorting the user list in reverse order ensures that the pattern will be "/TruDan123|TruDan/" and so give preference to the longer match.


来源: stackexchange

问:
Kafka connect doesn't find available brokers when volume attached
Symptom : A modified bitnami kafka image contains the kafka-connect jars, they work fine.
But once I add a volume for persistence, it can't find existing brokers.

Details:
I modded the bitnami image in a way to copy the connect jars and launching the connect-distributed.sh.
It works fine, connectors can consume and produce from/to the topics

But once I add persistent volume to the kafka image, the first startup is ok but the next onwards dont.  connect.log says:

```<code>"[2020-05-21 15:59:34,786] ERROR [Worker clientId=connect-1, groupId=my-group1] Uncaught exception in herder work thread, exiting:  (org.apache.kafka.connect.runtime.distributed.DistributedHerder:297)
g.apache.kafka.common.KafkaException: Unexpected error fetching metadata for topic connect-offsets
        at org.apache.kafka.clients.consumer.internals.Fetcher.getTopicMetadata(Fetcher.java:403)
        at org.apache.kafka.clients.consumer.KafkaConsumer.partitionsFor(KafkaConsumer.java:1965)
        at org.apache.kafka.clients.consumer.KafkaConsumer.partitionsFor(KafkaConsumer.java:1933)
        at org.apache.kafka.connect.util.KafkaBasedLog.start(KafkaBasedLog.java:138)
        at org.apache.kafka.connect.storage.KafkaOffsetBackingStore.start(KafkaOffsetBackingStore.java:109)
        at org.apache.kafka.connect.runtime.Worker.start(Worker.java:186)
        at org.apache.kafka.connect.runtime.AbstractHerder.startServices(AbstractHerder.java:123)
        at org.apache.kafka.connect.runtime.distributed.DistributedHerder.run(DistributedHerder.java:284)
        at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
        at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
        at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.apache.kafka.common.errors.InvalidReplicationFactorException: Replication factor is below 1 or larger than the number of available brokers."
</code>```

The kafka itself still works well, every topic is present (replfactor of 1) and I can consumer/produce messages by hand. And I can also launch the connector system by hand successfully.

edit: My guess is that without PV it will start the connectors after kafka is up, but with PV it sees immediatly that connectors are already present and tries to load them before the kafka started.

edit2:

   modded image:

```<code>    FROM bitnami/kafka
    // copying connect jars..
    ADD connect-distributed.properties /opt/prop/connect-distributed.properties
    ADD modded-kafka-run.sh /opt/bitnami/scripts/kafka/run.sh
    RUN chmod 755 /opt/bitnami/scripts/kafka/run.sh
</code>```

modded run.sh(I just added the distributed.sh and curl to it):

```<code>    info "** Starting Kafka **"
    /opt/bitnami/kafka/bin/connect-distributed.sh -daemon /opt/prop/connect-distributed.properties
   //.. adding the connectors with curl
    if am_i_root; then
        exec gosu "$KAFKA_DAEMON_USER" "${START_COMMAND[@]}"
    else
        exec "${START_COMMAND[@]}"
    fi
</code>```

original run.sh: https://github.com/bitnami/bitnami-docker-kafka/blob/master/2/debian-10/rootfs/opt/bitnami/scripts/kafka/run.sh

答:
Hard to tell what the issue is, but the ENTRYPOINT that starts Kafka actually starts after any RUN command.

Not clear why you need to create your own Kafka Connect image when at least two exist

You should be using docker-compose to start 3 separate Zookeeper, Kafka, and Connect clusters

ContentLicense: CC BY-SA 4.0

Body:
Symptom : A modified bitnami kafka image contains the kafka-connect jars, they work fine.
But once I add a volume for persistence, it can't find existing brokers.

Details:
I modded the bitnami image in a way to copy the connect jars and launching the connect-distributed.sh.
It works fine, connectors can consume and produce from/to the topics

But once I add persistent volume to the kafka image, the first startup is ok but the next onwards dont.  connect.log says:

"[2020-05-21 15:59:34,786] ERROR [Worker clientId=connect-1, groupId=my-group1] Uncaught exception in herder work thread, exiting:  (org.apache.kafka.connect.runtime.distributed.DistributedHerder:297)
g.apache.kafka.common.KafkaException: Unexpected error fetching metadata for topic connect-offsets
        at org.apache.kafka.clients.consumer.internals.Fetcher.getTopicMetadata(Fetcher.java:403)
        at org.apache.kafka.clients.consumer.KafkaConsumer.partitionsFor(KafkaConsumer.java:1965)
        at org.apache.kafka.clients.consumer.KafkaConsumer.partitionsFor(KafkaConsumer.java:1933)
        at org.apache.kafka.connect.util.KafkaBasedLog.start(KafkaBasedLog.java:138)
        at org.apache.kafka.connect.storage.KafkaOffsetBackingStore.start(KafkaOffsetBackingStore.java:109)
        at org.apache.kafka.connect.runtime.Worker.start(Worker.java:186)
        at org.apache.kafka.connect.runtime.AbstractHerder.startServices(AbstractHerder.java:123)
        at org.apache.kafka.connect.runtime.distributed.DistributedHerder.run(DistributedHerder.java:284)
        at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
        at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
        at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.apache.kafka.common.errors.InvalidReplicationFactorException: Replication factor is below 1 or larger than the number of available brokers."

The kafka itself still works well, every topic is present (replfactor of 1) and I can consumer/produce messages by hand. And I can also launch the connector system by hand successfully.

edit: My guess is that without PV it will start the connectors after kafka is up, but with PV it sees immediatly that connectors are already present and tries to load them before the kafka started.

edit2:

   modded image:

    FROM bitnami/kafka
    // copying connect jars..
    ADD connect-distributed.properties /opt/prop/connect-distributed.properties
    ADD modded-kafka-run.sh /opt/bitnami/scripts/kafka/run.sh
    RUN chmod 755 /opt/bitnami/scripts/kafka/run.sh

modded run.sh(I just added the distributed.sh and curl to it):

    info "** Starting Kafka **"
    /opt/bitnami/kafka/bin/connect-distributed.sh -daemon /opt/prop/connect-distributed.properties
   //.. adding the connectors with curl
    if am_i_root; then
        exec gosu "$KAFKA_DAEMON_USER" "${START_COMMAND[@]}"
    else
        exec "${START_COMMAND[@]}"
    fi

original run.sh: https://github.com/bitnami/bitnami-docker-kafka/blob/master/2/debian-10/rootfs/opt/bitnami/scripts/kafka/run.sh


问:
How to delete a function effect when a second click on the button in javascript?
maybe one of you can help me. I've written a feature in javascript that adds underlining to all "a" selectors. The function is called with the "onclick" attribute. I would like to reverse the effect, i.e. remove the underscore at second click on the same button. The question is how to do it ?

HTML code:

```<code><button type="button" class="underlineLinks" id="underlineLinks" onclick="underlineLinks()">Click</button>
</code>```

JS code:

```<code>function underlineLinks() {
    const links = document.querySelectorAll("a");
    links.forEach(a => a.style.textDecoration = "underline");
}
</code>```

答:
```<code>function underlineLinks() {
    const links = document.querySelectorAll("a");
    var toChange = "underline"
    if(links[0].style.textDecoration != "underline")) toChange = "none"
    links.forEach(a => a.style.textDecoration = toChange);
}
</code>```

<p>Probably there is an easier way but idk, I shoot my shot </p>

Body:
maybe one of you can help me. I've written a feature in javascript that adds underlining to all "a" selectors. The function is called with the "onclick" attribute. I would like to reverse the effect, i.e. remove the underscore at second click on the same button. The question is how to do it ?

HTML code:

<button type="button" class="underlineLinks" id="underlineLinks" onclick="underlineLinks()">Click</button>

JS code:

function underlineLinks() {
    const links = document.querySelectorAll("a");
    links.forEach(a => a.style.textDecoration = "underline");
}

Body:
function underlineLinks() {
    const links = document.querySelectorAll("a");
    var toChange = "underline"
    if(links[0].style.textDecoration != "underline")) toChange = "none"
    links.forEach(a => a.style.textDecoration = toChange);
}

Probably there is an easier way but idk, I shoot my shot


问:
Understanding TXT records after moving DNS from Route53 to Cloudflare
I'm moving DNS records for an existing website from Amazon Route53 to Cloudflare, and introducing an AWS load balancer into the mix.

Current Architecture

```<code>Route53 DNS --> EC2 Instance
</code>```

New Architecture

```<code>Cloudflare DNS --> AWS Load Balancer --> EC2 Instance
</code>```

In some of the DNS records, there are references to the Elastic IP assigned to the AWS Instance (this is shown as 11.22.33.44 below). I didn't set up the records previously.

TXT record #1

```<code>v=spf1 mx include:_SPF.google.com a:ec2-11-22-33-44.eu-west-1.compute.amazonaws.com include:servers.mcsv.net ~all
</code>```

TXT record #2

```<code>include:spf.protection.outlook.com  include:spf.mandrillapp.com  ip4:11.22.33.44
</code>```

I have a couple of questions here:

Does the Cloudflare proxy or the load balancer affect the existing IP in the TXT records? I should leave this as it is, right?

Do these need to be two separate TXT records? Can I combine them, and if so, does the order of the statements matter?

答:
Does the Cloudflare proxy or the load balancer affect the existing IP in the TXT records? I should leave this as it is, right?

Correct. Those do not affect the IP of the server.

Do these need to be two separate TXT records? Can I combine them, and if so, does the order of the statements matter?

Having more than one SPF record violates the RFC.

Duplicate SPF TXT records. Another commonly violated aspect of SPF is that a domain may only have a single SPF record. That means you can only have a single DNS TXT record that begins with “v=spf1”.

See https://www.socketlabs.com/blog/best-practices-sender-policy-framework-spf/

Background:

Those are SPF mail domain validation records, as you may know. They should always reflect the IP addresses or domains of any mail server that would be sending email on behalf of the given domain.

I would point out that since you now have a load balancer in the mix, that the instance IP number could change over time if it's replaced, assuming you have some Auto scaling group controlling instances. Every time that the instance restarts its IP address could change,  depending on your setup.  this would invalidate your SPF record and we need to be updated to maintain proper mail delivery.

For this reason I would suggest you consider using AWS SES for outbound email which will always be correct regardless of your instance IP chnages. The service provides fixed MX server names that you can use in your SPF records.

Body:
I'm moving DNS records for an existing website from Amazon Route53 to Cloudflare, and introducing an AWS load balancer into the mix.

Current Architecture

Route53 DNS --> EC2 Instance

New Architecture

Cloudflare DNS --> AWS Load Balancer --> EC2 Instance

In some of the DNS records, there are references to the Elastic IP assigned to the AWS Instance (this is shown as 11.22.33.44 below). I didn't set up the records previously.

TXT record #1

v=spf1 mx include:_SPF.google.com a:ec2-11-22-33-44.eu-west-1.compute.amazonaws.com include:servers.mcsv.net ~all

TXT record #2

include:spf.protection.outlook.com  include:spf.mandrillapp.com  ip4:11.22.33.44

I have a couple of questions here:

Does the Cloudflare proxy or the load balancer affect the existing IP in the TXT records? I should leave this as it is, right?

Do these need to be two separate TXT records? Can I combine them, and if so, does the order of the statements matter?


答:
Something like this?</p>

```<code>SELECT 10 * FLOOR(id / 10)  , AVG(speed), MIN( [from] ) , MAX( [to])
FROM dbo.Thous_Data
GROUP BY 10 * FLOOR(id / 10);
</code>```

Title: Converting Data to Tenths and averaging values

Body:
so I have a table in thousandths of a mile like this:

id |fk |from  |to    |speed|score
1  |123|10.002|10.003|20   |10
2  |123|10.003|10.004|25   |11
3  |123|10.004|10.005|40   |44
4  |123|10.005|10.006|50   |23
5  |123|10.006|10.007|20   |54
6  |123|10.007|10.008|10   |24
7  |123|10.008|10.009|65   |24
8  |123|10.009|10.010|23   |24
9  |123|10.010|10.011|74   |56
10 |123|10.011|10.012|25   |43
11 |123|10.012|10.013|10   |76
12 |123|10.013|10.014|5    |10
...

I need to convert the thousandth mile table to tenths of a mile and take average of speed and score like this:

id |fk |from  |to    |Avgspeed|Avgscore
1  |123|10.002|10.012|35.2    |31.3
10 |123|10.012|...   |...     |...

I came up with this query to get the tenth of a mile:

select CASE WHEN rn=1 then 1
when rn%10=0 then 1
else 0 end chk,x.* from
(
select row_number() over (partition by fk order by fk,from) rn,* from dbo.Thous_Data
)x

This gives me

id |fk |from  |to    |speed|score|chk|rn
1  |123|10.002|10.003|20   |10   |1  |1
2  |123|10.003|10.004|25   |11   |0  |2
3  |123|10.004|10.005|40   |44   |0  |3
4  |123|10.005|10.006|50   |23   |0  |4
5  |123|10.006|10.007|20   |54   |0  |5
6  |123|10.007|10.008|10   |24   |0  |6
7  |123|10.008|10.009|65   |24   |0  |7
8  |123|10.009|10.010|23   |24   |0  |8
9  |123|10.010|10.011|74   |56   |0  |9
10 |123|10.011|10.012|25   |43   |1  |10
11 |123|10.012|10.013|10   |76   |0  |11
12 |123|10.013|10.014|5    |10   |0  |12
...

Not sure how to proceed with getting the averages and setting up the from and to correctly. Any ideas appreciated.

Body:
Something like this?

SELECT 10 * FLOOR(id / 10)  , AVG(speed), MIN( [from] ) , MAX( [to])
FROM dbo.Thous_Data
GROUP BY 10 * FLOOR(id / 10);


问:
declaring an array of pointers in a C header file and assigning value?
Is it possible to declare an array of pointers and later on initialize either of them and assign a value, in a C header file?

```<code>char *i[2];
i[0] = "abc";
</code>```

the following does not work.

```<code>char *x = "def"; // this will, of course.
</code>```

How am I supposed to declare and assign values for an array of pointers?

答:
This has nothing to do with header files. You cannot create a .c file and put in it code like this:

```<code>char *i[2];
i[0] = "abc";
</code>```

In C, all code except definitions and initialisations must be inside functions, and your second statement is neither of these - it is an assignment.

An initialisation for your array would look like this:

```<code>char *i[2] = {"foo","bar"};
</code>```

And that could be put in a header file, but would cause multiple definition errors if the header were used in more than one translation unit.

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to declare an array of pointers and later on initialize either of them and assign a value, in a C header file?

char *i[2];
i[0] = "abc";

the following does not work.

char *x = "def"; // this will, of course.

How am I supposed to declare and assign values for an array of pointers?

Body:
This has nothing to do with header files. You cannot create a .c file and put in it code like this:

char *i[2];
i[0] = "abc";

In C, all code except definitions and initialisations must be inside functions, and your second statement is neither of these - it is an assignment.

An initialisation for your array would look like this:

char *i[2] = {"foo","bar"};

And that could be put in a header file, but would cause multiple definition errors if the header were used in more than one translation unit.


问:
Angular 9 -- Multiple Children inside Parent
Can someone explain to me, why the appropriate child switch won't update properly?
Click on the second child and the first child updates, but the console shows the correct method being called. Is it not possible to call the same child component in the parent like I am?

https://stackblitz.com/edit/angular-ivy-ch65ks

答: It is because you have the same id in both the cases. Try appending the ID of the <input> in the child component with some unique key from the parent in both the cases and it should work fine.


问:
Does Apple permit the usage of socket for communication between two iOS apps?
So basically I have two iOS apps installed on the same device, and they need to communicate by sending data to each other. I don't want to use URL scheme or Universal links as these two would open the other app in UI instead of sending message to each other in the background. Currently I have a solution of using a unix socket connection by binding one app to a specific port and have another app connect to it. This works fine but I am just wondering if Apple would allow the usage of this.
Note that these two iOS apps do not come from the same developer so anything else that relies on App Group would not work in this case..

Would Apple allow using a socket in this case?
Edit: One of the app is valid to run in background, so background execution is not a problem

答: It is totally doable as long as one of your apps has permissions to run on the background. Such example is music apps. Spotify does the same thing with their “app-remote” SDK.</p>


答:
You can create a CSS class with the decoration underline

```<code>.class
{
    text-decoration: underline
}
</code>```

and use toggle in the JS.

Toggle will add the class if it isn't applied to your link and remove the class if it is applied to your link

```<code>function underlineLinks() {
    const links = document.querySelectorAll("a");
    links.forEach(a => a.classList.toggle("class"));
}
</code>```

https://jsfiddle.net/u4sxfdy5/

Title: How to delete a function effect when a second click on the button in javascript?

Body:
You can create a CSS class with the decoration underline

.class
{
    text-decoration: underline
}

and use toggle in the JS.

Toggle will add the class if it isn't applied to your link and remove the class if it is applied to your link

function underlineLinks() {
    const links = document.querySelectorAll("a");
    links.forEach(a => a.classList.toggle("class"));
}

https://jsfiddle.net/u4sxfdy5/


问:
Sometimes methods fails with Fatal error: UnsafeMutablePointer.initialize overlapping range
I have the following code to decompress some Data back to a String in Swift 5. The method mostly works fine, but sometimes it fails with the following error message:

Thread 1: Fatal error: UnsafeMutablePointer.initialize overlapping range

```<code>extension Data
{
    func decompress(destinationSize: Int) -> String?
    {
        let destinationBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: destinationSize)

        let decodedString = self.withUnsafeBytes
        {
            unsafeRawBufferPointer -> String? in

            let unsafeBufferPointer = unsafeRawBufferPointer.bindMemory(to: UInt8.self)
            if let unsafePointer = unsafeBufferPointer.baseAddress
            {
                let decompressedSize = compression_decode_buffer(destinationBuffer, destinationSize, unsafePointer, self.count, nil, COMPRESSION_ZLIB)

                if decompressedSize == 0
                {
                    return String.empty
                }

                let string = String(cString: destinationBuffer)
                let substring = string.substring(0, decompressedSize)

                return substring
            }

            return nil
        }

        return decodedString
    }
}
</code>```

The error occurs at the following line:

```<code>let string = String(cString: destinationBuffer)
</code>```

Can someone please explain why this (sometimes) fails?

答:
I have switched to the following code and now everything works fine (Swift 5):</p>

```<code>import Compression

extension Data
{
    func compress() -> Data?
    {
        return self.withUnsafeBytes
        {
            dataBytes in

            let sourcePtr: UnsafePointer<UInt8> = dataBytes.baseAddress!.assumingMemoryBound(to: UInt8.self)

            return self.perform(operation: COMPRESSION_STREAM_ENCODE, source: sourcePtr, sourceSize: self.count)
        }
    }

    func decompress() -> Data?
    {
        return self.withUnsafeBytes
        {
            unsafeRawBufferPointer -> Data? in

            let unsafeBufferPointer = unsafeRawBufferPointer.bindMemory(to: UInt8.self)
            if let unsafePointer = unsafeBufferPointer.baseAddress
            {
                return self.perform(operation: COMPRESSION_STREAM_DECODE, source: unsafePointer, sourceSize: self.count)
            }

            return nil
        }
    }

    fileprivate func perform(operation: compression_stream_operation, source: UnsafePointer<UInt8>, sourceSize: Int, preload: Data = Data()) -> Data?
    {
        guard sourceSize > 0 else { return nil }

        let streamBase = UnsafeMutablePointer<compression_stream>.allocate(capacity: 1)
        defer { streamBase.deallocate() }
        var stream = streamBase.pointee

        let status = compression_stream_init(&stream, operation, COMPRESSION_ZLIB)
        guard status != COMPRESSION_STATUS_ERROR else { return nil }
        defer { compression_stream_destroy(&stream) }

        var result = preload
        var flags: Int32 = Int32(COMPRESSION_STREAM_FINALIZE.rawValue)
        let blockLimit = 64 * 1024
        var bufferSize = Swift.max(sourceSize, 64)

        if sourceSize > blockLimit
        {
            bufferSize = blockLimit
        }

        let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
        defer { buffer.deallocate() }

        stream.dst_ptr  = buffer
        stream.dst_size = bufferSize
        stream.src_ptr  = source
        stream.src_size = sourceSize

        while true
        {
            switch compression_stream_process(&stream, flags)
            {
                case COMPRESSION_STATUS_OK:
                    guard stream.dst_size == 0 else { return nil }
                    result.append(buffer, count: stream.dst_ptr - buffer)
                    stream.dst_ptr = buffer
                    stream.dst_size = bufferSize

                    if flags == 0 && stream.src_size == 0
                    {
                        flags = Int32(COMPRESSION_STREAM_FINALIZE.rawValue)
                    }

                case COMPRESSION_STATUS_END:
                    result.append(buffer, count: stream.dst_ptr - buffer)
                    return result

                default:
                    return nil
            }
        }
    }
}
</code>```

Body:
I have the following code to decompress some Data back to a String in Swift 5. The method mostly works fine, but sometimes it fails with the following error message:

Thread 1: Fatal error: UnsafeMutablePointer.initialize overlapping range

extension Data
{
    func decompress(destinationSize: Int) -> String?
    {
        let destinationBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: destinationSize)

        let decodedString = self.withUnsafeBytes
        {
            unsafeRawBufferPointer -> String? in

            let unsafeBufferPointer = unsafeRawBufferPointer.bindMemory(to: UInt8.self)
            if let unsafePointer = unsafeBufferPointer.baseAddress
            {
                let decompressedSize = compression_decode_buffer(destinationBuffer, destinationSize, unsafePointer, self.count, nil, COMPRESSION_ZLIB)

                if decompressedSize == 0
                {
                    return String.empty
                }

                let string = String(cString: destinationBuffer)
                let substring = string.substring(0, decompressedSize)

                return substring
            }

            return nil
        }

        return decodedString
    }
}

The error occurs at the following line:

let string = String(cString: destinationBuffer)

Can someone please explain why this (sometimes) fails?

Body:
I have switched to the following code and now everything works fine (Swift 5):

import Compression

extension Data
{
    func compress() -> Data?
    {
        return self.withUnsafeBytes
        {
            dataBytes in

            let sourcePtr: UnsafePointer<UInt8> = dataBytes.baseAddress!.assumingMemoryBound(to: UInt8.self)

            return self.perform(operation: COMPRESSION_STREAM_ENCODE, source: sourcePtr, sourceSize: self.count)
        }
    }

    func decompress() -> Data?
    {
        return self.withUnsafeBytes
        {
            unsafeRawBufferPointer -> Data? in

            let unsafeBufferPointer = unsafeRawBufferPointer.bindMemory(to: UInt8.self)
            if let unsafePointer = unsafeBufferPointer.baseAddress
            {
                return self.perform(operation: COMPRESSION_STREAM_DECODE, source: unsafePointer, sourceSize: self.count)
            }

            return nil
        }
    }

    fileprivate func perform(operation: compression_stream_operation, source: UnsafePointer<UInt8>, sourceSize: Int, preload: Data = Data()) -> Data?
    {
        guard sourceSize > 0 else { return nil }

        let streamBase = UnsafeMutablePointer<compression_stream>.allocate(capacity: 1)
        defer { streamBase.deallocate() }
        var stream = streamBase.pointee

        let status = compression_stream_init(&stream, operation, COMPRESSION_ZLIB)
        guard status != COMPRESSION_STATUS_ERROR else { return nil }
        defer { compression_stream_destroy(&stream) }

        var result = preload
        var flags: Int32 = Int32(COMPRESSION_STREAM_FINALIZE.rawValue)
        let blockLimit = 64 * 1024
        var bufferSize = Swift.max(sourceSize, 64)

        if sourceSize > blockLimit
        {
            bufferSize = blockLimit
        }

        let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
        defer { buffer.deallocate() }

        stream.dst_ptr  = buffer
        stream.dst_size = bufferSize
        stream.src_ptr  = source
        stream.src_size = sourceSize

        while true
        {
            switch compression_stream_process(&stream, flags)
            {
                case COMPRESSION_STATUS_OK:
                    guard stream.dst_size == 0 else { return nil }
                    result.append(buffer, count: stream.dst_ptr - buffer)
                    stream.dst_ptr = buffer
                    stream.dst_size = bufferSize

                    if flags == 0 && stream.src_size == 0
                    {
                        flags = Int32(COMPRESSION_STREAM_FINALIZE.rawValue)
                    }

                case COMPRESSION_STATUS_END:
                    result.append(buffer, count: stream.dst_ptr - buffer)
                    return result

                default:
                    return nil
            }
        }
    }
}


问:
Sorting a list based off of values in another list
I have two lists; invoice_ordering_list and pdfs. I need to sort pdfs based on the order of invoice_ordering_list.

```<code>invoice_ordering_list = ['265189', '265195', '265114', '265166', '265165', '265115']

pdfs = [
    'Est. 57349 April Bill Inv 265115.pdf',
    'AH_202015_JUN_57768 265189.pdf',
    'AH_202015_MAY FEE_265195.pdf',
    'Est. 56534 April Bill Inv 265165.pdf',
    'Est. 57279 April Bill Inv 265166.pdf',
    'Est. 42477 April Bill Inv 265114.pdf',
]
</code>```

I've tried:

```<code>keydict = dict(zip(pdfs, invoice_ordering_list))
pdfs.sort(key=keydict.get)
</code>```

For some reason it almost gets the order right but 265189 ends up at the end. I must be misunderstanding what's going on here. this seems like such an easy task that I just can't figure out.

The output should be:

```<code>pdfs_new = [
    'AH_202015_JUN_57768 265189.pdf',
    'AH_202015_MAY FEE_265195.pdf',
    'Est. 42477 April Bill Inv 265114.pdf',
    'Est. 57279 April Bill Inv 265166.pdf',
    'Est. 56534 April Bill Inv 265165.pdf',
    'Est. 57349 April Bill Inv 265115.pdf',
]
</code>```

答:
Create a dictionary from ordering list with file names as keys and index as values.

Use re.search() to get the id from the file names to match the file names with the indexes from the order dictionary.

Sort using the index from the order dictionary as the key and zip off the first index to give a sorted list of just the pdf names.

```<code>order_dict = {val: key for key, val in enumerate(invoice_ordering_list)}

sorted_list = sorted([[el, order_dict[re.search("\d+(?=\.\w+$)", el).group()]] \
                for el in pdfs], key = lambda l: l[1])

sorted_pdfs = [a for a in list(zip(*sorted_list))[0]]
</code>```

Live Code -> https://onlinegdb.com/SkoNfFajL

Or use a function to return the sort key

```<code>order_dict = {val: key for key, val in enumerate(invoice_ordering_list)}

def get_key(file):
    id_num = re.search("\d+(?=\.\w+$)", file).group()
    return order_dict[id_num] if id_num in order_dict else int(id_num)

pdfs.sort(key= lambda name: get_key(name))
</code>```

Here, I have the get_key() function returning the file id number if it isn't found in the ordering list.

Live Code -> https://onlinegdb.com/Sy1zH9ao8

Body:
I have two lists; invoice_ordering_list and pdfs. I need to sort pdfs based on the order of invoice_ordering_list.

invoice_ordering_list = ['265189', '265195', '265114', '265166', '265165', '265115']

pdfs = [
    'Est. 57349 April Bill Inv 265115.pdf',
    'AH_202015_JUN_57768 265189.pdf',
    'AH_202015_MAY FEE_265195.pdf',
    'Est. 56534 April Bill Inv 265165.pdf',
    'Est. 57279 April Bill Inv 265166.pdf',
    'Est. 42477 April Bill Inv 265114.pdf',
]

I've tried:

keydict = dict(zip(pdfs, invoice_ordering_list))
pdfs.sort(key=keydict.get)

For some reason it almost gets the order right but 265189 ends up at the end. I must be misunderstanding what's going on here. this seems like such an easy task that I just can't figure out.

The output should be:

pdfs_new = [
    'AH_202015_JUN_57768 265189.pdf',
    'AH_202015_MAY FEE_265195.pdf',
    'Est. 42477 April Bill Inv 265114.pdf',
    'Est. 57279 April Bill Inv 265166.pdf',
    'Est. 56534 April Bill Inv 265165.pdf',
    'Est. 57349 April Bill Inv 265115.pdf',
]

Body:
Create a dictionary from ordering list with file names as keys and index as values.

Use re.search() to get the id from the file names to match the file names with the indexes from the order dictionary.

Sort using the index from the order dictionary as the key and zip off the first index to give a sorted list of just the pdf names.

order_dict = {val: key for key, val in enumerate(invoice_ordering_list)}

sorted_list = sorted([[el, order_dict[re.search("\d+(?=\.\w+$)", el).group()]] \
                for el in pdfs], key = lambda l: l[1])

sorted_pdfs = [a for a in list(zip(*sorted_list))[0]]

Live Code -> https://onlinegdb.com/SkoNfFajL

Or use a function to return the sort key

order_dict = {val: key for key, val in enumerate(invoice_ordering_list)}

def get_key(file):
    id_num = re.search("\d+(?=\.\w+$)", file).group()
    return order_dict[id_num] if id_num in order_dict else int(id_num)

pdfs.sort(key= lambda name: get_key(name))

Here, I have the get_key() function returning the file id number if it isn't found in the ordering list.

Live Code -> https://onlinegdb.com/Sy1zH9ao8


问:
How to count how many posts the user has commented on?
I know how to get the number of all comments written by a specific user, but how to count how many posts the user has commented on (in WordPress).</p>

答:
If you want to count the comments a user made on posts:

You can use get_comments() function

https://developer.wordpress.org/reference/functions/get_comments/

which accepts an array of arguments

https://developer.wordpress.org/reference/classes/wp_comment_query/__construct/

In your arguments array, you use user_id to only get comments of this user. You also use count to return the number of comments.

The code looks like this:

```<code><?php
    $comments_args = array(
        'user_id' => 12,   // Your user ID, for example user with id 12
        'count'   => true // Return count
    );
    $comments_count = get_comments( $comments_args );

    echo $comments_count;
?>
</code>```

You now have the number of comments the user with id 12 wrote.

If you want to count the posts where the user added one or more comments:

You can use WP_Query and run through your posts and use wp_list_pluck() to pluck the field out of each object.

```<code>$args = array(
    'post_type'      => 'post',
    'posts_per_page' =>-1,
    'post__in' => array_unique(
         wp_list_pluck(
            get_comments( array(
                'user_id' => get_current_user_id()
                )
            ),
            'comment_post_ID'
         )
    ),
);
$comment_query = new WP_Query( $args );

// The Loop
$counter = 0;
if ( $comment_query ->have_posts() ) {
    while ( $comment_query ->have_posts() ) {
        $comment_query ->the_post();
            $counter++;
            // or display title or something
    }
    /* Restore original Post Data */
    wp_reset_postdata();
} else {
    // no posts found
}
</code>```

You can now display the number using echo $counter;.

Body:
If you want to count the comments a user made on posts:

You can use get_comments() function

https://developer.wordpress.org/reference/functions/get_comments/

which accepts an array of arguments

https://developer.wordpress.org/reference/classes/wp_comment_query/__construct/

In your arguments array, you use user_id to only get comments of this user. You also use count to return the number of comments.

The code looks like this:

<?php
    $comments_args = array(
        'user_id' => 12,   // Your user ID, for example user with id 12
        'count'   => true // Return count
    );
    $comments_count = get_comments( $comments_args );

    echo $comments_count;
?>

You now have the number of comments the user with id 12 wrote.

If you want to count the posts where the user added one or more comments:

You can use WP_Query and run through your posts and use wp_list_pluck() to pluck the field out of each object.

$args = array(
    'post_type'      => 'post',
    'posts_per_page' =>-1,
    'post__in' => array_unique(
         wp_list_pluck(
            get_comments( array(
                'user_id' => get_current_user_id()
                )
            ),
            'comment_post_ID'
         )
    ),
);
$comment_query = new WP_Query( $args );

// The Loop
$counter = 0;
if ( $comment_query ->have_posts() ) {
    while ( $comment_query ->have_posts() ) {
        $comment_query ->the_post();
            $counter++;
            // or display title or something
    }
    /* Restore original Post Data */
    wp_reset_postdata();
} else {
    // no posts found
}

You can now display the number using echo $counter;.


问:
problem with AsyncTask thread
I'm reading some data from a DB in an AsyncTask thread....
in this way:

```<code>    protected Void doInBackground(DBAdapter... db) {

        try {

            db[0].openDataBase();

            Cursor c = db[0].getCursor3(db[0].TABLE_3, user_id);

            float[] viteza = new float[c.getCount()];

            String[] time = new String[c.getCount()];

            if (c.moveToFirst()) {

                do {

                    viteza[i] = Float.parseFloat(c.getString(3));
                    time[i] = c.getString(4);

                    publishProgress(????);

                    Thread.sleep(2500);

                    i++;
                } while (c.moveToNext());

            }
            c.close();
            db[0].close();

        } catch (Exception e) {
            Log.d("Eroare", "doInBackground", e);
        }

        return null;
    }
</code>```

My problem is that each time I get a new value for viteza[i] and time[i] I have to send them to

```<code>protected void onProgressUpdate(....?) {

}
</code>```

both at the same time....but I don't know how to do that cause publishProgress() can take only one parameter!!!!

Can someone help me with this?Thx

答:
Consider a custom object that wraps the two values and pass this object as Progress as in:

```<code>private class MyAsynch extends AsyncTask<Void,MyObject,Void>{
</code>```

JAL

Title: problem with AsyncTask thread

Body:
I'm reading some data from a DB in an AsyncTask thread....
in this way:

    protected Void doInBackground(DBAdapter... db) {

        try {

            db[0].openDataBase();

            Cursor c = db[0].getCursor3(db[0].TABLE_3, user_id);

            float[] viteza = new float[c.getCount()];

            String[] time = new String[c.getCount()];

            if (c.moveToFirst()) {

                do {

                    viteza[i] = Float.parseFloat(c.getString(3));
                    time[i] = c.getString(4);

                    publishProgress(????);

                    Thread.sleep(2500);

                    i++;
                } while (c.moveToNext());

            }
            c.close();
            db[0].close();

        } catch (Exception e) {
            Log.d("Eroare", "doInBackground", e);
        }

        return null;
    }

My problem is that each time I get a new value for viteza[i] and time[i] I have to send them to

protected void onProgressUpdate(....?) {

}

both at the same time....but I don't know how to do that cause publishProgress() can take only one parameter!!!!

Can someone help me with this?Thx

Body:
Consider a custom object that wraps the two values and pass this object as Progress as in:

private class MyAsynch extends AsyncTask<Void,MyObject,Void>{

JAL


问:
postgres insert using CTE and use the inersted id in next sub query
I insert a user into the database. Then I need the user id generated to insert into a teamMember table. I am using CTE's, I read they run concurrently, is it possible to return the id of the inserted users to the next statement?

```<code>    with INPUT (col) as (
        VALUES ('
            {
               "insert":[
                {"username":"JSmith", "name":"John Smith", "mail":"JSmith@smith.com","jobTitle":"Lead","hasImage":true,"teamId":47}
               ],
               "delete":[
               ],
               "update":[{"username":"JDoe", "name":"Jane Doe","mail":"JDoe@mark.com","jobTitle":"Software Developer","hasImage":false, "uid": 255, "teamId":40}]
            }'::jsonb)
    ),
    -- Insert new users if username is unique
    do_insert as (
      INSERT INTO users (username, name, mail, "jobTitle", "hasImage")
      SELECT i.value ->> 'username',
             i.value ->> 'name',
             i.value ->> 'mail',
             i.value ->> 'jobTitle',
             (i.value ->> 'hasImage')::boolean
      FROM INPUT
       CROSS JOIN json_array_elements(to_json(col -> 'insert')) i
        WHERE NOT EXISTS (
            SELECT (username) FROM users
            WHERE username = i.value ->> 'username'
        )
        RETURNING *
    )
    -- Insert row in teamMembers
        INSERT INTO "teamMembers"("teamId", "userId")
      select (i.value ->> 'teamId')::int, t1.id
      from input
       cross join json_array_elements(to_json(col -> 'insert')) i
        left join users t1 ON i.value ->> 'username' = t1.username
left join do_insert on users.username = do_insert.username
</code>```

答:
You don't need the left join on users since do_insert is the same table but updated. In your select put do_insert.id instead of t1.id and get rid of the users left join and it should work.

```<code>    with INPUT (col) as (
        VALUES ('
            {
               "insert":[
                {"username":"JSmith", "name":"John Smith", "mail":"JSmith@smith.com","jobTitle":"Lead","hasImage":true,"teamId":47}
               ],
               "delete":[
               ],
               "update":[{"username":"JDoe", "name":"Jane Doe","mail":"JDoe@mark.com","jobTitle":"Software Developer","hasImage":false, "uid": 255, "teamId":40}]
            }'::jsonb)
    ),
    -- Insert new users if username is unique
    do_insert as (
      INSERT INTO users (username, name, mail, "jobTitle", "hasImage")
      SELECT i.value ->> 'username',
             i.value ->> 'name',
             i.value ->> 'mail',
             i.value ->> 'jobTitle',
             (i.value ->> 'hasImage')::boolean
      FROM INPUT
       CROSS JOIN json_array_elements(to_json(col -> 'insert')) i
        WHERE NOT EXISTS (
            SELECT (username) FROM users
            WHERE username = i.value ->> 'username'
        )
        RETURNING *
    )
    -- Insert row in teamMembers
        INSERT INTO "teamMembers"("teamId", "userId")
      select (i.value ->> 'teamId')::int, do_insert.id
      from input
       cross join json_array_elements(to_json(col -> 'insert')) i
      left join do_insert on users.username = do_insert.username
</code>```

Body:
I insert a user into the database. Then I need the user id generated to insert into a teamMember table. I am using CTE's, I read they run concurrently, is it possible to return the id of the inserted users to the next statement?

    with INPUT (col) as (
        VALUES ('
            {
               "insert":[
                {"username":"JSmith", "name":"John Smith", "mail":"JSmith@smith.com","jobTitle":"Lead","hasImage":true,"teamId":47}
               ],
               "delete":[
               ],
               "update":[{"username":"JDoe", "name":"Jane Doe","mail":"JDoe@mark.com","jobTitle":"Software Developer","hasImage":false, "uid": 255, "teamId":40}]
            }'::jsonb)
    ),
    -- Insert new users if username is unique
    do_insert as (
      INSERT INTO users (username, name, mail, "jobTitle", "hasImage")
      SELECT i.value ->> 'username',
             i.value ->> 'name',
             i.value ->> 'mail',
             i.value ->> 'jobTitle',
             (i.value ->> 'hasImage')::boolean
      FROM INPUT
       CROSS JOIN json_array_elements(to_json(col -> 'insert')) i
        WHERE NOT EXISTS (
            SELECT (username) FROM users
            WHERE username = i.value ->> 'username'
        )
        RETURNING *
    )
    -- Insert row in teamMembers
        INSERT INTO "teamMembers"("teamId", "userId")
      select (i.value ->> 'teamId')::int, t1.id
      from input
       cross join json_array_elements(to_json(col -> 'insert')) i
        left join users t1 ON i.value ->> 'username' = t1.username
left join do_insert on users.username = do_insert.username

Body:
You don't need the left join on users since do_insert is the same table but updated. In your select put do_insert.id instead of t1.id and get rid of the users left join and it should work.

    with INPUT (col) as (
        VALUES ('
            {
               "insert":[
                {"username":"JSmith", "name":"John Smith", "mail":"JSmith@smith.com","jobTitle":"Lead","hasImage":true,"teamId":47}
               ],
               "delete":[
               ],
               "update":[{"username":"JDoe", "name":"Jane Doe","mail":"JDoe@mark.com","jobTitle":"Software Developer","hasImage":false, "uid": 255, "teamId":40}]
            }'::jsonb)
    ),
    -- Insert new users if username is unique
    do_insert as (
      INSERT INTO users (username, name, mail, "jobTitle", "hasImage")
      SELECT i.value ->> 'username',
             i.value ->> 'name',
             i.value ->> 'mail',
             i.value ->> 'jobTitle',
             (i.value ->> 'hasImage')::boolean
      FROM INPUT
       CROSS JOIN json_array_elements(to_json(col -> 'insert')) i
        WHERE NOT EXISTS (
            SELECT (username) FROM users
            WHERE username = i.value ->> 'username'
        )
        RETURNING *
    )
    -- Insert row in teamMembers
        INSERT INTO "teamMembers"("teamId", "userId")
      select (i.value ->> 'teamId')::int, do_insert.id
      from input
       cross join json_array_elements(to_json(col -> 'insert')) i
      left join do_insert on users.username = do_insert.username


问:
Don't have right output while comparing chars
```<code>#include <stdio.h>
#include <stdlib.h>

struct patients{
char last_name[15];
int passport_number;
char disease[30];
char doctors_last_name[15];
};

int main (){
int n,i;
char enter_doctors_last_name [15];

struct patients mas_struct[3]={{"Ivanov",5457401,"COVID-18","Davis"},{"Petrov",2864228,"COVID-19","Davis"},{"Petrova",63863380,"COVID-19","Dixon"}};
    printf("\nPatients:");
    printf("\n Last name  |   Passport number  | \tDisease   |   Doctor's last name ");
for (i=0;i<3;i++)
    printf("\n %s \t%d \t%s \t%s",mas_struct[i].last_name,mas_struct[i].passport_number,mas_struct[i].disease,mas_struct[i].doctors_last_name);
    printf("\n");
    printf("\nEnter doctor's last name:");
    scanf("%s", enter_doctors_last_name);
    printf("\nPatients:");

for (i=0;i<3;i++)
 if(mas_struct[i].doctors_last_name == enter_doctors_last_name)
    printf("\n %s \t%d \t%s \t%s",mas_struct[i].last_name,mas_struct[i].passport_number,mas_struct[i].disease,mas_struct[i].doctors_last_name);

return 0;
}
</code>```

Got trouble in comparing chars, it doesn't work and I can't come up with the right words for googling it.

In the last lines when I type "Davis" or "Dixon" for enter_doctors_last_name

Output is just Patients

I also tried to use gets function

答:
You can't compare strings with == operator, use strcmp instead:

```<code>if (!strcmp(mas_struct[i].doctors_last_name,enter_doctors_last_name)){/*...*/}
</code>```

scanf with "%s" specifier is very unsafe use "%14s" instead, the -1 character is to reserve space for the null-terminator.

If you need names with more than 1 word you should use "%14[^\n]", reads everything until the newline character is found.

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

struct patients{
char last_name[15];
int passport_number;
char disease[30];
char doctors_last_name[15];
};

int main (){
int n,i;
char enter_doctors_last_name [15];

struct patients mas_struct[3]={{"Ivanov",5457401,"COVID-18","Davis"},{"Petrov",2864228,"COVID-19","Davis"},{"Petrova",63863380,"COVID-19","Dixon"}};
    printf("\nPatients:");
    printf("\n Last name  |   Passport number  | \tDisease   |   Doctor's last name ");
for (i=0;i<3;i++)
    printf("\n %s \t%d \t%s \t%s",mas_struct[i].last_name,mas_struct[i].passport_number,mas_struct[i].disease,mas_struct[i].doctors_last_name);
    printf("\n");
    printf("\nEnter doctor's last name:");
    scanf("%s", enter_doctors_last_name);
    printf("\nPatients:");

for (i=0;i<3;i++)
 if(mas_struct[i].doctors_last_name == enter_doctors_last_name)
    printf("\n %s \t%d \t%s \t%s",mas_struct[i].last_name,mas_struct[i].passport_number,mas_struct[i].disease,mas_struct[i].doctors_last_name);

return 0;
}

Got trouble in comparing chars, it doesn't work and I can't come up with the right words for googling it.

In the last lines when I type "Davis" or "Dixon" for enter_doctors_last_name

Output is just Patients

I also tried to use gets function

Body:
You can't compare strings with == operator, use strcmp instead:

if (!strcmp(mas_struct[i].doctors_last_name,enter_doctors_last_name)){/*...*/}

scanf with "%s" specifier is very unsafe use "%14s" instead, the -1 character is to reserve space for the null-terminator.

If you need names with more than 1 word you should use "%14[^\n]", reads everything until the newline character is found.


问:
Discord.js : reaction.message.guild.members.find is not a function
I am trying to make a Discord.js bot that add the "Joueur" role to the user who reacted with the ✅ emoji. I am new to JS and I found the reaction.message.guild.members.find function on the Internet but I somehow get the error TypeError: reaction.message.guild.members.find is not a function and the role is not added.
Here is the part of my code :

```<code>client.on('messageReactionAdd', async (reaction, user) => {
    if (reaction.emoji.name === "✅") {
      try {
        reaction.message.guild.members.find('id', user.id).addRole(reaction.message.guild.roles.find('name', 'Joueur'));
      } catch {
        console.log('Error : can\'t add the role');
      }
   }
});
</code>```

答:
If you are using latest version, here is an example:

They have also changed addRole to: roles.add in v12

```<code>let role = message.guild.roles.cache.find(role => role.name === 'somerolename');
reaction.message.guild.member(user).roles.add(role.id).catch(console.error);
</code>```

https://discordjs.guide/additional-info/changes-in-v12.html#roles

Body:
I am trying to make a Discord.js bot that add the "Joueur" role to the user who reacted with the ✅ emoji. I am new to JS and I found the reaction.message.guild.members.find function on the Internet but I somehow get the error TypeError: reaction.message.guild.members.find is not a function and the role is not added.
Here is the part of my code :

client.on('messageReactionAdd', async (reaction, user) => {
    if (reaction.emoji.name === "✅") {
      try {
        reaction.message.guild.members.find('id', user.id).addRole(reaction.message.guild.roles.find('name', 'Joueur'));
      } catch {
        console.log('Error : can\'t add the role');
      }
   }
});

Body:
If you are using latest version, here is an example:

They have also changed addRole to: roles.add in v12

let role = message.guild.roles.cache.find(role => role.name === 'somerolename');
reaction.message.guild.member(user).roles.add(role.id).catch(console.error);

https://discordjs.guide/additional-info/changes-in-v12.html#roles


问:
Optimizing MySQL "IN" Select?
I have the following MySQL query:

```<code>SELECT
    `influencers`.*,
    `locations`.`country_name`
FROM
    `influencers`
    LEFT JOIN `locations` ON `influencers`.`country_id` = `locations`.`id`
WHERE
    `is_dead` = 0
    AND `influencers`.`is_private` = 0
    AND `influencers`.`country_id` = '31'
    AND influencers.uuid IN(
        SELECT
            `influencer_uuid` FROM `category_influencer`
        WHERE
            `category_influencer`.`category_id` = 17
            AND `category_influencer`.`is_main` = 1)
ORDER BY
    `influencers`.`followed_by` DESC
LIMIT 7 OFFSET 6
</code>```

I have identified the IN subquery is causing a lag of around 10s for this query to complete. Here is the EXPLAIN:

I have indexes on all columns being queried.

How can I significantly speed this query up?

Updated with SHOW CREATE TABLE for both:

locations

```<code>CREATE TABLE `locations` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `country_name` varchar(255) DEFAULT NULL,
    `city_name` varchar(255) DEFAULT NULL,
    `type` varchar(255) DEFAULT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `unique_index` (`city_name`, `country_name`),
    KEY `type` (`type`)
    USING BTREE) ENGINE = InnoDB AUTO_INCREMENT = 6479 DEFAULT CHARSET = utf8mb4
</code>```

influencers

```<code>CREATE TABLE `influencers` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `bio` varchar(255) CHARACTER
    SET utf8mb4 DEFAULT NULL,
    `url` varchar(255) CHARACTER
    SET utf8mb4 DEFAULT NULL,
    `followed_by` int(11) DEFAULT NULL,
    `follows` int(11) DEFAULT NULL,
    `full_name` varchar(255) CHARACTER
    SET utf8mb4 NOT NULL,
    `social_id` varchar(255) DEFAULT NULL,
    `is_private` tinyint (1) DEFAULT NULL,
    `avatar` varchar(255) NOT NULL,
    `username` varchar(30) NOT NULL,
    `text_search` text CHARACTER
    SET utf8mb4 NOT NULL,
    `updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
    `uuid` varchar(255) DEFAULT NULL,
    `is_dead` tinyint (4) DEFAULT NULL,
    `country_id` int(11) DEFAULT NULL,
    `city_id` int(11) DEFAULT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `username` (`username`),
    UNIQUE KEY `uuid` (`uuid`),
    KEY `is_dead` (`is_dead`),
    KEY `updated_at` (`updated_at`),
    KEY `followed_by` (`followed_by`),
    KEY `social_id` (`social_id`),
    KEY `is_private` (`is_private`),
    KEY `country_id` (`country_id`),
    FULLTEXT KEY `text_search` (`text_search`)) ENGINE = InnoDB AUTO_INCREMENT = 2278376 DEFAULT CHARSET = utf8
</code>```

答:
You could avoid the in clause using an inner join  </p>

```<code>    SELECT
        `influencers`.*,
        `locations`.`country_name`
    FROM
        `influencers`
    INNER JOIN  (
        SELECT
                `influencer_uuid` FROM `category_influencer`
            WHERE
                `category_id` = 17
                AND `is_main` = 1

    ) T ON T.influencer_uuid = influencers.uuid
        LEFT JOIN `locations` ON `influencers`.`country_id` = `locations`.`id`
    WHERE
        `is_dead` = 0
        AND `is_private` = 0
        AND `country_id` = '31'

    ORDER BY
        `followed_by` DESC
    LIMIT 7 OFFSET 6
</code>```

<p>This way instead of an iteration on all the IN result you use just a single relational match  based  on join  </p>

Title: Optimizing MySQL "IN" Select?

Body:
I have the following MySQL query:

SELECT
    `influencers`.*,
    `locations`.`country_name`
FROM
    `influencers`
    LEFT JOIN `locations` ON `influencers`.`country_id` = `locations`.`id`
WHERE
    `is_dead` = 0
    AND `influencers`.`is_private` = 0
    AND `influencers`.`country_id` = '31'
    AND influencers.uuid IN(
        SELECT
            `influencer_uuid` FROM `category_influencer`
        WHERE
            `category_influencer`.`category_id` = 17
            AND `category_influencer`.`is_main` = 1)
ORDER BY
    `influencers`.`followed_by` DESC
LIMIT 7 OFFSET 6

I have identified the IN subquery is causing a lag of around 10s for this query to complete. Here is the EXPLAIN:

I have indexes on all columns being queried.

How can I significantly speed this query up?

Updated with SHOW CREATE TABLE for both:

locations

CREATE TABLE `locations` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `country_name` varchar(255) DEFAULT NULL,
    `city_name` varchar(255) DEFAULT NULL,
    `type` varchar(255) DEFAULT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `unique_index` (`city_name`, `country_name`),
    KEY `type` (`type`)
    USING BTREE) ENGINE = InnoDB AUTO_INCREMENT = 6479 DEFAULT CHARSET = utf8mb4

influencers

CREATE TABLE `influencers` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `bio` varchar(255) CHARACTER
    SET utf8mb4 DEFAULT NULL,
    `url` varchar(255) CHARACTER
    SET utf8mb4 DEFAULT NULL,
    `followed_by` int(11) DEFAULT NULL,
    `follows` int(11) DEFAULT NULL,
    `full_name` varchar(255) CHARACTER
    SET utf8mb4 NOT NULL,
    `social_id` varchar(255) DEFAULT NULL,
    `is_private` tinyint (1) DEFAULT NULL,
    `avatar` varchar(255) NOT NULL,
    `username` varchar(30) NOT NULL,
    `text_search` text CHARACTER
    SET utf8mb4 NOT NULL,
    `updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
    `uuid` varchar(255) DEFAULT NULL,
    `is_dead` tinyint (4) DEFAULT NULL,
    `country_id` int(11) DEFAULT NULL,
    `city_id` int(11) DEFAULT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `username` (`username`),
    UNIQUE KEY `uuid` (`uuid`),
    KEY `is_dead` (`is_dead`),
    KEY `updated_at` (`updated_at`),
    KEY `followed_by` (`followed_by`),
    KEY `social_id` (`social_id`),
    KEY `is_private` (`is_private`),
    KEY `country_id` (`country_id`),
    FULLTEXT KEY `text_search` (`text_search`)) ENGINE = InnoDB AUTO_INCREMENT = 2278376 DEFAULT CHARSET = utf8

Body:
You could avoid the in clause using an inner join

    SELECT
        `influencers`.*,
        `locations`.`country_name`
    FROM
        `influencers`
    INNER JOIN  (
        SELECT
                `influencer_uuid` FROM `category_influencer`
            WHERE
                `category_id` = 17
                AND `is_main` = 1

    ) T ON T.influencer_uuid = influencers.uuid
        LEFT JOIN `locations` ON `influencers`.`country_id` = `locations`.`id`
    WHERE
        `is_dead` = 0
        AND `is_private` = 0
        AND `country_id` = '31'

    ORDER BY
        `followed_by` DESC
    LIMIT 7 OFFSET 6

This way instead of an iteration on all the IN result you use just a single relational match  based  on join


问:
Socket in python is not connecting for some devices
I used python socket to connect to my other devices on a different network using port forwarding. It worked on some devices.

When I tried to connect with a device at a longer distance it shows a timeout error. Is it due to the long distance?

答:
It is probably not due to network latency.  Socket timeout is usually on the order of tens of seconds, whereas network latency is rarely more than a second.  It's more likely you can't reach the destination server.

Try ping  to see if you can reach the destination server and how long a round trip takes (last column).

```<code>% ping www.google.com
PING www.google.com (172.217.164.100): 56 data bytes
64 bytes from 172.217.164.100: icmp_seq=0 ttl=54 time=300.335 ms
64 bytes from 172.217.164.100: icmp_seq=1 ttl=54 time=334.197 ms
</code>```

If it really is taking too long, you can set your socket's timeout

```<code>import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# set timeout to 60 seconds
s.settimeout(60)
</code>```

Body:
It is probably not due to network latency.  Socket timeout is usually on the order of tens of seconds, whereas network latency is rarely more than a second.  It's more likely you can't reach the destination server.

Try ping  to see if you can reach the destination server and how long a round trip takes (last column).

% ping www.google.com
PING www.google.com (172.217.164.100): 56 data bytes
64 bytes from 172.217.164.100: icmp_seq=0 ttl=54 time=300.335 ms
64 bytes from 172.217.164.100: icmp_seq=1 ttl=54 time=334.197 ms

If it really is taking too long, you can set your socket's timeout

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# set timeout to 60 seconds
s.settimeout(60)


答: You should use strcmp() function for comparing strings.

Title: Don't have right output while comparing chars


问:
Has anyone figured out how to program the STWBC-MC module by STM?
The documents say that we can flash custom firmware on this module but it doesn't say how. I am unable to locate any build tool chain either. I tried raising a customer support ticket with STM and they don't seem to have any answers. Has anyone used this module in any of their products?</p>

答:
It is STM8 and you need IAR workbench for it. I believe that you need to sign NDA first, then (when accepted) you get more detailed documentation and libraries.

Contact you STM FAE for more details.


问:
Questions about boxing
I know that boxing is a popular concept with plenty of information available on it, but I have a few questions which I can't really find answers to:

1) If boxing leads to a value type (struct) being converted to an object (Reference type), or reference type, then why use a value type which will be boxed and incur a performance penalty? I am aware of the benefits and suitability in certain cases of either a struct or class. It is said (1) that values (value types) tend to live on the stack in a temporary storage space, but how long for? If I don't need the type, how can I ensure it is taken care of and disposed at that moment? Or is this where the disposable pattern comes into play? I assume the reason to use a struct will be due to its benefits.

Interestingly, if I use a struct to store two strings and a DateTime field, the struct will hold two references (strings) and the DateTime together. I obviously assume this is quicker than the values being scattered. Is there anything I need to be aware of in this design? (2).

1) http://en.csharp-online.net/Classes, Structs, and Objects—Boxing and Unboxing

2) http://dotnetperls.com/Content/Struct-Examples.aspx

I have done a search on here for the answers I am after, but no luck. I usually do searches on this site for topics such as GC, generics, exception handling, etc, as there is a lot of wisdom to learn and share.

Thanks for the (potential) education to all posters! Please excuse any potential naivety. Learning the internals takes me nicely to spending some time on understanding IL, etc (something to tackle, soon).

答: You should use value types because of their logical benefit, not the performance gains.  That being said, because value types are managed on the stack, do not need to participate in garbage collection.  If you have a type that is constantly created and discarded (like an int, float, double, etc), then you can get a good boost by turning these into structs.  The thing to be careful of is that you should only really consider this if you can also make the struct immutable.</p>

OwnerDisplayName: GSS

ContentLicense: CC BY-SA 2.5

Title: Questions about boxing

LastEditorDisplayName: jpalecek

OwnerDisplayName: Michael Meadows


问:
ajax not sending parameter to script
Trying to populate a datatable using ajax.  Passing the parameter as follows:

```<code>$('#submitDetails').on('click', function()
{
  let details = $('#searchDetails').val();

  $.ajax({
        url: 'api/searchDetailInfo.php',
        type: 'POST',
        data: details,
        dataType: 'html',
        success: function(data, textStatus, jqXHR){
          console.log(data); // <-- printing the return from the php script
          let jsonObject = JSON.parse(data);
          var table = $('#example1').DataTable({
                "data": jsonObject,
                "columns": [
                        { "data": "COLUMN1" },
                        { "data": "COLUMN2" },
                        { "data": "COLUMN3" }
                ],
                "iDisplayLength": 50,
                "order": [[ 1, "desc" ]],
                "paging": true,
                "scrollY": 550,
                "scrollX": true,
                "bDestroy": true,
                "stateSave": true,
                "sPaginationType":"full_numbers",
                "autoWidth": true
        },
        error: function(jqHHR, textStatus, errorThrown) {
            $('#loadingDiv').hide();
            $('#errorModal').modal('show');
            $('.message').text('There was an error conducting your search.');
            console.log('fail: '+ errorThrown);
            return false;
        }
});
</code>```

I am getting to the PHP script, but the script is not receiving the parameter.

```<code><?php
  include("../include/database.php");

  if(isset($_POST['details']))
  {
    echo "good";
  }
  else
  {
    echo "bad";
  }
?>
</code>```

I'm only getting "bad" in the console.  I am not sure why the parameter is not being sent to the script.

How can I fix this?

答: You need to change data: details, to data: {details:details}, giving the post variable an identifier, making $_POST['details'] valid.

Title: ajax not sending parameter to script

Body:
Trying to populate a datatable using ajax.  Passing the parameter as follows:

$('#submitDetails').on('click', function()
{
  let details = $('#searchDetails').val();

  $.ajax({
        url: 'api/searchDetailInfo.php',
        type: 'POST',
        data: details,
        dataType: 'html',
        success: function(data, textStatus, jqXHR){
          console.log(data); // <-- printing the return from the php script
          let jsonObject = JSON.parse(data);
          var table = $('#example1').DataTable({
                "data": jsonObject,
                "columns": [
                        { "data": "COLUMN1" },
                        { "data": "COLUMN2" },
                        { "data": "COLUMN3" }
                ],
                "iDisplayLength": 50,
                "order": [[ 1, "desc" ]],
                "paging": true,
                "scrollY": 550,
                "scrollX": true,
                "bDestroy": true,
                "stateSave": true,
                "sPaginationType":"full_numbers",
                "autoWidth": true
        },
        error: function(jqHHR, textStatus, errorThrown) {
            $('#loadingDiv').hide();
            $('#errorModal').modal('show');
            $('.message').text('There was an error conducting your search.');
            console.log('fail: '+ errorThrown);
            return false;
        }
});

I am getting to the PHP script, but the script is not receiving the parameter.

<?php
  include("../include/database.php");

  if(isset($_POST['details']))
  {
    echo "good";
  }
  else
  {
    echo "bad";
  }
?>

I'm only getting "bad" in the console.  I am not sure why the parameter is not being sent to the script.

How can I fix this?


问:
How to check build variant inside the module's build.gradle
I have the following modules in my project:

```<code>MyProject
 - app  // the usual module that contains the java codes
 - theLibraryModule  // this is the module in question
   - theLibraryDebug.aar
   - theLibraryRelease.aar
   - build.gradle
</code>```

The theLibraryModule's build.gradle is below:

```<code>configurations.maybeCreate("default")
artifacts.add("default", file('theLibraryDebug.aar'))
</code>```

Is there a way to check the build variant (debug/release) I am using and load the proper AAR in my theLibraryModule module?

答:
I gave up. I used the good old technique by moving the AAR files to app/libs folder. I deleted my theLibraryModule module, then added the following in my app's build.gradle file:

```<code>dependencies {
    debugImplementation files('libs/theLibraryDebug.aar')
    releaseImplementation files('libs/theLibraryDebug.aar')
}
</code>```

Body:
I have the following modules in my project:

MyProject
 - app  // the usual module that contains the java codes
 - theLibraryModule  // this is the module in question
   - theLibraryDebug.aar
   - theLibraryRelease.aar
   - build.gradle

The theLibraryModule's build.gradle is below:

configurations.maybeCreate("default")
artifacts.add("default", file('theLibraryDebug.aar'))

Is there a way to check the build variant (debug/release) I am using and load the proper AAR in my theLibraryModule module?

Body:
I gave up. I used the good old technique by moving the AAR files to app/libs folder. I deleted my theLibraryModule module, then added the following in my app's build.gradle file:

dependencies {
    debugImplementation files('libs/theLibraryDebug.aar')
    releaseImplementation files('libs/theLibraryDebug.aar')
}


问:
Python: using regex and while loop to break out paragraphs in a PDF
I have a pdf file that has 82 paragraphs, my goal is to use python to break each paragraph into its own block of text. I have already extracted the text using PyPDF2.

The paragraphs all begin with a number and a period (1. 42. 76. etc.). It is working for most of the paragraphs with the code below, but it doesn't always take the period into account. For example, number 18's match output is: "18 (06/". This shouldn't have gotten picked up though because there isn't a period after it. Any suggestions?

Code for finding positions:

```<code>i = 1
all_positions = []
found = "found"

while found == "found":
    matches = []
    matches_positions =[]
    standard_length = 0
    substring = str(i) + "."
    matches = re.finditer(substring, text, re.IGNORECASE)
    matches_positions = [match.start() for match in matches]
    standard_length = len(matches_positions)
    if standard_length > 0:
        all_positions.append(matches_positions[0])
        i += 1
    else:
        found = "not found"
</code>```

Code for printing output:

```<code>for i in range(0,len(all_positions)):
     print('---')
     print(text[all_positions[i]:all_positions[i+1]])
</code>```

答:
You can use the below regex to achieve your result:

```<code>^\d+\. ?(.*)
</code>```

Explanation of the above regex:

^ - Represents the start of the given test String.

\d+ - Matches digits[0-9] one or more times.

\. - Matches dot literally.

 ? - Represents zero or one space character.

(.*) - Represents capturing group capturing the paragraph text greedily.

You can find the regex demo here.

IMPLEMENTATION IN PYTHON:

```<code>import re
pattern = re.compile(r"^\d+\. ?(.*)", re.MULTILINE)
match = pattern.findall("1. Hellow World\n"
    "23. This is loremIpsum text\n"
    "9001. Some random textbcjsbcskcbksck sbcksbcksckscsk\n"
    "90 (89. Some other")
print (match)
# Output - ['Hellow World', 'This is loremIpsum text', 'Some random textbcjsbcskcbksck sbcksbcksckscsk']
</code>```

You can find the implementation of the above code here.

Body:
I have a pdf file that has 82 paragraphs, my goal is to use python to break each paragraph into its own block of text. I have already extracted the text using PyPDF2.

The paragraphs all begin with a number and a period (1. 42. 76. etc.). It is working for most of the paragraphs with the code below, but it doesn't always take the period into account. For example, number 18's match output is: "18 (06/". This shouldn't have gotten picked up though because there isn't a period after it. Any suggestions?

Code for finding positions:

i = 1
all_positions = []
found = "found"

while found == "found":
    matches = []
    matches_positions =[]
    standard_length = 0
    substring = str(i) + "."
    matches = re.finditer(substring, text, re.IGNORECASE)
    matches_positions = [match.start() for match in matches]
    standard_length = len(matches_positions)
    if standard_length > 0:
        all_positions.append(matches_positions[0])
        i += 1
    else:
        found = "not found"

Code for printing output:

for i in range(0,len(all_positions)):
     print('---')
     print(text[all_positions[i]:all_positions[i+1]])

Body:
You can use the below regex to achieve your result:

^\d+\. ?(.*)

Explanation of the above regex:

^ - Represents the start of the given test String.

\d+ - Matches digits[0-9] one or more times.

\. - Matches dot literally.

 ? - Represents zero or one space character.

(.*) - Represents capturing group capturing the paragraph text greedily.

You can find the regex demo here.

IMPLEMENTATION IN PYTHON:

import re
pattern = re.compile(r"^\d+\. ?(.*)", re.MULTILINE)
match = pattern.findall("1. Hellow World\n"
    "23. This is loremIpsum text\n"
    "9001. Some random textbcjsbcskcbksck sbcksbcksckscsk\n"
    "90 (89. Some other")
print (match)
# Output - ['Hellow World', 'This is loremIpsum text', 'Some random textbcjsbcskcbksck sbcksbcksckscsk']

You can find the implementation of the above code here.


问:
TiddlyWiki5 and highlight.js - How to change style / theme of syntax highlighting?
I am using TiddlyWiki version 5.1.13. I have added the highlight plugin (version 5.1.13) which uses highlight.js (version 8.8.0).

In a tiddler I successfully highlight XML like this:

```<code>```xml

```
</code>```

How can I change the highlight style / theme to one of highlight.js various styles? (Highlight.js styles)

答:
Here is the URL to the styles directory in the
highlight.js repo.

I found it useful to locate the name of the Vs 2015 theme which isn't vs-2015 but rather vs2015.

I'm importing the styles from a CDN:

```<code><link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/10.0.3/styles/default.min.css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/10.0.3/styles/vs2015.min.css">
</code>```

Also, for the record, Vs 2015 is very similar to VS Code's Dark+ (default dark) theme. That's the default theme that ships with VS Code.

Body:
I am using TiddlyWiki version 5.1.13. I have added the highlight plugin (version 5.1.13) which uses highlight.js (version 8.8.0).

In a tiddler I successfully highlight XML like this:

```xml
  <html>
    <body>
    </body>
  </html>
```

How can I change the highlight style / theme to one of highlight.js various styles? (Highlight.js styles)

Body:
Here is the URL to the styles directory in the
highlight.js repo.

I found it useful to locate the name of the Vs 2015 theme which isn't vs-2015 but rather vs2015.

I'm importing the styles from a CDN:

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/10.0.3/styles/default.min.css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/10.0.3/styles/vs2015.min.css">

Also, for the record, Vs 2015 is very similar to VS Code's Dark+ (default dark) theme. That's the default theme that ships with VS Code.


问:
Using antd Select props for TreeSelect
I was using antd TreeSelect, which has similar look as Select.

Now my question is the TreeSelect doesn't have tagRender props documented, however the Select has it.

Now I have used tagRender on TreeSelect anyway and it seems to work.
My question is: is this safe? can this behavior change if I don't update major version of antd?
It seems tree select is based on select anyway.

答:
In general almost all AntD components have more options available than they document in the component page on https://ant.design/components.

A lot of the components are just CSS skins on top of the corresponding https://github.com/react-component, and quite often it is worthwhile to read the github docs for the underlying rc-component since they usually are more complete, and using the props available on those components is supported by AntD.

For TreeSelect you are correct that it is based on Select, and in this case specifically https://github.com/react-component/select/blob/master/src/generate.tsx for tagRender, so you should be fine using that.

Title: Using antd Select props for TreeSelect


问:
code::blocks creates a .dat file but it's empty
I've been writing a code of random walk in c language. The program compiles perfectly and I can see the results in the code::blocks console. But I need to create a file .dat for import its data and make a plot of "iterations number vs the mean of the square displacement" in qtgrace.

The problem is that code::blocks creates the .dat file but it's empty. I don't know why this is happening.

This is my code:

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

FILE *fp;

int c,i;//c is the number of walkers and i is the iterations number
double x,r; //x is the displacement and r is a random number
double s[2000]; //array for the displacement squared
int n[10]; //array for the number of walkers

double main(){
fp=fopen("caminata.dat","w");

    printf("Write the iterations number i=");
    scanf("%d",&i);
    printf("Write the number of walkers c=");
    scanf("%d",&c);

    n[10]=0;
    s[2000]=0;

    for (int j=0; j<c; j++){

        //srand((long)time((time_t *)(NULL)));
        x=0.;

        for(int k=0; k<i; k++){

            r=rand()/(double)RAND_MAX;

            if(r<=0.5){

                x=x+1;

            }

            if(r>0.5){

                x=x-1;

            }

        s[k]=s[k]+x*x;//
        }

        }

    for (int k=0; k<i; k++){//mean of the square displacement
            s[k]=s[k]/c; //divided by the number of walkers
            printf("\n%d    %lf",k,s[k]);
            fprintf(fp, "\n%d    %lf",k,s[k]);
        }
        fclose(fp);
    }

</code>```

This is  the plot I must obtain

Random_Walk: iterations number vs the mean of the square displacement

答:
I see 2 times k<i in for loops but I don't see i being defined.
There is 1 chance out of 2 that value is defined to a negative value, in which case it makes sense your file is empty.

Body:
I've been writing a code of random walk in c language. The program compiles perfectly and I can see the results in the code::blocks console. But I need to create a file .dat for import its data and make a plot of "iterations number vs the mean of the square displacement" in qtgrace.

The problem is that code::blocks creates the .dat file but it's empty. I don't know why this is happening.

This is my code:

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

FILE *fp;

int c,i;//c is the number of walkers and i is the iterations number
double x,r; //x is the displacement and r is a random number
double s[2000]; //array for the displacement squared
int n[10]; //array for the number of walkers

double main(){
fp=fopen("caminata.dat","w");

    printf("Write the iterations number i=");
    scanf("%d",&i);
    printf("Write the number of walkers c=");
    scanf("%d",&c);

    n[10]=0;
    s[2000]=0;

    for (int j=0; j<c; j++){

        //srand((long)time((time_t *)(NULL)));
        x=0.;

        for(int k=0; k<i; k++){

            r=rand()/(double)RAND_MAX;

            if(r<=0.5){

                x=x+1;

            }

            if(r>0.5){

                x=x-1;

            }

        s[k]=s[k]+x*x;//
        }

        }

    for (int k=0; k<i; k++){//mean of the square displacement
            s[k]=s[k]/c; //divided by the number of walkers
            printf("\n%d    %lf",k,s[k]);
            fprintf(fp, "\n%d    %lf",k,s[k]);
        }
        fclose(fp);
    }

This is  the plot I must obtain

Random_Walk: iterations number vs the mean of the square displacement


答:
First remove testthat,crayon,Rcurl and swirl
the versions you require of each should be testthat version .11 , Rcurl 1.95-4.7 and swirl 2.4.0
make sure you have these and it will work for sure</p>

Title: Error Running coomand swirl() for Swirl2.4.0 on Rstudio 3.3.3 on MAC 10.9.5

Body:
> swirl()
Error in match.arg(type, c("success", "failure", "error", "skip", "warning")) :
  'arg' must be NULL or a character vector

| Leaving swirl now. Type swirl() to resume.

> devtools::session_info()
─ Session info ───────────────────────────────────────
 setting  value
 version  R version 3.3.3 (2017-03-06)
 os       OS X Mavericks 10.9.5
 system   x86_64, darwin13.4.0
 ui       RStudio
 language (EN)
 collate  en_US.UTF-8
 ctype    en_US.UTF-8
 tz       Asia/Kolkata
 date     2020-05-26

─ Packages ───────────────────────────────────────────
 package     * version  date       lib source
 assertthat    0.2.1    2019-03-21 [1] CRAN (R 3.3.3)
 backports     1.1.7    2020-05-13 [1] CRAN (R 3.3.3)
 bitops        1.0-6    2013-08-17 [1] CRAN (R 3.3.0)
 callr         3.4.3    2020-03-28 [1] CRAN (R 3.3.3)
 cli           2.0.2    2020-02-28 [1] CRAN (R 3.3.3)
 crayon        1.3.4    2017-09-16 [1] CRAN (R 3.3.2)
 curl          4.3      2019-12-02 [1] CRAN (R 3.3.3)
 desc          1.2.0    2018-05-01 [1] CRAN (R 3.3.3)
 devtools      2.3.0    2020-04-10 [1] CRAN (R 3.3.3)
 digest        0.6.25   2020-02-23 [1] CRAN (R 3.3.3)
 ellipsis      0.3.1    2020-05-15 [1] CRAN (R 3.3.3)
 fansi         0.4.1    2020-01-08 [1] CRAN (R 3.3.3)
 fs            1.4.1    2020-04-04 [1] CRAN (R 3.3.3)
 glue          1.4.1    2020-05-13 [1] CRAN (R 3.3.3)
 httr          1.4.1    2019-08-05 [1] CRAN (R 3.3.3)
 magrittr      1.5      2014-11-22 [1] CRAN (R 3.3.0)
 memoise       1.1.0    2017-04-21 [1] CRAN (R 3.3.2)
 pkgbuild      1.0.8    2020-05-07 [1] CRAN (R 3.3.3)
 pkgload       1.0.2    2018-10-29 [1] CRAN (R 3.3.3)
 prettyunits   1.1.1    2020-01-24 [1] CRAN (R 3.3.3)
 processx      3.4.2    2020-02-09 [1] CRAN (R 3.3.3)
 ps            1.3.3    2020-05-08 [1] CRAN (R 3.3.3)
 R6            2.4.1    2019-11-12 [1] CRAN (R 3.3.3)
 RCurl         1.95-4.9 2017-12-27 [1] CRAN (R 3.3.3)
 remotes       2.1.1    2020-02-15 [1] CRAN (R 3.3.3)
 rlang         0.4.6    2020-05-02 [1] CRAN (R 3.3.3)
 rprojroot     1.3-2    2018-01-03 [1] CRAN (R 3.3.2)
 rstudioapi    0.11     2020-02-07 [1] CRAN (R 3.3.3)
 sessioninfo   1.1.1    2018-11-05 [1] CRAN (R 3.3.3)
 stringi       1.4.6    2020-02-17 [1] CRAN (R 3.3.3)
 stringr       1.4.0    2019-02-10 [1] CRAN (R 3.3.3)
 swirl       * 2.4.0    2016-03-25 [1] CRAN (R 3.3.3)
 testthat      2.3.2    2020-03-02 [1] CRAN (R 3.3.3)
 usethis       1.6.1    2020-04-29 [1] CRAN (R 3.3.3)
 withr         2.2.0    2020-04-20 [1] CRAN (R 3.3.3)
 yaml          2.2.1    2020-02-01 [1] CRAN (R 3.3.3)

I Do not know what the error I have referred to previous queries here and on Github. I have updated remotes and testthat (recommended solutions) but none of the following has worked.


问:
req.session is undefined using express-session
I am just starting to learn how to use cookies with node and express and I would like some help with getting this to work. I tried to follow the expressjs/session tutorial on GitHub, however I am getting req.session as undefined, so I am unable to set or get any values.

My goal is to save the first and last name of a user to a cookie so that an input field will auto populate. I'm not sure if I need to use cookie-parser as well or if express-session can handle that alone. I'm not sure of how to proceed as I am new to cookies and express-session.

All help is appreciated! Thanks in advance.

Code

```<code>let express = require('express');
let app = express();
let credentials = require('../modules/credentials.js');
let session = require('express-session');
let sessionOptions = {
  secret: credentials.cookieSecret,
  cookie: {
    maxAge:269999999999
  },
  saveUninitialized: true,
  resave:true
};

if (app.get('env') === 'production') {
  app.set('trust proxy', 1);
  sessionOptions.cookie.secure = true;
}
else {
  sessionOptions.cookie.secure = false;
}

app.use(session(sessionOptions));
let router = express.Router();
app.use(router);

let request = require('request');
let db = require('../modules/queries');
let bodyParser = require('body-parser');
let cookieParser = require('cookie-parser');

// app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

router.get('/me', function(req, res, next) {
  console.log('req.session: '+req.session);

  let firstName = req.session.firstName;
  let lastName = req.session.lastName;
  if (firstName && lastName) {
    res.render('student/me.jade', {firstName, lastName});
  }
  else {
    res.render('student/me.jade', { firstName: '', lastName: ''});
  }
});

router.post('/api/me', function(req, res, next) {
  let firstName = req.body.firstName;
  let lastName = req.body.lastName;
  // session.firstName = firstName;
  // session.lastName = lastName;
  req.session.firstName = firstName;
  req.session.lastName = lastName;
  console.log('session.firstName: '+session.firstName);
  db.addEvent(req, res, next);
});

module.exports = router;
</code>```

答:
This problem occurred with me while trying to maintain req.session object in my app. I was setting req.session.user in a login route, but was not able to get the same outside that route.

```<code>console.log(req.session)
// undefined
</code>```

Since there was no use of cookie in my app, I removed it.

Before removing cookie variable:

```<code>app.use(
session({
    resave: false,
    saveUninitialized: true,
    secret: "anyrandomstring",
    cookie: { secure: true},
  })
);
</code>```

After removing cookie variable:

```<code>app.use(
session({
    resave: false,
    saveUninitialized: true,
    secret: "anyrandomstring",
  })
);
</code>```

This resolved my issue. And now I was able to access req.session from anywhere in the app.

```<code>console.log(req.session)
/* Session{
     ......
     ......
    }
*/
</code>```

Note: This issue might also occurs if you have initialized app.use(session({...})) at bottom of the file. Try to bring it to the top.

Why this happens: Click here

Body:
I am just starting to learn how to use cookies with node and express and I would like some help with getting this to work. I tried to follow the expressjs/session tutorial on GitHub, however I am getting req.session as undefined, so I am unable to set or get any values.

My goal is to save the first and last name of a user to a cookie so that an input field will auto populate. I'm not sure if I need to use cookie-parser as well or if express-session can handle that alone. I'm not sure of how to proceed as I am new to cookies and express-session.

All help is appreciated! Thanks in advance.

Code

let express = require('express');
let app = express();
let credentials = require('../modules/credentials.js');
let session = require('express-session');
let sessionOptions = {
  secret: credentials.cookieSecret,
  cookie: {
    maxAge:269999999999
  },
  saveUninitialized: true,
  resave:true
};

if (app.get('env') === 'production') {
  app.set('trust proxy', 1);
  sessionOptions.cookie.secure = true;
}
else {
  sessionOptions.cookie.secure = false;
}

app.use(session(sessionOptions));
let router = express.Router();
app.use(router);

let request = require('request');
let db = require('../modules/queries');
let bodyParser = require('body-parser');
let cookieParser = require('cookie-parser');

// app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

router.get('/me', function(req, res, next) {
  console.log('req.session: '+req.session);

  let firstName = req.session.firstName;
  let lastName = req.session.lastName;
  if (firstName && lastName) {
    res.render('student/me.jade', {firstName, lastName});
  }
  else {
    res.render('student/me.jade', { firstName: '', lastName: ''});
  }
});

router.post('/api/me', function(req, res, next) {
  let firstName = req.body.firstName;
  let lastName = req.body.lastName;
  // session.firstName = firstName;
  // session.lastName = lastName;
  req.session.firstName = firstName;
  req.session.lastName = lastName;
  console.log('session.firstName: '+session.firstName);
  db.addEvent(req, res, next);
});

module.exports = router;

Body:
This problem occurred with me while trying to maintain req.session object in my app. I was setting req.session.user in a login route, but was not able to get the same outside that route.

console.log(req.session)
// undefined

Since there was no use of cookie in my app, I removed it.

Before removing cookie variable:

app.use(
session({
    resave: false,
    saveUninitialized: true,
    secret: "anyrandomstring",
    cookie: { secure: true},
  })
);

After removing cookie variable:

app.use(
session({
    resave: false,
    saveUninitialized: true,
    secret: "anyrandomstring",
  })
);

This resolved my issue. And now I was able to access req.session from anywhere in the app.

console.log(req.session)
/* Session{
     ......
     ......
    }
*/

Note: This issue might also occurs if you have initialized app.use(session({...})) at bottom of the file. Try to bring it to the top.

Why this happens: Click here


问:
Android App context null in Activity.onCreate()
This code in Activity

```<code>public void onCreate(Bundle bundle)
{
    super.onCreate(bundle);
    DisplayMetrics metrics = App.getAppContext().getResources().getDisplayMetrics(); //crash
}
</code>```

sometimes produces a NullPointerException.

This is the custom App class:

```<code>public class App extends Application
{
    private static Context context;

    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
    }

    public static Context getAppContext()
    {
        return context;
    }
}
</code>```

How can the NullPointerException be fixed?

答:
You don't need App.getAppContext()

just

```<code> DisplayMetrics metrics = getResources().getDisplayMetrics();
</code>```

or

```<code>DisplayMetrics metrics = this.getResources().getDisplayMetrics();
</code>```

or

```<code>DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
</code>```

Body:
This code in Activity

public void onCreate(Bundle bundle)
{
    super.onCreate(bundle);
    DisplayMetrics metrics = App.getAppContext().getResources().getDisplayMetrics(); //crash
}

sometimes produces a NullPointerException.

This is the custom App class:

public class App extends Application
{
    private static Context context;

    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
    }

    public static Context getAppContext()
    {
        return context;
    }
}

How can the NullPointerException be fixed?

Body:
You don't need App.getAppContext()

just

 DisplayMetrics metrics = getResources().getDisplayMetrics();

or

DisplayMetrics metrics = this.getResources().getDisplayMetrics();

or

DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();


问:
How can i configure the macOS firewall to access my docker nginx container?
MacOS firewall is preventing me from accessing my docker nginx container

I can use my domain name to get to non-docker nginx running on my laptop.

I cannot use my domain name to get to docker nginx running on my laptop unless I disable the macOS firewall.

docker nginx is running on port 80

docker nginx is accessible with curl localhost

When I turn off my macOS firewall I can access my docker nginx.

How can i configure the macOS firewall to access my docker nginx container?

答:
macOS is failing to recognize the connection attempts to ask if it should allow them.

We added app: bundleid = com.ht.kubecontext to allow in the firewall config on macOS and magically connections worked. Not sure if this is a bug in docker.app not including kube connections to its context when enabled or a macOS sensing failure, but this unblocked us on the issue.


问:
Pyspark read csv with schema, header check, and store corrupt records
I'm trying to use pyspark csv reader with the following criteria:

Read csv according to datatypes in schema

Check that column names in header and schema matches

Store broken records in a new field

Here is what I have tried.

```<code>file: ab.csv
------
a,b
1,2
3,four
</code>```
```<code>from pyspark.sql import SparkSession

spark = SparkSession.builder.getOrCreate()
DDL = "a INTEGER, b INTEGER"
df = spark.read.csv('ab.csv', header=True, schema=DDL, enforceSchema=False,
                    columnNameOfCorruptRecord='broken')
print(df.show())
</code>```

Output:

```<code>+----+----+
|   a|   b|
+----+----+
|   1|   2|
|null|null|
+----+----+
</code>```

This command does not store the corrupted records. If I add broken to
the schema and remove header validation the command
works with a warning.

```<code>DDL = "a INTEGER, b INTEGER, broken STRING"
df = spark.read.csv('ab.csv', header=True, schema=DDL, enforceSchema=True,
                    columnNameOfCorruptRecord='broken')
print(df.show())
</code>```

Output:

```<code>WARN  CSVDataSource:66 - Number of column in CSV header is not equal to number of fields in the schema:
 Header length: 2, schema size: 3
CSV file: file:/// ... /ab.csv
+----+----+------+
|   a|   b|broken|
+----+----+------+
|   1|   2|  null|
|null|null|3,four|
+----+----+------+
</code>```

Is this intended behavior or is there a bug that breaks the first example?
Is there a better way to do this?

One more thing. I want to process well-formed fields in corrupted records
to get a dataframe like this.

```<code>+--+----+------+
| a|   b|broken|
+--+----+------+
| 1|   2|  null|
| 3|null|3,four|
+--+----+------+
</code>```

Should I make an extra step post reading to get that, or is there some
option I have missed to be more permissive.

答:
Like @deo said, when using columnNameOfCorruptRecord, Spark will implicitly create the column before dropping it during parsing. In order to keep the column, you need to explicitly add it to your schema. Note that this behavior also depends on what mode you specify when reading.

See this snippet  for the mode param in the Spark documentation:

PERMISSIVE : when it meets a corrupted record, puts the malformed string into a field configured by columnNameOfCorruptRecord, and sets other fields to null. To keep corrupt records, an user can set a string type field named columnNameOfCorruptRecord in an user-defined schema. If a schema does not have the field, it drops corrupt records during parsing. A record with less/more tokens than schema is not a corrupted record to CSV. When it meets a record having fewer tokens than the length of the schema, sets null to extra fields. When the record has more tokens than the length of the schema, it drops extra tokens.

Body:
I'm trying to use pyspark csv reader with the following criteria:

Read csv according to datatypes in schema

Check that column names in header and schema matches

Store broken records in a new field

Here is what I have tried.

file: ab.csv
------
a,b
1,2
3,four

from pyspark.sql import SparkSession

spark = SparkSession.builder.getOrCreate()
DDL = "a INTEGER, b INTEGER"
df = spark.read.csv('ab.csv', header=True, schema=DDL, enforceSchema=False,
                    columnNameOfCorruptRecord='broken')
print(df.show())

Output:

+----+----+
|   a|   b|
+----+----+
|   1|   2|
|null|null|
+----+----+

This command does not store the corrupted records. If I add broken to
the schema and remove header validation the command
works with a warning.

DDL = "a INTEGER, b INTEGER, broken STRING"
df = spark.read.csv('ab.csv', header=True, schema=DDL, enforceSchema=True,
                    columnNameOfCorruptRecord='broken')
print(df.show())

Output:

WARN  CSVDataSource:66 - Number of column in CSV header is not equal to number of fields in the schema:
 Header length: 2, schema size: 3
CSV file: file:/// ... /ab.csv
+----+----+------+
|   a|   b|broken|
+----+----+------+
|   1|   2|  null|
|null|null|3,four|
+----+----+------+

Is this intended behavior or is there a bug that breaks the first example?
Is there a better way to do this?

One more thing. I want to process well-formed fields in corrupted records
to get a dataframe like this.

+--+----+------+
| a|   b|broken|
+--+----+------+
| 1|   2|  null|
| 3|null|3,four|
+--+----+------+

Should I make an extra step post reading to get that, or is there some
option I have missed to be more permissive.


问:
How to specify the filter condition with spark DataFrameReader API for a table?
I was reading about spark on databricks documentation https://docs.databricks.com/data/tables.html#partition-pruning-1

It says

When the table is scanned, Spark pushes down the filter predicates
  involving the partitionBy keys. In that case, Spark avoids reading
  data that doesn’t satisfy those predicates. For example, suppose you
  have a table  that is partitioned by <date>. A query
  such as SELECT max(id) FROM <example-data> WHERE date = '2010-10-10'
  reads only the data files containing tuples whose date value matches
  the one specified in the query.

How can I specify such filter condition in DataFrameReader API while reading a table?

答:
As spark is lazily evaluated when your read the data using dataframe reader it is just added as a stage in the underlying DAG.

Now when you run SQL query over the data it is also added as another stage in the DAG.

And when you apply any action over the dataframe, then the  DAG is evaluated and all the stages are optimized by catalyst optimized which in the end generated the most cost effective physical plan.

At the time of DAG evaluation predicate conditions are pushed down and only the required data is read into the memory.