问:
cpan problems with 02packages.details.txt.gz
I'm getting complaints about 02packages.details.txt.gz when I'm trying to install a package with cpan. The error is "Warning: Your /root/.cpan/sources/modules/02packages.details.txt.gz does not contain a Line-Count header.
"

Apparently, according to cpan, this is not a valid zip file, which it isn't. It's just a web page which I'll paste later. I do not use a proxy and I had five mirrors in my configuration. I've deleted one then the next off the list and I'm still getting the same data back. I have deleted the file and attempted to allow cpan to fetch it again. I have fetched the page with curl and I'm seeing a web page and not anything that looks like a gz file.

I have tried "install cpan" from the cpan command line in case I missed an update but that runs into the exact same problem.

Example fetch:

```<code>curl http://noodle.portalus.net/CPAN/modules/02packages.details.txt.gz
</code>```

Result (parts obsfucated)

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
function getCookie(c_name) { // Local function for getting a cookie value
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start!=-1) {
        c_start=c_start + c_name.length + 1;
        c_end=document.cookie.indexOf(";", c_start);

        if (c_end==-1)
            c_end = document.cookie.length;

        return unescape(document.cookie.substring(c_start,c_end));
        }
    }
    return "";
}
function setCookie(c_name, value, expiredays) { // Local function for setting a value of a cookie
    var exdate = new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie = c_name + "=" + escape(value) + ((expiredays==null) ? "" : ";expires=" + exdate.toGMTString()) + ";path=/";
}
function getHostUri() {
    var loc = document.location;
    return loc.toString();
}
setCookie('XXXXXXXXXXXXXXXXXXXXiw_9289NNNNNNNNJAX666', 'MY.IP.ADDRESS.HERE', 10);
try {
    location.reload(true);
} catch (err1) {
    try {
        location.reload();
    } catch (err2) {
        location.href = getHostUri();
    }
}
</script>
</head>
<body>
<noscript>This site requires JavaScript and Cookies to be enabled. Please change your browser settings or upgrade your browser.</noscript>
</body>
</html>
</code>```

Note that this is the same as the contents as fetched by cpan.

答:
CPAN stands for Comprehensive Perl Archive Network. The network once consisted of a slew of mirrors, but this has been replaced with a transparent Content Delivery Network (CDN).

The once-valuable service offered by the mirrors is therefore no longer needed, so many sites have ceased mirroring CPAN. It appears to be the case for the mirror your cpan is configured to use.

A simple configuration change is needed to fix the issue. From within the cpan tool, use either

o conf init urllist
```
<p>or</p>
<pre class="lang-none prettyprint-override"><code>o conf urllist http://www.cpan.org/
</code>```

The first picks a mirror from the "official" list. There is only one URL in the list: http://www.cpan.org/. The second picks that URL directly.

To save the changes, follow up with

o conf commit
```
<p>(This may not be necessary for everyone, but there's no harm in always using it.)</p>
<hr />
<p>Example:</p>
<pre class="lang-none prettyprint-override"><code>C:\Users\ikegami>cpan
Loading internal logger. Log::Log4perl recommended for better logging
Unable to get Terminal Size. The Win32 GetConsoleScreenBufferInfo call didn't work. The COLUMNS and LINES environment variables didn't work. at C:\progs\sp5032001001\perl\vendor\lib/Term/ReadLine/readline.pm line 410.

cpan shell -- CPAN exploration and modules installation (v2.28)
Enter 'h' for help.

cpan> o conf init urllist

Now you need to choose your CPAN mirror sites.  You can let me
pick mirrors for you, you can select them from a list or you
can enter them by hand.

Would you like me to automatically choose some CPAN mirror
sites for you? (This means connecting to the Internet) [yes] y

Trying to fetch a mirror list from the Internet
Fetching with LWP:
init/MIRRORED.BY
Fetching with LWP:
init/MIRRORED.BY.gz
Fetching with LWP:
http://www.perl.org/CPAN/MIRRORED.BY

Looking for CPAN mirrors near you (please be patient)
.. done!

New urllist
  http://www.cpan.org/

commit: wrote 'C:\progs\sp5032001001\perl\lib/CPAN/Config.pm'

cpan> quit
Lockfile removed.

C:\Users\ikegami>
</code>```

commit: wrote indicates the changes were saved, so I didn't need to use o conf commit.

Body:
I'm getting complaints about 02packages.details.txt.gz when I'm trying to install a package with cpan. The error is "Warning: Your /root/.cpan/sources/modules/02packages.details.txt.gz does not contain a Line-Count header.
"

Apparently, according to cpan, this is not a valid zip file, which it isn't. It's just a web page which I'll paste later. I do not use a proxy and I had five mirrors in my configuration. I've deleted one then the next off the list and I'm still getting the same data back. I have deleted the file and attempted to allow cpan to fetch it again. I have fetched the page with curl and I'm seeing a web page and not anything that looks like a gz file.

I have tried "install cpan" from the cpan command line in case I missed an update but that runs into the exact same problem.

Example fetch:

curl http://noodle.portalus.net/CPAN/modules/02packages.details.txt.gz

Result (parts obsfucated)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Script-Type" content="text/javascript">

This site requires JavaScript and Cookies to be enabled. Please change your browser settings or upgrade your browser.

Note that this is the same as the contents as fetched by cpan.

Body:
CPAN stands for Comprehensive Perl Archive Network. The network once consisted of a slew of mirrors, but this has been replaced with a transparent Content Delivery Network (CDN).

The once-valuable service offered by the mirrors is therefore no longer needed, so many sites have ceased mirroring CPAN. It appears to be the case for the mirror your cpan is configured to use.

A simple configuration change is needed to fix the issue. From within the cpan tool, use either

o conf init urllist

or

o conf urllist http://www.cpan.org/

The first picks a mirror from the "official" list. There is only one URL in the list: http://www.cpan.org/. The second picks that URL directly.

To save the changes, follow up with

o conf commit

(This may not be necessary for everyone, but there's no harm in always using it.)

Example:

C:\Users\ikegami>cpan
Loading internal logger. Log::Log4perl recommended for better logging
Unable to get Terminal Size. The Win32 GetConsoleScreenBufferInfo call didn't work. The COLUMNS and LINES environment variables didn't work. at C:\progs\sp5032001001\perl\vendor\lib/Term/ReadLine/readline.pm line 410.

cpan shell -- CPAN exploration and modules installation (v2.28)
Enter 'h' for help.

cpan> o conf init urllist

Now you need to choose your CPAN mirror sites.  You can let me
pick mirrors for you, you can select them from a list or you
can enter them by hand.

Would you like me to automatically choose some CPAN mirror
sites for you? (This means connecting to the Internet) [yes] y

Trying to fetch a mirror list from the Internet
Fetching with LWP:
init/MIRRORED.BY
Fetching with LWP:
init/MIRRORED.BY.gz
Fetching with LWP:
http://www.perl.org/CPAN/MIRRORED.BY

Looking for CPAN mirrors near you (please be patient)
.. done!

New urllist
  http://www.cpan.org/

commit: wrote 'C:\progs\sp5032001001\perl\lib/CPAN/Config.pm'

cpan> quit
Lockfile removed.

C:\Users\ikegami>

commit: wrote indicates the changes were saved, so I didn't need to use o conf commit.


来源: stackexchange

问:
Why do I get LinkageError when only one version of Java seems to be available?
This is my Java environment:

```<code>~: java -version
    java version "11.0.1" 2018-10-16 LTS
    Java(TM) SE Runtime Environment 18.9 (build 11.0.1+13-LTS)
    Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.1+13-LTS, mixed mode)
</code>```

But when trying to execute a program after compiling it I get the following error:

```<code>Error: LinkageError occurred while loading main class ClassName
    java.lang.UnsupportedClassVersionError: ClassName has been
    compiled by a more recent version of the Java Runtime
    (class file version 55.0), this version of the Java Runtime
    only recognizes class file versions up to 54.0
</code>```

My PATH and JAVA_HOME variables both point to this version of java. I
have other versions downloaded but it seems they are not registered in the system:

```<code>update-alternatives --display java
java - auto mode
  link best version is /usr/lib/jvm/java-11-openjdk-amd64/bin/java
  link currently points to /usr/lib/jvm/java-11-openjdk-amd64/bin/java
  link java is /usr/bin/java
  slave java.1.gz is /usr/share/man/man1/java.1.gz
/usr/lib/jvm/java-11-openjdk-amd64/bin/java - priority 1101
  slave java.1.gz: /usr/lib/jvm/java-11-openjdk-amd64/man/man1/java.1.gz
</code>```

So how come the compilation and execution are done with different versions?

答:
I got this error in eclipse:

```<code>LinkageError occurred while loading main class com.example.demo.SpringDemo1Application
    java.lang.UnsupportedClassVersionError: com/example/demo/SpringDemo1Application has been compiled by a more recent version of the Java Runtime (class file version 61.0), this version of the Java Runtime only recognizes class file versions up to 60.0
</code>```

Right Click on Project Name

Select Properties

select Java Compiler

Click on Restore Defaults.

Apply and close.

This works for me.
enter image description here

ContentLicense: CC BY-SA 4.0

Body:
This is my Java environment:

~: java -version
    java version "11.0.1" 2018-10-16 LTS
    Java(TM) SE Runtime Environment 18.9 (build 11.0.1+13-LTS)
    Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.1+13-LTS, mixed mode)

But when trying to execute a program after compiling it I get the following error:

Error: LinkageError occurred while loading main class ClassName
    java.lang.UnsupportedClassVersionError: ClassName has been
    compiled by a more recent version of the Java Runtime
    (class file version 55.0), this version of the Java Runtime
    only recognizes class file versions up to 54.0

My PATH and JAVA_HOME variables both point to this version of java. I
have other versions downloaded but it seems they are not registered in the system:

update-alternatives --display java
java - auto mode
  link best version is /usr/lib/jvm/java-11-openjdk-amd64/bin/java
  link currently points to /usr/lib/jvm/java-11-openjdk-amd64/bin/java
  link java is /usr/bin/java
  slave java.1.gz is /usr/share/man/man1/java.1.gz
/usr/lib/jvm/java-11-openjdk-amd64/bin/java - priority 1101
  slave java.1.gz: /usr/lib/jvm/java-11-openjdk-amd64/man/man1/java.1.gz

So how come the compilation and execution are done with different versions?

Body:
I got this error in eclipse:

LinkageError occurred while loading main class com.example.demo.SpringDemo1Application
    java.lang.UnsupportedClassVersionError: com/example/demo/SpringDemo1Application has been compiled by a more recent version of the Java Runtime (class file version 61.0), this version of the Java Runtime only recognizes class file versions up to 60.0

Right Click on Project Name

Select Properties

select Java Compiler

Click on Restore Defaults.

Apply and close.

This works for me.
enter image description here


问:
Display Django time variable as full hours, minutes am/pm
I want to use a time variable instead of a CharField for a model, which displays multiple saved times. My issue is it displays as "9 am" instead of "9:00 am", and "noon" instead of "12:00 pm".
Can anyone help? Thanks in advance.

Relevant code below-

models.py

```<code>class Post(models.Model):
time=models.TimeField()
free=models.CharField(max_length=50, default="")
player1=models.CharField(max_length=50, default="Player 1")
player2=models.CharField(max_length=50, default="Player 2")
player3=models.CharField(max_length=50, default="Player 3")
player4=models.CharField(max_length=50, default="Player 4")

def __str__(self):
    return self.time
</code>```

HTML

```<code> <h7>{{post.time}}     <a href="{% url 'update0' post.id %}"  class="btn-sm btn-success" >Update</a></h7>
</code>```

答:
You can achieve this by just using the built-in template datetime format like so:

{{ post.time|date:"h:i A" }}

This will display the datetime as: 09:00 AM. You can read more about this in the Django docs.

Body:
I want to use a time variable instead of a CharField for a model, which displays multiple saved times. My issue is it displays as "9 am" instead of "9:00 am", and "noon" instead of "12:00 pm".
Can anyone help? Thanks in advance.

Relevant code below-

models.py

class Post(models.Model):
time=models.TimeField()
free=models.CharField(max_length=50, default="")
player1=models.CharField(max_length=50, default="Player 1")
player2=models.CharField(max_length=50, default="Player 2")
player3=models.CharField(max_length=50, default="Player 3")
player4=models.CharField(max_length=50, default="Player 4")

def __str__(self):
    return self.time

HTML

 <h7>{{post.time}}     Update</h7>


问:
Parse the arguments of a git rebase command to determine the upstream, if one is specified
I'm trying to do this:

User runs git rebase-like [same arguments as rebase]

The script

determines the upstream if one is specified

pulls out other select options from the command

does stuff

then passes the original arguments on to rebase

This question is about 2.1 and 2.2. I expect the most reliable way to do this would be parsing with Git. But for now I'm taking a more manual command line parsing approach. Maybe you can think of a nice regex, or some bash cleverness?

(I've tried reading git-rebase source working back from $switch_to, and git-rebase--merge source working back from $base but I'm fairly new to shell scripts and can't tell whether there's a smallish piece of the source I could use.)

Here's what I have so far. It's limited: it's stricter about the order of arguments than git-rebase is. If [ <upstream> [<branch]] is used, it has to be at the end of the command. I can determine the specified upstream for

```<code>git rebase [...] --onto <newbase> [...]
</code>```

and for

```<code>git rebase <upstream> [<branch]
</code>```

but not for

```<code>git rebase <upstream> [<branch>] ...
</code>```

My script is not beautiful, and it's a brittle. I'd really like a way to get this more directly with Git. At the least I'd like to upgrade my script so it accepts arguments in any order. Ideas?

# !/bin/bash

NEWBASE QUIET UPSTREAM branch
# the "environment" for those env vars is the command line input
# I'm open to hearing arguments for lowercasing them

options () {
    local onto_index
    for ((i=1; i<=$#; i++)); do
      case "${!i}" in
        "--onto")
          newbase_index=$((i+1))
          NEWBASE="${!newbase_index}"
          ;;
        "-q"|"--quiet") QUIET=-q ;;
      esac
    done
}

opt_with_arg () {
    [[ \
        "$1" == "--fork" \
        || "$1" == "--onto" \
        || "$1" == "-s" \
        || "$1" == "-X" \
        || "$1" == "-x" \
        || "$1" == "-exec" \
    ]] \
    || [[ "$1" == "--root" ]]
    # though --root doesn't actually have an argument, including it here
    # is shorter than checking `opt_with_arg $1 || [[ $1 == "--root" ]]`
}

options "$@"

if [[ -n "$1" && "${!#}" != "-"* ]]; then
    [[ $# -gt 3 ]] && shift "$(($#-3))"
    opt_with_arg "$1" && shift 2
    [[ -n "$3" ]] && shift
    opt_with_arg "$1" && shift 2
    [[ "$1" == "-"* ]] && shift
    UPSTREAM="$1"
    #
    # possibilites after first shift:
    # (uppercase is what we want to preserve, lowercase we want to cut,
    # u is <upstream>, b is <branch>, x is <someoption>.)
    #    U,
    #    U B, X U, --root b, --opt_with_arg n,
    #    X U B, X X U, x --root b, x --opt_with_arg n, --opt_with_arg N U, --opt_with_arg n x
    # possibilites after second shift: U,
    #    U B, X U, x
    #    X U B, X X U, x --root b, x --opt_with_arg n
    # possibilites after third shift:
    #    U, x
    #    U B, X U, --root b, --opt_with_arg n
    # possibilites after fourth shift:
    #    U, x
    #    U B, X U
    # possibilites after fifth shift:
    #    U, U B
fi

branch="${NEWBASE:=$UPSTREAM}"
```

答:
Simplest is going to be getopts. Rebase is a big grab-bag of configurable tools and options for history surgery with hunk shuffling galore, so "simplest" is both desperately needed and relative here.  Here's a starter kit to give you the idea of handling the different cases, it passes a smoketest.

edit: to make it scan options wherever they are

#!/bin/bash
# use getopts to scan/skip options and their args,
# first separate arg that isn’t an optarg is an explicit upstream

unset upstream

while (( OPTIND <= $# )); do
    # skip non-option args, set upstream on first one
    while [[ ${@:$OPTIND:1} != -* ]]; do
        [[ ! -v upstream ]] && upstream=`git rev-parse "${@:$OPTIND:1}"`
        (( ++OPTIND > $# )) && break
    done

    # scan options+args, remember options we care about
    while getopts ?qvnfms:x:X:C:ir-: opt; do
        case $opt in
            \?) set -x ;; # for debugging this script, real rebase will choke on it
            f)  echo noticed the -f option go by ;;
            -)  case $OPTARG in
                    root) echo noticed the --root option go by ;;
                    *=*) ;;
                    onto|exec|empty|strategy|strategy-option|whitespace) let ++OPTIND ;;
                esac
                ;;
        esac
    done
done

[[ ! -v upstream ]] && upstream=`git rev-parse @{upstream}`

# your pre-rebase stuff here, then

git rebase "$@"
```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to do this:

User runs git rebase-like [same arguments as rebase]

The script

determines the upstream if one is specified

pulls out other select options from the command

does stuff

then passes the original arguments on to rebase

This question is about 2.1 and 2.2. I expect the most reliable way to do this would be parsing with Git. But for now I'm taking a more manual command line parsing approach. Maybe you can think of a nice regex, or some bash cleverness?

(I've tried reading git-rebase source working back from $switch_to, and git-rebase--merge source working back from $base but I'm fairly new to shell scripts and can't tell whether there's a smallish piece of the source I could use.)

Here's what I have so far. It's limited: it's stricter about the order of arguments than git-rebase is. If [ <upstream> [<branch]] is used, it has to be at the end of the command. I can determine the specified upstream for

git rebase [...] --onto <newbase> [...]

and for

git rebase <upstream> [<branch]

but not for

git rebase <upstream> [<branch>] ...

My script is not beautiful, and it's a brittle. I'd really like a way to get this more directly with Git. At the least I'd like to upgrade my script so it accepts arguments in any order. Ideas?

# !/bin/bash

NEWBASE QUIET UPSTREAM branch
# the "environment" for those env vars is the command line input
# I'm open to hearing arguments for lowercasing them

options () {
    local onto_index
    for ((i=1; i<=$#; i++)); do
      case "${!i}" in
        "--onto")
          newbase_index=$((i+1))
          NEWBASE="${!newbase_index}"
          ;;
        "-q"|"--quiet") QUIET=-q ;;
      esac
    done
}

opt_with_arg () {
    [[ \
        "$1" == "--fork" \
        || "$1" == "--onto" \
        || "$1" == "-s" \
        || "$1" == "-X" \
        || "$1" == "-x" \
        || "$1" == "-exec" \
    ]] \
    || [[ "$1" == "--root" ]]
    # though --root doesn't actually have an argument, including it here
    # is shorter than checking `opt_with_arg $1 || [[ $1 == "--root" ]]`
}

options "$@"

if [[ -n "$1" && "${!#}" != "-"* ]]; then
    [[ $# -gt 3 ]] && shift "$(($#-3))"
    opt_with_arg "$1" && shift 2
    [[ -n "$3" ]] && shift
    opt_with_arg "$1" && shift 2
    [[ "$1" == "-"* ]] && shift
    UPSTREAM="$1"
    #
    # possibilites after first shift:
    # (uppercase is what we want to preserve, lowercase we want to cut,
    # u is <upstream>, b is <branch>, x is <someoption>.)
    #    U,
    #    U B, X U, --root b, --opt_with_arg n,
    #    X U B, X X U, x --root b, x --opt_with_arg n, --opt_with_arg N U, --opt_with_arg n x
    # possibilites after second shift: U,
    #    U B, X U, x
    #    X U B, X X U, x --root b, x --opt_with_arg n
    # possibilites after third shift:
    #    U, x
    #    U B, X U, --root b, --opt_with_arg n
    # possibilites after fourth shift:
    #    U, x
    #    U B, X U
    # possibilites after fifth shift:
    #    U, U B
fi

branch="${NEWBASE:=$UPSTREAM}"


问:
A portable boost.xpressive
I want to use Boost.Xpressive in my C++ homework, and contain it in my source. But the whole boost header file is 70MB+, so is there any standalone xpressive distribution that contains only dependent files?</p>

答:
Use bcp. http://www.boost.org/tools/bcp/index.html.

it allows you to pull a header and all of its dependencies into a separate directory. Which will be much smaller than the whole boost library!

I don't know specifically, but the command line you are looking for is probably something like this:

```<code>bcp xpressive /foo
</code>```

Title: A portable boost.xpressive

Body:
Use bcp. http://www.boost.org/tools/bcp/index.html.

it allows you to pull a header and all of its dependencies into a separate directory. Which will be much smaller than the whole boost library!

I don't know specifically, but the command line you are looking for is probably something like this:

bcp xpressive /foo


问:
Reverse an array without using iteration
A question was asked to me today and I do not believe it is possible, but I could be wrong or am over thinking it. How can you reverse an array without using iteration in C?

My thought is that it's impossible because of the fact that the array can be any size and that no C program can be expressed with that kind of support in mind without using some form of iteration.

答:
One solution could be:</p>
```<code>#include <stdio.h>
#include <stdlib.h>

void swap(int v[], int v_start, int v_middle, int v_end) {
    int *aux = calloc(v_middle - v_start, sizeof(int));

    int k = 0;
    for(int i = v_start; i <= v_middle; i++) {
        aux[k] = v[i];
        k = k + 1;
    }

    k = v_start;
    for(int i = v_middle + 1; i <= v_end; i++) {
        v[k] = v[i];
        k = k + 1;
    }

    for(int i = 0; i <= v_middle - v_start; i++) {
        v[k] = aux[i];
        k = k + 1;
    }
}

void divide(int v[], int v_start, int v_end) {
    if(v_start < v_end) {
        int v_middle = (v_start + v_start)/2;
        divide(v, v_start, v_middle);
        divide(v, v_middle + 1, v_end);
        swap(v, v_start, v_middle, v_end);
    }
}

int main() {
    int v[10] = {4, 20, 12, 100, 50, 9}, n = 6;

    printf("Array: \n");
    for (int i = 0; i < n; i++) {
        printf("%d ", v[i]);
    }
    printf("\n\n");

    divide(v, 0, n - 1);

    printf("Reversed: \n");
    for (int i = 0; i < n; i++) {
        printf("%d ", v[i]);
    }

    return 0;
}
</code>```

Body:
One solution could be:

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

void swap(int v[], int v_start, int v_middle, int v_end) {
    int *aux = calloc(v_middle - v_start, sizeof(int));

    int k = 0;
    for(int i = v_start; i <= v_middle; i++) {
        aux[k] = v[i];
        k = k + 1;
    }

    k = v_start;
    for(int i = v_middle + 1; i <= v_end; i++) {
        v[k] = v[i];
        k = k + 1;
    }

    for(int i = 0; i <= v_middle - v_start; i++) {
        v[k] = aux[i];
        k = k + 1;
    }
}

void divide(int v[], int v_start, int v_end) {
    if(v_start < v_end) {
        int v_middle = (v_start + v_start)/2;
        divide(v, v_start, v_middle);
        divide(v, v_middle + 1, v_end);
        swap(v, v_start, v_middle, v_end);
    }
}

int main() {
    int v[10] = {4, 20, 12, 100, 50, 9}, n = 6;

    printf("Array: \n");
    for (int i = 0; i < n; i++) {
        printf("%d ", v[i]);
    }
    printf("\n\n");

    divide(v, 0, n - 1);

    printf("Reversed: \n");
    for (int i = 0; i < n; i++) {
        printf("%d ", v[i]);
    }

    return 0;
}


问:
Haskell RSA crypto random generator type
My goal is to generate a keypair using generateKeyPair from Codec.Crypto.RSA.

This function requires a generator of type RandomGen. I have tried to make this generator with newGenIO, but I'm having a hard time specifying its type.

```<code>import qualified Codec.Crypto.RSA as Crypto
import Crypto.Random

someFunc = do
  let g = newGenIO :: CryptoRandomGen (IO SystemRandom)
  let keyPair = Crypto.generateKeyPair g 10
</code>```

Haskell suggested CryptoRandomGen SystemRandom when I didn't specify a type after newGenIO.

This is the error message that comes when trying to run the code.

```<code>    • Expected a type, but
      ‘CryptoRandomGen (IO SystemRandom)’ has kind
      ‘Constraint’
</code>```

Does anyone know what type I have use to get it to work?

答:
Try replacing that line with this one:

```<code>  g <- newGenIO :: IO SystemRandom
</code>```

When you want a specific instance of a class, you just use the type, rather than specifying the class again. And to get something out of IO, you need to bind into it rather than just using =.

Body:
My goal is to generate a keypair using generateKeyPair from Codec.Crypto.RSA.

This function requires a generator of type RandomGen. I have tried to make this generator with newGenIO, but I'm having a hard time specifying its type.

import qualified Codec.Crypto.RSA as Crypto
import Crypto.Random

someFunc = do
  let g = newGenIO :: CryptoRandomGen (IO SystemRandom)
  let keyPair = Crypto.generateKeyPair g 10

Haskell suggested CryptoRandomGen SystemRandom when I didn't specify a type after newGenIO.

This is the error message that comes when trying to run the code.

    • Expected a type, but
      ‘CryptoRandomGen (IO SystemRandom)’ has kind
      ‘Constraint’

Does anyone know what type I have use to get it to work?

Body:
Try replacing that line with this one:

  g <- newGenIO :: IO SystemRandom

When you want a specific instance of a class, you just use the type, rather than specifying the class again. And to get something out of IO, you need to bind into it rather than just using =.


问:
How to have component re-render after its props change in Vue 2?
My component is simple:

<template>
  <btn :color="color" @click="toggleColor">{{btnmsg}}</btn>
</template>

```
<p>The <code><Btn></code> from the ChicoFamily goes something like this:</p>
<pre class="lang-html prettyprint-override"><code><template>
  <button :is="tag" :class="[className, {'active': active}]" :type="type" :role="role">
    <slot></slot>
  </button>
</template>

<script>
import classNames from 'classnames';
export default {
  props: {
    tag: {
      type: String,
      default: "button"
    },
    color: {
      type: String,
      default: "default"
    },
    //...it takes a lot of props...
  },
  data() {
    return {
      className: classNames(
        this.floating ? 'btn-floating' : 'btn',
        this.outline ? 'btn-outline-' + this.outline : this.flat ? 'btn-flat' : this.transparent ? '' : 'btn-' + this.color,
        //...classes derived from these props...
      ),
    };
  }
}
</script>
</code>```

It's a button that, when clicked, should change its color. Clicking it indeed changes the prop passed, but does not re-render the button in the new color.

Why does passing a different prop not re-render the button?

The <Btn> takes its color from Bootstrap classes deriving from the prop. Could it be that the Btn gets the proper prop, but the className mechanic does not catch up?

答: Setting a :key on the component is the best way to force Vue to re-render the component. If you require the component to be re-rendered, simply modify the value of the key, and Vue will re-render it.</p>

Body:
My component is simple:

<template>
  <btn :color="color" @click="toggleColor">{{btnmsg}}</btn>
</template>

The <Btn> from the ChicoFamily goes something like this:

<template>
  <button :is="tag" :class="[className, {'active': active}]" :type="type" :role="role">
    <slot></slot>
  </button>
</template>

It's a button that, when clicked, should change its color. Clicking it indeed changes the prop passed, but does not re-render the button in the new color.

Why does passing a different prop not re-render the button?

The <Btn> takes its color from Bootstrap classes deriving from the prop. Could it be that the Btn gets the proper prop, but the className mechanic does not catch up?


问:
error LNK2019: "unresolved external symbol" using variadic function
Trying to build function that gets unknown number of arguments.

Header.h:

```<code>void WriteHeaderToCSVFile() {}

template <typename FieldType, typename... Types>
void WriteHeaderToCSVFile(FieldType field1, Types...field2);
</code>```

Source.cpp:

```<code>template <typename FieldType, typename... Types>
void CSVWriter::WriteHeaderToCSVFile(FieldType field1, Types... field2)
{
    mFileStream->Write(field1);
    mFileStream->Write(scComma);
    WriteHeaderToCSVFile(field2...);
}

void main()
{
   myFile2.WriteHeaderToCSVFile(L("no.record"), L("no.page"), L("values"));
}
</code>```

Getting the error bellow:

```<code>error LNK2019: unresolved external symbol "public: void __cdecl CSVWriter::WriteHeaderToCSVFile<wchar_t const *,wchar_t const *,wchar_t const *>(wchar_t const *,wchar_t const *,wchar_t const *)" (??$WriteHeaderToCSVFile@PEB_WPEB_WPEB_W@XMPCSVWriter@@QEAAXPEB_W00@Z) referenced in function "void __cdecl TestCSVFileWriter(void)" (?TestCSVFileWriter@@YAXXZ)
</code>```

答:
I suppose the problem is that you need an "empty" overload for WriteHeaderToCSVFile() as ground case for the recursion; I mean

```<code>void CSVWriter::WriteHeaderToCSVFile ()
{ }
</code>```

I mean... myFile2.WriteHeaderToCSVFile(L("no.record"), L("no.page"), L("values")); call myFile2.WriteHeaderToCSVFile(L("no.page"), L("values")); that matches the variadic method (L("no.page") matches field1, L("values") matches field2...)

Then myFile2.WriteHeaderToCSVFile(L("no.page"), L("values")); call myFile2.WriteHeaderToCSVFile(L("values")); that matches the variadic method (L("values") matches field1, field2... matches as empty).

The myFile2.WriteHeaderToCSVFile(L("values")); call myFile2.WriteHeaderToCSVFile(); but nothing matches field1, for the variadic method.

So you need another WriteHeaderToCSVFile() that can match an empty list of argument.

Off Topic Unrequested Suggestion: define your templates (classes, functions, methods, variables, etc.) directly in the header files where they are declared.

The reason is well described in here

Body:
Trying to build function that gets unknown number of arguments.

Header.h:

void WriteHeaderToCSVFile() {}

template <typename FieldType, typename... Types>
void WriteHeaderToCSVFile(FieldType field1, Types...field2);

Source.cpp:

template <typename FieldType, typename... Types>
void CSVWriter::WriteHeaderToCSVFile(FieldType field1, Types... field2)
{
    mFileStream->Write(field1);
    mFileStream->Write(scComma);
    WriteHeaderToCSVFile(field2...);
}

void main()
{
   myFile2.WriteHeaderToCSVFile(L("no.record"), L("no.page"), L("values"));
}

Getting the error bellow:

error LNK2019: unresolved external symbol "public: void __cdecl CSVWriter::WriteHeaderToCSVFile<wchar_t const *,wchar_t const *,wchar_t const *>(wchar_t const *,wchar_t const *,wchar_t const *)" (??$WriteHeaderToCSVFile@PEB_WPEB_WPEB_W@XMPCSVWriter@@QEAAXPEB_W00@Z) referenced in function "void __cdecl TestCSVFileWriter(void)" (?TestCSVFileWriter@@YAXXZ)

Body:
I suppose the problem is that you need an "empty" overload for WriteHeaderToCSVFile() as ground case for the recursion; I mean

void CSVWriter::WriteHeaderToCSVFile ()
{ }

I mean... myFile2.WriteHeaderToCSVFile(L("no.record"), L("no.page"), L("values")); call myFile2.WriteHeaderToCSVFile(L("no.page"), L("values")); that matches the variadic method (L("no.page") matches field1, L("values") matches field2...)

Then myFile2.WriteHeaderToCSVFile(L("no.page"), L("values")); call myFile2.WriteHeaderToCSVFile(L("values")); that matches the variadic method (L("values") matches field1, field2... matches as empty).

The myFile2.WriteHeaderToCSVFile(L("values")); call myFile2.WriteHeaderToCSVFile(); but nothing matches field1, for the variadic method.

So you need another WriteHeaderToCSVFile() that can match an empty list of argument.

Off Topic Unrequested Suggestion: define your templates (classes, functions, methods, variables, etc.) directly in the header files where they are declared.

The reason is well described in here


问:
NestJS | Passport: TypeError: Cannot read properties of undefined (reading 'logIn')
Situation:

Developing api in nest & grapqhql

Worked on one laptop, everything was working well

Then cloned my repo on other laptops, installed dependencies, created a new local database.

App is being built with no errors

When following localhost:4000 in browser to open graphql playground I'm receiving 500 error end next message:
```<code>ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'logIn')
TypeError: Cannot read properties of undefined (reading 'logIn')
    at authenticate (/home/gleb/Projects/artwine-api/node_modules/passport/lib/middleware/authenticate.js:96:21)
    at /home/gleb/Projects/artwine-api/node_modules/@nestjs/passport/dist/auth.guard.js:91:3
    at new Promise (<anonymous>)
    at /home/gleb/Projects/artwine-api/node_modules/@nestjs/passport/dist/auth.guard.js:83:83
    at JWTAccessAuthGuard.<anonymous> (/home/gleb/Projects/artwine-api/node_modules/@nestjs/passport/dist/auth.guard.js:49:36)
    at Generator.next (<anonymous>)
    at fulfilled (/home/gleb/Projects/artwine-api/node_modules/@nestjs/passport/dist/auth.guard.js:17:58)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
</code>```

Code of a passport lib function where the error is caught:

```<code>return function authenticate(req, res, next) {
    req.login =
    req.logIn = req.logIn || IncomingMessageExt.logIn;
    req.logout =
    req.logOut = req.logOut || IncomingMessageExt.logOut;
    req.isAuthenticated = req.isAuthenticated || IncomingMessageExt.isAuthenticated;
    req.isUnauthenticated = req.isUnauthenticated || IncomingMessageExt.isUnauthenticated;

    req._sessionManager = passport._sm;
..............
</code>```

Link to the repo: https://github.com/Gleb-Gaiduk/artwine-api
Any ideas on what could go wrong after cloning the working repository?

答:
You should look your Guard and strategy you are using and should handle errors from there for example:</p>
```<code>@Injectable()
export class PassportLocalGuard extends AuthGuard('local') {
protected readonly logger = new Logger(PassportLocalGuard.name);

canActivate(context: ExecutionContext) {
const ctx = GqlExecutionContext.create(context);
const { req } = ctx.getContext();

return super.canActivate(new ExecutionContextHost([req]));
   }

handleRequest(err: any, user: any) {
  if (err) {
   this.logger.error(`Auth Error! ${err.message}`);
   throw err;
   }

  if (!user) {
   this.logger.error('Auth Error! User not found');
   throw new AuthenticationError('Auth Error! User not found');
   }

  return user;
 }
}
</code>```

Body:
Situation:

Developing api in nest & grapqhql

Worked on one laptop, everything was working well

Then cloned my repo on other laptops, installed dependencies, created a new local database.

App is being built with no errors

When following localhost:4000 in browser to open graphql playground I'm receiving 500 error end next message:

ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'logIn')
TypeError: Cannot read properties of undefined (reading 'logIn')
    at authenticate (/home/gleb/Projects/artwine-api/node_modules/passport/lib/middleware/authenticate.js:96:21)
    at /home/gleb/Projects/artwine-api/node_modules/@nestjs/passport/dist/auth.guard.js:91:3
    at new Promise (<anonymous>)
    at /home/gleb/Projects/artwine-api/node_modules/@nestjs/passport/dist/auth.guard.js:83:83
    at JWTAccessAuthGuard.<anonymous> (/home/gleb/Projects/artwine-api/node_modules/@nestjs/passport/dist/auth.guard.js:49:36)
    at Generator.next (<anonymous>)
    at fulfilled (/home/gleb/Projects/artwine-api/node_modules/@nestjs/passport/dist/auth.guard.js:17:58)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

Code of a passport lib function where the error is caught:

return function authenticate(req, res, next) {
    req.login =
    req.logIn = req.logIn || IncomingMessageExt.logIn;
    req.logout =
    req.logOut = req.logOut || IncomingMessageExt.logOut;
    req.isAuthenticated = req.isAuthenticated || IncomingMessageExt.isAuthenticated;
    req.isUnauthenticated = req.isUnauthenticated || IncomingMessageExt.isUnauthenticated;

    req._sessionManager = passport._sm;
..............

Link to the repo: https://github.com/Gleb-Gaiduk/artwine-api
Any ideas on what could go wrong after cloning the working repository?

Body:
You should look your Guard and strategy you are using and should handle errors from there for example:

@Injectable()
export class PassportLocalGuard extends AuthGuard('local') {
protected readonly logger = new Logger(PassportLocalGuard.name);

canActivate(context: ExecutionContext) {
const ctx = GqlExecutionContext.create(context);
const { req } = ctx.getContext();

return super.canActivate(new ExecutionContextHost([req]));
   }

handleRequest(err: any, user: any) {
  if (err) {
   this.logger.error(`Auth Error! ${err.message}`);
   throw err;
   }

  if (!user) {
   this.logger.error('Auth Error! User not found');
   throw new AuthenticationError('Auth Error! User not found');
   }

  return user;
 }
}


问:
Node saying sh: 1: main.js: not found when main.js is there
As the title says, node cannot find main.js. I am doing this through replit and my .replit file is run = "npm test". My package.json file is

```<code>{
  "name": "Adventure",
  "version": "1.0.0",
  "description": "This is The Adventure Bot By BrainDead_Dev",
  "main": "main.js",
  "dependencies": {
    "@replit/database": "^2.0.1",
    "discord-buttons": "^4.0.0-deprecated",
    "discord.js": "^13.6.0",
    "moment": "^2.29.1",
    "winston": "^3.6.0"
  },
  "devDependencies": {},
  "scripts": {
    "test": "main.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/BrainDeadDev/Adventure.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/BrainDeadDev/Adventure/issues"
  },
  "homepage": "https://github.com/BrainDeadDev/Adventure#readme"
}
</code>```

This is for a discord bot, and it has been working perfectly fine up until the point where I wanted to update discord.js and had to reinstall npm. Any help would be appreciated as I am quite lost.

答:
When you updated the discord.js package, it now requires a more current version of node js (v16.6).

To update to the version of node using npm simply run:

```<code>npm install -g n
</code>```

If you are using nvm you can do:

```<code>nvm install 16.6
</code>```

then tell nvm to use the new version:

```<code>nvm use 16.6
</code>```

Then you can check the version you are using by running:

```<code>node --version
</code>```

Edit for Repl.it:

following this blog, you should be able to do it by running this:

```<code>npm i --save-dev node@16 && npm config set prefix=$(pwd)/node_modules/node && export PATH=$(pwd)/node_modules/node/bin:$PATH
</code>```

You can also try following this question on repl.it forums

Body:
As the title says, node cannot find main.js. I am doing this through replit and my .replit file is run = "npm test". My package.json file is

{
  "name": "Adventure",
  "version": "1.0.0",
  "description": "This is The Adventure Bot By BrainDead_Dev",
  "main": "main.js",
  "dependencies": {
    "@replit/database": "^2.0.1",
    "discord-buttons": "^4.0.0-deprecated",
    "discord.js": "^13.6.0",
    "moment": "^2.29.1",
    "winston": "^3.6.0"
  },
  "devDependencies": {},
  "scripts": {
    "test": "main.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/BrainDeadDev/Adventure.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/BrainDeadDev/Adventure/issues"
  },
  "homepage": "https://github.com/BrainDeadDev/Adventure#readme"
}

This is for a discord bot, and it has been working perfectly fine up until the point where I wanted to update discord.js and had to reinstall npm. Any help would be appreciated as I am quite lost.

Body:
When you updated the discord.js package, it now requires a more current version of node js (v16.6).

To update to the version of node using npm simply run:

npm install -g n

If you are using nvm you can do:

nvm install 16.6

then tell nvm to use the new version:

nvm use 16.6

Then you can check the version you are using by running:

node --version

Edit for Repl.it:

following this blog, you should be able to do it by running this:

npm i --save-dev node@16 && npm config set prefix=$(pwd)/node_modules/node && export PATH=$(pwd)/node_modules/node/bin:$PATH

You can also try following this question on repl.it forums


问:
How are stack and heap segment managed in x86 without utilizing the segmentation mechanism?
From Understanding the Linux Kernel:

Segmentation has been included in 80x86 microprocessors to encourage programmers to split their applications into logically related entities, such as subroutines or global and local data areas. However, Linux uses segmentation in a very limited way. In fact, segmentation and paging are somewhat redundant, because both can be used to separate the physical address spaces of processes: segmentation can assign a different linear address space to each process, while paging can map the same linear address space into different physical address spaces. Linux prefers paging to segmentation for the following reasons:

Memory management is simpler when all processes use the same segment register values—that is, when they share the same set of linear addresses.

One of the design objectives of Linux is portability to a wide range of architectures; RISC architectures, in particular, have limited support for segmentation.

The 2.6 version of Linux uses segmentation only when required by the 80x86 architecture.

The x86-64 architecture does not use segmentation in long mode (64-bit mode). As the x86 has segments, it is not possible to not use them. Four of the segment registers: CS, SS, DS, and ES are forced to 0, and the limit to 2^64. If so, two questions have been raised:

Stack data (stack segment) and heap data (data segment) are mixed together, then pop from the stack and increase the ESP register is not available.

How does the operating system know which type of data is (stack or heap) in a specific virtual memory address?

How do different programs share the kernel code by sharing memory?

答:
Stack data (stack segment) and heap data (data segment) are mixed together, then pop from the stack and increase the ESP register is not available.

As Peter states in the above comment, even though CS, SS, ES and DS are all treated as having zero base, this does not change the behavior of PUSH/POP in any way. It is no different than any other segment descriptor usage really. You could get overlapping segments even in 32-bit multi-segment mode if you point multiple selectors to the same descriptor. The only thing that "changes" in 64-bit mode is that you have a base forced by the CPU, and RSP can be used to point anywhere in addressable memory. PUSH/POP operations will work as usual.

How does the operating system know which type of data is (stack or heap) in a specific virtual memory address?

User-space programs can (and will) move the stack and heap around as they please. The operating system doesn't really need to know where stack and heap are, but it can keep track of those to some extent, assuming the user-space application does everything according to convention, that is uses the stack allocated by the kernel at program startup and the program break as heap.

Using the stack allocated by the kernel at program startup, or a memory area obtained through mmap(2) with MAP_GROWSDOWN, the kernel tries to help by automatically growing the memory area when its size is exceeded (i.e. stack overflow), but this has its limits. Manual MAP_GROWSDOWN mappings are rarely used in practice (see 1, 2, 3, 4). POSIX threads and other more modern implementations use fixed-size mappings for threads.

"Heap" is a pretty abstract concept in modern user-space applications. Linux provides user-space applications with the basic ability to manipulate the program break through brk(2) and sbrk(2), but this is rarely in a 1-to-1 correspondence with what we got used to call "heap" nowadays. So in general the kernel does not know where the heap of an application resides.

How do different programs share the kernel code by sharing memory?

This is simply done through paging. You could say there is one hierarchy of page tables for the kernel and many others for user-space processes (one for each task). When switching to kernel-space (e.g. through a syscall) the kernel changes the value of the CR3 register to make it point to the kernel's page global directory. When switching back to user-space, CR3 is changed back to point to the current process' page global directory before giving control to user-space code.


问:
ref.map is not a function?
this is my first post. Thank you all for the years, of assistance btw, I hope to pour in, as much as I've gotten from you guys/gals. Let's get started.

I have a Next.js / React-Redux application and here is my problem:

I'm attempting to update the Redux store, with JSON, that is returned from `fs.readFile' (the 'fs/promises' module:

//Product.js

```<code>function Product() {
   const suggested_products = useSelector((state) => state.user.suggested_products) // json read from /api/products
   const updateProducts = () => {
            (JSON.parse(JSON.stringify(suggested_products)))?.map((product) =>  { // Compliler does not like this line
                <div>
                    <input type='checkbox'>
                      <p> {product.category}</p>
                      <p>{product.service_name}</p>
                    </input
                </div>
            })
        }
        return (
            if (userSelectedProduct) ? updateProducts() : <p>No data found</p>
    }

</code>```

//Form.js

```<code>
import { useSWR } from 'swr'

const fetcher = (...args) => fetch(...args).then((res) => res.json());

function Form() {
  const [url, setURL] = useState('');
  const { data, error } = useSWR(url, fetcher);

  <input
    value={product}
    onChange={

       dispatch(updateCustomerCSP((JSON.parse(JSON.stringify(e.target.value)))));
                            setURL(`api/${product}/`); //Attempt to dynamically fetch data, from client side
                            dispatch(updateSuggestedProducts(data)); //Update data in store returned from client side fetching

                        }}
  </input>

}
</code>```

// pages/api/products

```<code>import fs from 'fs/promises';
export default function handler(req, res) {
   const filePath = path.join(process.cwd(),`/data.js'); // /data.js contains JSON array [{"product-1": "value"}, {"product-2": "value"}], which is why I need to use map function.
   try {
      const fileData = fs.readFile(filePath);
      const data = JSON.parse(JSON.stringify(fileData));
      res.status(200).json(data);
} catch (err)
   {
    res.status(500).json({ error: 'Failed to load data' })
   }
}
</code>```

// This error throws ref.map is not a function from the Products.js component.
Here is the only info that I could find in regards to ref's in React.
Also, the JSON.parse and JSON.stringify wrappers, are to keep Redux happy with object going into the store. Thanks for reading community, looking forward to your input. Should any oneed more info, please let me know. Also, here is info in regards to refs, that I could find:

https://reactjs.org/docs/refs-and-the-dom.html

答:
I figured it out. I actually had the input wrapped in a HOC, and the event handler wasn't properly registered to the input element itself., therefore failing to load in the array object into the store to use.

So be careful of that, when building your own components.

For instance,

```<code>function Component() {
  function loadArrayInStore() {
    loadInStore()
 }
  const MyButton = (props) => {
    <input  onChange={props.handler} // I had an inline handler here such as onChange={ (e)= { doNotLoadArrayInStoreAndDontWork()}
  }
  return (
     <MyButton handler={loadArrayInStore} />
  )
}
</code>```

So be watchful, when creating HOC's :)

Title: ref.map is not a function?

Body:
this is my first post. Thank you all for the years, of assistance btw, I hope to pour in, as much as I've gotten from you guys/gals. Let's get started.

I have a Next.js / React-Redux application and here is my problem:

I'm attempting to update the Redux store, with JSON, that is returned from `fs.readFile' (the 'fs/promises' module:

//Product.js

function Product() {
   const suggested_products = useSelector((state) => state.user.suggested_products) // json read from /api/products
   const updateProducts = () => {
            (JSON.parse(JSON.stringify(suggested_products)))?.map((product) =>  { // Compliler does not like this line

                    <input type='checkbox'>

 {product.category}

{product.service_name}

                    </input

            })
        }
        return (
            if (userSelectedProduct) ? updateProducts() :
No data found

    }

//Form.js

import { useSWR } from 'swr'

const fetcher = (...args) => fetch(...args).then((res) => res.json());

function Form() {
  const [url, setURL] = useState('');
  const { data, error } = useSWR(url, fetcher);

  <input
    value={product}
    onChange={

       dispatch(updateCustomerCSP((JSON.parse(JSON.stringify(e.target.value)))));
                            setURL(`api/${product}/`); //Attempt to dynamically fetch data, from client side
                            dispatch(updateSuggestedProducts(data)); //Update data in store returned from client side fetching

                        }}
  </input>

}

// pages/api/products

import fs from 'fs/promises';
export default function handler(req, res) {
   const filePath = path.join(process.cwd(),`/data.js'); // /data.js contains JSON array [{"product-1": "value"}, {"product-2": "value"}], which is why I need to use map function.
   try {
      const fileData = fs.readFile(filePath);
      const data = JSON.parse(JSON.stringify(fileData));
      res.status(200).json(data);
} catch (err)
   {
    res.status(500).json({ error: 'Failed to load data' })
   }
}

// This error throws ref.map is not a function from the Products.js component.
Here is the only info that I could find in regards to ref's in React.
Also, the JSON.parse and JSON.stringify wrappers, are to keep Redux happy with object going into the store. Thanks for reading community, looking forward to your input. Should any oneed more info, please let me know. Also, here is info in regards to refs, that I could find:

https://reactjs.org/docs/refs-and-the-dom.html

Body:
I figured it out. I actually had the input wrapped in a HOC, and the event handler wasn't properly registered to the input element itself., therefore failing to load in the array object into the store to use.

So be careful of that, when building your own components.

For instance,

function Component() {
  function loadArrayInStore() {
    loadInStore()
 }
  const MyButton = (props) => {
    <input  onChange={props.handler} // I had an inline handler here such as onChange={ (e)= { doNotLoadArrayInStoreAndDontWork()}
  }
  return (
     <MyButton handler={loadArrayInStore} />
  )
}

So be watchful, when creating HOC's :)


问:
Text with arc direction in Canvas, but letters should keep vertical
This is what I'm trying to make:

Closer I got was bridge text like this example, but it uses a Top baseline for the bridge and I'm not sure how to addapt it to my needs:

Bridge Text Effect in HTML5 Canvas

Fiddle:
https://jsfiddle.net/0btz7a1g/

/// (c) Ken Fyrstenberg Nilsen, Abidas Software .com
/// License: CC-Attribute

var ctx = demo.getContext('2d'),
    font = '64px impact',
    w = demo.width,
    h = demo.height,
    curve,
    offsetY,
    bottom,
    textHeight,
    isTri = false,
    dltY,
    angleSteps = 180 / w,
    i = w,
    y,
    os = document.createElement('canvas'),
    octx = os.getContext('2d');

os.width = w;
os.height = h;

octx.font = font;
octx.textBaseline = 'top';
octx.textAlign = 'center';

function renderBridgeText() {

    curve = parseInt(iCurve.value, 10);
    offsetY = parseInt(iOffset.value, 10);
    textHeight = parseInt(iHeight.value, 10);
    bottom = parseInt(iBottom.value, 10);
    isTri = iTriangle.checked;

    vCurve.innerHTML = curve;
    vOffset.innerHTML = offsetY;
    vHeight.innerHTML = textHeight;
    vBottom.innerHTML = bottom;

    octx.clearRect(0, 0, w, h);
    ctx.clearRect(0, 0, w, h);

    octx.fillText(iText.value.toUpperCase(), w * 0.5, 0);

    /// slide and dice
    i = w;
    dltY = curve / textHeight;
    y = 0;
    while (i--) {
        if (isTri) {
            y += dltY;
            if (i === (w * 0.5)|0) dltY = -dltY;
        } else {
            y = bottom - curve * Math.sin(i * angleSteps * Math.PI / 180);
        }
        ctx.drawImage(os, i, 0, 1, textHeight,
        i, h * 0.5 - offsetY / textHeight * y, 1, y);
    }
}

iCurve.onchange = iOffset.onchange = iHeight.onchange = iBottom.onchange = iText.onkeyup = iTriangle.onchange = renderBridgeText;

renderBridgeText()```
<pre class="snippet-code-css lang-css prettyprint-override"><code>span {
    display:inline-block;
    width:70px;
    text-align:right;
    font:12px sans-serif;
}</code>```

<canvas id=demo width=400 height=300></canvas>

    Curve:
<input id="iCurve" type="range" min=0 max=200 value=110>
110

OffsetY:
<input id="iOffset" type="range" min=0 max=100 value=4>
0

Text height:
<input id="iHeight" type="range" min=0 max=200 value=64>
64

Bottom:
<input id="iBottom" type="range" min=0 max=200 value=200>
200

Triangle:
    <input id="iTriangle" type="checkbox">

Text:
<input id="iText" type="text" value="BRIDGE TEXT">
 ```

Is there any way to arc text while keeping each letter vertical like in the images?

答:
The tool works by drawing the text normally, slicing it into 1px wide vertical strips, then redrawing those strips with vertical scaling and offset. Knowing how .drawImage() functions helps a lot in making this possible. Changing this algorithm to your needs is a matter of changing how the scaling and offset are calculated.

Two parameters are calculated for each strip: Offset and height. y controls the arc but is used directly to set the target height. h * 0.5 - offsetY / textHeight * y scales and offsets y to produce the offset.

Since y is derived almost directly from sin(), we can use that as the offset instead. The height would remain fixed so we use textHeight for that.

Changing

```<code>ctx.drawImage(os, i, 0, 1, textHeight,
                  i, h * 0.5 - offsetY / textHeight * y, 1, y);
</code>```

to

```<code>ctx.drawImage(os, i, 0, 1, textHeight,
                  i, y, 1, textHeight);
</code>```

does the trick.

This is the minimum change necessary. I'll leave it as an exercise for yourself as to how to further clean up the code.

Body:
This is what I'm trying to make:

Closer I got was bridge text like this example, but it uses a Top baseline for the bridge and I'm not sure how to addapt it to my needs:

Bridge Text Effect in HTML5 Canvas

Fiddle:
https://jsfiddle.net/0btz7a1g/

/// (c) Ken Fyrstenberg Nilsen, Abidas Software .com
/// License: CC-Attribute

var ctx = demo.getContext('2d'),
    font = '64px impact',
    w = demo.width,
    h = demo.height,
    curve,
    offsetY,
    bottom,
    textHeight,
    isTri = false,
    dltY,
    angleSteps = 180 / w,
    i = w,
    y,
    os = document.createElement('canvas'),
    octx = os.getContext('2d');

os.width = w;
os.height = h;

octx.font = font;
octx.textBaseline = 'top';
octx.textAlign = 'center';

function renderBridgeText() {

    curve = parseInt(iCurve.value, 10);
    offsetY = parseInt(iOffset.value, 10);
    textHeight = parseInt(iHeight.value, 10);
    bottom = parseInt(iBottom.value, 10);
    isTri = iTriangle.checked;

    vCurve.innerHTML = curve;
    vOffset.innerHTML = offsetY;
    vHeight.innerHTML = textHeight;
    vBottom.innerHTML = bottom;

    octx.clearRect(0, 0, w, h);
    ctx.clearRect(0, 0, w, h);

    octx.fillText(iText.value.toUpperCase(), w * 0.5, 0);

    /// slide and dice
    i = w;
    dltY = curve / textHeight;
    y = 0;
    while (i--) {
        if (isTri) {
            y += dltY;
            if (i === (w * 0.5)|0) dltY = -dltY;
        } else {
            y = bottom - curve * Math.sin(i * angleSteps * Math.PI / 180);
        }
        ctx.drawImage(os, i, 0, 1, textHeight,
        i, h * 0.5 - offsetY / textHeight * y, 1, y);
    }
}

iCurve.onchange = iOffset.onchange = iHeight.onchange = iBottom.onchange = iText.onkeyup = iTriangle.onchange = renderBridgeText;

renderBridgeText()

span {
    display:inline-block;
    width:70px;
    text-align:right;
    font:12px sans-serif;
}

<canvas id=demo width=400 height=300></canvas>

    Curve:
<input id="iCurve" type="range" min=0 max=200 value=110>
110

OffsetY:
<input id="iOffset" type="range" min=0 max=100 value=4>
0

Text height:
<input id="iHeight" type="range" min=0 max=200 value=64>
64

Bottom:
<input id="iBottom" type="range" min=0 max=200 value=200>
200

Triangle:
    <input id="iTriangle" type="checkbox">

Text:
<input id="iText" type="text" value="BRIDGE TEXT">

Is there any way to arc text while keeping each letter vertical like in the images?

Body:
The tool works by drawing the text normally, slicing it into 1px wide vertical strips, then redrawing those strips with vertical scaling and offset. Knowing how .drawImage() functions helps a lot in making this possible. Changing this algorithm to your needs is a matter of changing how the scaling and offset are calculated.

Two parameters are calculated for each strip: Offset and height. y controls the arc but is used directly to set the target height. h * 0.5 - offsetY / textHeight * y scales and offsets y to produce the offset.

Since y is derived almost directly from sin(), we can use that as the offset instead. The height would remain fixed so we use textHeight for that.

Changing

ctx.drawImage(os, i, 0, 1, textHeight,
                  i, h * 0.5 - offsetY / textHeight * y, 1, y);

to

ctx.drawImage(os, i, 0, 1, textHeight,
                  i, y, 1, textHeight);

does the trick.

This is the minimum change necessary. I'll leave it as an exercise for yourself as to how to further clean up the code.


问:
Trying to connect to Heroku: MongoParseError: URI malformedm cannot be parsed
I'm trying to post my app to Heroku for class and it keeps crashing. This is the error code I'm receiving. I'm not exactly sure what's happening, the H10 error is a blanket statement, maybe someone here could shed some light. This is what I'm getting when using heroku logs --tail.
Edit: My app works totally fine on my local machine, I'm only getting this error when trying to post to Heroku

```<code>2022-02-13T18:27:21.000000+00:00 app[api]: Build started by user nmendez6594@gmail.com
2022-02-13T18:27:38.841499+00:00 app[api]: Release v5 created by user nmendez6594@gmail.com
2022-02-13T18:27:38.841499+00:00 app[api]: Deploy 7d112609 by user nmendez6594@gmail.com
2022-02-13T18:27:39.000000+00:00 app[api]: Build succeeded
2022-02-13T18:27:39.104174+00:00 heroku[web.1]: State changed from crashed to starting
2022-02-13T18:27:40.901836+00:00 heroku[web.1]: Starting process with command `npm start`
2022-02-13T18:27:42.058731+00:00 app[web.1]:
2022-02-13T18:27:42.058745+00:00 app[web.1]: > budget-app@1.0.0 start
2022-02-13T18:27:42.058746+00:00 app[web.1]: > node server.js
2022-02-13T18:27:42.058746+00:00 app[web.1]:
2022-02-13T18:27:42.395832+00:00 app[web.1]: App running on port 55680!
2022-02-13T18:27:42.401378+00:00 app[web.1]: /app/node_modules/mongodb/lib/core/uri_parser.js:580
2022-02-13T18:27:42.401379+00:00 app[web.1]: return callback(new MongoParseError('URI malformed, cannot be parsed'));
2022-02-13T18:27:42.401380+00:00 app[web.1]: ^
2022-02-13T18:27:42.401380+00:00 app[web.1]:
2022-02-13T18:27:42.401380+00:00 app[web.1]: MongoParseError: URI malformed, cannot be parsed
2022-02-13T18:27:42.401381+00:00 app[web.1]: at parseConnectionString (/app/node_modules/mongodb/lib/core/uri_parser.js:580:21)
2022-02-13T18:27:42.401381+00:00 app[web.1]: at connect (/app/node_modules/mongodb/lib/operations/connect.js:283:3)
2022-02-13T18:27:42.401382+00:00 app[web.1]: at /app/node_modules/mongodb/lib/mongo_client.js:284:5
2022-02-13T18:27:42.401382+00:00 app[web.1]: at maybePromise (/app/node_modules/mongodb/lib/utils.js:692:3)
2022-02-13T18:27:42.401382+00:00 app[web.1]: at MongoClient.connect (/app/node_modules/mongodb/lib/mongo_client.js:280:10)
2022-02-13T18:27:42.401382+00:00 app[web.1]: at /app/node_modules/mongoose/lib/connection.js:836:12
2022-02-13T18:27:42.401383+00:00 app[web.1]: at new Promise (<anonymous>)
2022-02-13T18:27:42.401383+00:00 app[web.1]: at NativeConnection.Connection.openUri (/app/node_modules/mongoose/lib/connection.js:832:19)
2022-02-13T18:27:42.401384+00:00 app[web.1]: at /app/node_modules/mongoose/lib/index.js:351:10
2022-02-13T18:27:42.401384+00:00 app[web.1]: at /app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:32:5
2022-02-13T18:27:42.401384+00:00 app[web.1]: at new Promise (<anonymous>)
2022-02-13T18:27:42.401384+00:00 app[web.1]: at promiseOrCallback (/app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:10)
2022-02-13T18:27:42.401384+00:00 app[web.1]: at Mongoose._promiseOrCallback (/app/node_modules/mongoose/lib/index.js:1149:10)
2022-02-13T18:27:42.401385+00:00 app[web.1]: at Mongoose.connect (/app/node_modules/mongoose/lib/index.js:350:20)
2022-02-13T18:27:42.401385+00:00 app[web.1]: at Object.<anonymous> (/app/server.js:19:10)
2022-02-13T18:27:42.401385+00:00 app[web.1]: at Module._compile (node:internal/modules/cjs/loader:1103:14)
2022-02-13T18:27:42.521294+00:00 heroku[web.1]: Process exited with status 1
2022-02-13T18:27:42.598710+00:00 heroku[web.1]: State changed from starting to crashed
2022-02-13T18:27:48.281004+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=budget-app-pwa4.herokuapp.com request_id=5de2651b-5f3f-4a1e-84f2-18c0123b8dd7 fwd="32.215.142.46" dyno= connect= service= status=503 bytes= protocol=https
2022-02-13T18:27:49.746492+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=budget-app-pwa4.herokuapp.com request_id=f15d0dc1-7a19-49e1-a743-13f31cac6c31 fwd="32.215.142.46" dyno= connect= service= status=503 bytes= protocol=https
</code>```

This is my server.js file

```<code>const express = require("express");
const logger = require("morgan");
const mongoose = require("mongoose");
const compression = require("compression");

const PORT = process.env.PORT || 3001;
const MONGODB_URI = process.env.MONGODB_URI || "mongodb://localhost/budget";

const app = express();

app.use(logger("dev"));

app.use(compression());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

app.use(express.static("public"));

mongoose.connect(MONGODB_URI, {
  useNewUrlParser: true,
  useFindAndModify: false,
  useUnifiedTopology: true
});

// routes
app.use(require("./routes/api.js"));

app.listen(PORT, () => {
  console.log(`App running on port ${PORT}!`);
});
</code>```

答: Hello and thank you everyone for helping. My issue was that I was using my Mongo username/password login info in the URI string, instead of my Mongo database username/password combination. I'm not sure if that makes any sense but I have it up and running. Thank you again!</p>

Body:
I'm trying to post my app to Heroku for class and it keeps crashing. This is the error code I'm receiving. I'm not exactly sure what's happening, the H10 error is a blanket statement, maybe someone here could shed some light. This is what I'm getting when using heroku logs --tail.
Edit: My app works totally fine on my local machine, I'm only getting this error when trying to post to Heroku

2022-02-13T18:27:21.000000+00:00 app[api]: Build started by user nmendez6594@gmail.com
2022-02-13T18:27:38.841499+00:00 app[api]: Release v5 created by user nmendez6594@gmail.com
2022-02-13T18:27:38.841499+00:00 app[api]: Deploy 7d112609 by user nmendez6594@gmail.com
2022-02-13T18:27:39.000000+00:00 app[api]: Build succeeded
2022-02-13T18:27:39.104174+00:00 heroku[web.1]: State changed from crashed to starting
2022-02-13T18:27:40.901836+00:00 heroku[web.1]: Starting process with command `npm start`
2022-02-13T18:27:42.058731+00:00 app[web.1]:
2022-02-13T18:27:42.058745+00:00 app[web.1]: > budget-app@1.0.0 start
2022-02-13T18:27:42.058746+00:00 app[web.1]: > node server.js
2022-02-13T18:27:42.058746+00:00 app[web.1]:
2022-02-13T18:27:42.395832+00:00 app[web.1]: App running on port 55680!
2022-02-13T18:27:42.401378+00:00 app[web.1]: /app/node_modules/mongodb/lib/core/uri_parser.js:580
2022-02-13T18:27:42.401379+00:00 app[web.1]: return callback(new MongoParseError('URI malformed, cannot be parsed'));
2022-02-13T18:27:42.401380+00:00 app[web.1]: ^
2022-02-13T18:27:42.401380+00:00 app[web.1]:
2022-02-13T18:27:42.401380+00:00 app[web.1]: MongoParseError: URI malformed, cannot be parsed
2022-02-13T18:27:42.401381+00:00 app[web.1]: at parseConnectionString (/app/node_modules/mongodb/lib/core/uri_parser.js:580:21)
2022-02-13T18:27:42.401381+00:00 app[web.1]: at connect (/app/node_modules/mongodb/lib/operations/connect.js:283:3)
2022-02-13T18:27:42.401382+00:00 app[web.1]: at /app/node_modules/mongodb/lib/mongo_client.js:284:5
2022-02-13T18:27:42.401382+00:00 app[web.1]: at maybePromise (/app/node_modules/mongodb/lib/utils.js:692:3)
2022-02-13T18:27:42.401382+00:00 app[web.1]: at MongoClient.connect (/app/node_modules/mongodb/lib/mongo_client.js:280:10)
2022-02-13T18:27:42.401382+00:00 app[web.1]: at /app/node_modules/mongoose/lib/connection.js:836:12
2022-02-13T18:27:42.401383+00:00 app[web.1]: at new Promise (<anonymous>)
2022-02-13T18:27:42.401383+00:00 app[web.1]: at NativeConnection.Connection.openUri (/app/node_modules/mongoose/lib/connection.js:832:19)
2022-02-13T18:27:42.401384+00:00 app[web.1]: at /app/node_modules/mongoose/lib/index.js:351:10
2022-02-13T18:27:42.401384+00:00 app[web.1]: at /app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:32:5
2022-02-13T18:27:42.401384+00:00 app[web.1]: at new Promise (<anonymous>)
2022-02-13T18:27:42.401384+00:00 app[web.1]: at promiseOrCallback (/app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:10)
2022-02-13T18:27:42.401384+00:00 app[web.1]: at Mongoose._promiseOrCallback (/app/node_modules/mongoose/lib/index.js:1149:10)
2022-02-13T18:27:42.401385+00:00 app[web.1]: at Mongoose.connect (/app/node_modules/mongoose/lib/index.js:350:20)
2022-02-13T18:27:42.401385+00:00 app[web.1]: at Object.<anonymous> (/app/server.js:19:10)
2022-02-13T18:27:42.401385+00:00 app[web.1]: at Module._compile (node:internal/modules/cjs/loader:1103:14)
2022-02-13T18:27:42.521294+00:00 heroku[web.1]: Process exited with status 1
2022-02-13T18:27:42.598710+00:00 heroku[web.1]: State changed from starting to crashed
2022-02-13T18:27:48.281004+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=budget-app-pwa4.herokuapp.com request_id=5de2651b-5f3f-4a1e-84f2-18c0123b8dd7 fwd="32.215.142.46" dyno= connect= service= status=503 bytes= protocol=https
2022-02-13T18:27:49.746492+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=budget-app-pwa4.herokuapp.com request_id=f15d0dc1-7a19-49e1-a743-13f31cac6c31 fwd="32.215.142.46" dyno= connect= service= status=503 bytes= protocol=https

This is my server.js file

const express = require("express");
const logger = require("morgan");
const mongoose = require("mongoose");
const compression = require("compression");

const PORT = process.env.PORT || 3001;
const MONGODB_URI = process.env.MONGODB_URI || "mongodb://localhost/budget";

const app = express();

app.use(logger("dev"));

app.use(compression());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

app.use(express.static("public"));

mongoose.connect(MONGODB_URI, {
  useNewUrlParser: true,
  useFindAndModify: false,
  useUnifiedTopology: true
});

// routes
app.use(require("./routes/api.js"));

app.listen(PORT, () => {
  console.log(`App running on port ${PORT}!`);
});


问:
AWS Application load balancer throwing 502
I am currently learning about AWS and I have a single EC2 instance running with a nodejs server on port 3000, an Application load balancer with SSL setup that listen on port 80 and 443 (http & https). When I make requests to the http route it returns back the successful health check message. But when I try to access my api via the https method, I get a 502 Error. I googled around and read some articles and they pointed out that the nodejs server keepAliveTimeout and headersTimeout should be higher than the timeout option of the ALB. I tried that and it didn't work. I also tried to set the max-http-header-value to 16384, I also tried to check the access logs for the load balancer on my S3 bucket and the logs just showed that I am getting a 502 error and nothing more. What could be the issue? Because I have tried all solutions that presented but they don't seem to work.

答: The 443 listener needs to be pointed to port 80 on the ec2 instance</p>


问:
WCF Service Proxy throws exception when more than one parameter is used in [OperationContract] method
I have a WebServiceHost that is being used to host some web services in a console app. I added a service reference to it in my client app and create the proxy like so:

```<code>var binding = new WebHttpBinding();
var endPoint = new EndpointAddress(string.Format(Settings.serviceBase, Settings.wcfPort));

ChannelFactory<IzWaveSVC> factory = new ChannelFactory<IzWaveSVC>(new WebHttpBinding(), endPoint);

factory.Endpoint.Behaviors.Add(new WebHttpBehavior());
// **Exception occurs here**
var proxy = (IzWaveSVC)factory.CreateChannel();
</code>```

It works, but once I added a new method that requires more than one parameter, I started getting this exception when the proxy was created (this was before any communication even took place):

```<code>Operation 'setDeviceState' of contract 'IzWaveSVC' specifies multiple request
body parameters to be serialized without any wrapper elements. At most one
body parameter can be serialized without wrapper elements. Either remove the
extra body parameters or set the BodyStyle property on the WebGetAttribute /
WebInvokeAttribute to Wrapped.
</code>```

Adding a WebInvokeAttribute and setting the BodyStyle to wrapped has no effect:

```<code>[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped)]
bool setDeviceState(byte nodeId, bool powered, byte level);
</code>```

It should be noted that I have other methods that work, but they only have a single parameter so they don't have the above problem.

Just FYI, here's how I setup the host:

```<code>endPoint = new EndpointAddress(string.Format(Settings.serviceBase, port));
binding = new WebHttpBinding();

host = new WebServiceHost(singletonObject, new Uri(string.Format(Settings.serviceBase, port)));

host.AddServiceEndpoint(typeof(IzWaveSVC), binding, "");
ServiceMetadataBehavior mexBehavior = new ServiceMetadataBehavior();
mexBehavior.HttpGetEnabled = true;
host.Description.Behaviors.Add(mexBehavior);
host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), endPoint.Uri.AbsoluteUri + "mex");
host.Open();
</code>```

Any help is appreciated.

Thanks!

答:
updating tha app.config in the client and setting the defaultBodyStyle as WrappedRequest worked for me, where as removing the webHttp cause other issues.</p>
```<code><behaviors>
  <endpointBehaviors>
    <behavior name="webHttp">
      <webHttp defaultBodyStyle="WrappedRequest"/>
    </behavior>
  </endpointBehaviors>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a WebServiceHost that is being used to host some web services in a console app. I added a service reference to it in my client app and create the proxy like so:

var binding = new WebHttpBinding();
var endPoint = new EndpointAddress(string.Format(Settings.serviceBase, Settings.wcfPort));

ChannelFactory<IzWaveSVC> factory = new ChannelFactory<IzWaveSVC>(new WebHttpBinding(), endPoint);

factory.Endpoint.Behaviors.Add(new WebHttpBehavior());
// **Exception occurs here**
var proxy = (IzWaveSVC)factory.CreateChannel();

It works, but once I added a new method that requires more than one parameter, I started getting this exception when the proxy was created (this was before any communication even took place):

Operation 'setDeviceState' of contract 'IzWaveSVC' specifies multiple request
body parameters to be serialized without any wrapper elements. At most one
body parameter can be serialized without wrapper elements. Either remove the
extra body parameters or set the BodyStyle property on the WebGetAttribute /
WebInvokeAttribute to Wrapped.

Adding a WebInvokeAttribute and setting the BodyStyle to wrapped has no effect:

[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped)]
bool setDeviceState(byte nodeId, bool powered, byte level);

It should be noted that I have other methods that work, but they only have a single parameter so they don't have the above problem.

Just FYI, here's how I setup the host:

endPoint = new EndpointAddress(string.Format(Settings.serviceBase, port));
binding = new WebHttpBinding();

host = new WebServiceHost(singletonObject, new Uri(string.Format(Settings.serviceBase, port)));

host.AddServiceEndpoint(typeof(IzWaveSVC), binding, "");
ServiceMetadataBehavior mexBehavior = new ServiceMetadataBehavior();
mexBehavior.HttpGetEnabled = true;
host.Description.Behaviors.Add(mexBehavior);
host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), endPoint.Uri.AbsoluteUri + "mex");
host.Open();

Any help is appreciated.

Thanks!

Body:
updating tha app.config in the client and setting the defaultBodyStyle as WrappedRequest worked for me, where as removing the webHttp cause other issues.

<behaviors>
  <endpointBehaviors>
    <behavior name="webHttp">
      <webHttp defaultBodyStyle="WrappedRequest"/>
    </behavior>
  </endpointBehaviors>


问:
How to use python socket.settimeout() properly
As far as I know, when you call socket.settimeout(value) and you set a float value greater than 0.0, that socket will raise a scocket.timeout when a call to, for example, socket.recv has to wait longer than the value specified.

But imagine I have to receive a big amount of data, and I have to call recv() several times, then how does settimeout affect that?

Given the following code:

```<code>to_receive = # an integer representing the bytes we want to receive
socket = # a connected socket

socket.settimeout(20)
received = 0
received_data = b""

while received < to_receive:
    tmp = socket.recv(4096)
    if len(tmp) == 0:
        raise Exception()
    received += len(tmp)
    received_data += tmp

socket.settimeout(None)
</code>```

The third line of the code sets the timeout of the socket to 20 seconds. Does that timeout reset every iteration? Will timeout be raised only if one of those iteration takes more than 20 seconds?

A) How can I recode it so that it raises an exception if it is taking more than 20 seconds to receive all the expected data?

B) If I don't set the timeout to None after we read all data, could anything bad happen? (the connection is keep-alive and more data could be requested in the future).

答:
https://docs.python.org/3/library/socket.html#socket.socket.settimeout

"Changed in version 3.5: The socket timeout is no more reset each time data is sent successfully. The socket timeout is now the maximum total duration to send all data."

Body:
As far as I know, when you call socket.settimeout(value) and you set a float value greater than 0.0, that socket will raise a scocket.timeout when a call to, for example, socket.recv has to wait longer than the value specified.

But imagine I have to receive a big amount of data, and I have to call recv() several times, then how does settimeout affect that?

Given the following code:

to_receive = # an integer representing the bytes we want to receive
socket = # a connected socket

socket.settimeout(20)
received = 0
received_data = b""

while received < to_receive:
    tmp = socket.recv(4096)
    if len(tmp) == 0:
        raise Exception()
    received += len(tmp)
    received_data += tmp

socket.settimeout(None)

The third line of the code sets the timeout of the socket to 20 seconds. Does that timeout reset every iteration? Will timeout be raised only if one of those iteration takes more than 20 seconds?

A) How can I recode it so that it raises an exception if it is taking more than 20 seconds to receive all the expected data?

B) If I don't set the timeout to None after we read all data, could anything bad happen? (the connection is keep-alive and more data could be requested in the future).


问:
How to substitute different number of digits behind special character with regex
I have the following kind of string:"§ 9,12,14,15 und 16" or "§ 9,12 und 16".

I want to change the string to:"§ 9, § 12, § 14, § 15 und §16" or "§ 9, § 12 und § 16", respectively.

The number of digits varies and I want a code snipped that is applicable for all length:

```<code>text = "§§ 9,12,14,15 und 16"
text = re.sub(r'§* (\d+),(\d+),(\d+),(\d+) und (\d+)', r'§ \1, § \2, § \3, § \4 und § \5', text)
</code>```

I only manage to match the string if I know the number of digits.

答:
There is no single regex which can do that. What you can do is split your string into parts, and perform a substitution on each.

```<code>text = "§§ 9,12,14,15 und 16"
parts = re.search(r'(§*)\s*((?:\d+,?\s*)+)\s*und\s+(\d+)', text)
if parts:
    sections = parts.group(2)
    text = re.sub(r'(\d+)', r'§\1', parts.group(2)) + ' und §' + parts.group(3)
</code>```

The spacing in your example ends up being a bit irregular but this can be fixed up with some light post-processing.

```<code>text = re.sub(r',(?!\s)', ', ', re.sub('\s+', ' ', text))
</code>```

Body:
I have the following kind of string:"§ 9,12,14,15 und 16" or "§ 9,12 und 16".

I want to change the string to:"§ 9, § 12, § 14, § 15 und §16" or "§ 9, § 12 und § 16", respectively.

The number of digits varies and I want a code snipped that is applicable for all length:

text = "§§ 9,12,14,15 und 16"
text = re.sub(r'§* (\d+),(\d+),(\d+),(\d+) und (\d+)', r'§ \1, § \2, § \3, § \4 und § \5', text)

I only manage to match the string if I know the number of digits.

Body:
There is no single regex which can do that. What you can do is split your string into parts, and perform a substitution on each.

text = "§§ 9,12,14,15 und 16"
parts = re.search(r'(§*)\s*((?:\d+,?\s*)+)\s*und\s+(\d+)', text)
if parts:
    sections = parts.group(2)
    text = re.sub(r'(\d+)', r'§\1', parts.group(2)) + ' und §' + parts.group(3)

The spacing in your example ends up being a bit irregular but this can be fixed up with some light post-processing.

text = re.sub(r',(?!\s)', ', ', re.sub('\s+', ' ', text))


问:
Why does MIN_VERSION_GLASGOW_HASKELL not work in GHC 9.2?
Per GHC guide we expect the MIN_VERSION_GLASGOW_HASKELL(x,y,z,z') CPP to work on the corresponding GHC version. However, the following fails to compile on GHC 9.2

#if MIN_VERSION_GLASGOW_HASKELL(9,2,1,0)
```
<p><img src="https://i.stack.imgur.com/yToVn.png" alt="enter image description here" /></p>
<p>What's happening here?</p>
<hr />
<p>To resolve this, I find myself using:</p>
<pre class="lang-hs prettyprint-override"><code>#if MIN_VERSION_base(4,16,0)
</code>```

But why would MIN_VERSION_GLASGOW_HASKELL not work?

答:
GHC versions consist of a major version, minor version, first patchlevel, and optional second patchlevel.  So GHC 9.2.1 has major 9, minor 2, first patchlevel 1, and no second patch level.

There's a bug in GHC, possibly in existence since the macro MIN_VERSION_GLASGOW_HASKELL was introduced, where that macro depends on a macro variable __GLASGOW_HASKELL_PATCHLEVEL2__ which is not defined when, as is usual for release versions, the GHC version has only one patch level (like 9.2.1).

This usually doesn't matter, except if the -Wcpp-undef flag is in force AND the test is performed on a version that matches on the major, minor, and first patch level.  Then, the check on the second patch level will generate a compiler warning message.  (Despite the fact that it looks like an "error" rather than a warning, the compilation appears to complete.)

You can work around this by:

ignoring it -- despite appearances, it looks like it's only a warning, not an error, and compilation should complete

shutting off -Wcpp-undef by either removing the flag or, if feasible, adding a -Wno-cpp-undef flag;

adding some code to define the missing patchlevel before calling the macro:

```<code> #ifndef __GLASGOW_HASKELL_PATCHLEVEL2__
 #define __GLASGOW_HASKELL_PATCHLEVEL2__ 0
 #endif
</code>```

Body:
Per GHC guide we expect the MIN_VERSION_GLASGOW_HASKELL(x,y,z,z') CPP to work on the corresponding GHC version. However, the following fails to compile on GHC 9.2

#if MIN_VERSION_GLASGOW_HASKELL(9,2,1,0)

What's happening here?

To resolve this, I find myself using:

#if MIN_VERSION_base(4,16,0)

But why would MIN_VERSION_GLASGOW_HASKELL not work?

Body:
GHC versions consist of a major version, minor version, first patchlevel, and optional second patchlevel.  So GHC 9.2.1 has major 9, minor 2, first patchlevel 1, and no second patch level.

There's a bug in GHC, possibly in existence since the macro MIN_VERSION_GLASGOW_HASKELL was introduced, where that macro depends on a macro variable __GLASGOW_HASKELL_PATCHLEVEL2__ which is not defined when, as is usual for release versions, the GHC version has only one patch level (like 9.2.1).

This usually doesn't matter, except if the -Wcpp-undef flag is in force AND the test is performed on a version that matches on the major, minor, and first patch level.  Then, the check on the second patch level will generate a compiler warning message.  (Despite the fact that it looks like an "error" rather than a warning, the compilation appears to complete.)

You can work around this by:

ignoring it -- despite appearances, it looks like it's only a warning, not an error, and compilation should complete

shutting off -Wcpp-undef by either removing the flag or, if feasible, adding a -Wno-cpp-undef flag;

adding some code to define the missing patchlevel before calling the macro:

 #ifndef __GLASGOW_HASKELL_PATCHLEVEL2__
 #define __GLASGOW_HASKELL_PATCHLEVEL2__ 0
 #endif