问:
Shell split string and convert it to json objects format
I have a string in this format:

```<code>string= "[one,two,three,four,five]"
</code>```

I want to convert it to json format likely, without using any specific tool (jq or other) , I want to do it with pure shell:

```<code>[
{"id" : 0 , "word": "one"} ,
{"id" : 1 , "word": "two"} ,
{"id" : 2 , "word": "three"} ,
{"id" : 3 , "word": "four"} ,
{"id" : 4 , "word": "five"}
]
</code>```

Suggestions ?

答:
This may be still tedious but how about:

```<code>string="[one,two,three,four,five]"

out=$(while read -r -d, i; do
    printf '{"id" : %d , "word": "%s"},\n' "$((c++))" "${i%]}"
done <<< "${string#[},")
printf "[\n%s\n]\n" "${out%,}"
</code>```

Output:

```<code>[
{"id" : 0 , "word": "one"},
{"id" : 1 , "word": "two"},
{"id" : 2 , "word": "three"},
{"id" : 3 , "word": "four"},
{"id" : 4 , "word": "five"}
]
</code>```

Body:
I have a string in this format:

string= "[one,two,three,four,five]"

I want to convert it to json format likely, without using any specific tool (jq or other) , I want to do it with pure shell:

[
{"id" : 0 , "word": "one"} ,
{"id" : 1 , "word": "two"} ,
{"id" : 2 , "word": "three"} ,
{"id" : 3 , "word": "four"} ,
{"id" : 4 , "word": "five"}
]

Suggestions ?

Body:
This may be still tedious but how about:

string="[one,two,three,four,five]"

out=$(while read -r -d, i; do
    printf '{"id" : %d , "word": "%s"},\n' "$((c++))" "${i%]}"
done <<< "${string#[},")
printf "[\n%s\n]\n" "${out%,}"

Output:

[
{"id" : 0 , "word": "one"},
{"id" : 1 , "word": "two"},
{"id" : 2 , "word": "three"},
{"id" : 3 , "word": "four"},
{"id" : 4 , "word": "five"}
]


来源: stackexchange

问:
Javascript: indexOf() & substr() not returning expected result on date string
In the image you will see the value being passed in and all the string functions I tried, but nothing seems to be working. I even tried putting it into a variable via new Date(d), but got "Invalid Date". I also tried using trim(). If I hard-coded a date string as the value for "d" then everything functioned as expected.
Can someone let me know what I am doing wrong?
Image: JS console.log of values

```<code>function convertDate2ISO(dateToConvert){
    var strDate = dateToConvert.trim();
    if (dateToConvert.indexOf("-") > 0) { strDate = dateToConvert.replace(/-/g, ' ');}

    if (dateToConvert.indexOf("/") > 0) {
        var substrValue = dateToConvert.substr(0,3);
        var indexOfValue = dateToConvert.indexOf('/');
        var toStringIndexOfValue = dateToConvert.toString().indexOf('/');
        var sliceValue = dateToConvert.slice(0,2);
        console.log("Incoming value (dateToConvert): " + dateToConvert + "\r\n" + "Using dateToConvert.substr(0,3): " +substrValue+ "\r\nUsing dateToConvert.indexOf('/'): " +indexOfValue+ "\r\nUsing dateToConvert.toString().indexOf('/'): " +toStringIndexOfValue+ "\r\nUsing dateToConvert.slice(0,2): " +sliceValue+ "\r\nUsing dateToConvert.length: " +dateToConvert.length );
        //was trying to use dateToConvert.indexOf('/') to test on, but result was unexpected
        //add 0 to begining if month is a singel digit
        strDate = "0" + strDate;
    }

    var myDate = new Date(strDate);
    myDate.toISOString(); //"2011-23-12T15:28:46.493Z
    return myDate
}
</code>```

The default for the incoming parameter is...

```<code>var myDateObj = new Date();
var strDTGReceived = myDateObj.toLocaleDateString();
</code>```

The call to the function is...

```<code>var dtISOReceivedDate = convertDate2ISO(strDTGReceived);
</code>```

Values I am getting are...

```<code>Incoming Parameter (dateToConvert): 2/18/2020
Using dateToConvert.substr(0,3): 2
dateToConvert.indexOf('/'): 3
Using dateToConvert.toString().indexOf('/'): 3
Using dateToConvert.slice(0,2): 2
Using dateToConvert.length: 14
</code>```

答:
function convertDate( d ) {
        var myDate = new Date( d );
            if( "" + myDate == "Invalid Date" )return console.info("Invalid Date Format!");
        return myDate.toISOString();
    }

     console.log('Result: ' + convertDate('2m18d2020'));
     console.log('Result: ' + convertDate('2/18/2020'));
     console.log('Result: ' + convertDate('2 18 2020'));
     console.log('Result: ' + convertDate('2-18-2020'));
     console.log('Result: ' + convertDate('2.18.2020'));```
</div>
</div>
</p>

<p>You should always try to keep things as simple as possible.</p>

```function convertDate( d ) {
    var myDate = new Date( d );
        if( "" + myDate == "Invalid Date" )return console.info("Invalid Date Format!");
    return myDate.toISOString();
}
```

This approach will accept any useful date literal and will not be limited only to "/"and "-", but will be able to accept all of the commonly used separators: white-space, comma, dot, included.

ContentLicense: CC BY-SA 4.0

Body:
In the image you will see the value being passed in and all the string functions I tried, but nothing seems to be working. I even tried putting it into a variable via new Date(d), but got "Invalid Date". I also tried using trim(). If I hard-coded a date string as the value for "d" then everything functioned as expected.
Can someone let me know what I am doing wrong?
Image: JS console.log of values

function convertDate2ISO(dateToConvert){
    var strDate = dateToConvert.trim();
    if (dateToConvert.indexOf("-") > 0) { strDate = dateToConvert.replace(/-/g, ' ');}

    if (dateToConvert.indexOf("/") > 0) {
        var substrValue = dateToConvert.substr(0,3);
        var indexOfValue = dateToConvert.indexOf('/');
        var toStringIndexOfValue = dateToConvert.toString().indexOf('/');
        var sliceValue = dateToConvert.slice(0,2);
        console.log("Incoming value (dateToConvert): " + dateToConvert + "\r\n" + "Using dateToConvert.substr(0,3): " +substrValue+ "\r\nUsing dateToConvert.indexOf('/'): " +indexOfValue+ "\r\nUsing dateToConvert.toString().indexOf('/'): " +toStringIndexOfValue+ "\r\nUsing dateToConvert.slice(0,2): " +sliceValue+ "\r\nUsing dateToConvert.length: " +dateToConvert.length );
        //was trying to use dateToConvert.indexOf('/') to test on, but result was unexpected
        //add 0 to begining if month is a singel digit
        strDate = "0" + strDate;
    }

    var myDate = new Date(strDate);
    myDate.toISOString(); //"2011-23-12T15:28:46.493Z
    return myDate
}

The default for the incoming parameter is...

var myDateObj = new Date();
var strDTGReceived = myDateObj.toLocaleDateString();

The call to the function is...

var dtISOReceivedDate = convertDate2ISO(strDTGReceived);

Values I am getting are...

Incoming Parameter (dateToConvert): 2/18/2020
Using dateToConvert.substr(0,3): 2
dateToConvert.indexOf('/'): 3
Using dateToConvert.toString().indexOf('/'): 3
Using dateToConvert.slice(0,2): 2
Using dateToConvert.length: 14

Body:
function convertDate( d ) {
        var myDate = new Date( d );
            if( "" + myDate == "Invalid Date" )return console.info("Invalid Date Format!");
        return myDate.toISOString();
    }

     console.log('Result: ' + convertDate('2m18d2020'));
     console.log('Result: ' + convertDate('2/18/2020'));
     console.log('Result: ' + convertDate('2 18 2020'));
     console.log('Result: ' + convertDate('2-18-2020'));
     console.log('Result: ' + convertDate('2.18.2020'));

You should always try to keep things as simple as possible.

function convertDate( d ) {
    var myDate = new Date( d );
        if( "" + myDate == "Invalid Date" )return console.info("Invalid Date Format!");
    return myDate.toISOString();
}

This approach will accept any useful date literal and will not be limited only to "/"and "-", but will be able to accept all of the commonly used separators: white-space, comma, dot, included.


问:
Passing helper variables to dataclass __init__ without assigning them
I have a root-level config class that I pass throughout my codebase through dependency injection.

Problem is, I have this dataclass that needs some attributes from this config to calculate a value world_coords in __post_init__().

In order to keep my tests clean and to circumvent other test import issues (not discussed here), I want to be able to pass in the config directly to this object instead of reading these values from an import. If I structure the config as an argument, however, it becomes an attribute of the dataclass, which I'm trying to avoid. There isn't really a need for RoadSegmentNode to hold on to a reference of the config once used.

Here's the basic structure of the class:

```<code>@dataclass(eq=True, frozen=True)  # make hashable
class RoadSegmentNode:

    tile_index: Tuple[int, int]  # (r, c)
    dir: Direction
    node_type: RoadNodeType
    world_coords: Tuple[int, int] = field(init=False)

    def __post_init__(self):

        # (Use config variables here, e.g. `config.TILE_WIDTH`, to calculate x and y)

        # Hack to get around frozen=True. We don't care that we're mutating
        # an "immutable" object on __init__().
        object.__setattr__(self, "world_coords", (x, y))
</code>```

Here's the stopgap I went with to keep with the dependency injection model to unblock my tests for now. Note how RoadSegmentNode now has a bunch of new attributes that would only use for initialization. It's a little better than keeping a reference to the config, because at least they're explicit, but it's still a pretty poor design.

```<code>@dataclass(eq=True, frozen=True)  # make hashable
class RoadSegmentNode:

    # NOTE: DO NOT ACCESS THESE ATTRIBUTES!
    grid_width: int
    grid_height: int
    tile_width: int
    tile_height: int
    road_width: int

    tile_index: Tuple[int, int]  # (r, c)
    dir: Direction
    node_type: RoadNodeType
    world_coords: Tuple[int, int] = field(init=False)

    def __post_init__(self):

        # (Use attributes here, e.g. `self.tile_width`, to calculate x and y)

        # Hack to get around frozen=True. We don't care that we're mutating
        # an "immutable" object on __init__().
        object.__setattr__(self, "world_coords", (x, y))
</code>```

How can I pass the config to the dataclass for initialization without making it an attribute of the dataclass? Should I even be considering a dataclass for this use case? I believe the original intention was to keep all instances immutable, but I can't confirm.

答:
You should define config as an init-only variable. This way it'll be passed to __post_init__(), but will disappear after that:

from dataclasses import dataclass, field, InitVar

@dataclass(eq=True, frozen=True)
class RoadSegmentNode:

    tile_index: Tuple[int, int]
    dir: Direction
    node_type: RoadNodeType
    world_coords: Tuple[int, int] = field(init=False)
    config: InitVar[Config]  # will not appear in instances

    def __post_init__(self, config):
        x, y = ..., ...  # calculate using config

        # looks hacky for sure, but is the right way to work with frozen dataclasses
        object.__setattr__(self, "world_coords", (x, y))
```

Body:
I have a root-level config class that I pass throughout my codebase through dependency injection.

Problem is, I have this dataclass that needs some attributes from this config to calculate a value world_coords in __post_init__().

In order to keep my tests clean and to circumvent other test import issues (not discussed here), I want to be able to pass in the config directly to this object instead of reading these values from an import. If I structure the config as an argument, however, it becomes an attribute of the dataclass, which I'm trying to avoid. There isn't really a need for RoadSegmentNode to hold on to a reference of the config once used.

Here's the basic structure of the class:

@dataclass(eq=True, frozen=True)  # make hashable
class RoadSegmentNode:

    tile_index: Tuple[int, int]  # (r, c)
    dir: Direction
    node_type: RoadNodeType
    world_coords: Tuple[int, int] = field(init=False)

    def __post_init__(self):

        # (Use config variables here, e.g. `config.TILE_WIDTH`, to calculate x and y)

        # Hack to get around frozen=True. We don't care that we're mutating
        # an "immutable" object on __init__().
        object.__setattr__(self, "world_coords", (x, y))

Here's the stopgap I went with to keep with the dependency injection model to unblock my tests for now. Note how RoadSegmentNode now has a bunch of new attributes that would only use for initialization. It's a little better than keeping a reference to the config, because at least they're explicit, but it's still a pretty poor design.

@dataclass(eq=True, frozen=True)  # make hashable
class RoadSegmentNode:

    # NOTE: DO NOT ACCESS THESE ATTRIBUTES!
    grid_width: int
    grid_height: int
    tile_width: int
    tile_height: int
    road_width: int

    tile_index: Tuple[int, int]  # (r, c)
    dir: Direction
    node_type: RoadNodeType
    world_coords: Tuple[int, int] = field(init=False)

    def __post_init__(self):

        # (Use attributes here, e.g. `self.tile_width`, to calculate x and y)

        # Hack to get around frozen=True. We don't care that we're mutating
        # an "immutable" object on __init__().
        object.__setattr__(self, "world_coords", (x, y))

How can I pass the config to the dataclass for initialization without making it an attribute of the dataclass? Should I even be considering a dataclass for this use case? I believe the original intention was to keep all instances immutable, but I can't confirm.


问:
How can i format the date into specified format which comes from db in <g:select>
I need to have a dropdown which holds dates.

when i write

```<code><g:select id="dob" name="dob" from="${Person.list().dateOfBirth}"  value="${personInstance?.dateOfBirth}" />
</code>```

this displays the date in the format 2011-05-17 00:00:00.0 But i need to have the format mm/dd/yyyy.

How can i do that?

答:
Does this work?</p>

```<code><g:set var="sdf" value="${new java.text.SimpleDateFormat('MM/dd/yyyy')}"/>
<g:select from="${Person.list()}" name="dob" optionValue="${{sdf.format(it.dateOfBirth)}}" optionKey="${{sdf.format(it.dateOfBirth)}}"/>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to have a dropdown which holds dates.

when i write

<g:select id="dob" name="dob" from="${Person.list().dateOfBirth}"  value="${personInstance?.dateOfBirth}" />

this displays the date in the format 2011-05-17 00:00:00.0 But i need to have the format mm/dd/yyyy.

How can i do that?

Body:
Does this work?

<g:set var="sdf" value="${new java.text.SimpleDateFormat('MM/dd/yyyy')}"/>
<g:select from="${Person.list()}" name="dob" optionValue="${{sdf.format(it.dateOfBirth)}}" optionKey="${{sdf.format(it.dateOfBirth)}}"/>


问:
Undefined method mysqli_result, stuck in this error
I'm trying to learn PHP, AJAX, JS, etc.
I am trying to make a sales system, I am following some tutorial videos step by step, but I am stuck in this error and I am not able to solve on my own.

This is the error that appears to me:

Fatal error: Uncaught Error: Call to undefined method mysqli_result::fetch_objet() in C:\xampp\htdocs\sistema\ajax\categoria.php:45 Stack trace: #0 {main} thrown in C:\xampp\htdocs\sistema\ajax\categoria.php on line 45

This is my code:

```<code>    case 'listar':
    $rspta=$categoria->listar();
    $data= Array();

    while($reg=$rspta->fetch_objet())
    {
        $data[]=array(
            "0"=>$reg->idcategoria,
            "1"=>$reg->nombre,
            "2"=>$reg->descripcion,
            "3"=>$reg->condicion
            );
    }
    $results = array(
        "sEcho"=>1, //Information for Datatable
        "iTotalRecords"=>count($data), //send the total records to the datatable
        "iTotalDisplayRecords"=>count($data), // send the total records to the datatable to show
        "aaData"=>$data);
    echo json_encode($results);
</code>```

My 45 line is: while($reg=$rspta->fetch_objet())

I'm almost sure I wrote it well, I checked it many times

Sorry i don't have the best english

答: Looks like you misspelt “object”, missing the “c”.</p>

Body:
I'm trying to learn PHP, AJAX, JS, etc.
I am trying to make a sales system, I am following some tutorial videos step by step, but I am stuck in this error and I am not able to solve on my own.

This is the error that appears to me:

Fatal error: Uncaught Error: Call to undefined method mysqli_result::fetch_objet() in C:\xampp\htdocs\sistema\ajax\categoria.php:45 Stack trace: #0 {main} thrown in C:\xampp\htdocs\sistema\ajax\categoria.php on line 45

This is my code:

    case 'listar':
    $rspta=$categoria->listar();
    $data= Array();

    while($reg=$rspta->fetch_objet())
    {
        $data[]=array(
            "0"=>$reg->idcategoria,
            "1"=>$reg->nombre,
            "2"=>$reg->descripcion,
            "3"=>$reg->condicion
            );
    }
    $results = array(
        "sEcho"=>1, //Information for Datatable
        "iTotalRecords"=>count($data), //send the total records to the datatable
        "iTotalDisplayRecords"=>count($data), // send the total records to the datatable to show
        "aaData"=>$data);
    echo json_encode($results);

My 45 line is: while($reg=$rspta->fetch_objet())

I'm almost sure I wrote it well, I checked it many times

Sorry i don't have the best english


问:
Frozen on "Opening STARTTLS connection to ‘smtp.qq.com:587’...done"
I referenced the answer to question sending-emails-with-emacs24-via-smtp-with-gnutls-and-extra-arguments

and set my config as

```<code>(setq user-mail-address "abst.proc.do@qq.com")
(setq user-full-name "abst.proc.do")

(require 'smtpmail)
(require 'starttls)

(setq message-send-mail-function 'smtpmail-send-it)
(defun gnutls-available-p ()
  "Function redefined in order not to use built-in GnuTLS support"
  nil)
(setq starttls-gnutls-program "gnutls-cli")
(setq starttls-use-gnutls t)
(setq smtpmail-stream-type 'starttls)
(setq smtpmail-smtp-server "smtp.qq.com")
(setq smtpmail-smtp-service 587) ;;587(starttls) or 465(tls/ssl)
(setq starttls-extra-arguments '("--priority" "NORMAL:%COMPAT"))
</code>```

Then try to send a testing mail as

```<code>From: abst.proc.do@qq.com (abst.proc.do)
To: abst.proc.do@qq.com
Subject: Testing
Date: Thu, 23 Jan 2020 07:11:44 +0800
Message-ID: <877e1j2ij3.fsf@qq.com>
--text follows this line--
Testing
</code>```

It freeze in the minibuffer with prompt

```<code>Opening STARTTLS connection to ‘smtp.qq.com:587’...done
</code>```

and got a messages

```<code> Saving file /home/me/*message*-20200123-071130...
</code>```

the mail was not sent.

The appreciate stmp service was checked and token placed in .authinfo

What's the problem with my configuration?

Machine: Ubuntu 19.10 Emacs 26.3

The error trace:

```<code>220 newxmesmtplogicsvrszc2.qq.com XMail Esmtp QQ Mail Server.
250-newxmesmtplogicsvrszc2.qq.com
250-PIPELINING
250-SIZE 73400320
250-STARTTLS
250-AUTH LOGIN PLAIN
250-AUTH=LOGIN
250-MAILCOMPRESS
250 8BITMIME

Process smtpmail deleted
220 newxmesmtplogicsvrsza3.qq.com XMail Esmtp QQ Mail Server.
250-newxmesmtplogicsvrsza3.qq.com
250-PIPELINING
250-SIZE 73400320
250-STARTTLS
250-AUTH LOGIN PLAIN
250-AUTH=LOGIN
250-MAILCOMPRESS
250 8BITMIME
220 Ready to start TLS from 106.39.174.180 to newxmesmtplogicsvrsza3.qq.com.
*** Starting TLS handshake
- Certificate type: X.509
- Got a certificate list of 3 certificates.
- Certificate[0] info:
 - subject `CN=*.mail.qq.com,O=Tencent Technology (Shenzhen) Company Limited,L=shenzhen,ST=guangdong,C=CN', issuer `CN=GlobalSign Organization Validation CA - SHA256 - G2,O=GlobalSign nv-sa,C=BE', serial 0x41110235e23a37f3ead2dc5e, RSA key 2048 bits, signed using RSA-SHA256, activated `2019-11-11 10:32:16 UTC', expires `2020-06-03 04:00:33 UTC', pin-sha256="3gHtBaJCDCS2wo6ho7kKEE6rUA1YXM3A6R1XiFejm48="
    Public Key ID:
        sha1:5df67c6c87174f49828307072b0922d6da77cab0
        sha256:de01ed05a2420c24b6c28ea1a3b90a104eab500d585ccdc0e91d578857a39b8f
    Public Key PIN:
        pin-sha256:3gHtBaJCDCS2wo6ho7kKEE6rUA1YXM3A6R1XiFejm48=

- Certificate[1] info:
 - subject `CN=GlobalSign Organization Validation CA - SHA256 - G2,O=GlobalSign nv-sa,C=BE', issuer `CN=GlobalSign Root CA,OU=Root CA,O=GlobalSign nv-sa,C=BE', serial 0x040000000001444ef04247, RSA key 2048 bits, signed using RSA-SHA256, activated `2014-02-20 10:00:00 UTC', expires `2024-02-20 10:00:00 UTC', pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4="
- Certificate[2] info:
 - subject `CN=GlobalSign Root CA,OU=Root CA,O=GlobalSign nv-sa,C=BE', issuer `CN=GlobalSign Root CA,OU=Root CA,O=GlobalSign nv-sa,C=BE', serial 0x040000000001154b5ac394, RSA key 2048 bits, signed using RSA-SHA1 (broken!), activated `1998-09-01 12:00:00 UTC', expires `2028-01-28 12:00:00 UTC', pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="
- Status: The certificate is trusted.
- Description: (TLS1.2)-(ECDHE-SECP256R1)-(RSA-SHA512)-(AES-128-GCM)
- Session ID: CB:34:DB:07:B8:3D:32:D8:13:BD:9B:4E:6B:5D:0A:72:1A:85:83:20:68:BB:70:8A:5A:43:15:51:3E:7D:19:BD
- Options: safe renegotiation,
</code>```

答:
I have had a number of ongoing problems with starttls, i.e. open-tls-stream, when it is using openssl in Emacs -- it is extremely hard to debug, and upgrading either emacs or openssl can cause connections to hang as you have observed -- and this usually happens far enough apart to allow one to completely forget that it happened before and how to debug and fix it again.

I've changed the definition of tls-end-of-info to solve this:

;; xxx gnutls-cli is broken, at least when used with emacs-23.3
;; (xxx "-no_ssl2" might still be required for older openssl?)
;; n.b. the "-crlf" is now necessary for Gmail, but not Cyrus
;;
(setq tls-program '("openssl s_client -connect %h:%p -ign_eof"))

(setq starttls-use-gnutls nil)  ; XXX requires security/starttls be installed!!!
;;
;; XXX as of OpenSSL 1.1.1a  20 Nov 2018 there's a new ending to the noise
;; c_client prints before real data starts.
;;
;; (XXX debugging this was HARD!  No clues -- emacs just "hung" without responding)
;;
(setq tls-end-of-info
      "\\(^\s*Verify return code: .+
---
\\|^    Extended master secret: .+
---
\\|^- Simple Client Mode:
\\(
\\|^\\*\\*\\* Starting TLS handshake
\\)*\\)")
```

To help with the debugging I use a slightly hacked up version of open-tls-stream.  You can find it all at my ~/.emacs.el file

Body:
I referenced the answer to question sending-emails-with-emacs24-via-smtp-with-gnutls-and-extra-arguments

and set my config as

(setq user-mail-address "abst.proc.do@qq.com")
(setq user-full-name "abst.proc.do")

(require 'smtpmail)
(require 'starttls)

(setq message-send-mail-function 'smtpmail-send-it)
(defun gnutls-available-p ()
  "Function redefined in order not to use built-in GnuTLS support"
  nil)
(setq starttls-gnutls-program "gnutls-cli")
(setq starttls-use-gnutls t)
(setq smtpmail-stream-type 'starttls)
(setq smtpmail-smtp-server "smtp.qq.com")
(setq smtpmail-smtp-service 587) ;;587(starttls) or 465(tls/ssl)
(setq starttls-extra-arguments '("--priority" "NORMAL:%COMPAT"))

Then try to send a testing mail as

From: abst.proc.do@qq.com (abst.proc.do)
To: abst.proc.do@qq.com
Subject: Testing
Date: Thu, 23 Jan 2020 07:11:44 +0800
Message-ID: <877e1j2ij3.fsf@qq.com>
--text follows this line--
Testing

It freeze in the minibuffer with prompt

Opening STARTTLS connection to ‘smtp.qq.com:587’...done

and got a messages

 Saving file /home/me/*message*-20200123-071130...

the mail was not sent.

The appreciate stmp service was checked and token placed in .authinfo

What's the problem with my configuration?

Machine: Ubuntu 19.10 Emacs 26.3

The error trace:

220 newxmesmtplogicsvrszc2.qq.com XMail Esmtp QQ Mail Server.
250-newxmesmtplogicsvrszc2.qq.com
250-PIPELINING
250-SIZE 73400320
250-STARTTLS
250-AUTH LOGIN PLAIN
250-AUTH=LOGIN
250-MAILCOMPRESS
250 8BITMIME

Process smtpmail deleted
220 newxmesmtplogicsvrsza3.qq.com XMail Esmtp QQ Mail Server.
250-newxmesmtplogicsvrsza3.qq.com
250-PIPELINING
250-SIZE 73400320
250-STARTTLS
250-AUTH LOGIN PLAIN
250-AUTH=LOGIN
250-MAILCOMPRESS
250 8BITMIME
220 Ready to start TLS from 106.39.174.180 to newxmesmtplogicsvrsza3.qq.com.
*** Starting TLS handshake
- Certificate type: X.509
- Got a certificate list of 3 certificates.
- Certificate[0] info:
 - subject `CN=*.mail.qq.com,O=Tencent Technology (Shenzhen) Company Limited,L=shenzhen,ST=guangdong,C=CN', issuer `CN=GlobalSign Organization Validation CA - SHA256 - G2,O=GlobalSign nv-sa,C=BE', serial 0x41110235e23a37f3ead2dc5e, RSA key 2048 bits, signed using RSA-SHA256, activated `2019-11-11 10:32:16 UTC', expires `2020-06-03 04:00:33 UTC', pin-sha256="3gHtBaJCDCS2wo6ho7kKEE6rUA1YXM3A6R1XiFejm48="
    Public Key ID:
        sha1:5df67c6c87174f49828307072b0922d6da77cab0
        sha256:de01ed05a2420c24b6c28ea1a3b90a104eab500d585ccdc0e91d578857a39b8f
    Public Key PIN:
        pin-sha256:3gHtBaJCDCS2wo6ho7kKEE6rUA1YXM3A6R1XiFejm48=

- Certificate[1] info:
 - subject `CN=GlobalSign Organization Validation CA - SHA256 - G2,O=GlobalSign nv-sa,C=BE', issuer `CN=GlobalSign Root CA,OU=Root CA,O=GlobalSign nv-sa,C=BE', serial 0x040000000001444ef04247, RSA key 2048 bits, signed using RSA-SHA256, activated `2014-02-20 10:00:00 UTC', expires `2024-02-20 10:00:00 UTC', pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4="
- Certificate[2] info:
 - subject `CN=GlobalSign Root CA,OU=Root CA,O=GlobalSign nv-sa,C=BE', issuer `CN=GlobalSign Root CA,OU=Root CA,O=GlobalSign nv-sa,C=BE', serial 0x040000000001154b5ac394, RSA key 2048 bits, signed using RSA-SHA1 (broken!), activated `1998-09-01 12:00:00 UTC', expires `2028-01-28 12:00:00 UTC', pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="
- Status: The certificate is trusted.
- Description: (TLS1.2)-(ECDHE-SECP256R1)-(RSA-SHA512)-(AES-128-GCM)
- Session ID: CB:34:DB:07:B8:3D:32:D8:13:BD:9B:4E:6B:5D:0A:72:1A:85:83:20:68:BB:70:8A:5A:43:15:51:3E:7D:19:BD
- Options: safe renegotiation,

Body:
I have had a number of ongoing problems with starttls, i.e. open-tls-stream, when it is using openssl in Emacs -- it is extremely hard to debug, and upgrading either emacs or openssl can cause connections to hang as you have observed -- and this usually happens far enough apart to allow one to completely forget that it happened before and how to debug and fix it again.

I've changed the definition of tls-end-of-info to solve this:

;; xxx gnutls-cli is broken, at least when used with emacs-23.3
;; (xxx "-no_ssl2" might still be required for older openssl?)
;; n.b. the "-crlf" is now necessary for Gmail, but not Cyrus
;;
(setq tls-program '("openssl s_client -connect %h:%p -ign_eof"))

(setq starttls-use-gnutls nil)  ; XXX requires security/starttls be installed!!!
;;
;; XXX as of OpenSSL 1.1.1a  20 Nov 2018 there's a new ending to the noise
;; c_client prints before real data starts.
;;
;; (XXX debugging this was HARD!  No clues -- emacs just "hung" without responding)
;;
(setq tls-end-of-info
      "\\(^\s*Verify return code: .+
---
\\|^    Extended master secret: .+
---
\\|^- Simple Client Mode:
\\(
\\|^\\*\\*\\* Starting TLS handshake
\\)*\\)")

To help with the debugging I use a slightly hacked up version of open-tls-stream.  You can find it all at my ~/.emacs.el file


问:
Id is added but not removed
When I click on the code button <> a second id is correctly added, but when I click on the code button again <> the new added id is not removed, so how can I remove the added id, since I have tried some alternatives and They don't work for me.

What I try to do is delete the following id newID

```<code>if (codeMode) {
    var formattedHtml = formatHtmlCode(htmlDiv.html());
    htmlDiv.css("white-space", "normal"); //pre
    htmlDiv.text(formattedHtml);
    var editor = $("#editor");
    editor.addClass("black-bg-colr codeMode");
    editor.attr('id', 'editor newID');
} else {
    htmlDiv.css("white-space", "normal");
    htmlDiv.html(htmlDiv.text().replace(/\r?\n|\r/g, ""));
    var editor = $("#editor");
    editor.removeClass("black-bg-colr codeMode");
    //editor.attr('id', 'editor');
    //$('div#newID').removeAttr('id');
    //editor.removeAttr( "newID" )
}
</code>```

Snippet:

 $(function() {
  function formatHtmlCode(str) {
   var div = document.createElement('div');
   div.innerHTML = str.trim();
   return format(div, 0).innerHTML;
  }
  function format(node, level) {
   var indentBefore = new Array(level++ + 1).join('  '),
   indentAfter = new Array(level - 1).join('  '),
   textNode;
   for (var i = 0; i < node.children.length; i++) {
    textNode = document.createTextNode('\n' + indentBefore);
    node.insertBefore(textNode, node.children[i]);
    format(node.children[i], level);
    if (node.lastElementChild == node.children[i]) {
     textNode = document.createTextNode('\n' + indentAfter);
     node.appendChild(textNode);
    }
   }
   return node;
  }
  $('#editControls a').click(function(e) {
   switch ($(this).data('role')) {
    case 'p':
     document.execCommand('formatBlock', false, $(this).data('role'));
     break;
    case 'code':
     codeMode = !codeMode;
     if (codeMode) {
      var formattedHtml = formatHtmlCode(htmlDiv.html());
      htmlDiv.css("white-space", "normal"); //pre
      htmlDiv.text(formattedHtml);
      var editor = $("#editor");
      editor.addClass("black-bg-colr codeMode");
      editor.attr('id', 'editor newID');
     } else {
      htmlDiv.css("white-space", "normal");
      htmlDiv.html(htmlDiv.text().replace(/\r?\n|\r/g, ""));
      var editor = $("#editor");
      editor.removeClass("black-bg-colr codeMode");
      //editor.attr('id', 'editor');
            //$('div#newID').removeAttr('id');
            //editor.removeAttr( "newID" )
     }
     break;
    default:
     document.execCommand($(this).data('role'), false, null);
     break;
   }
  });

  let codeMode = false;
  let htmlDiv = $("#editor");
  htmlDiv.on('keyup', function(e) {
   if (!e.shiftKey && e.keyCode === 13) {
    document.execCommand('formatBlock', false, 'p');
   } else if (e.shiftKey) {
    document.execCommand('formatBlock', false, 'div');
   }
  });

  htmlDiv.on("paste", function(e) {
   e.preventDefault();
   var text = (e.originalEvent || e).clipboardData.getData('text/plain');
   document.execCommand('formatBlock', false, 'div');
   document.execCommand('insertText', false, text);
  });

  htmlDiv.on("input", function(e) {
   $(".editor-preview").val(htmlDiv.html());
   $(".editor-preview").keyup();
  });

  $('.editor-preview').keyup(function() {
   var contentAttr = $(this).attr('class');
   if (!codeMode) {
    var value = $(this).val();
    $('.' + contentAttr).html(value);
   } else {
    $('.' + contentAttr).html(htmlDiv.text());
   }
  });

 });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#editControls {
    overflow: auto;
    border-top: 1px solid transparent;
    border-left: 1px solid transparent;
    border-right: 1px solid transparent;
    border-color: silver;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
    padding: .5em 1em .5em 1em;
    background-color: #fbfbfb;
    margin: 0 auto;
    width: 100%; /*90*/
}
#editor {
    resize: vertical;
    overflow: auto;
    border: 1px solid silver;
    border-bottom-right-radius: 5px;
    border-bottom-left-radius: 5px;
    min-height: 100px;
    padding: 1em;
    background: white;
    margin: 0 auto;
    width: 100%;/*90*/
}
#editor:focus {
    outline: none !important;
    box-shadow: inset 0 0 2px silver;
}
.codeMode {
    font-family:Courier New,Source Code Pro Light,Medium,Source Code Pro ExtraLight,Menlo,Consola,Monaco Linux,Consola Regular,Fira Code Regular,DejaVu Sans Mono;
    /*font-family: inherit;*/
    /*font-family: 'Courier New';*/
    border: 0px;
    font-style: inherit;
    font-variant: inherit;
    font-weight: inherit;
    font-stretch: inherit;
    line-height: inherit;
    vertical-align: baseline;
    box-sizing: inherit;
    color: #fff;
}
.black-bg-colr {
  background-color: #000 !important;
}
.btn-group {
    position: relative;
    display: inline-block;
    font-size: 0;
    vertical-align: middle;
    white-space: nowrap;
}
.btn-group+.btn-group {
    margin-left: 5px;
}
.btn-group a {
    text-decoration: none;
}
.btn-editor {
    height: 30px;
    display: inline-block;
    padding: 6px 12px;
    margin-bottom: 0;
    font-size: 11px;
    font-weight: normal;
    line-height: 1.42857143;
    text-align: center;
    white-space: nowrap;
    vertical-align: middle;
    -ms-touch-action: manipulation;
    touch-action: manipulation;
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    background-image: none;
    border-radius: 4px;
    border: 1px solid transparent;
    color: #333;
    background-color: #fff;
    border-color: #ccc;
}
.btn-group>.btn-editor:first-child {
    margin-left: 0;
    -webkit-border-top-left-radius: 4px;
    -moz-border-radius-topleft: 4px;
    border-top-left-radius: 4px;
    -webkit-border-bottom-left-radius: 4px;
    -moz-border-radius-bottomleft: 4px;
    border-bottom-left-radius: 4px;
}
.btn-group>.btn-editor+.btn-editor {
    margin-left: -1px !important;
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
}
.btn-not-space{
    position: relative;
    float: left;
    margin-left: 0 !important;
    border-radius: inherit;
    border: 1px solid transparent;
    border-color: #ccc;
}
.btn-editor.btn-not-space:hover {
    background-color: rgba(230, 230, 230, 0.32);
}
#preview {
    padding: 1em;
    margin: 0 auto;
    width: 97%;
    border-top: 1px dotted #c8ccd0;
    border-bottom: 1px dotted #c8ccd0;
    clear: both;
}</code>```

   Bold
   Italic
   U
   abc

   </>

  <textarea id="textarea" name="detail" class="editor-preview" style="display: none;"></textarea>

```

Fiddle: https://jsfiddle.net/n4ctd795/

答:
by adding & removing classes you can toggle the code mode

don't need to alter id in any situation

https://jsfiddle.net/rkv88/61xbkfto/

```<code>if (codeMode) {
    var formattedHtml = formatHtmlCode(htmlDiv.html());
    htmlDiv.css("white-space", "normal"); //pre
    htmlDiv.text(formattedHtml);
    var editor = $("#editor");
    editor.addClass("black-bg-colr codeMode");
} else {
    htmlDiv.css("white-space", "normal");
    htmlDiv.html(htmlDiv.text().replace(/\r?\n|\r/g, ""));
    var editor = $("#editor");
    editor.removeClass("black-bg-colr codeMode");
}
</code>```

Title: Id is added but not removed

Body:
When I click on the code button <> a second id is correctly added, but when I click on the code button again <> the new added id is not removed, so how can I remove the added id, since I have tried some alternatives and They don't work for me.

What I try to do is delete the following id newID

if (codeMode) {
    var formattedHtml = formatHtmlCode(htmlDiv.html());
    htmlDiv.css("white-space", "normal"); //pre
    htmlDiv.text(formattedHtml);
    var editor = $("#editor");
    editor.addClass("black-bg-colr codeMode");
    editor.attr('id', 'editor newID');
} else {
    htmlDiv.css("white-space", "normal");
    htmlDiv.html(htmlDiv.text().replace(/\r?\n|\r/g, ""));
    var editor = $("#editor");
    editor.removeClass("black-bg-colr codeMode");
    //editor.attr('id', 'editor');
    //$('div#newID').removeAttr('id');
    //editor.removeAttr( "newID" )
}

Snippet:

 $(function() {
  function formatHtmlCode(str) {
   var div = document.createElement('div');
   div.innerHTML = str.trim();
   return format(div, 0).innerHTML;
  }
  function format(node, level) {
   var indentBefore = new Array(level++ + 1).join('  '),
   indentAfter = new Array(level - 1).join('  '),
   textNode;
   for (var i = 0; i < node.children.length; i++) {
    textNode = document.createTextNode('\n' + indentBefore);
    node.insertBefore(textNode, node.children[i]);
    format(node.children[i], level);
    if (node.lastElementChild == node.children[i]) {
     textNode = document.createTextNode('\n' + indentAfter);
     node.appendChild(textNode);
    }
   }
   return node;
  }
  $('#editControls a').click(function(e) {
   switch ($(this).data('role')) {
    case 'p':
     document.execCommand('formatBlock', false, $(this).data('role'));
     break;
    case 'code':
     codeMode = !codeMode;
     if (codeMode) {
      var formattedHtml = formatHtmlCode(htmlDiv.html());
      htmlDiv.css("white-space", "normal"); //pre
      htmlDiv.text(formattedHtml);
      var editor = $("#editor");
      editor.addClass("black-bg-colr codeMode");
      editor.attr('id', 'editor newID');
     } else {
      htmlDiv.css("white-space", "normal");
      htmlDiv.html(htmlDiv.text().replace(/\r?\n|\r/g, ""));
      var editor = $("#editor");
      editor.removeClass("black-bg-colr codeMode");
      //editor.attr('id', 'editor');
            //$('div#newID').removeAttr('id');
            //editor.removeAttr( "newID" )
     }
     break;
    default:
     document.execCommand($(this).data('role'), false, null);
     break;
   }
  });

  let codeMode = false;
  let htmlDiv = $("#editor");
  htmlDiv.on('keyup', function(e) {
   if (!e.shiftKey && e.keyCode === 13) {
    document.execCommand('formatBlock', false, 'p');
   } else if (e.shiftKey) {
    document.execCommand('formatBlock', false, 'div');
   }
  });

  htmlDiv.on("paste", function(e) {
   e.preventDefault();
   var text = (e.originalEvent || e).clipboardData.getData('text/plain');
   document.execCommand('formatBlock', false, 'div');
   document.execCommand('insertText', false, text);
  });

  htmlDiv.on("input", function(e) {
   $(".editor-preview").val(htmlDiv.html());
   $(".editor-preview").keyup();
  });

  $('.editor-preview').keyup(function() {
   var contentAttr = $(this).attr('class');
   if (!codeMode) {
    var value = $(this).val();
    $('.' + contentAttr).html(value);
   } else {
    $('.' + contentAttr).html(htmlDiv.text());
   }
  });

 });

#editControls {
    overflow: auto;
    border-top: 1px solid transparent;
    border-left: 1px solid transparent;
    border-right: 1px solid transparent;
    border-color: silver;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
    padding: .5em 1em .5em 1em;
    background-color: #fbfbfb;
    margin: 0 auto;
    width: 100%; /*90*/
}
#editor {
    resize: vertical;
    overflow: auto;
    border: 1px solid silver;
    border-bottom-right-radius: 5px;
    border-bottom-left-radius: 5px;
    min-height: 100px;
    padding: 1em;
    background: white;
    margin: 0 auto;
    width: 100%;/*90*/
}
#editor:focus {
    outline: none !important;
    box-shadow: inset 0 0 2px silver;
}
.codeMode {
    font-family:Courier New,Source Code Pro Light,Medium,Source Code Pro ExtraLight,Menlo,Consola,Monaco Linux,Consola Regular,Fira Code Regular,DejaVu Sans Mono;
    /*font-family: inherit;*/
    /*font-family: 'Courier New';*/
    border: 0px;
    font-style: inherit;
    font-variant: inherit;
    font-weight: inherit;
    font-stretch: inherit;
    line-height: inherit;
    vertical-align: baseline;
    box-sizing: inherit;
    color: #fff;
}
.black-bg-colr {
  background-color: #000 !important;
}
.btn-group {
    position: relative;
    display: inline-block;
    font-size: 0;
    vertical-align: middle;
    white-space: nowrap;
}
.btn-group+.btn-group {
    margin-left: 5px;
}
.btn-group a {
    text-decoration: none;
}
.btn-editor {
    height: 30px;
    display: inline-block;
    padding: 6px 12px;
    margin-bottom: 0;
    font-size: 11px;
    font-weight: normal;
    line-height: 1.42857143;
    text-align: center;
    white-space: nowrap;
    vertical-align: middle;
    -ms-touch-action: manipulation;
    touch-action: manipulation;
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    background-image: none;
    border-radius: 4px;
    border: 1px solid transparent;
    color: #333;
    background-color: #fff;
    border-color: #ccc;
}
.btn-group>.btn-editor:first-child {
    margin-left: 0;
    -webkit-border-top-left-radius: 4px;
    -moz-border-radius-topleft: 4px;
    border-top-left-radius: 4px;
    -webkit-border-bottom-left-radius: 4px;
    -moz-border-radius-bottomleft: 4px;
    border-bottom-left-radius: 4px;
}
.btn-group>.btn-editor+.btn-editor {
    margin-left: -1px !important;
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
}
.btn-not-space{
    position: relative;
    float: left;
    margin-left: 0 !important;
    border-radius: inherit;
    border: 1px solid transparent;
    border-color: #ccc;
}
.btn-editor.btn-not-space:hover {
    background-color: rgba(230, 230, 230, 0.32);
}
#preview {
    padding: 1em;
    margin: 0 auto;
    width: 97%;
    border-top: 1px dotted #c8ccd0;
    border-bottom: 1px dotted #c8ccd0;
    clear: both;
}

   Bold
   Italic
   U
   abc

   </>

  <textarea id="textarea" name="detail" class="editor-preview" style="display: none;"></textarea>

Fiddle: https://jsfiddle.net/n4ctd795/

Body:
by adding & removing classes you can toggle the code mode

don't need to alter id in any situation

https://jsfiddle.net/rkv88/61xbkfto/

if (codeMode) {
    var formattedHtml = formatHtmlCode(htmlDiv.html());
    htmlDiv.css("white-space", "normal"); //pre
    htmlDiv.text(formattedHtml);
    var editor = $("#editor");
    editor.addClass("black-bg-colr codeMode");
} else {
    htmlDiv.css("white-space", "normal");
    htmlDiv.html(htmlDiv.text().replace(/\r?\n|\r/g, ""));
    var editor = $("#editor");
    editor.removeClass("black-bg-colr codeMode");
}


问:
Steps for redesigning an iPad app for Mac OS X?
What commonly expected user-visible design idioms need to change from an iPad app to a Mac app for an app, that is to provide basically identical functionality, to seem at least reasonably Mac OS X native?

Some of these changes, commonly expected by users, might include:

Move the Settings button and Info button to Menu selections for Preferences... and About...

Move the Settings view and Info view or popover to their own independent Preferences and About windows instead of being views in the main window.

Add some menu items and menu keys for commonly used buttons (like the forward and back buttons in a browser).

Support arrow keys for scrolling any custom view items.

Support mouse-over for help popups or dynamic menus.

If the app supports "documents", allow more than one document to be open at a time, each in their own windows.

What else?  What's the minimum change required for a simple generic 2D game?

Added clarifications:

Note that I do not consider re-coding similar UI classes to NS classes (for instance UIButtons to NSButtons), with similar look, positions and behaviors, to be a significant change.  Those changes are pretty much invisible to the user.

The goal is to change as little as possible so that a user who purchased app X to do Y on an iPad might purchase app X to do Y on their Mac, as a Mac application, but with as close to zero learning curve as possible.  But it seems that some changes need to be made, or the app would not seem to be a Mac app (for instance, a missing About... menu item would seem a bit strange.)

答:
We are in the same boat and faced the same question.

Our conclusion is to start with a "fresh" real application for Mac and make it look similar, i.e. using the same or similar UI components and graphics. The app should be otherwise developed as if there was no iPad version.

First, there will be many users that don't have the iPad version. Those users expect a full-blown Mac application and it doesn't make sense to make it feel iPad in any way.

Second, users coming from the iPad version will feel ripped of if the Mac app is just a pure clone of the iPad version with no added value. Think of the first transitions from iPhone to iPad - paying again for nothing but pure upscales is frustrating and might harm your business in the long run.

Starting out designing a fresh streamlined UI and then think of what you can reuse and make similar. Functionality may differ in one direction or the other. Your model code should work in all places anyway.


问:
Spring MVC Test empty json
How can I test for an empty JSON response from a rest endpoint. I was hoping for something along the lines:

```<code>    ResultActions actions = mockMvc.perform(..);
    actions.andExpect(jsonPath("$", empty()));
</code>```

obviously this fails as {} is not exactly empty.
Any advice?

答:
In JSON, {} is a non-null, but empty, object. This translates into Java as an empty map. You can validate that a JSON element is non-null and empty like this:

actions.andExpect(jsonPath("$").value(Collections.EMPTY_MAP))

Title: Spring MVC Test empty json

Body:
How can I test for an empty JSON response from a rest endpoint. I was hoping for something along the lines:

    ResultActions actions = mockMvc.perform(..);
    actions.andExpect(jsonPath("$", empty()));

obviously this fails as {} is not exactly empty.
Any advice?


问:
Azure Search switch index on full reuild
We have a requirement to rebuild the azure index without any downtime. Does Azure Search have out of box feature to rebuild an index on secondary index and swap once it's fully build?

The swap should happen without impacting the customer.

答:
It does not have the feature to automatically rebuild and switch in-place.

You would need to rebuild the Index in parallel, and redirect calls to the newly-created Index, as detailed in How to rebuild an index in Azure Cognitive Search.


问:
How do I reset the numbers after calculating the Total
How will I clear the total after the first calculation?
I want it to reset if I add a new item after the first calculation. Right now it's adding it to the previous one.
For example, for the first calculation (item1 + item2) = total
if I add another item, it becomes (item1 + item 2) + (item1 + item2 + item3) = total

What I want is for it to reset and calculate the new total with the new item added.

 var count = 0;
    var tax = 0.05;
    var taxFeild = document.getElementById("Tax");
    var checkBoxes = document.getElementById("checkBoxes");
    var checks=document.querySelectorAll('.items');
    var ItemTotal=document.getElementById('ItemTotal');
    var Total=document.getElementById('TotalWithTax');
    var btn = document.getElementById("btn");

function Calculate()
      {

       for(var i =0 ;i< checks.length;i++)
         {
           if(checks[i].checked)
             {
               count+=parseFloat(checks[i].value);
             }
         }
        ItemTotal.textContent += count;
        taxFeild.textContent += (parseFloat(tax*count).toFixed(2));
        Total.textContent += ((tax*count) + count).toFixed(2);
      }

        btn.addEventListener('click',Calculate);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">

</head>
<body>

<h2 class="first-heading">Assignment 1</h2>
<div class="row">
  <div class="column">
      <div id="checkBoxes">
            <input type="checkbox" class="items" value='7.99'>Fried Chicken ($7.99)<br>
            <input type="checkbox" class="items" value='9.99'> Fried Halibut ($9.99)<br>
            <input type="checkbox" class="items" value='7.99'> Hamburger ($7.99)<br>
            <input type="checkbox" class="items" value='12.99'> Grilled salmon($12.99)<br>
            <input type="checkbox" class="items" value='5.99'> Side salad ($5.99)<br>
            <button id="btn">Calculate</button>
        </div>
  </div>
  <div class="column" >

        <div id="Sums">
                <p id="ItemTotal"> Item Total: </p>
                <p id="Tax"> Tax: </p>
                <p id="TotalWithTax">Total with Tax: </p>
        </div>
  </div>
</div>
<script src="java.js"></script>

</body>
</html></code>```

答:
Problem seems to be plus sign when asigning content. Just replace += with = and it should work

```<code>    ItemTotal.textContent = count;
    taxFeild.textContent = (parseFloat(tax*count).toFixed(2));
    Total.textContent = ((tax*count) + count).toFixed(2);
</code>```

And place captions in span like this:

```<code><p> Item Total:<span id="ItemTotal"></span> </p>
<p> Tax: <span id="Tax"></span></p>
<p>Total with Tax: <span id="TotalWithTax"></span></p>
</code>```

Body:
How will I clear the total after the first calculation?
I want it to reset if I add a new item after the first calculation. Right now it's adding it to the previous one.
For example, for the first calculation (item1 + item2) = total
if I add another item, it becomes (item1 + item 2) + (item1 + item2 + item3) = total

What I want is for it to reset and calculate the new total with the new item added.

 var count = 0;
    var tax = 0.05;
    var taxFeild = document.getElementById("Tax");
    var checkBoxes = document.getElementById("checkBoxes");
    var checks=document.querySelectorAll('.items');
    var ItemTotal=document.getElementById('ItemTotal');
    var Total=document.getElementById('TotalWithTax');
    var btn = document.getElementById("btn");

function Calculate()
      {

       for(var i =0 ;i< checks.length;i++)
         {
           if(checks[i].checked)
             {
               count+=parseFloat(checks[i].value);
             }
         }
        ItemTotal.textContent += count;
        taxFeild.textContent += (parseFloat(tax*count).toFixed(2));
        Total.textContent += ((tax*count) + count).toFixed(2);
      }

        btn.addEventListener('click',Calculate);

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">

Assignment 1

            <input type="checkbox" class="items" value='7.99'>Fried Chicken ($7.99)

            <input type="checkbox" class="items" value='9.99'> Fried Halibut ($9.99)

            <input type="checkbox" class="items" value='7.99'> Hamburger ($7.99)

            <input type="checkbox" class="items" value='12.99'> Grilled salmon($12.99)

            <input type="checkbox" class="items" value='5.99'> Side salad ($5.99)

            <button id="btn">Calculate</button>

 Item Total:

 Tax:

Total with Tax:

Body:
Problem seems to be plus sign when asigning content. Just replace += with = and it should work

    ItemTotal.textContent = count;
    taxFeild.textContent = (parseFloat(tax*count).toFixed(2));
    Total.textContent = ((tax*count) + count).toFixed(2);

And place captions in span like this:

<p> Item Total:<span id="ItemTotal"></span> </p>
<p> Tax: <span id="Tax"></span></p>
<p>Total with Tax: <span id="TotalWithTax"></span></p>


问:
Is there a way to install an ipa file to tester without all the apple stuff?
I have some ipa files and it turns out that I can install directly on my device without having to do anything unusual, just itunes. These apps are not in the app store, so I guess they've done something with Xcode or with the ipas, right? How is this possible?

When I pass the apps I've done to some beta testers I have to ask IDs and after putting it in the certificate, it can be installed, but if not, no.

So anyone have any idea? What happened?

If you have an Enterprise account, you still need the ID's of the testers, right?

sorry for my bad english, but at least I try!

Greetings and thanks!

答:
We can do in Xcode "build and archive", which will then create an ipa file. This is done by the developers to pass on the app to the client for testing or reviewing.

Ofcourse, if you want to run this archive your device should have been added in the provisioning profile with which the archive was created.


问:
regex pattern to tokenize sentence while stripping end punctuation?
I need to make a regex pattern that can tokenize a sentence with that also has punctuation tokenized separately, except for acronyms, contractions, and hyphens.

```<code>"This is a test sentence. I won't write this sentence. J. Smith lives in the U.S.A. and it is nice there."
</code>```

should return as

```<code>["This" "is" "a" "test" "sentence" "." "I" "won't" "write" "this" "sentence" "." "J." "Smith" "lives"
 "in" "the" "U.S.A." "and" "it" "is" "nice" "there" ."]
</code>```

My code currently is:

```<code>tokens = re.findall(r'((\.\s)|(\S+))', sentence)
</code>```

But this doesn't work correctly. It matches the period at the end of words as part of the word.

答:
Here is one that works for what you have and can be used for similar sentences. Again, can not always be used if there's different variations.</p>

```<code>([A-Z]\.\S*|\w+\'*\w*|[A-Z]\.|\.)
</code>```

Body:
I need to make a regex pattern that can tokenize a sentence with that also has punctuation tokenized separately, except for acronyms, contractions, and hyphens.

"This is a test sentence. I won't write this sentence. J. Smith lives in the U.S.A. and it is nice there."

should return as

["This" "is" "a" "test" "sentence" "." "I" "won't" "write" "this" "sentence" "." "J." "Smith" "lives"
 "in" "the" "U.S.A." "and" "it" "is" "nice" "there" ."]

My code currently is:

tokens = re.findall(r'((\.\s)|(\S+))', sentence)

But this doesn't work correctly. It matches the period at the end of words as part of the word.

Body:
Here is one that works for what you have and can be used for similar sentences. Again, can not always be used if there's different variations.

([A-Z]\.\S*|\w+\'*\w*|[A-Z]\.|\.)


问:
Here Maps Api for Javascript 3.1 - Very Slow
Between Here Maps Api for Javascript version  3.1 and Here Maps Api for Javascript version 3 is a big difference.
The loading time, zooming, routes displaying is much much slower , up to 3 times.

We are usisng the default settings, but even so, on half of our computers on which we used HERE version 3 we cannot use the new version 3.1. It is not loading (cannot be used).

What can be done? I cannot afford to change all the computer to another computers of last generation.
Are there some settings which can be used to reduce the responsive time of the maps?

答:
What you could do is to load legacy packages and use legacy rendering engine (no tilting/rotation, only raster base layer):

load legacy core package:

<!DOCTYPE html>

    .....

    .....
```

<p><strong>create map with legacy rendering engine:</strong></p>

<pre class="lang-js prettyprint-override"><code>// assuming platform is instantiated

// Obtain the default map types from the platform object:
let defaultLayers = platform.createDefaultLayers();

let map = new H.Map(
    document.getElementById('mapContainer'),
    defaultLayers.raster.normal.map,
    {
      zoom: 10,
      center: { lat: 52.5, lng: 13.4 },
      engineType: H.map.render.RenderEngine.EngineType.P2D
    });
</code>```

by default, fractional zoom levels are enabled in 3.1, therefore to have crisp map it is recommended to disable it:

//assuming that UI and mapevents behavior are instantiated

// disable fractional zooming for Behavior
behavior.disable(H.mapevents.Behavior.Feature.FRACTIONAL_ZOOM);

// add H.ui.ZoomControl with the disabled fractional zooming
var zoomControl = new H.ui.ZoomControl({fractionalZoom: false});
ui.addControl('zoom', zoomControl);
```

For more information check the Migration guide

Body:
What you could do is to load legacy packages and use legacy rendering engine (no tilting/rotation, only raster base layer):

load legacy core package:

<!DOCTYPE html>
  <html>
    <head>
    .....
      <script src="https://js.api.here.com/v3/3.1/mapsjs-core-legacy.js" type="text/javascript" charset="utf-8"></script>
    .....

create map with legacy rendering engine:

// assuming platform is instantiated

// Obtain the default map types from the platform object:
let defaultLayers = platform.createDefaultLayers();

let map = new H.Map(
    document.getElementById('mapContainer'),
    defaultLayers.raster.normal.map,
    {
      zoom: 10,
      center: { lat: 52.5, lng: 13.4 },
      engineType: H.map.render.RenderEngine.EngineType.P2D
    });

by default, fractional zoom levels are enabled in 3.1, therefore to have crisp map it is recommended to disable it:

//assuming that UI and mapevents behavior are instantiated

// disable fractional zooming for Behavior
behavior.disable(H.mapevents.Behavior.Feature.FRACTIONAL_ZOOM);

// add H.ui.ZoomControl with the disabled fractional zooming
var zoomControl = new H.ui.ZoomControl({fractionalZoom: false});
ui.addControl('zoom', zoomControl);

For more information check the Migration guide


问:
Check which condition in IF statement is true
Is there any method in JavaScript to define which condition inside IF statement is fulfilled?

For example:

```<code>if(a === 1 || b === 2) {
  // do something apart of fulfilled condition
  if(a === 1) {
    // do something
  } else if(b === 2) {
    // do something else
  }
}
</code>```

Code above working as expected but I'm wondering if there is a clever way to do this easier, especially when there will be more conditions.

Thanks for answers.

答:
No, there is no provided way to do what you ask other than making explicit tests. In this specific case, the following is equivalent:</p>

```<code>if (a === 1) {
  // do something
}
else if (b === 2) {
  // do something else
}
</code>```

Body:
Is there any method in JavaScript to define which condition inside IF statement is fulfilled?

For example:

if(a === 1 || b === 2) {
  // do something apart of fulfilled condition
  if(a === 1) {
    // do something
  } else if(b === 2) {
    // do something else
  }
}

Code above working as expected but I'm wondering if there is a clever way to do this easier, especially when there will be more conditions.

Thanks for answers.

Body:
No, there is no provided way to do what you ask other than making explicit tests. In this specific case, the following is equivalent:

if (a === 1) {
  // do something
}
else if (b === 2) {
  // do something else
}


答:
You can use the onblur event on your calculator button. The onblur event occurs when you click off of an object. After a user clicks the "calculate" button, when they click anywhere else, the onblur function will call.

You can find out more about the onblur event at: https://www.w3schools.com/jsref/event_onblur.asp

W3Schools has a lot of easy to learn information. Here are other events which may prove to be useful in the future (or for expanding this project): https://www.w3schools.com/jsref/dom_obj_event.asp

A simple reset function can reset your counter and your paragraph tags.

var count = 0;
var tax = 0.05;
var taxFeild = document.getElementById("Tax");
var checkBoxes = document.getElementById("checkBoxes");
var checks=document.querySelectorAll('.items');
var ItemTotal=document.getElementById('ItemTotal');
var Total=document.getElementById('TotalWithTax');
var btn = document.getElementById("btn");

// RESET YOUR CALCULATOR FIELDS & COUNT
function resetCalc(){
 count = 0;
 ItemTotal.textContent = "Item Total: ";
 taxFeild.textContent = "Tax: ";
 Total.textContent = "Total with Tax: ";
}

function Calculate()
  {

   for(var i =0 ;i< checks.length;i++)
     {
       if(checks[i].checked)
         {
           count+=parseFloat(checks[i].value);
         }
     }
    ItemTotal.textContent += count;
    taxFeild.textContent += (parseFloat(tax*count).toFixed(2));
    Total.textContent += ((tax*count) + count).toFixed(2);
  }

    btn.addEventListener('click',Calculate);

 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">

</head>
<body>

<h2 class="first-heading">Assignment 1</h2>
<div class="row">
  <div class="column">
     <div id="checkBoxes">
        <input type="checkbox" class="items" value='7.99'>Fried Chicken ($7.99)<br>
        <input type="checkbox" class="items" value='9.99'> Fried Halibut ($9.99)<br>
        <input type="checkbox" class="items" value='7.99'> Hamburger ($7.99)<br>
        <input type="checkbox" class="items" value='12.99'> Grilled salmon($12.99)<br>
        <input type="checkbox" class="items" value='5.99'> Side salad ($5.99)<br>

   <!-- NOTICE THE ONBLUR -->
        <button id="btn" onblur="resetCalc();">Calculate</button>

    </div>
   </div>
   <div class="column" >

    <div id="Sums">
            <p id="ItemTotal"> Item Total: </p>
            <p id="Tax"> Tax: </p>
            <p id="TotalWithTax">Total with Tax: </p>
    </div>
  </div>
</div>
<script src="java.js"></script>

</body>
</html>
 </code>```

Title: How do I reset the numbers after calculating the Total

Body:
You can use the onblur event on your calculator button. The onblur event occurs when you click off of an object. After a user clicks the "calculate" button, when they click anywhere else, the onblur function will call.

You can find out more about the onblur event at: https://www.w3schools.com/jsref/event_onblur.asp

W3Schools has a lot of easy to learn information. Here are other events which may prove to be useful in the future (or for expanding this project): https://www.w3schools.com/jsref/dom_obj_event.asp

A simple reset function can reset your counter and your paragraph tags.

var count = 0;
var tax = 0.05;
var taxFeild = document.getElementById("Tax");
var checkBoxes = document.getElementById("checkBoxes");
var checks=document.querySelectorAll('.items');
var ItemTotal=document.getElementById('ItemTotal');
var Total=document.getElementById('TotalWithTax');
var btn = document.getElementById("btn");

// RESET YOUR CALCULATOR FIELDS & COUNT
function resetCalc(){
 count = 0;
 ItemTotal.textContent = "Item Total: ";
 taxFeild.textContent = "Tax: ";
 Total.textContent = "Total with Tax: ";
}

function Calculate()
  {

   for(var i =0 ;i< checks.length;i++)
     {
       if(checks[i].checked)
         {
           count+=parseFloat(checks[i].value);
         }
     }
    ItemTotal.textContent += count;
    taxFeild.textContent += (parseFloat(tax*count).toFixed(2));
    Total.textContent += ((tax*count) + count).toFixed(2);
  }

    btn.addEventListener('click',Calculate);

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">

</head>
<body>

<h2 class="first-heading">Assignment 1</h2>
<div class="row">
  <div class="column">
     <div id="checkBoxes">
        <input type="checkbox" class="items" value='7.99'>Fried Chicken ($7.99)<br>
        <input type="checkbox" class="items" value='9.99'> Fried Halibut ($9.99)<br>
        <input type="checkbox" class="items" value='7.99'> Hamburger ($7.99)<br>
        <input type="checkbox" class="items" value='12.99'> Grilled salmon($12.99)<br>
        <input type="checkbox" class="items" value='5.99'> Side salad ($5.99)<br>

   <!-- NOTICE THE ONBLUR -->
        <button id="btn" onblur="resetCalc();">Calculate</button>

    </div>
   </div>
   <div class="column" >

    <div id="Sums">
            <p id="ItemTotal"> Item Total: </p>
            <p id="Tax"> Tax: </p>
            <p id="TotalWithTax">Total with Tax: </p>
    </div>
  </div>
</div>
<script src="java.js"></script>

</body>
</html>


问:
merge multiple txt file to csv - add header
I have multiple txt file, only one column in each and I'm trying to merge them all into one csv. Ideally I want each column to have the name of the file where they come from, and I am stuck at this last part.

text files look like this (2 examples but I got many more):

```<code>c.Daphnia.txt
geneA
geneB
geneC

c.Drosophila.txt
geneA
geneD
geneE

c.Mouse.txt
geneA
geneV
geneX
</code>```

Desired output:

At the moment im doing this:
paste -d',' c* > all.csv
The output looks like this, it got all the columns but no header.

Could you help me please?

Thanks

答:
In case it can help someone I ended up using python and doing it like this:</p>

```<code>import pandas as pd
df1=pd.read_csv('a.txt',names=['a'])
df2=pd.read_csv('b.txt',names=['b'])
df3=pd.read_csv('c.txt',names=['c'])
df4=pd.read_csv('d.txt',names=['d'])
df5=pd.read_csv('e.txt',names=['e'])

result=pd.concat([df1,df2,df3,df4,df5],axis=1)
result.to_csv('mergedfile.csv',index=False)
</code>```

Body:
I have multiple txt file, only one column in each and I'm trying to merge them all into one csv. Ideally I want each column to have the name of the file where they come from, and I am stuck at this last part.

text files look like this (2 examples but I got many more):

c.Daphnia.txt
geneA
geneB
geneC

c.Drosophila.txt
geneA
geneD
geneE

c.Mouse.txt
geneA
geneV
geneX

Desired output:

At the moment im doing this:
paste -d',' c* > all.csv
The output looks like this, it got all the columns but no header.

Could you help me please?

Thanks

Body:
In case it can help someone I ended up using python and doing it like this:

import pandas as pd
df1=pd.read_csv('a.txt',names=['a'])
df2=pd.read_csv('b.txt',names=['b'])
df3=pd.read_csv('c.txt',names=['c'])
df4=pd.read_csv('d.txt',names=['d'])
df5=pd.read_csv('e.txt',names=['e'])

result=pd.concat([df1,df2,df3,df4,df5],axis=1)
result.to_csv('mergedfile.csv',index=False)


问:
How to make checkbox of “Ship to different address” on Woocommerce checkout page unchecked by default
Recently I used the following to change the text of “Ship to different address” on Woocommerce checkout page

```<code>function shipchange( $translated_text, $text, $domain ) {
    switch ( $translated_text ) {
        case 'Ship to different address?' :
           $translated_text = __( 'Other', 'woocommerce' );
           break;
    }

    return $translated_text;
}

add_filter('gettext', 'shipchange', 20, 3);
</code>```

but I noticed that the checkbox is checked from the start. How can I have the checkbox unchecked by default?

答:
There's a filter for this.

add_filter( 'woocommerce_ship_to_different_address_checked', '__return_false' );

_return_true makes it checked by default.

Body:
Recently I used the following to change the text of “Ship to different address” on Woocommerce checkout page

function shipchange( $translated_text, $text, $domain ) {
    switch ( $translated_text ) {
        case 'Ship to different address?' :
           $translated_text = __( 'Other', 'woocommerce' );
           break;
    }

    return $translated_text;
}

add_filter('gettext', 'shipchange', 20, 3);

but I noticed that the checkbox is checked from the start. How can I have the checkbox unchecked by default?


问:
How to handle a translation Matrix in an inverted Y axis point of view
My usercase is an iphone application where I do an animation on the scale, rotation and translation of an image.

So, I concat everything and feed it to the transform property, but there is one problem:

Since my images vary in size, it is a problem to position them correctly. I'm used to an inverted y axis coordinate system, so I want my image to positioned exactly at 60 pixels in the y axis.

So, how do I change from the original cartesian y axis to an inverted y axis point of view?

答:
As smacl points out, the easiest way to do this is to shift your origin to the bottom-left of the screen by using (screenheight - viewheight - y) instead of y in the origins of your views.

However, you can flip the coordinate system of your main view's layers using a CATransform3D.  I do this so that I can share the same Core Animation CALayer layout code between my iPhone application and a Mac client (the iPhone inverts the normal Quartz coordinate system for CALayers to match that of the UIViews).  All you need to do to enable this is to place the line

```<code>self.layer.sublayerTransform = CATransform3DMakeScale(1.0f, -1.0f, 1.0f);
</code>```

in your initialization code for your layer-hosting UIView.  Remember that this will flip your CALayers, so any UIKit text rendering in those layers may also need to be flipped using code similar to the following:

```<code>CGContextSaveGState(context);
CGContextTranslateCTM(context, 0.0f, self.frame.size.height);
CGContextScaleCTM(context, 1.0f, -1.0f);

UIFont *theFont = [UIFont fontWithName:@"Helvetica" size:fontSize];
[text drawAtPoint:CGPointZero withFont:theFont];

CGContextRestoreGState(context);
</code>```

You can do a similar sort of inversion using a CGAffineTransform, but you will also need to apply a translation to make that work:

```<code>CGAffineTransform flipTransform = CGAffineTransformMakeTranslation(0.0f, self.frame.size.height);
flipTransform = CGAffineTransformScale(flipTransform, 1.0f, -1.0f);
</code>```

You may be able to use the affine transform to convert your origin coordinates using CGPointApplyAffineTransform().

OwnerDisplayName: Andy Jacobs

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Svante

Body:
As smacl points out, the easiest way to do this is to shift your origin to the bottom-left of the screen by using (screenheight - viewheight - y) instead of y in the origins of your views.

However, you can flip the coordinate system of your main view's layers using a CATransform3D.  I do this so that I can share the same Core Animation CALayer layout code between my iPhone application and a Mac client (the iPhone inverts the normal Quartz coordinate system for CALayers to match that of the UIViews).  All you need to do to enable this is to place the line

self.layer.sublayerTransform = CATransform3DMakeScale(1.0f, -1.0f, 1.0f);

in your initialization code for your layer-hosting UIView.  Remember that this will flip your CALayers, so any UIKit text rendering in those layers may also need to be flipped using code similar to the following:

CGContextSaveGState(context);
CGContextTranslateCTM(context, 0.0f, self.frame.size.height);
CGContextScaleCTM(context, 1.0f, -1.0f);

UIFont *theFont = [UIFont fontWithName:@"Helvetica" size:fontSize];
[text drawAtPoint:CGPointZero withFont:theFont];

CGContextRestoreGState(context);

You can do a similar sort of inversion using a CGAffineTransform, but you will also need to apply a translation to make that work:

CGAffineTransform flipTransform = CGAffineTransformMakeTranslation(0.0f, self.frame.size.height);
flipTransform = CGAffineTransformScale(flipTransform, 1.0f, -1.0f);

You may be able to use the affine transform to convert your origin coordinates using CGPointApplyAffineTransform().

OwnerDisplayName: Brad Larson


问:
Test connectivity using specific NIC
We need to change DNS configuration for several servers, before I do that I need to test DNS ports on those servers.
The problem is that our servers have multiple NICs, so we need to ensure that the DNS ports test go through a specific NIC, in this case would be the NIC that has DNS configured already.

So, we need to retrieve the NICs list, identify which one has DNS configured and then use that specific NIC to perform the port test to the new DNS servers and check if it is Ok/NOTOK.

The second problem is that our network ranges from Windows 2003 to Windows 2019, so the solution must work through different PowerShell versions ranging from 2.0 to the latest.

With more recent PowerShell versions this wouldn't be a problem, but since we have PS 2.0 and up, the scenario changes.

Anyone has or knows any example out there for this task?

Thank you.

答:
The cmdlet,

Test-Connection

does provide a mechanism for this use case.

```<code>Test-Connection -Source 'SomeIPA' -Destination 'SomeDest'
</code>```

Native ping in any OS provides this as well via the source switch.

You can get InterfaceIndex using

Get-Netadapter

cmdlet in recent versions of PowerShell. ---

```<code>Get-NetAdapter -Physical | Where Status -eq 'up'
</code>```

---  below v3, you'd do ---

```<code>netsh interface ipv4 show interfaces
</code>```

--- or ---

```<code>Get-WmiObject -Class  win32_networkadapter
</code>```

Any connectivity test will only occur with a nic that has connectivity and is properly routed.  There are several articles and Q&A's that talk to your use case. A quick web search will show them to you. 'ping using a specific nic'

Examples:

Ping from specific network adapter on Windows

The adapter chosen is based on the routing tables. You can examine the
  routing tables by running 'route print' or 'netstat -r'. Each entry
  will have a metric which dictates the weighting of the route - lower
  numbers are preferred. You can manipulate the routing table with the
  'route' command. route /? for details.

route add (destination subnet) MASK (destination subnet mask)
  (gateway) IF (interface)

Probably easier is to use the -S switch, which lets you specify the
  source IP address (see ping /? for more infos).

Another thing you can do is change the binding order, which meets your
  "option to prefer one adapter over the other". Although it varies from
  Windows OS to OS, it is in a similar location as this example: For
  Windows 7 you right click on Network, and click properties. Then you
  click on ""Change adapter settings". Then click on the menu
  Advanced>Advanced Settings and move the connection you want to have
  priority to the top.

From Windows 7 (Version 6.1 Build 7601: Service Pack 1) ping /? Usage:
  ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
          [-r count] [-s count] [[-j host-list] | [-k host-list]]
          [-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name

Ping using specific gateway interface or source IP address

Ping using specific source IP address One can set socket stuff. The
  syntax is:

```<code>ping -S ip dest
ping -S 192.168.2.24 www.cyberciti.biz
ping -c 4 -S 10.207.0.54 1.1.1.1
</code>```

Can I try to ping a website through a specific adapter?

OK, missed the Port thing, but, Test-NetConnection is not in legacy PowerShell period, so not an option, and it does not provide a source switch either anyway.

```<code>(Get-Command Test-Connection).Parameters.Keys
AsJob
DcomAuthentication
WsmanAuthentication
Protocol
BufferSize
ComputerName
Count
Credential
Source
Impersonation
ThrottleLimit
TimeToLive
Delay
Quiet
Verbose
Debug
ErrorAction
WarningAction
InformationAction
ErrorVariable
WarningVariable
InformationVariable
OutVariable
OutBuffer
PipelineVariable

(Get-Command Test-NetConnection).Parameters.Keys
ComputerName
TraceRoute
Hops
CommonTCPPort
Port
DiagnoseRouting
ConstrainSourceAddress
ConstrainInterface
InformationLevel
Verbose
Debug
ErrorAction
WarningAction
InformationAction
ErrorVariable
WarningVariable
InformationVariable
OutVariable
OutBuffer
PipelineVariable
</code>```

You could take the route of using the .Net libraries. Which is how it's been documented in legacy PowerShell. Using stuff like ...

--- New-Object Net.Sockets.TcpClient ---

```<code>$tcpObj = New-Object Net.Sockets.TcpClient
$tcpObj.Connect($Ipaddress,$Port)
</code>```

More info on that namespace is here:

https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.tcpclient?view=netframework-4.8

... combining the results from ping or Test-Connection and piping that to Net.Sockets to deal with the port check.

For example (since this was sort of interesting I threw this together and tested it - so I know it works - well not on W2K3 as I've had none of those in over a decade.):

```<code>Clear-Host
$SourceIpa = 'SomeSourceNicIpa'
$TargetDestination = 'Stackoverflow.com'
$TargetResponseCount = 1
$DestinationPort = 443

try
{
    $DestinationIpa = (Test-Connection -Source $SourceIpa -ComputerName $TargetDestination -Count $TargetResponseCount).ipv4address.ipaddressToString
    $tcpObj = New-Object Net.Sockets.TcpClient($DestinationIpa,$DestinationPort)

    if($tcpObj -ne $null)
    {
        "Using the source $SourceIpa. The port $DestinationPort on destination $TargetDestination is open."
        $tcpObj.close()
    }
}
catch
{
    Write-Warning -Message "Using the source $SourceIpa. The port $DestinationPort on destination $TargetDestination is not open."
    $tcpObj.close()
}
</code>```

And a similar approach could have been done with ping and the .Net namespace as well.

Title: Test connectivity using specific NIC

Body:
The cmdlet,

Test-Connection

does provide a mechanism for this use case.

Test-Connection -Source 'SomeIPA' -Destination 'SomeDest'

Native ping in any OS provides this as well via the source switch.

You can get InterfaceIndex using

Get-Netadapter

cmdlet in recent versions of PowerShell. ---

Get-NetAdapter -Physical | Where Status -eq 'up'

---  below v3, you'd do ---

netsh interface ipv4 show interfaces

--- or ---

Get-WmiObject -Class  win32_networkadapter

Any connectivity test will only occur with a nic that has connectivity and is properly routed.  There are several articles and Q&A's that talk to your use case. A quick web search will show them to you. 'ping using a specific nic'

Examples:

Ping from specific network adapter on Windows

The adapter chosen is based on the routing tables. You can examine the
  routing tables by running 'route print' or 'netstat -r'. Each entry
  will have a metric which dictates the weighting of the route - lower
  numbers are preferred. You can manipulate the routing table with the
  'route' command. route /? for details.

route add (destination subnet) MASK (destination subnet mask)
  (gateway) IF (interface)

Probably easier is to use the -S switch, which lets you specify the
  source IP address (see ping /? for more infos).

Another thing you can do is change the binding order, which meets your
  "option to prefer one adapter over the other". Although it varies from
  Windows OS to OS, it is in a similar location as this example: For
  Windows 7 you right click on Network, and click properties. Then you
  click on ""Change adapter settings". Then click on the menu
  Advanced>Advanced Settings and move the connection you want to have
  priority to the top.

From Windows 7 (Version 6.1 Build 7601: Service Pack 1) ping /? Usage:
  ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
          [-r count] [-s count] [[-j host-list] | [-k host-list]]
          [-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name

Ping using specific gateway interface or source IP address

Ping using specific source IP address One can set socket stuff. The
  syntax is:

ping -S ip dest
ping -S 192.168.2.24 www.cyberciti.biz
ping -c 4 -S 10.207.0.54 1.1.1.1

Can I try to ping a website through a specific adapter?

OK, missed the Port thing, but, Test-NetConnection is not in legacy PowerShell period, so not an option, and it does not provide a source switch either anyway.

(Get-Command Test-Connection).Parameters.Keys
AsJob
DcomAuthentication
WsmanAuthentication
Protocol
BufferSize
ComputerName
Count
Credential
Source
Impersonation
ThrottleLimit
TimeToLive
Delay
Quiet
Verbose
Debug
ErrorAction
WarningAction
InformationAction
ErrorVariable
WarningVariable
InformationVariable
OutVariable
OutBuffer
PipelineVariable

(Get-Command Test-NetConnection).Parameters.Keys
ComputerName
TraceRoute
Hops
CommonTCPPort
Port
DiagnoseRouting
ConstrainSourceAddress
ConstrainInterface
InformationLevel
Verbose
Debug
ErrorAction
WarningAction
InformationAction
ErrorVariable
WarningVariable
InformationVariable
OutVariable
OutBuffer
PipelineVariable

You could take the route of using the .Net libraries. Which is how it's been documented in legacy PowerShell. Using stuff like ...

--- New-Object Net.Sockets.TcpClient ---

$tcpObj = New-Object Net.Sockets.TcpClient
$tcpObj.Connect($Ipaddress,$Port)

More info on that namespace is here:

https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.tcpclient?view=netframework-4.8

... combining the results from ping or Test-Connection and piping that to Net.Sockets to deal with the port check.

For example (since this was sort of interesting I threw this together and tested it - so I know it works - well not on W2K3 as I've had none of those in over a decade.):

Clear-Host
$SourceIpa = 'SomeSourceNicIpa'
$TargetDestination = 'Stackoverflow.com'
$TargetResponseCount = 1
$DestinationPort = 443

try
{
    $DestinationIpa = (Test-Connection -Source $SourceIpa -ComputerName $TargetDestination -Count $TargetResponseCount).ipv4address.ipaddressToString
    $tcpObj = New-Object Net.Sockets.TcpClient($DestinationIpa,$DestinationPort)

    if($tcpObj -ne $null)
    {
        "Using the source $SourceIpa. The port $DestinationPort on destination $TargetDestination is open."
        $tcpObj.close()
    }
}
catch
{
    Write-Warning -Message "Using the source $SourceIpa. The port $DestinationPort on destination $TargetDestination is not open."
    $tcpObj.close()
}

And a similar approach could have been done with ping and the .Net namespace as well.


问:
How do I retrieve the data input from a scanner to use in a method?
Basically I have to write a program that uses data that was inputted by the user and put it in a mathematical formula so it spits out an answer. The formula has to be created as a method. This is what I have so far. When I run the code it lets me input a number, but when I do that the program does not output anything and it just finishes running.</p>

```<code>import java.util.Scanner;

public class Namek {
    static int myMethod(int radius) {
        return ((radius * radius) * (22/7));
    }

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter Radius");
        String radius = keyboard.nextLine();

    }

    private static void myMethod() {
    }
</code>```

答:
Below is what you were trying to do I think</p>

```<code>public class Formula {
        static int myMethod(int radius) {
            return ((radius * radius) * (22/7));
        }

        public static void main(String[] args) {
            Scanner keyboard = new Scanner(System.in);
            System.out.println("Enter Radius");
            int radius = Integer.valueOf(keyboard.nextLine());
            float output = myMethod(radius);
            System.out.println(output);
        }

}
</code>```

Body:
Basically I have to write a program that uses data that was inputted by the user and put it in a mathematical formula so it spits out an answer. The formula has to be created as a method. This is what I have so far. When I run the code it lets me input a number, but when I do that the program does not output anything and it just finishes running.

import java.util.Scanner;

public class Namek {
    static int myMethod(int radius) {
        return ((radius * radius) * (22/7));
    }

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter Radius");
        String radius = keyboard.nextLine();

    }

    private static void myMethod() {
    }

Body:
Below is what you were trying to do I think

public class Formula {
        static int myMethod(int radius) {
            return ((radius * radius) * (22/7));
        }

        public static void main(String[] args) {
            Scanner keyboard = new Scanner(System.in);
            System.out.println("Enter Radius");
            int radius = Integer.valueOf(keyboard.nextLine());
            float output = myMethod(radius);
            System.out.println(output);
        }

}


问:
Terraform :depends_on resource created with count
I have created a set of  NAT gateway with count

```<code>resource "aws_nat_gateway" "nat_gateway_ec1_dev" {
  count         = 3

}
</code>```

And I would like to this as dependence resource  while creating route table in which I am also using count

```<code>resource "aws_route_table" "route_table_ics_ec1_dev_private" {
  vpc_id = module.vpc_dev.vpc_id
  count  = 3
  depends_on = [
     ##HOW TO ADD NAT GATEWAY DEPENDCIE HERE
    ]

}
</code>```

My question how can I add the NAT gateway dependencies in the route_table resource ?? Since  both resources are created with count i can't statically specify the name here

答:
We don't usually need to use depends_on because in most cases the dependencies between objects are implied by data flow between them. In this case, this would become true when you write the route block describing the route to the NAT gateway:

```<code>resource "aws_route_table" "route_table_ics_ec1_dev_private" {
  vpc_id = module.vpc_dev.vpc_id
  count  = 3

  route {
    cidr_block     = "0.0.0.0/0"
    nat_gateway_id = aws_nat_gateway.nat_gateway_ec1_dev[count.index].id
  }
}
</code>```

Because the configuration for that route depends on the id of the NAT gateway, Terraform can see that it must wait until after the NAT gateway is created before it starts creating the route table.

depends_on is for more complicated situations where the data flow between objects is insufficient because the final result depends on some side-effects that are implied by the remote API rather than explicit in Terraform. One example of such a situation is where an object doesn't become usable until an access policy is applied to it in a separate step, such as with an S3 bucket and an associated bucket policy:

```<code>resource "aws_s3_bucket" "example" {
  # ...
}

resource "aws_s3_bucket_policy" "example" {
  bucket = aws_s3_bucket.example.bucket
  policy = # ...
}
</code>```

In the above, Terraform can understand that it must create the bucket before creating the policy, but if something elsewhere in the configuration is also using that S3 bucket then it might be necessary for it to declare an explicit dependency on the policy to make sure that the necessary access rules will be in effect before trying that operation:

```<code>  # Service cannot access the data from the S3 bucket
  # until the policy has been activated.
  depends_on = [aws_s3_bucket_policy.example]
</code>```

Neither count and for_each make any difference to depends_on: dependencies between resources in Terraform are always for entire resource and data blocks, not for the individual instances created from them. Therefore in your case if an explicit dependency on the NAT gateway were needed (which is isn't) then you would write it the same way, regardless of the fact that count is set on that resource:

```<code>  # Not actually needed, but included for the sake of example.
  depends_on = [aws_nat_gateway.nat_gateway_ec1_dev]
</code>```

Body:
I have created a set of  NAT gateway with count

resource "aws_nat_gateway" "nat_gateway_ec1_dev" {
  count         = 3

}

And I would like to this as dependence resource  while creating route table in which I am also using count

resource "aws_route_table" "route_table_ics_ec1_dev_private" {
  vpc_id = module.vpc_dev.vpc_id
  count  = 3
  depends_on = [
     ##HOW TO ADD NAT GATEWAY DEPENDCIE HERE
    ]

}

My question how can I add the NAT gateway dependencies in the route_table resource ?? Since  both resources are created with count i can't statically specify the name here

Body:
We don't usually need to use depends_on because in most cases the dependencies between objects are implied by data flow between them. In this case, this would become true when you write the route block describing the route to the NAT gateway:

resource "aws_route_table" "route_table_ics_ec1_dev_private" {
  vpc_id = module.vpc_dev.vpc_id
  count  = 3

  route {
    cidr_block     = "0.0.0.0/0"
    nat_gateway_id = aws_nat_gateway.nat_gateway_ec1_dev[count.index].id
  }
}

Because the configuration for that route depends on the id of the NAT gateway, Terraform can see that it must wait until after the NAT gateway is created before it starts creating the route table.

depends_on is for more complicated situations where the data flow between objects is insufficient because the final result depends on some side-effects that are implied by the remote API rather than explicit in Terraform. One example of such a situation is where an object doesn't become usable until an access policy is applied to it in a separate step, such as with an S3 bucket and an associated bucket policy:

resource "aws_s3_bucket" "example" {
  # ...
}

resource "aws_s3_bucket_policy" "example" {
  bucket = aws_s3_bucket.example.bucket
  policy = # ...
}

In the above, Terraform can understand that it must create the bucket before creating the policy, but if something elsewhere in the configuration is also using that S3 bucket then it might be necessary for it to declare an explicit dependency on the policy to make sure that the necessary access rules will be in effect before trying that operation:

  # Service cannot access the data from the S3 bucket
  # until the policy has been activated.
  depends_on = [aws_s3_bucket_policy.example]

Neither count and for_each make any difference to depends_on: dependencies between resources in Terraform are always for entire resource and data blocks, not for the individual instances created from them. Therefore in your case if an explicit dependency on the NAT gateway were needed (which is isn't) then you would write it the same way, regardless of the fact that count is set on that resource:

  # Not actually needed, but included for the sake of example.
  depends_on = [aws_nat_gateway.nat_gateway_ec1_dev]


问:
Is there a way to know what activated QAction?
I have created instance of QAction inside QGraphicsView child class and connected it to my slot in the same class.

```<code>QAction *action   = new QAction(tr("New"), this);
action->setObjectName("addStopAction");
action->setShortcut(QKeySequence(Qt::ControlModifier | Qt::Key_N));
connect(action, SIGNAL(triggered()), this, SLOT(addNew()));
addAction(action);
</code>```

Slot is a function creating new instance of QGraphicsItem on scene assigned to QGraphicsView.

```<code>void MyGraphicsView::addNew() {
    // Insert new item at cursor position
}
</code>```

I also add this action to a QMenu which serves as my class context menu.

```<code>QMenu *contextMenu = new QMenu(this);
contextMenu->addAction(action);
</code>```

Everything works fine. When I press Command/Ctrl + N new item is created at cursor position. But when I right-click and select action from context menu I want new item to be created at menu positon.

I can, of course, do some little hack to flag if SLOT was called after contextMenuEvent or something like that, but what I would like to know is:

Is there any way to find out what made QAction emit its triggered() signal inside connected SLOT? That way I could handle when I should place new item at cursor position and when at context menu position inside SLOT implementation.

答:
You can reference self.sender() in the function that is called when by customContextMenuRequested signal.

```<code>self.tree1.customContextMenuRequested.connect(self.menu1pop)  # rightclick menu signal

...

def menu1pop(self, pos):

    widget = self.sender()

    item = widget.itemAt(pos)
    if item is None: return            # only show contextmenu if on an item
    self.setProperty("mywidget", widget)  # pass current widget
    self.menu1.popup(QCursor.pos())    # show menu at right click cursor position
</code>```

self.sender() will return your widget object and then you can set the widget object inside a property.

Then when your action function is called you can recall the widget object by reading the property.

```<code>widget = self.property("mywidget")
</code>```

It's a bit of a hack, but a simple and reliable way to know which widget your action was called from.

Body:
I have created instance of QAction inside QGraphicsView child class and connected it to my slot in the same class.

QAction *action   = new QAction(tr("New"), this);
action->setObjectName("addStopAction");
action->setShortcut(QKeySequence(Qt::ControlModifier | Qt::Key_N));
connect(action, SIGNAL(triggered()), this, SLOT(addNew()));
addAction(action);

Slot is a function creating new instance of QGraphicsItem on scene assigned to QGraphicsView.

void MyGraphicsView::addNew() {
    // Insert new item at cursor position
}

I also add this action to a QMenu which serves as my class context menu.

QMenu *contextMenu = new QMenu(this);
contextMenu->addAction(action);

Everything works fine. When I press Command/Ctrl + N new item is created at cursor position. But when I right-click and select action from context menu I want new item to be created at menu positon.

I can, of course, do some little hack to flag if SLOT was called after contextMenuEvent or something like that, but what I would like to know is:

Is there any way to find out what made QAction emit its triggered() signal inside connected SLOT? That way I could handle when I should place new item at cursor position and when at context menu position inside SLOT implementation.

Body:
You can reference self.sender() in the function that is called when by customContextMenuRequested signal.

self.tree1.customContextMenuRequested.connect(self.menu1pop)  # rightclick menu signal

...

def menu1pop(self, pos):

    widget = self.sender()

    item = widget.itemAt(pos)
    if item is None: return            # only show contextmenu if on an item
    self.setProperty("mywidget", widget)  # pass current widget
    self.menu1.popup(QCursor.pos())    # show menu at right click cursor position

self.sender() will return your widget object and then you can set the widget object inside a property.

Then when your action function is called you can recall the widget object by reading the property.

widget = self.property("mywidget")

It's a bit of a hack, but a simple and reliable way to know which widget your action was called from.


问:
Python regex to findall across multiple lines
I've tried solving this problem over the past week without making any progress. Any help from y'all is much appreciated.

I've got 1000s of files with the following text:

```<code>,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,
Location:,,,ADDRESS_HERE_THAT I WANT
BUT IT CAN ALSO BE ACROSS,
MULTIPLE LINES, BUT NOT A SPECIFIC SET OF LINES,
AND IT ENDS AS ABRUPTLY,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,
</code>```

But a few files also have it in this manner

```<code>,,,,,,,,,,,,,,,,
Location:,,,ADDRESS,IS,IN,ONE,LINE,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,
</code>```

I need to extract the uppercase address using regex in Python.

It's technically a CSV file that's been exported by a very old system. It is effectively unusable as a CSV and hence I've opted to extract the string assuming it is a plain-text file.

My current code is this, but I've tried quite a few other combinations without arriving at a working solution.

```<code>location = re.findall(r'^Location:,,,(.*),,,,,,,,,,,,,\n$|^Location:,,,(.*)[\n.*]{1,2,3,4,5,6},,,,,,,,,,,,,', CSV, flags=re.DOTALL | re.MULTILINE)
</code>```

Am I even close? Or is there a better way to solve this?

I'm grateful for any help here.

答:
Here is an idea: You can use simple looping to detect and extract the multi-lines location data

```<code># Test data
TEXT=""",,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,
Location:,,,ADDRESS_HERE_THAT I WANT
BUT IT CAN ALSO BE ACROSS,
MULTIPLE LINES, BUT NOT A SPECIFIC SET OF LINES,
AND IT ENDS AS ABRUPTLY,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,
Location:,,,ADDRESS,IS,IN,ONE,LINE,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,
"""

in_location = False
tmp_location = None

def extract_location(l):
    global in_location
    global tmp_location
    if l.startswith("Location:"):
        in_location = True
        tmp_location = []
        # special case
        if l.endswith(',,,,,,,,,,,,,'):
            print(l[13:-13])
            in_location = False
        else:
            tmp_location.append(l[13:]) # Don't need 'Location:,,,'
    else:
        if in_location:
            tmp_location.append(l)
            if l.endswith(',,,,,,,,,,,,,'):
                # The end
                in_location = False
                res =  " ".join(tmp_location)
                print(res[0:-13])  # Remove trailing commas

def main():
    for line in TEXT.split("\n"):
        extract_location(line)

if __name__ == "__main__":
    main()
</code>```

let's say it is saved to a file called concept.py,

```<code>$ python3 concept.py
DDRESS_HERE_THAT I WANT BUT IT CAN ALSO BE ACROSS, MULTIPLE LINES, BUT NOT A SPECIFIC SET OF LINES, AND IT ENDS AS ABRUPTLY
DDRESS,IS,IN,ONE,LINE
</code>```

Body:
I've tried solving this problem over the past week without making any progress. Any help from y'all is much appreciated.

I've got 1000s of files with the following text:

,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,
Location:,,,ADDRESS_HERE_THAT I WANT
BUT IT CAN ALSO BE ACROSS,
MULTIPLE LINES, BUT NOT A SPECIFIC SET OF LINES,
AND IT ENDS AS ABRUPTLY,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,

But a few files also have it in this manner

,,,,,,,,,,,,,,,,
Location:,,,ADDRESS,IS,IN,ONE,LINE,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,

I need to extract the uppercase address using regex in Python.

It's technically a CSV file that's been exported by a very old system. It is effectively unusable as a CSV and hence I've opted to extract the string assuming it is a plain-text file.

My current code is this, but I've tried quite a few other combinations without arriving at a working solution.

location = re.findall(r'^Location:,,,(.*),,,,,,,,,,,,,\n$|^Location:,,,(.*)[\n.*]{1,2,3,4,5,6},,,,,,,,,,,,,', CSV, flags=re.DOTALL | re.MULTILINE)

Am I even close? Or is there a better way to solve this?

I'm grateful for any help here.

Body:
Here is an idea: You can use simple looping to detect and extract the multi-lines location data

# Test data
TEXT=""",,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,
Location:,,,ADDRESS_HERE_THAT I WANT
BUT IT CAN ALSO BE ACROSS,
MULTIPLE LINES, BUT NOT A SPECIFIC SET OF LINES,
AND IT ENDS AS ABRUPTLY,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,
Location:,,,ADDRESS,IS,IN,ONE,LINE,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,
"""

in_location = False
tmp_location = None

def extract_location(l):
    global in_location
    global tmp_location
    if l.startswith("Location:"):
        in_location = True
        tmp_location = []
        # special case
        if l.endswith(',,,,,,,,,,,,,'):
            print(l[13:-13])
            in_location = False
        else:
            tmp_location.append(l[13:]) # Don't need 'Location:,,,'
    else:
        if in_location:
            tmp_location.append(l)
            if l.endswith(',,,,,,,,,,,,,'):
                # The end
                in_location = False
                res =  " ".join(tmp_location)
                print(res[0:-13])  # Remove trailing commas

def main():
    for line in TEXT.split("\n"):
        extract_location(line)

if __name__ == "__main__":
    main()

let's say it is saved to a file called concept.py,

$ python3 concept.py
DDRESS_HERE_THAT I WANT BUT IT CAN ALSO BE ACROSS, MULTIPLE LINES, BUT NOT A SPECIFIC SET OF LINES, AND IT ENDS AS ABRUPTLY
DDRESS,IS,IN,ONE,LINE