问:
SSH times out while connecting via ipv6 but works with ipv4
Yesterday I reinstalled my Ubuntu (for unrelated reasons) and since then ssh behaves very weirdly.

It takes suuuper long to connect (multiple minutes). Using -vvv I found that it first tries to connect using an ipv6 (which times out) and after that tries to connect via ipv4 which works almost instantly.

I never had any issues with ssh before.

running

```<code>ssh login@address.net -vvv
</code>```

(with the address I want to connect to) returns

```<code>OpenSSH_8.2p1 Ubuntu-4, OpenSSL 1.1.1f  31 Mar 2020
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: include /etc/ssh/ssh_config.d/*.conf matched no files
debug1: /etc/ssh/ssh_config line 21: Applying options for *
debug2: resolving "address.net" port 22
debug2: ssh_connect_direct
debug1: Connecting to address.net [*:*:*:*::*] port 22.
debug1: connect to address *:*:*:*::* port 22: Connection timed out
debug1: Connecting to address.net [*.*.*.*] port 22.
debug1: Connection established.
debug1: identity file /home/malte/.ssh/id_rsa type 0
debug1: identity file /home/malte/.ssh/id_rsa-cert type -1
debug1: identity file /home/malte/.ssh/id_dsa type -1
debug1: identity file /home/malte/.ssh/id_dsa-cert type -1
debug1: identity file /home/malte/.ssh/id_ecdsa type -1
debug1: identity file /home/malte/.ssh/id_ecdsa-cert type -1
debug1: identity file /home/malte/.ssh/id_ecdsa_sk type -1
debug1: identity file /home/malte/.ssh/id_ecdsa_sk-cert type -1
debug1: identity file /home/malte/.ssh/id_ed25519 type -1
debug1: identity file /home/malte/.ssh/id_ed25519-cert type -1
debug1: identity file /home/malte/.ssh/id_ed25519_sk type -1
debug1: identity file /home/malte/.ssh/id_ed25519_sk-cert type -1
debug1: identity file /home/malte/.ssh/id_xmss type -1
debug1: identity file /home/malte/.ssh/id_xmss-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_8.2p1 Ubuntu-4
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.6p1 Ubuntu-4ubuntu0.3
debug1: match: OpenSSH_7.6p1 Ubuntu-4ubuntu0.3 pat OpenSSH_7.0*,OpenSSH_7.1*,OpenSSH_7.2*,OpenSSH_7.3*,OpenSSH_7.4*,OpenSSH_7.5*,OpenSSH_7.6*,OpenSSH_7.7* compat 0x04000002
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to login.caps.in.tum.de:22 as 'ehren'
debug3: hostkeys_foreach: reading file "/home/malte/.ssh/known_hosts"
debug3: record_hostkey: found key type ED25519 in file /home/malte/.ssh/known_hosts:1
debug3: load_hostkeys: loaded 1 keys from login.caps.in.tum.de
debug3: order_hostkeyalgs: prefer hostkeyalgs: ssh-ed25519-cert-v01@openssh.com,ssh-ed25519
debug3: send packet: type 20
debug1: SSH2_MSG_KEXINIT sent
debug3: receive packet: type 20
debug1: SSH2_MSG_KEXINIT received
debug2: local client KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256,ext-info-c
debug2: host key algorithms: ssh-ed25519-cert-v01@openssh.com,ssh-ed25519,ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,sk-ecdsa-sha2-nistp256-cert-v01@openssh.com,sk-ssh-ed25519-cert-v01@openssh.com,rsa-sha2-512-cert-v01@openssh.com,rsa-sha2-256-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,sk-ecdsa-sha2-nistp256@openssh.com,sk-ssh-ed25519@openssh.com,rsa-sha2-512,rsa-sha2-256,ssh-rsa
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com,zlib
debug2: compression stoc: none,zlib@openssh.com,zlib
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug2: peer server KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1
debug2: host key algorithms: ssh-rsa,rsa-sha2-512,rsa-sha2-256,ecdsa-sha2-nistp256,ssh-ed25519,ssh-ed25519-cert-v01@openssh.com
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com
debug2: compression stoc: none,zlib@openssh.com
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug1: kex: algorithm: curve25519-sha256
debug1: kex: host key algorithm: ssh-ed25519-cert-v01@openssh.com
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug3: send packet: type 30
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug3: receive packet: type 31
debug1: Server host certificate: ssh-ed25519-cert-v01@openssh.com SHA256:3rfJzCTfq9xb2UYjwCf+FLMo5s46IDcAeKWN4OEN9Qw, serial 0 ID "host:intum:vmschulz30" CA ssh-ed25519 SHA256:xw6Z8D0o6klmmOcnCzhqhTkitvGcjuuQ9JsunW4bvm8 valid forever
debug2: Server host certificate hostname: vmschulz30
debug2: Server host certificate hostname: vmschulz30.in.tum.de
debug3: hostkeys_foreach: reading file "/home/malte/.ssh/known_hosts"
debug3: record_hostkey: found key type ED25519 in file /home/malte/.ssh/known_hosts:1
debug3: load_hostkeys: loaded 1 keys from login.caps.in.tum.de
debug1: No matching CA found. Retry with plain key
debug1: Host 'login.caps.in.tum.de' is known and matches the ED25519 host key.
debug1: Found key in /home/malte/.ssh/known_hosts:1
debug3: send packet: type 21
debug2: set_newkeys: mode 1
debug1: rekey out after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug3: receive packet: type 21
debug1: SSH2_MSG_NEWKEYS received
debug2: set_newkeys: mode 0
debug1: rekey in after 134217728 blocks
debug1: Will attempt key: /home/malte/.ssh/id_rsa RSA SHA256:nmOOjBiUCmQEF8b08sB9LIwjSfwxA03cRStE6BrNe2g agent
debug1: Will attempt key: /home/malte/.ssh/id_dsa
debug1: Will attempt key: /home/malte/.ssh/id_ecdsa
debug1: Will attempt key: /home/malte/.ssh/id_ecdsa_sk
debug1: Will attempt key: /home/malte/.ssh/id_ed25519
debug1: Will attempt key: /home/malte/.ssh/id_ed25519_sk
debug1: Will attempt key: /home/malte/.ssh/id_xmss
debug2: pubkey_prepare: done
debug3: send packet: type 5
debug3: receive packet: type 7
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<ssh-ed25519,ssh-rsa,rsa-sha2-256,rsa-sha2-512,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521>
debug3: receive packet: type 6
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug3: send packet: type 50
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey,password
debug3: start over, passed a different list publickey,password
debug3: preferred gssapi-with-mic,publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering public key: /home/malte/.ssh/id_rsa RSA SHA256:nmOOjBiUCmQEF8b08sB9LIwjSfwxA03cRStE6BrNe2g agent
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey,password
debug1: Trying private key: /home/malte/.ssh/id_dsa
debug3: no such identity: /home/malte/.ssh/id_dsa: No such file or directory
debug1: Trying private key: /home/malte/.ssh/id_ecdsa
debug3: no such identity: /home/malte/.ssh/id_ecdsa: No such file or directory
debug1: Trying private key: /home/malte/.ssh/id_ecdsa_sk
debug3: no such identity: /home/malte/.ssh/id_ecdsa_sk: No such file or directory
debug1: Trying private key: /home/malte/.ssh/id_ed25519
debug3: no such identity: /home/malte/.ssh/id_ed25519: No such file or directory
debug1: Trying private key: /home/malte/.ssh/id_ed25519_sk
debug3: no such identity: /home/malte/.ssh/id_ed25519_sk: No such file or directory
debug1: Trying private key: /home/malte/.ssh/id_xmss
debug3: no such identity: /home/malte/.ssh/id_xmss: No such file or directory
debug2: we did not send a packet, disable method
debug3: authmethod_lookup password
debug3: remaining preferred: ,password
debug3: authmethod_is_enabled password
debug1: Next authentication method: password
login@address.net's password:
debug3: send packet: type 50
debug2: we sent a password packet, wait for reply
debug3: receive packet: type 52
debug1: Authentication succeeded (password).
Authenticated to address.net ([*.*.*.*]:22).
debug1: channel 0: new [client-session]
debug3: ssh_session2_open: channel_new: 0
debug2: channel 0: send open
debug3: send packet: type 90
debug1: Requesting no-more-sessions@openssh.com
debug3: send packet: type 80
debug1: Entering interactive session.
debug1: pledge: network
debug3: receive packet: type 80
debug1: client_input_global_request: rtype hostkeys-00@openssh.com want_reply 0
debug3: receive packet: type 91
debug2: channel_input_open_confirmation: channel 0: callback start
debug2: fd 3 setting TCP_NODELAY
debug3: ssh_packet_set_tos: set IP_TOS 0x10
debug2: client_session2_setup: id 0
debug2: channel 0: request pty-req confirm 1
debug3: send packet: type 98
debug1: Sending environment.
debug3: Ignored env SHELL
debug3: Ignored env SESSION_MANAGER
debug3: Ignored env QT_ACCESSIBILITY
debug3: Ignored env COLORTERM
debug3: Ignored env XDG_CONFIG_DIRS
debug3: Ignored env XDG_MENU_PREFIX
debug3: Ignored env GNOME_DESKTOP_SESSION_ID
debug3: Ignored env GTK_IM_MODULE
debug3: Ignored env QT4_IM_MODULE
debug1: Sending env LC_ADDRESS = de_DE.UTF-8
debug2: channel 0: request env confirm 0
debug3: send packet: type 98
debug3: Ignored env GNOME_SHELL_SESSION_MODE
debug1: Sending env LC_NAME = de_DE.UTF-8
debug2: channel 0: request env confirm 0
debug3: send packet: type 98
debug3: Ignored env SSH_AUTH_SOCK
debug3: Ignored env XMODIFIERS
debug3: Ignored env DESKTOP_SESSION
debug1: Sending env LC_MONETARY = de_DE.UTF-8
debug2: channel 0: request env confirm 0
debug3: send packet: type 98
debug3: Ignored env SSH_AGENT_PID
debug3: Ignored env GTK_MODULES
debug3: Ignored env PWD
debug3: Ignored env LOGNAME
debug3: Ignored env XDG_SESSION_DESKTOP
debug3: Ignored env XDG_SESSION_TYPE
debug3: Ignored env GPG_AGENT_INFO
debug3: Ignored env XAUTHORITY
debug3: Ignored env GJS_DEBUG_TOPICS
debug3: Ignored env WINDOWPATH
debug3: Ignored env HOME
debug3: Ignored env USERNAME
debug3: Ignored env IM_CONFIG_PHASE
debug1: Sending env LC_PAPER = de_DE.UTF-8
debug2: channel 0: request env confirm 0
debug3: send packet: type 98
debug1: Sending env LANG = en_US.UTF-8
debug2: channel 0: request env confirm 0
debug3: send packet: type 98
debug3: Ignored env LS_COLORS
debug3: Ignored env XDG_CURRENT_DESKTOP
debug3: Ignored env VTE_VERSION
debug3: Ignored env GNOME_TERMINAL_SCREEN
debug3: Ignored env INVOCATION_ID
debug3: Ignored env MANAGERPID
debug3: Ignored env CLUTTER_IM_MODULE
debug3: Ignored env GJS_DEBUG_OUTPUT
debug3: Ignored env LESSCLOSE
debug3: Ignored env XDG_SESSION_CLASS
debug3: Ignored env TERM
debug1: Sending env LC_IDENTIFICATION = de_DE.UTF-8
debug2: channel 0: request env confirm 0
debug3: send packet: type 98
debug3: Ignored env LESSOPEN
debug3: Ignored env USER
debug3: Ignored env GNOME_TERMINAL_SERVICE
debug3: Ignored env DISPLAY
debug3: Ignored env SHLVL
debug1: Sending env LC_TELEPHONE = de_DE.UTF-8
debug2: channel 0: request env confirm 0
debug3: send packet: type 98
debug3: Ignored env QT_IM_MODULE
debug1: Sending env LC_MEASUREMENT = de_DE.UTF-8
debug2: channel 0: request env confirm 0
debug3: send packet: type 98
debug3: Ignored env XDG_RUNTIME_DIR
debug1: Sending env LC_TIME = de_DE.UTF-8
debug2: channel 0: request env confirm 0
debug3: send packet: type 98
debug3: Ignored env JOURNAL_STREAM
debug3: Ignored env XDG_DATA_DIRS
debug3: Ignored env PATH
debug3: Ignored env GDMSESSION
debug3: Ignored env DBUS_SESSION_BUS_ADDRESS
debug1: Sending env LC_NUMERIC = de_DE.UTF-8
debug2: channel 0: request env confirm 0
debug3: send packet: type 98
debug3: Ignored env OLDPWD
debug3: Ignored env _
debug2: channel 0: request shell confirm 1
debug3: send packet: type 98
debug2: channel_input_open_confirmation: channel 0: callback done
debug2: channel 0: open confirm rwindow 0 rmax 32768
debug3: receive packet: type 99
debug2: channel_input_status_confirm: type 99 id 0
debug2: PTY allocation request accepted on channel 0
debug2: channel 0: rcvd adjust 2097152
debug3: receive packet: type 99
debug2: channel_input_status_confirm: type 99 id 0
debug2: shell request accepted on channel 0
</code>```

annoyling this happens will all servers I try to connect to and also affects git (over ssh)

thanks in advance for any hints as to what the issue could be <3

答: The symptom suggests that after the reinstall there's a different ssh config; check /etc/ssh/ssh_config for AddressFamily set to any; you could set to inet there or privately in ~/.ssh/config

Body:
Yesterday I reinstalled my Ubuntu (for unrelated reasons) and since then ssh behaves very weirdly.

It takes suuuper long to connect (multiple minutes). Using -vvv I found that it first tries to connect using an ipv6 (which times out) and after that tries to connect via ipv4 which works almost instantly.

I never had any issues with ssh before.

running

ssh login@address.net -vvv

(with the address I want to connect to) returns

OpenSSH_8.2p1 Ubuntu-4, OpenSSL 1.1.1f  31 Mar 2020
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: include /etc/ssh/ssh_config.d/*.conf matched no files
debug1: /etc/ssh/ssh_config line 21: Applying options for *
debug2: resolving "address.net" port 22
debug2: ssh_connect_direct
debug1: Connecting to address.net [*:*:*:*::*] port 22.
debug1: connect to address *:*:*:*::* port 22: Connection timed out
debug1: Connecting to address.net [*.*.*.*] port 22.
debug1: Connection established.
debug1: identity file /home/malte/.ssh/id_rsa type 0
debug1: identity file /home/malte/.ssh/id_rsa-cert type -1
debug1: identity file /home/malte/.ssh/id_dsa type -1
debug1: identity file /home/malte/.ssh/id_dsa-cert type -1
debug1: identity file /home/malte/.ssh/id_ecdsa type -1
debug1: identity file /home/malte/.ssh/id_ecdsa-cert type -1
debug1: identity file /home/malte/.ssh/id_ecdsa_sk type -1
debug1: identity file /home/malte/.ssh/id_ecdsa_sk-cert type -1
debug1: identity file /home/malte/.ssh/id_ed25519 type -1
debug1: identity file /home/malte/.ssh/id_ed25519-cert type -1
debug1: identity file /home/malte/.ssh/id_ed25519_sk type -1
debug1: identity file /home/malte/.ssh/id_ed25519_sk-cert type -1
debug1: identity file /home/malte/.ssh/id_xmss type -1
debug1: identity file /home/malte/.ssh/id_xmss-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_8.2p1 Ubuntu-4
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.6p1 Ubuntu-4ubuntu0.3
debug1: match: OpenSSH_7.6p1 Ubuntu-4ubuntu0.3 pat OpenSSH_7.0*,OpenSSH_7.1*,OpenSSH_7.2*,OpenSSH_7.3*,OpenSSH_7.4*,OpenSSH_7.5*,OpenSSH_7.6*,OpenSSH_7.7* compat 0x04000002
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to login.caps.in.tum.de:22 as 'ehren'
debug3: hostkeys_foreach: reading file "/home/malte/.ssh/known_hosts"
debug3: record_hostkey: found key type ED25519 in file /home/malte/.ssh/known_hosts:1
debug3: load_hostkeys: loaded 1 keys from login.caps.in.tum.de
debug3: order_hostkeyalgs: prefer hostkeyalgs: ssh-ed25519-cert-v01@openssh.com,ssh-ed25519
debug3: send packet: type 20
debug1: SSH2_MSG_KEXINIT sent
debug3: receive packet: type 20
debug1: SSH2_MSG_KEXINIT received
debug2: local client KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256,ext-info-c
debug2: host key algorithms: ssh-ed25519-cert-v01@openssh.com,ssh-ed25519,ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,sk-ecdsa-sha2-nistp256-cert-v01@openssh.com,sk-ssh-ed25519-cert-v01@openssh.com,rsa-sha2-512-cert-v01@openssh.com,rsa-sha2-256-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,sk-ecdsa-sha2-nistp256@openssh.com,sk-ssh-ed25519@openssh.com,rsa-sha2-512,rsa-sha2-256,ssh-rsa
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com,zlib
debug2: compression stoc: none,zlib@openssh.com,zlib
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug2: peer server KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1
debug2: host key algorithms: ssh-rsa,rsa-sha2-512,rsa-sha2-256,ecdsa-sha2-nistp256,ssh-ed25519,ssh-ed25519-cert-v01@openssh.com
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com
debug2: compression stoc: none,zlib@openssh.com
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug1: kex: algorithm: curve25519-sha256
debug1: kex: host key algorithm: ssh-ed25519-cert-v01@openssh.com
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug3: send packet: type 30
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug3: receive packet: type 31
debug1: Server host certificate: ssh-ed25519-cert-v01@openssh.com SHA256:3rfJzCTfq9xb2UYjwCf+FLMo5s46IDcAeKWN4OEN9Qw, serial 0 ID "host:intum:vmschulz30" CA ssh-ed25519 SHA256:xw6Z8D0o6klmmOcnCzhqhTkitvGcjuuQ9JsunW4bvm8 valid forever
debug2: Server host certificate hostname: vmschulz30
debug2: Server host certificate hostname: vmschulz30.in.tum.de
debug3: hostkeys_foreach: reading file "/home/malte/.ssh/known_hosts"
debug3: record_hostkey: found key type ED25519 in file /home/malte/.ssh/known_hosts:1
debug3: load_hostkeys: loaded 1 keys from login.caps.in.tum.de
debug1: No matching CA found. Retry with plain key
debug1: Host 'login.caps.in.tum.de' is known and matches the ED25519 host key.
debug1: Found key in /home/malte/.ssh/known_hosts:1
debug3: send packet: type 21
debug2: set_newkeys: mode 1
debug1: rekey out after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug3: receive packet: type 21
debug1: SSH2_MSG_NEWKEYS received
debug2: set_newkeys: mode 0
debug1: rekey in after 134217728 blocks
debug1: Will attempt key: /home/malte/.ssh/id_rsa RSA SHA256:nmOOjBiUCmQEF8b08sB9LIwjSfwxA03cRStE6BrNe2g agent
debug1: Will attempt key: /home/malte/.ssh/id_dsa
debug1: Will attempt key: /home/malte/.ssh/id_ecdsa
debug1: Will attempt key: /home/malte/.ssh/id_ecdsa_sk
debug1: Will attempt key: /home/malte/.ssh/id_ed25519
debug1: Will attempt key: /home/malte/.ssh/id_ed25519_sk
debug1: Will attempt key: /home/malte/.ssh/id_xmss
debug2: pubkey_prepare: done
debug3: send packet: type 5
debug3: receive packet: type 7
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<ssh-ed25519,ssh-rsa,rsa-sha2-256,rsa-sha2-512,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521>
debug3: receive packet: type 6
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug3: send packet: type 50
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey,password
debug3: start over, passed a different list publickey,password
debug3: preferred gssapi-with-mic,publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering public key: /home/malte/.ssh/id_rsa RSA SHA256:nmOOjBiUCmQEF8b08sB9LIwjSfwxA03cRStE6BrNe2g agent
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey,password
debug1: Trying private key: /home/malte/.ssh/id_dsa
debug3: no such identity: /home/malte/.ssh/id_dsa: No such file or directory
debug1: Trying private key: /home/malte/.ssh/id_ecdsa
debug3: no such identity: /home/malte/.ssh/id_ecdsa: No such file or directory
debug1: Trying private key: /home/malte/.ssh/id_ecdsa_sk
debug3: no such identity: /home/malte/.ssh/id_ecdsa_sk: No such file or directory
debug1: Trying private key: /home/malte/.ssh/id_ed25519
debug3: no such identity: /home/malte/.ssh/id_ed25519: No such file or directory
debug1: Trying private key: /home/malte/.ssh/id_ed25519_sk
debug3: no such identity: /home/malte/.ssh/id_ed25519_sk: No such file or directory
debug1: Trying private key: /home/malte/.ssh/id_xmss
debug3: no such identity: /home/malte/.ssh/id_xmss: No such file or directory
debug2: we did not send a packet, disable method
debug3: authmethod_lookup password
debug3: remaining preferred: ,password
debug3: authmethod_is_enabled password
debug1: Next authentication method: password
login@address.net's password:
debug3: send packet: type 50
debug2: we sent a password packet, wait for reply
debug3: receive packet: type 52
debug1: Authentication succeeded (password).
Authenticated to address.net ([*.*.*.*]:22).
debug1: channel 0: new [client-session]
debug3: ssh_session2_open: channel_new: 0
debug2: channel 0: send open
debug3: send packet: type 90
debug1: Requesting no-more-sessions@openssh.com
debug3: send packet: type 80
debug1: Entering interactive session.
debug1: pledge: network
debug3: receive packet: type 80
debug1: client_input_global_request: rtype hostkeys-00@openssh.com want_reply 0
debug3: receive packet: type 91
debug2: channel_input_open_confirmation: channel 0: callback start
debug2: fd 3 setting TCP_NODELAY
debug3: ssh_packet_set_tos: set IP_TOS 0x10
debug2: client_session2_setup: id 0
debug2: channel 0: request pty-req confirm 1
debug3: send packet: type 98
debug1: Sending environment.
debug3: Ignored env SHELL
debug3: Ignored env SESSION_MANAGER
debug3: Ignored env QT_ACCESSIBILITY
debug3: Ignored env COLORTERM
debug3: Ignored env XDG_CONFIG_DIRS
debug3: Ignored env XDG_MENU_PREFIX
debug3: Ignored env GNOME_DESKTOP_SESSION_ID
debug3: Ignored env GTK_IM_MODULE
debug3: Ignored env QT4_IM_MODULE
debug1: Sending env LC_ADDRESS = de_DE.UTF-8
debug2: channel 0: request env confirm 0
debug3: send packet: type 98
debug3: Ignored env GNOME_SHELL_SESSION_MODE
debug1: Sending env LC_NAME = de_DE.UTF-8
debug2: channel 0: request env confirm 0
debug3: send packet: type 98
debug3: Ignored env SSH_AUTH_SOCK
debug3: Ignored env XMODIFIERS
debug3: Ignored env DESKTOP_SESSION
debug1: Sending env LC_MONETARY = de_DE.UTF-8
debug2: channel 0: request env confirm 0
debug3: send packet: type 98
debug3: Ignored env SSH_AGENT_PID
debug3: Ignored env GTK_MODULES
debug3: Ignored env PWD
debug3: Ignored env LOGNAME
debug3: Ignored env XDG_SESSION_DESKTOP
debug3: Ignored env XDG_SESSION_TYPE
debug3: Ignored env GPG_AGENT_INFO
debug3: Ignored env XAUTHORITY
debug3: Ignored env GJS_DEBUG_TOPICS
debug3: Ignored env WINDOWPATH
debug3: Ignored env HOME
debug3: Ignored env USERNAME
debug3: Ignored env IM_CONFIG_PHASE
debug1: Sending env LC_PAPER = de_DE.UTF-8
debug2: channel 0: request env confirm 0
debug3: send packet: type 98
debug1: Sending env LANG = en_US.UTF-8
debug2: channel 0: request env confirm 0
debug3: send packet: type 98
debug3: Ignored env LS_COLORS
debug3: Ignored env XDG_CURRENT_DESKTOP
debug3: Ignored env VTE_VERSION
debug3: Ignored env GNOME_TERMINAL_SCREEN
debug3: Ignored env INVOCATION_ID
debug3: Ignored env MANAGERPID
debug3: Ignored env CLUTTER_IM_MODULE
debug3: Ignored env GJS_DEBUG_OUTPUT
debug3: Ignored env LESSCLOSE
debug3: Ignored env XDG_SESSION_CLASS
debug3: Ignored env TERM
debug1: Sending env LC_IDENTIFICATION = de_DE.UTF-8
debug2: channel 0: request env confirm 0
debug3: send packet: type 98
debug3: Ignored env LESSOPEN
debug3: Ignored env USER
debug3: Ignored env GNOME_TERMINAL_SERVICE
debug3: Ignored env DISPLAY
debug3: Ignored env SHLVL
debug1: Sending env LC_TELEPHONE = de_DE.UTF-8
debug2: channel 0: request env confirm 0
debug3: send packet: type 98
debug3: Ignored env QT_IM_MODULE
debug1: Sending env LC_MEASUREMENT = de_DE.UTF-8
debug2: channel 0: request env confirm 0
debug3: send packet: type 98
debug3: Ignored env XDG_RUNTIME_DIR
debug1: Sending env LC_TIME = de_DE.UTF-8
debug2: channel 0: request env confirm 0
debug3: send packet: type 98
debug3: Ignored env JOURNAL_STREAM
debug3: Ignored env XDG_DATA_DIRS
debug3: Ignored env PATH
debug3: Ignored env GDMSESSION
debug3: Ignored env DBUS_SESSION_BUS_ADDRESS
debug1: Sending env LC_NUMERIC = de_DE.UTF-8
debug2: channel 0: request env confirm 0
debug3: send packet: type 98
debug3: Ignored env OLDPWD
debug3: Ignored env _
debug2: channel 0: request shell confirm 1
debug3: send packet: type 98
debug2: channel_input_open_confirmation: channel 0: callback done
debug2: channel 0: open confirm rwindow 0 rmax 32768
debug3: receive packet: type 99
debug2: channel_input_status_confirm: type 99 id 0
debug2: PTY allocation request accepted on channel 0
debug2: channel 0: rcvd adjust 2097152
debug3: receive packet: type 99
debug2: channel_input_status_confirm: type 99 id 0
debug2: shell request accepted on channel 0

annoyling this happens will all servers I try to connect to and also affects git (over ssh)

thanks in advance for any hints as to what the issue could be <3


来源: stackexchange

问:
Is an empty block optimized away? C#
I am developing a game server in C# and a specific packet gets sent to my server 3 to 5 times per second per player. We will call that packet PacketA. I don't do anything with it except make sure that I receive it.

Since this packet gets sent the most, I want to place it first in the switch block so I don't have to make so many unnecessary comparisons. Will the compiler end up optimizing it away anyways (which will cause me to make all the comparisons down the switch block?)

```<code>switch (packetId)
{
    case PacketID.PacketA: // I do not want to do anything here.
        break;             // Just avoid all other packet id comparisons.

    case PacketID.PacketB:
        HandlePacketB(data);
        break;

    case PacketID.PacketC:
        HandlePacketC(data);
        break;

    // ...

    case PacketID.PacketZ:
       HandlePacketZ(data);
       break;
}
</code>```

If the compiler does optimize this away, how can I change my code so I don't have to check all the other packet ids?

答:
The switch statement in C# is optimized in a way that allows for a very quick evaluation of where to go.  It doesn't read down through the list of options exactly.  Instead it creates a jump list that it optimized for identifying which case to execute.  Here is a link with more information about it:

http://www.dotnetperls.com/switch-char

Basically, I would suggest that you test the performance of this statement compared to another statement (such as doing an if statement for just that first case and then doing a switch statement if it isn't PacketA).  I would imagine that in the end the switch statement is the way to go.

If you decide that you want to dig into your app by decompiling it, you can use the new (free) tool from Telerik:

http://www.telerik.com/products/decompiling.aspx

ContentLicense: CC BY-SA 3.0

Title: Is an empty block optimized away? C#

Body:
I am developing a game server in C# and a specific packet gets sent to my server 3 to 5 times per second per player. We will call that packet PacketA. I don't do anything with it except make sure that I receive it.

Since this packet gets sent the most, I want to place it first in the switch block so I don't have to make so many unnecessary comparisons. Will the compiler end up optimizing it away anyways (which will cause me to make all the comparisons down the switch block?)

switch (packetId)
{
    case PacketID.PacketA: // I do not want to do anything here.
        break;             // Just avoid all other packet id comparisons.

    case PacketID.PacketB:
        HandlePacketB(data);
        break;

    case PacketID.PacketC:
        HandlePacketC(data);
        break;

    // ...

    case PacketID.PacketZ:
       HandlePacketZ(data);
       break;
}

If the compiler does optimize this away, how can I change my code so I don't have to check all the other packet ids?


问:
Fill missing values based unique IDs from another column
I have a data frame with User ID and a Device Model values

The User ID is unique for each user however there are duplicates for multiple logins and there are no missing values
Device Model has missing value

I need to address the same device model for users that has the same User ID. Like This:

```<code>    Device Model        User ID

0   iPhone 11   1590761773215-7300441
1   iPhone XR   1590761549649-1399336
2   NAN         1590761549649-1399336
3   iPhone 7    1589030810407-6386535
4   NAN         1590761773215-7300441

    Device Model        User ID

0   iPhone 11   1590761773215-7300441
1   iPhone XR   1590761549649-1399336
2   iPhone XR   1590761549649-1399336
3   iPhone 7    1589030810407-6386535
4   iPhone 11   1590761773215-7300441
</code>```

Does anybody knows how to solve this? I tried to use join (below) but it didnt work and I dont know any other solution for this

```<code>join_df_device = pd.merge(device_model_df,device_type_nonull,on ='Device Model',how ='left')
</code>```

join_df_device

答:
From what I understood,

Use df.groupby to group all similar User ID and use df.fillna

```<code>df['Device_Model'] = df.groupby('User_ID')['Device_Model'].ffill().bfill()

    Device_Model        User_ID
0   iPhone 11   1590761773215-7300441
1   iPhone XR   1590761549649-1399336
2   iPhone XR   1590761549649-1399336
3   iPhone 7    1589030810407-6386535
4   iPhone 11   1590761773215-7300441
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a data frame with User ID and a Device Model values

The User ID is unique for each user however there are duplicates for multiple logins and there are no missing values
Device Model has missing value

I need to address the same device model for users that has the same User ID. Like This:

    Device Model        User ID

0   iPhone 11   1590761773215-7300441
1   iPhone XR   1590761549649-1399336
2   NAN         1590761549649-1399336
3   iPhone 7    1589030810407-6386535
4   NAN         1590761773215-7300441

    Device Model        User ID

0   iPhone 11   1590761773215-7300441
1   iPhone XR   1590761549649-1399336
2   iPhone XR   1590761549649-1399336
3   iPhone 7    1589030810407-6386535
4   iPhone 11   1590761773215-7300441

Does anybody knows how to solve this? I tried to use join (below) but it didnt work and I dont know any other solution for this

join_df_device = pd.merge(device_model_df,device_type_nonull,on ='Device Model',how ='left')

join_df_device

Body:
From what I understood,

Use df.groupby to group all similar User ID and use df.fillna

df['Device_Model'] = df.groupby('User_ID')['Device_Model'].ffill().bfill()

    Device_Model        User_ID
0   iPhone 11   1590761773215-7300441
1   iPhone XR   1590761549649-1399336
2   iPhone XR   1590761549649-1399336
3   iPhone 7    1589030810407-6386535
4   iPhone 11   1590761773215-7300441


问:
How to hide files from getting pushed to Github but still have them push to Heroku
Sorry if this is a stupid question.

I'm using OAuth2 in a heroku app that also has a public github repo. If I exclude the file that has the OAuth2 credentials via the .gitignore, will that file still get pushed to the Heroku app? If not, what's the ebst way to keep the credentials from getting published on github, but still have access to them in my heroku app?

答:
I had a similar problem and the above solution worked fine. In my case I just did

heroku config:add KEY1=VALUE1 KEY2=VALUE2
```

The only thing is to separate multiple values with a space I guess :)

Body:
I had a similar problem and the above solution worked fine. In my case I just did

heroku config:add KEY1=VALUE1 KEY2=VALUE2

The only thing is to separate multiple values with a space I guess :)


问:
How to check if an element from an ArrayList is equal to a certain value?
I have an ArrayList list1 which contains the following values: {"A", "A", "A", "B", "B", "A", "C", "C", "B", "B", "B"}.

I want to count how many times each of the letters (A, B and C) repeat in list1.

I have done the following, but the result is 0.

```<code>for (i=0; i<=list1.size(); i++) {
    switch (list1.get(i)) {
        case "A":
            LetterA = LetterA + 1;
        case "B":
            LetterB = LetterB + 1;
        case "C":
            LetterC = LetterC + 1;
    }
}

Toast.makeText(getApplicationContext(), "Letter A repeats: " + LetterA + " times" + "\nLetter B repeats: " + LetterB + " times" +
"\nLetterC repeats: " + LetterC + " times", Toast.LENGTH_LONG).show();
</code>```

UPDATE: The problem was that I accidentally looped through list1 instead of list2, which actually contained the letters. However, even when I changed this, it still showed incorrect values. Therefore I changed the switch to this:

```<code>for (i=0; i<=list2.size(); i++) {
    if (list2.get(i).equals("A")) {
        LetterA = LetterA + 1;
    } else if (list2.get(i).equals("B")) {
        LetterB = LetterB + 1;
    } else if (list2.get(i).equals("C")) {
        LetterC = LetterC + 1;
    }
}
</code>```

Now everything works perfectly.

答:
Could you try this?</p>

```<code>        Map<String, Long> counted = list1.stream()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        System.out.println(counted);
</code>```

Body:
I have an ArrayList list1 which contains the following values: {"A", "A", "A", "B", "B", "A", "C", "C", "B", "B", "B"}.

I want to count how many times each of the letters (A, B and C) repeat in list1.

I have done the following, but the result is 0.

for (i=0; i<=list1.size(); i++) {
    switch (list1.get(i)) {
        case "A":
            LetterA = LetterA + 1;
        case "B":
            LetterB = LetterB + 1;
        case "C":
            LetterC = LetterC + 1;
    }
}

Toast.makeText(getApplicationContext(), "Letter A repeats: " + LetterA + " times" + "\nLetter B repeats: " + LetterB + " times" +
"\nLetterC repeats: " + LetterC + " times", Toast.LENGTH_LONG).show();

UPDATE: The problem was that I accidentally looped through list1 instead of list2, which actually contained the letters. However, even when I changed this, it still showed incorrect values. Therefore I changed the switch to this:

for (i=0; i<=list2.size(); i++) {
    if (list2.get(i).equals("A")) {
        LetterA = LetterA + 1;
    } else if (list2.get(i).equals("B")) {
        LetterB = LetterB + 1;
    } else if (list2.get(i).equals("C")) {
        LetterC = LetterC + 1;
    }
}

Now everything works perfectly.

Body:
Could you try this?

        Map<String, Long> counted = list1.stream()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        System.out.println(counted);


问:
Call child component method from parent class - Angular
I have created a child component which has a method I want to invoke.

When I invoke this method it only fires the console.log() line, it will not set the test property??

Below is the quick start Angular app with my changes.

Parent

```<code>import { Component } from '@angular/core';
import { NotifyComponent }  from './notify.component';

@Component({
    selector: 'my-app',
    template:
    `
    <button (click)="submit()">Call Child Component Method</button>
    `
})
export class AppComponent {
    private notify: NotifyComponent;

    constructor() {
      this.notify = new NotifyComponent();
    }

    submit(): void {
        // execute child component method
        notify.callMethod();
    }
}
</code>```

Child

```<code>import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'notify',
    template: '<h3>Notify {{test}}</h3>'
})
export class NotifyComponent implements OnInit {
   test:string;
   constructor() { }

    ngOnInit() { }

    callMethod(): void {
        console.log('successfully executed.');
        this.test = 'Me';
    }
}
</code>```

How can I set the test property as well?

答:
I had an exact situation where the Parent-component had a Select element in a form and on submit, I needed to call the relevant Child-Component's method according to the selected value from the select element.

Parent.HTML:

```<code><form (ngSubmit)='selX' [formGroup]="xSelForm">
    <select formControlName="xSelector">
      ...
    </select>
<button type="submit">Submit</button>
</form>
<child [selectedX]="selectedX"></child>
</code>```

Parent.TS:

```<code>selX(){
  this.selectedX = this.xSelForm.value['xSelector'];
}
</code>```

Child.TS:

```<code>export class ChildComponent implements OnChanges {
  @Input() public selectedX;

  //ngOnChanges will execute if there is a change in the value of selectedX which has been passed to child as an @Input.

  ngOnChanges(changes: { [propKey: string]: SimpleChange }) {
    this.childFunction();
  }
  childFunction(){ }
}
</code>```

Hope this helps.

Body:
I have created a child component which has a method I want to invoke.

When I invoke this method it only fires the console.log() line, it will not set the test property??

Below is the quick start Angular app with my changes.

Parent

import { Component } from '@angular/core';
import { NotifyComponent }  from './notify.component';

@Component({
    selector: 'my-app',
    template:
    `
    <button (click)="submit()">Call Child Component Method</button>
    `
})
export class AppComponent {
    private notify: NotifyComponent;

    constructor() {
      this.notify = new NotifyComponent();
    }

    submit(): void {
        // execute child component method
        notify.callMethod();
    }
}

Child

import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'notify',
    template: '
Notify {{test}}
'
})
export class NotifyComponent implements OnInit {
   test:string;
   constructor() { }

    ngOnInit() { }

    callMethod(): void {
        console.log('successfully executed.');
        this.test = 'Me';
    }
}

How can I set the test property as well?

Body:
I had an exact situation where the Parent-component had a Select element in a form and on submit, I needed to call the relevant Child-Component's method according to the selected value from the select element.

Parent.HTML:

<form (ngSubmit)='selX' [formGroup]="xSelForm">
    <select formControlName="xSelector">
      ...
    </select>
<button type="submit">Submit</button>
</form>
<child [selectedX]="selectedX"></child>

Parent.TS:

selX(){
  this.selectedX = this.xSelForm.value['xSelector'];
}

Child.TS:

export class ChildComponent implements OnChanges {
  @Input() public selectedX;

  //ngOnChanges will execute if there is a change in the value of selectedX which has been passed to child as an @Input.

  ngOnChanges(changes: { [propKey: string]: SimpleChange }) {
    this.childFunction();
  }
  childFunction(){ }
}

Hope this helps.


问:
Map new array based on object's nested attributes
I feel like this has been asked a thousand times, but for the life of me I can't figure it out and the objects are somewhat complicated.

I'm building a photography portfolio site where galleries contain images. I have a response from a Wordpress API coming in that looks like this (simplified):

```<code>[
  {
    id: 20,
    date: '2020-05-25T20:39:28',
    slug: 'test-image',
    status: 'inherit',
    type: 'attachment',
    author: 1,
    media_category: [
      9
    ],
    acf: {
      location: 'North Carolina',
      category: {
        term_id: 9,
        name: 'North Carolina',
        slug: 'north-carolina',
        term_group: 0,
        term_taxonomy_id: 9,
        taxonomy: 'media_category',
        description: '',
        parent: 0,
        count: 1,
        filter: 'raw'
      }
    },
    ... other details
  },
  ... other objects
]
</code>```

These are just the raw media objects from the Wordpress media endpoint. What I'm trying to do though, is group them together by category slug (acf.category.slug), so I figure I can have an outer array that I can map over for later use, which then contains arrays (galleries), and each of those arrays contain the media objects. Something like:

```<code>[
  [               <-- Gallery 1
    { Image 1 },
    { Image 2 },
  ],
  [               <-- Gallery 2
    { Image 3 },
    { Image 4 },
  ],
  [               <-- Gallery 3
    { Image 5 },
    { Image 6 },
  ]
]
</code>```

I hope that makes sense.

EDIT:
I wanted to include where I was headed initially with a .reduce function:

```<code>let res = await this.$axios.$get(`${process.env.WP_API_URL}/wp/v2/media`);
const data = res.reduce((images, item) => {
  const image = (images[item.acf.category.term_taxonomy_id]);
  image.push(item);
  images[item.acf.category.slug] = image;
  return images;
}, []);
</code>```

As of now, I'm getting a `TypeError: Cannot read property 'push' of undefined.

答:
This should work:

let res = await this.$axios.$get(`${process.env.WP_API_URL}/wp/v2/media`);

const data = res.reduce((acc, item) => {
  const {slug} = item.acf.category;
  (acc[slug] || (acc[slug]=[])).push(item)
  return acc
}, {});
```

<p>It generates a structure like:</p>

<pre class="lang-js prettyprint-override"><code>{
  "north-carolina": [
    {
      id: 20,
      date: '2020-05-25T20:39:28',
      slug: 'test-image',
      status: 'inherit',
      type: 'attachment',
      author: 1,
      media_category: [
        9
      ],
      acf: {
        location: 'North Carolina',
        category: {
          term_id: 9,
          name: 'North Carolina',
          slug: 'north-carolina',
          term_group: 0,
          term_taxonomy_id: 9,
          taxonomy: 'media_category',
          description: '',
          parent: 0,
          count: 1,
          filter: 'raw'
        }
      },
      //... other details
    },
    //... other objects
  ],
  //... objects with different slugs
}
</code>```

Try it on CodePen

Body:
I feel like this has been asked a thousand times, but for the life of me I can't figure it out and the objects are somewhat complicated.

I'm building a photography portfolio site where galleries contain images. I have a response from a Wordpress API coming in that looks like this (simplified):

[
  {
    id: 20,
    date: '2020-05-25T20:39:28',
    slug: 'test-image',
    status: 'inherit',
    type: 'attachment',
    author: 1,
    media_category: [
      9
    ],
    acf: {
      location: 'North Carolina',
      category: {
        term_id: 9,
        name: 'North Carolina',
        slug: 'north-carolina',
        term_group: 0,
        term_taxonomy_id: 9,
        taxonomy: 'media_category',
        description: '',
        parent: 0,
        count: 1,
        filter: 'raw'
      }
    },
    ... other details
  },
  ... other objects
]

These are just the raw media objects from the Wordpress media endpoint. What I'm trying to do though, is group them together by category slug (acf.category.slug), so I figure I can have an outer array that I can map over for later use, which then contains arrays (galleries), and each of those arrays contain the media objects. Something like:

[
  [               <-- Gallery 1
    { Image 1 },
    { Image 2 },
  ],
  [               <-- Gallery 2
    { Image 3 },
    { Image 4 },
  ],
  [               <-- Gallery 3
    { Image 5 },
    { Image 6 },
  ]
]

I hope that makes sense.

EDIT:
I wanted to include where I was headed initially with a .reduce function:

let res = await this.$axios.$get(`${process.env.WP_API_URL}/wp/v2/media`);
const data = res.reduce((images, item) => {
  const image = (images[item.acf.category.term_taxonomy_id]);
  image.push(item);
  images[item.acf.category.slug] = image;
  return images;
}, []);

As of now, I'm getting a `TypeError: Cannot read property 'push' of undefined.

Body:
This should work:

let res = await this.$axios.$get(`${process.env.WP_API_URL}/wp/v2/media`);

const data = res.reduce((acc, item) => {
  const {slug} = item.acf.category;
  (acc[slug] || (acc[slug]=[])).push(item)
  return acc
}, {});

It generates a structure like:

{
  "north-carolina": [
    {
      id: 20,
      date: '2020-05-25T20:39:28',
      slug: 'test-image',
      status: 'inherit',
      type: 'attachment',
      author: 1,
      media_category: [
        9
      ],
      acf: {
        location: 'North Carolina',
        category: {
          term_id: 9,
          name: 'North Carolina',
          slug: 'north-carolina',
          term_group: 0,
          term_taxonomy_id: 9,
          taxonomy: 'media_category',
          description: '',
          parent: 0,
          count: 1,
          filter: 'raw'
        }
      },
      //... other details
    },
    //... other objects
  ],
  //... objects with different slugs
}

Try it on CodePen


问:
How to make function return reports based on report categoryID Paramter on service.ts?
I work on angular 7 app I need to return data from allReportsubCategory based on report Category ID

but I face issue how to return data from allReportsubCategory based on reportcategoryID .

so How to write function return reports based on ReportCategoryID ?

```<code>allReportsubCategory:any[];
this.allReportsubCategory =[
    {
        "reportID": 1,
        "reportName": "xxx",
        "reportIndex": 1,
        "reportCategoryID": 3,

    },
    {
        "reportID": 17,
        "reportName": "Jobs Monitor",
        "reportIndex": 1,
        "reportCategoryID": 3
    },
    {
        "reportID": 2025,
        "reportName": "Old Tables Report",
        "reportIndex": 1,
        "reportCategoryID": 3

    }];
</code>```

on service.ts

```<code> GetreportByCategoryId(reportCategoryID:string){
    return this.allReportsubCategory.??????

  }
</code>```

so I need when pass 3 to function GetreportByCategoryId(reportcategoryID) return all data above based on
reportcategoryid= 3

updated post

when call it on component as below

```<code>reportByCategoryId:any[]
 this.reportByCategoryId = this._displayreport.GetreportByCategoryId("3");
  console.log("data by category id" + this.reportByCategoryId )
</code>```

no return for data above and console log as below :

data by category idundefined

答:
To filter the values in array by some condition you can use filter method. Also you need to use number type in this method due to reportCategoryID in provided data has number type.

```<code>GetreportByCategoryId(id: number) {
  return this.allReportsubCategory
    .filter(category => category.reportCategoryID === id);
}
</code>```

Body:
I work on angular 7 app I need to return data from allReportsubCategory based on report Category ID

but I face issue how to return data from allReportsubCategory based on reportcategoryID .

so How to write function return reports based on ReportCategoryID ?

allReportsubCategory:any[];
this.allReportsubCategory =[
    {
        "reportID": 1,
        "reportName": "xxx",
        "reportIndex": 1,
        "reportCategoryID": 3,

    },
    {
        "reportID": 17,
        "reportName": "Jobs Monitor",
        "reportIndex": 1,
        "reportCategoryID": 3
    },
    {
        "reportID": 2025,
        "reportName": "Old Tables Report",
        "reportIndex": 1,
        "reportCategoryID": 3

    }];

on service.ts

 GetreportByCategoryId(reportCategoryID:string){
    return this.allReportsubCategory.??????

  }

so I need when pass 3 to function GetreportByCategoryId(reportcategoryID) return all data above based on
reportcategoryid= 3

updated post

when call it on component as below

reportByCategoryId:any[]
 this.reportByCategoryId = this._displayreport.GetreportByCategoryId("3");
  console.log("data by category id" + this.reportByCategoryId )

no return for data above and console log as below :

data by category idundefined

Body:
To filter the values in array by some condition you can use filter method. Also you need to use number type in this method due to reportCategoryID in provided data has number type.

GetreportByCategoryId(id: number) {
  return this.allReportsubCategory
    .filter(category => category.reportCategoryID === id);
}


问:
float() argument must be a string or a number, not 'Timestamp': python pandas
I have the following command:

```<code>from datetime import datetime
import pandas as pd
import matplotlib.pyplot as plt

data = pd.read_csv('data/C2A2_data/BinnedCsvs_d400/fb441e62df2d58994928907a91895ec62c2c42e6cd075c2700843b89.csv')
newdata = data[(data['Date'] >= '2005-01-01') & (data['Date'] <= '2014-12-12')]
datamax = newdata[newdata['Element']=='TMAX']
datamin = newdata[newdata['Element']=='TMIN']
datamax = datamax.groupby('Date').max()
datamin = datamin.groupby('Date').min()
datamax = datamax.reset_index()
datamin = datamin.reset_index()
datamax = datamax[~datamax['Date'].str.contains("02-29")]
datamin = datamin[~datamin['Date'].str.contains("02-29")]

breakoutdata = data[(data['Date']  > '2014-12-31')]
datamax2015 = breakoutdata[breakoutdata['Element']=='TMAX']
datamin2015 = breakoutdata[breakoutdata['Element']=='TMIN']
datamax2015 = datamax2015.groupby('Date').max()
datamin2015 = datamin2015.groupby('Date').min()
datamax2015 = datamax2015.reset_index()
datamin2015 = datamin2015.reset_index()
datamax2015 = datamax2015[~datamax2015['Date'].str.contains("02-29")]
datamin2015 = datamin2015[~datamin2015['Date'].str.contains("02-29")]

datamin['Date'] = pd.to_datetime(datamin['Date'])
datamin2015['Date'] = pd.to_datetime(datamin2015['Date'])
datamin["day_of_year"] = datamin["Date"].dt.dayofyear
datamin2015["day_of_year"] = datamin["Date"].dt.dayofyear
dataminappend = datamin2015.join(datamin,on="day_of_year",how="left",lsuffix="2015")
lower = dataminappend.loc[dataminappend["Data_Value2015"]<dataminappend["Data_Value"]]

datamax['Date'] = pd.to_datetime(datamax['Date'])
datamax2015['Date'] = pd.to_datetime(datamax2015['Date'])
datamax["day_of_year"] = datamax["Date"].dt.dayofyear
datamax2015["day_of_year"] = datamax["Date"].dt.dayofyear
datamaxappend = datamax2015.join(datamax,on="day_of_year",how="left",lsuffix="2015")

upper = datamaxappend.loc[datamaxappend["Data_Value2015"]>datamaxappend["Data_Value"]]
upper = upper.rename(columns={"Date2015":"Date","Data_Value2015":"Data_Value"})
lower = lower.rename(columns={"Date2015":"Date","Data_Value2015":"Data_Value"})
upper['Date'] = upper['Date'].map(lambda x: x.strftime("%d/%m/%Y, %H:%M:%S"))
lower['Date'] = lower['Date'].map(lambda x: x.strftime("%d/%m/%Y, %H:%M:%S"))

ax = plt.gca()
plt.plot(datamax['Date'],datamax['Data_Value'],color='red')
plt.plot(datamax['Date'],datamax['Data_Value'], color='blue')
plt.scatter(upper['Date'],upper['Data_Value'],color='red')
plt.scatter(lower['Date'],lower['Data_Value'], color='blue')

plt.ylabel("Temperature (degrees C)",color='navy')
plt.xlabel("Date",color='navy',labelpad=15)
plt.title('Record high and low temperatures by day (2005-2014)', alpha=1.0,color='brown',y=1.08)
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.35),
          fancybox=False,labels=['Record high','Record low'])
plt.xticks(rotation=30)
plt.fill_between(range(len(datamax['Date'])), datamax['Data_Value'], datamin['Data_Value'],color='yellow',alpha=0.8)
plt.show()
</code>```

However, I keep getting the error: TypeError: float() argument must be a string or a number, not 'Timestamp'

For this line: plt.scatter(upper['Date'],upper['Data_Value'],color='red')

Would anybody be able to give me a helping hand?

I cannot see anything obviously wrong with my code...

Here is a snippet of the dataframe data:

```<code> ID        Date Element  Data_Value
0       USW00094889  2014-11-12    TMAX          22
1       USC00208972  2009-04-29    TMIN          56
2       USC00200032  2008-05-26    TMAX         278
3       USC00205563  2005-11-11    TMAX         139
4       USC00200230  2014-02-27    TMAX        -106
5       USW00014833  2010-10-01    TMAX         194
6       USC00207308  2010-06-29    TMIN         144
7       USC00203712  2005-10-04    TMAX         289
8       USW00004848  2007-12-14    TMIN         -16
9       USC00200220  2011-04-21    TMAX          72
10      USC00205822  2013-01-16    TMAX          11
11      USC00205822  2008-05-29    TMIN          28
12      USC00203712  2008-10-17    TMIN          17
13      USC00205563  2006-05-14    TMAX         183
14      USC00200842  2006-05-14    TMAX         122
15      USC00205563  2014-12-07    TMAX          67
16      USC00205822  2008-09-07    TMAX         250
17      USC00205450  2006-04-22    TMIN          67
18      USC00203712  2008-02-22    TMAX         -44
19      USC00205563  2015-01-03    TMIN         -39
20      USC00201250  2011-03-28    TMIN         -78
21      USC00200230  2008-02-10    TMAX          -6
22      USC00207320  2008-02-03    TMIN         -39

[165085 rows x 4 columns]
</code>```

In case anybody wants an easier way to manipulate the code above.

答:
```<code>upper = upper['Date'].map(lambda x: x.strftime("%d/%m/%Y, %H:%M:%S")
print(upper)
</code>```

You cant simply transform a timestamp to a string, you need to use the .strftime() method.
More info here: https://www.programiz.com/python-programming/datetime/strftime

Try this:

```<code>import pandas as pd
import datetime
now = datetime.datetime.now()
df = pd.DataFrame(data=[[now]]*10, columns=["Date"])
df['Date_new'] = df['Date'].map(lambda x:x.strftime("%d.%m.%Y, %H:%M:%S"))
print(df['Date_new'])
</code>```

output:

```<code>0    30.05.2020, 18:21:30
1    30.05.2020, 18:21:30
2    30.05.2020, 18:21:30
3    30.05.2020, 18:21:30
4    30.05.2020, 18:21:30
5    30.05.2020, 18:21:30
6    30.05.2020, 18:21:30
7    30.05.2020, 18:21:30
8    30.05.2020, 18:21:30
9    30.05.2020, 18:21:30
Name: Date_new, dtype: object
</code>```

Body:
I have the following command:

from datetime import datetime
import pandas as pd
import matplotlib.pyplot as plt

data = pd.read_csv('data/C2A2_data/BinnedCsvs_d400/fb441e62df2d58994928907a91895ec62c2c42e6cd075c2700843b89.csv')
newdata = data[(data['Date'] >= '2005-01-01') & (data['Date'] <= '2014-12-12')]
datamax = newdata[newdata['Element']=='TMAX']
datamin = newdata[newdata['Element']=='TMIN']
datamax = datamax.groupby('Date').max()
datamin = datamin.groupby('Date').min()
datamax = datamax.reset_index()
datamin = datamin.reset_index()
datamax = datamax[~datamax['Date'].str.contains("02-29")]
datamin = datamin[~datamin['Date'].str.contains("02-29")]

breakoutdata = data[(data['Date']  > '2014-12-31')]
datamax2015 = breakoutdata[breakoutdata['Element']=='TMAX']
datamin2015 = breakoutdata[breakoutdata['Element']=='TMIN']
datamax2015 = datamax2015.groupby('Date').max()
datamin2015 = datamin2015.groupby('Date').min()
datamax2015 = datamax2015.reset_index()
datamin2015 = datamin2015.reset_index()
datamax2015 = datamax2015[~datamax2015['Date'].str.contains("02-29")]
datamin2015 = datamin2015[~datamin2015['Date'].str.contains("02-29")]

datamin['Date'] = pd.to_datetime(datamin['Date'])
datamin2015['Date'] = pd.to_datetime(datamin2015['Date'])
datamin["day_of_year"] = datamin["Date"].dt.dayofyear
datamin2015["day_of_year"] = datamin["Date"].dt.dayofyear
dataminappend = datamin2015.join(datamin,on="day_of_year",how="left",lsuffix="2015")
lower = dataminappend.loc[dataminappend["Data_Value2015"]<dataminappend["Data_Value"]]

datamax['Date'] = pd.to_datetime(datamax['Date'])
datamax2015['Date'] = pd.to_datetime(datamax2015['Date'])
datamax["day_of_year"] = datamax["Date"].dt.dayofyear
datamax2015["day_of_year"] = datamax["Date"].dt.dayofyear
datamaxappend = datamax2015.join(datamax,on="day_of_year",how="left",lsuffix="2015")

upper = datamaxappend.loc[datamaxappend["Data_Value2015"]>datamaxappend["Data_Value"]]
upper = upper.rename(columns={"Date2015":"Date","Data_Value2015":"Data_Value"})
lower = lower.rename(columns={"Date2015":"Date","Data_Value2015":"Data_Value"})
upper['Date'] = upper['Date'].map(lambda x: x.strftime("%d/%m/%Y, %H:%M:%S"))
lower['Date'] = lower['Date'].map(lambda x: x.strftime("%d/%m/%Y, %H:%M:%S"))

ax = plt.gca()
plt.plot(datamax['Date'],datamax['Data_Value'],color='red')
plt.plot(datamax['Date'],datamax['Data_Value'], color='blue')
plt.scatter(upper['Date'],upper['Data_Value'],color='red')
plt.scatter(lower['Date'],lower['Data_Value'], color='blue')

plt.ylabel("Temperature (degrees C)",color='navy')
plt.xlabel("Date",color='navy',labelpad=15)
plt.title('Record high and low temperatures by day (2005-2014)', alpha=1.0,color='brown',y=1.08)
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.35),
          fancybox=False,labels=['Record high','Record low'])
plt.xticks(rotation=30)
plt.fill_between(range(len(datamax['Date'])), datamax['Data_Value'], datamin['Data_Value'],color='yellow',alpha=0.8)
plt.show()

However, I keep getting the error: TypeError: float() argument must be a string or a number, not 'Timestamp'

For this line: plt.scatter(upper['Date'],upper['Data_Value'],color='red')

Would anybody be able to give me a helping hand?

I cannot see anything obviously wrong with my code...

Here is a snippet of the dataframe data:

 ID        Date Element  Data_Value
0       USW00094889  2014-11-12    TMAX          22
1       USC00208972  2009-04-29    TMIN          56
2       USC00200032  2008-05-26    TMAX         278
3       USC00205563  2005-11-11    TMAX         139
4       USC00200230  2014-02-27    TMAX        -106
5       USW00014833  2010-10-01    TMAX         194
6       USC00207308  2010-06-29    TMIN         144
7       USC00203712  2005-10-04    TMAX         289
8       USW00004848  2007-12-14    TMIN         -16
9       USC00200220  2011-04-21    TMAX          72
10      USC00205822  2013-01-16    TMAX          11
11      USC00205822  2008-05-29    TMIN          28
12      USC00203712  2008-10-17    TMIN          17
13      USC00205563  2006-05-14    TMAX         183
14      USC00200842  2006-05-14    TMAX         122
15      USC00205563  2014-12-07    TMAX          67
16      USC00205822  2008-09-07    TMAX         250
17      USC00205450  2006-04-22    TMIN          67
18      USC00203712  2008-02-22    TMAX         -44
19      USC00205563  2015-01-03    TMIN         -39
20      USC00201250  2011-03-28    TMIN         -78
21      USC00200230  2008-02-10    TMAX          -6
22      USC00207320  2008-02-03    TMIN         -39

[165085 rows x 4 columns]

In case anybody wants an easier way to manipulate the code above.

Body:
upper = upper['Date'].map(lambda x: x.strftime("%d/%m/%Y, %H:%M:%S")
print(upper)

You cant simply transform a timestamp to a string, you need to use the .strftime() method.
More info here: https://www.programiz.com/python-programming/datetime/strftime

Try this:

import pandas as pd
import datetime
now = datetime.datetime.now()
df = pd.DataFrame(data=[[now]]*10, columns=["Date"])
df['Date_new'] = df['Date'].map(lambda x:x.strftime("%d.%m.%Y, %H:%M:%S"))
print(df['Date_new'])

output:

0    30.05.2020, 18:21:30
1    30.05.2020, 18:21:30
2    30.05.2020, 18:21:30
3    30.05.2020, 18:21:30
4    30.05.2020, 18:21:30
5    30.05.2020, 18:21:30
6    30.05.2020, 18:21:30
7    30.05.2020, 18:21:30
8    30.05.2020, 18:21:30
9    30.05.2020, 18:21:30
Name: Date_new, dtype: object


问:
Problem on installing metview package on Anaconda
I am trying to install Metview package through its installation page:

https://anaconda.org/conda-forge/metview

using the code: conda install -c conda-forge metview

I encounter this problem:

```<code>(base) C:\Users\Saeed>conda install -c conda-forge metview
Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Collecting package metadata (repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.

PackagesNotFoundError: The following packages are not available from current channels:

  - metview

Current channels:

      - https://conda.anaconda.org/conda-forge/win-64
      - https://conda.anaconda.org/conda-forge/noarch
      - https://repo.anaconda.com/pkgs/main/win-64
      - https://repo.anaconda.com/pkgs/main/noarch
      - https://repo.anaconda.com/pkgs/r/win-64
      - https://repo.anaconda.com/pkgs/r/noarch
      - https://repo.anaconda.com/pkgs/msys2/win-64
      - https://repo.anaconda.com/pkgs/msys2/noarch
      - https://conda.anaconda.org/conda-canary/win-64

  - https://conda.anaconda.org/conda-canary/noarch

To search for alternate channels that may provide the conda package you're
looking for, navigate to

    https://anaconda.org

and use the search bar at the top of the page.
</code>```

I am using Anaconda and tried to use the Anaconda prompt.

Thank you in advance for your help.

答:
I just did and got this:

```<code>(base) C:\Users\Saeed>pip install metview
Collecting metview
  Using cached metview-1.4.2-py2.py3-none-any.whl (19 kB)
Requirement already satisfied: pandas in c:\programdata\anaconda3\lib\site-packages (from metview) (1.0.3)
Requirement already satisfied: cffi in c:\programdata\anaconda3\lib\site-packages (from metview) (1.14.0)
Requirement already satisfied: numpy in c:\programdata\anaconda3\lib\site-packages (from metview) (1.18.1)
Requirement already satisfied: pytz>=2017.2 in c:\programdata\anaconda3\lib\site-packages (from pandas->metview) (2020.1)
Requirement already satisfied: python-dateutil>=2.6.1 in c:\programdata\anaconda3\lib\site-packages (from pandas->metview) (2.8.1)
Requirement already satisfied: pycparser in c:\programdata\anaconda3\lib\site-packages (from cffi->metview) (2.20)
Requirement already satisfied: six>=1.5 in c:\programdata\anaconda3\lib\site-packages (from python-dateutil>=2.6.1->pandas->metview) (1.14.0)
Installing collected packages: metview
Successfully installed metview-1.4.2
</code>```

The thing is it is not the right and appropriate package! it is installing a wrong version, or at least sth not right!
I ran this in jupyter and got this:

```<code>import metview as mv
--------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-1-6bf5b378b3e8> in <module>
----> 1 import metview as mv

C:\ProgramData\Anaconda3\lib\site-packages\metview\__init__.py in <module>
     24 if len(sys.argv) != 2 or sys.argv[0] != "-m" or sys.argv[1] != "selfcheck":
     25
---> 26     from . import bindings as _bindings
     27
     28     _bindings.bind_functions(globals(), module_name=__name__)

C:\ProgramData\Anaconda3\lib\site-packages\metview\bindings.py in <module>
    168
    169
--> 170 mi = MetviewInvoker()
    171
    172 try:

C:\ProgramData\Anaconda3\lib\site-packages\metview\bindings.py in __init__(self)
     64         pid = os.getpid()
     65         # print('PYTHON:', pid, ' ', env_file.name, ' ', repr(signal.SIGUSR1))
---> 66         signal.signal(signal.SIGUSR1, self.signal_from_metview)
     67         # p = subprocess.Popen(['metview', '-edbg', 'tv8 -a', '-slog', '-python-serve',
     68         #     env_file.name, str(pid)], stdout=subprocess.PIPE)

AttributeError: module 'signal' has no attribute 'SIGUSR1'
</code>```

Body:
I am trying to install Metview package through its installation page:

https://anaconda.org/conda-forge/metview

using the code: conda install -c conda-forge metview

I encounter this problem:

(base) C:\Users\Saeed>conda install -c conda-forge metview
Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Collecting package metadata (repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.

PackagesNotFoundError: The following packages are not available from current channels:

  - metview

Current channels:

      - https://conda.anaconda.org/conda-forge/win-64
      - https://conda.anaconda.org/conda-forge/noarch
      - https://repo.anaconda.com/pkgs/main/win-64
      - https://repo.anaconda.com/pkgs/main/noarch
      - https://repo.anaconda.com/pkgs/r/win-64
      - https://repo.anaconda.com/pkgs/r/noarch
      - https://repo.anaconda.com/pkgs/msys2/win-64
      - https://repo.anaconda.com/pkgs/msys2/noarch
      - https://conda.anaconda.org/conda-canary/win-64

  - https://conda.anaconda.org/conda-canary/noarch

To search for alternate channels that may provide the conda package you're
looking for, navigate to

    https://anaconda.org

and use the search bar at the top of the page.

I am using Anaconda and tried to use the Anaconda prompt.

Thank you in advance for your help.

Body:
I just did and got this:

(base) C:\Users\Saeed>pip install metview
Collecting metview
  Using cached metview-1.4.2-py2.py3-none-any.whl (19 kB)
Requirement already satisfied: pandas in c:\programdata\anaconda3\lib\site-packages (from metview) (1.0.3)
Requirement already satisfied: cffi in c:\programdata\anaconda3\lib\site-packages (from metview) (1.14.0)
Requirement already satisfied: numpy in c:\programdata\anaconda3\lib\site-packages (from metview) (1.18.1)
Requirement already satisfied: pytz>=2017.2 in c:\programdata\anaconda3\lib\site-packages (from pandas->metview) (2020.1)
Requirement already satisfied: python-dateutil>=2.6.1 in c:\programdata\anaconda3\lib\site-packages (from pandas->metview) (2.8.1)
Requirement already satisfied: pycparser in c:\programdata\anaconda3\lib\site-packages (from cffi->metview) (2.20)
Requirement already satisfied: six>=1.5 in c:\programdata\anaconda3\lib\site-packages (from python-dateutil>=2.6.1->pandas->metview) (1.14.0)
Installing collected packages: metview
Successfully installed metview-1.4.2

The thing is it is not the right and appropriate package! it is installing a wrong version, or at least sth not right!
I ran this in jupyter and got this:

import metview as mv
--------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-1-6bf5b378b3e8> in <module>
----> 1 import metview as mv

C:\ProgramData\Anaconda3\lib\site-packages\metview\__init__.py in <module>
     24 if len(sys.argv) != 2 or sys.argv[0] != "-m" or sys.argv[1] != "selfcheck":
     25
---> 26     from . import bindings as _bindings
     27
     28     _bindings.bind_functions(globals(), module_name=__name__)

C:\ProgramData\Anaconda3\lib\site-packages\metview\bindings.py in <module>
    168
    169
--> 170 mi = MetviewInvoker()
    171
    172 try:

C:\ProgramData\Anaconda3\lib\site-packages\metview\bindings.py in __init__(self)
     64         pid = os.getpid()
     65         # print('PYTHON:', pid, ' ', env_file.name, ' ', repr(signal.SIGUSR1))
---> 66         signal.signal(signal.SIGUSR1, self.signal_from_metview)
     67         # p = subprocess.Popen(['metview', '-edbg', 'tv8 -a', '-slog', '-python-serve',
     68         #     env_file.name, str(pid)], stdout=subprocess.PIPE)

AttributeError: module 'signal' has no attribute 'SIGUSR1'


问:
How to manage memory/usage of a NSMutableArray of NSMutableArrays
I am currently trying to write a class to create faux grid system to keep track of a NSMutableArray of game entities using a NSMutableArray of NSMutableArrays. Given my limited experience with Objective-C programming, I am unsure of how certain things work.

Here is the init method:

```<code>#define MAX_BALL_ROWCOUNT 6
#define MAX_BALL_COLCOUNT 4
- (id) initWithMutableArray:(NSMutableArray *)aList {
self = [super init];
if (self != nil) {
    ballList = [[NSMutableArray alloc] initWithCapacity: MAX_BALL_ROWCOUNT];

    for (int i=0; i<MAX_BALL_ROWCOUNT; i++) {
        NSMutableArray *balls = [[NSMutableArray alloc] initWithCapacity:MAX_BALL_COLCOUNT];
        [ballList addObject:balls];
        [balls release];
    }

    int x = 0;

    for (NSMutableArray *array in ballList) {
        for (int i = 0; i<MAX_BALL_COLCOUNT; i++) {
            [array addObject:[aList objectAtIndex:x]];
            x++;
            }
        }
    }

return self;
}
</code>```

ballList is the class's NSMutableArray that will store NSMutableArrays.

aList is the NSMutableArray containing the GameEntities I wish to keep track of that is passed into this class.

All the sizes and amount of entities to store are fixed, which is why there is no checks on the sizes of the arrays nor the number of entities to store.

So the first question I have involves freeing memory. This is the dealloc function I currently have:

```<code>- (void) dealloc {
    [ballList release];
    [super dealloc];
}
</code>```

Does calling a release on ballList cause the release to be called on the NSMutableArrays that it contains (which will subsequently call the release on the objects those NSMutableArrays contain) or do I have to write something like:

```<code>for (NSMutableArray *array in ballList) {
    [array release];
}
[ballList release];
</code>```

My second question involves the usage of this array of arrays. Is this the proper way to traverse through ballList?

```<code>- (void) update {
    for (NSMutableArray *array in ballList) {
        for (GameEntity *balls in array) {
            (CGPoint) location = [balls getLocation];
            [balls setLocation: CGPointMake(location.x+1, location.y+1)];
        }
    }
}
</code>```

Lastly, in the code above where it sets the balls location, does it only affect the contents within ballList or does the original aList that is passed into ballList change as well? If the contents in the original aList do not change, how would I write it so that they do?

If people have suggestions for a better way to keep track of the entities in a grid system, I'd be open to those too. Thanks in advance.

答:
When the dealloc of a NSArray or NSMutableArray is called, all its contents gets a release message. So when you release ballList, if there there is no other owner (I guess in this case there is none) then its dealloc is called and you don't need to release the other arrays here.

Your loop traversal is fine. Though for 2D arrays instead of NSArray of NSArray I personally prefer pure C 2D array, at least in most of the cases.

When you are adding object in this way you are adding a reference in the array. So any change via the array's reference will be reflected in all references of the object. If you don't want that then add a copy of the object in the array.

Body:
I am currently trying to write a class to create faux grid system to keep track of a NSMutableArray of game entities using a NSMutableArray of NSMutableArrays. Given my limited experience with Objective-C programming, I am unsure of how certain things work.

Here is the init method:

#define MAX_BALL_ROWCOUNT 6
#define MAX_BALL_COLCOUNT 4
- (id) initWithMutableArray:(NSMutableArray *)aList {
self = [super init];
if (self != nil) {
    ballList = [[NSMutableArray alloc] initWithCapacity: MAX_BALL_ROWCOUNT];

    for (int i=0; i<MAX_BALL_ROWCOUNT; i++) {
        NSMutableArray *balls = [[NSMutableArray alloc] initWithCapacity:MAX_BALL_COLCOUNT];
        [ballList addObject:balls];
        [balls release];
    }

    int x = 0;

    for (NSMutableArray *array in ballList) {
        for (int i = 0; i<MAX_BALL_COLCOUNT; i++) {
            [array addObject:[aList objectAtIndex:x]];
            x++;
            }
        }
    }

return self;
}

ballList is the class's NSMutableArray that will store NSMutableArrays.

aList is the NSMutableArray containing the GameEntities I wish to keep track of that is passed into this class.

All the sizes and amount of entities to store are fixed, which is why there is no checks on the sizes of the arrays nor the number of entities to store.

So the first question I have involves freeing memory. This is the dealloc function I currently have:

- (void) dealloc {
    [ballList release];
    [super dealloc];
}

Does calling a release on ballList cause the release to be called on the NSMutableArrays that it contains (which will subsequently call the release on the objects those NSMutableArrays contain) or do I have to write something like:

for (NSMutableArray *array in ballList) {
    [array release];
}
[ballList release];

My second question involves the usage of this array of arrays. Is this the proper way to traverse through ballList?

- (void) update {
    for (NSMutableArray *array in ballList) {
        for (GameEntity *balls in array) {
            (CGPoint) location = [balls getLocation];
            [balls setLocation: CGPointMake(location.x+1, location.y+1)];
        }
    }
}

Lastly, in the code above where it sets the balls location, does it only affect the contents within ballList or does the original aList that is passed into ballList change as well? If the contents in the original aList do not change, how would I write it so that they do?

If people have suggestions for a better way to keep track of the entities in a grid system, I'd be open to those too. Thanks in advance.


问:
Change the declaring class of a method with Javassist?
Is it possible to move/copy a method from one class to another with Javassist?

public class A {
    public static void test() {
        System.out.println("hello world");
    }
}

public class B {
    // add test() here
}
```

<p>What I've tried:</p>

<pre class="lang-java prettyprint-override"><code>ctClassB.addMethod(ctClassA.getDeclaredMethod("test"));
</code>```

This results in an exception: javassist.CannotCompileException: bad declaring class.

Looking at the Javassist javadocs, I don't believe this is possible, but is there some way to change the declaring class of the method?

答:
Constructing a new CtMethod appears to be working:</p>

```<code>CtMethod method = ctClassA.getDeclaredMethod("test");
ctClassB.addMethod(new CtMethod(method, ctClassB, null));
</code>```

Body:
Is it possible to move/copy a method from one class to another with Javassist?

public class A {
    public static void test() {
        System.out.println("hello world");
    }
}

public class B {
    // add test() here
}

What I've tried:

ctClassB.addMethod(ctClassA.getDeclaredMethod("test"));

This results in an exception: javassist.CannotCompileException: bad declaring class.

Looking at the Javassist javadocs, I don't believe this is possible, but is there some way to change the declaring class of the method?

Body:
Constructing a new CtMethod appears to be working:

CtMethod method = ctClassA.getDeclaredMethod("test");
ctClassB.addMethod(new CtMethod(method, ctClassB, null));


问:
WPF: How to get current absolute line and column numbers from TextBox (ignoring text wrapping)
I am trying to get the absolute position of the line and column/character of caret in TextBox (like it implemented in Windows notepad).
I know about TextBox.GetLineIndexFromCharacterIndex() or TextBox.GetCharacterIndexFromLineIndex(), but those methods returns relative postion (I mean that this methods counts wrapped lines) and for example if first line wraps to second line, this method will return index of second line, so I need another solution for this.
Also I tried calculate position by myself (using loop through the string) but with large amount of text it works very slowly.

Text without wrapping
Text with wrapping

答:
I don't think there's any way you'll be able to get the line number of a given offset (character) without looping through the text in some way. However, some methods will be more efficient than others.

You can take some inspiration from the TextBox control itself, since the source code is freely available here:

https://referencesource.microsoft.com/#PresentationFramework/src/Framework/System/windows/Controls/TextBox.cs

The TextBox needs to enumerate over every character anyway in order to display the text. As part of that process it also needs to decide when to start new lines. To make future calculations faster, it keeps an internal list of "line metrics"- basically a list of where each line starts and how long each line is. It uses this internal list to do  calculations like GetCharacterIndexFromLineIndex and GetLineIndexFromCharacterIndex more efficiently, without having to go through each character again.

You should be able to do something similar. Make your own list of line positions at the start by looping through the text in the background when it's first loaded, then keep that list up to date as changes are made.


问:
ListView Builder Only static members can be accessed in initializers
Hi i am new on flutter

I use a ListView.Builder to do something like this:

I use two widgets one for adress information and one for add new adress item to ListView

I use a callback to inform that add IconButton was pressed but I received an error: Only static members can be accessed in initializers. when I call addItemToList() method

this is the code:

```<code>class TestPage2 extends StatefulWidget {
  @override
  _TestPage2State createState() => _TestPage2State();
}

class _TestPage2State extends State<TestPage2> {
  List<Widget> lwidgets = [
    _Adresses(),
    _HorizontalDivider(),
    _AddElement(() {
      addItemToList();
    })
  ];

  void addItemToList() {
    setState(() {
      lwidgets.insert(lwidgets.length - 1, _Adresses());
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Contacts'),
      ),
      backgroundColor: Color(0xFFE5E5EA),
      body: Column(
        children: <Widget>[
          Text('ADRESS'),
          Container(
            height: 200,
            child: ListView.builder(
              itemCount: lwidgets.length,
              itemBuilder: (BuildContext context, int index) {
                return (lwidgets[index]);
              },
              physics: NeverScrollableScrollPhysics(),
            ),
          ),
        ],
      ),
    );
  }
}
</code>```

This is te _AddElement Widget:

```<code>class _AddElement extends StatelessWidget {
  final Function() onAddItem;

  const _AddElement(this.onAddItem);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 40,
      color: Colors.white,
      child: Row(
        children: <Widget>[
          Container(
            height: 40,
            color: Colors.white,
            child: IconButton(
              icon: Icon(Icons.add_circle),
              iconSize: 24,
              color: Color(0xFF34C759),
              onPressed: () {
                onAddItem();
              },
            ),
          ),
        ],
      ),
    );
  }
}
</code>```

I Expect when i tap on green button a new item will be added to ListView like this:

I will appreciate any help.

Jose Rodriguez

答:
This is another way to do:

I put only one _Adress widget to lwidgets and use initState to put AddElement widget

BEFORE

```<code>List<Widget> lwidgets = [
    _Adresses(),
    _HorizontalDivider(),
    _AddElement(() {
      addItemToList();
    })
  ];

  void addItemToList() {
    setState(() {
      lwidgets.insert(lwidgets.length - 1, _Adresses());
    });
  }
</code>```

AFTER

```<code> List<Widget> lwidgets = [
    _Adress(),
  ];

  @override
  void initState() {
    lwidgets.insert(lwidgets.length, _AddElement(() => {addItemToList()}));
    super.initState();
  }

  void addItemToList() {
    setState(() {
      lwidgets.insert(lwidgets.length - 1, _Adress());
    });
  }
</code>```

And I Put _HorizontalDivider() into _Adress widget

Body:
Hi i am new on flutter

I use a ListView.Builder to do something like this:

I use two widgets one for adress information and one for add new adress item to ListView

I use a callback to inform that add IconButton was pressed but I received an error: Only static members can be accessed in initializers. when I call addItemToList() method

this is the code:

class TestPage2 extends StatefulWidget {
  @override
  _TestPage2State createState() => _TestPage2State();
}

class _TestPage2State extends State<TestPage2> {
  List<Widget> lwidgets = [
    _Adresses(),
    _HorizontalDivider(),
    _AddElement(() {
      addItemToList();
    })
  ];

  void addItemToList() {
    setState(() {
      lwidgets.insert(lwidgets.length - 1, _Adresses());
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Contacts'),
      ),
      backgroundColor: Color(0xFFE5E5EA),
      body: Column(
        children: <Widget>[
          Text('ADRESS'),
          Container(
            height: 200,
            child: ListView.builder(
              itemCount: lwidgets.length,
              itemBuilder: (BuildContext context, int index) {
                return (lwidgets[index]);
              },
              physics: NeverScrollableScrollPhysics(),
            ),
          ),
        ],
      ),
    );
  }
}

This is te _AddElement Widget:

class _AddElement extends StatelessWidget {
  final Function() onAddItem;

  const _AddElement(this.onAddItem);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 40,
      color: Colors.white,
      child: Row(
        children: <Widget>[
          Container(
            height: 40,
            color: Colors.white,
            child: IconButton(
              icon: Icon(Icons.add_circle),
              iconSize: 24,
              color: Color(0xFF34C759),
              onPressed: () {
                onAddItem();
              },
            ),
          ),
        ],
      ),
    );
  }
}

I Expect when i tap on green button a new item will be added to ListView like this:

I will appreciate any help.

Jose Rodriguez

Body:
This is another way to do:

I put only one _Adress widget to lwidgets and use initState to put AddElement widget

BEFORE

List<Widget> lwidgets = [
    _Adresses(),
    _HorizontalDivider(),
    _AddElement(() {
      addItemToList();
    })
  ];

  void addItemToList() {
    setState(() {
      lwidgets.insert(lwidgets.length - 1, _Adresses());
    });
  }

AFTER

 List<Widget> lwidgets = [
    _Adress(),
  ];

  @override
  void initState() {
    lwidgets.insert(lwidgets.length, _AddElement(() => {addItemToList()}));
    super.initState();
  }

  void addItemToList() {
    setState(() {
      lwidgets.insert(lwidgets.length - 1, _Adress());
    });
  }

And I Put _HorizontalDivider() into _Adress widget


问:
How do I specify a clang-format file?
I just built clang 5.0.0 on a Redhat 6 machine and tried to run clang-format. I'm unable to get the -style option to read in a style file. Here's an example of a set of commands that I think should work:

```<code>./clang-format -style=llvm -dump-config > .llvm-format
./clang-format -style=.llvm-format ~/myFile.cc
</code>```

When I run this command I get the following error:

```<code>Invalid value for -style
</code>```

It appears to find and use .clang-format when placed in a parent directory as expect. The built-in types also work:

```<code>./clang-format -style=Mozilla ~/myFile.cc
</code>```

The problem, then, is that I can't specify explicitly a .clang-format file to use. Is this a problem with my build or am I misusing clang-format oir misunderstanding the documentation?

答:
Just an additional hint:
(in my case on Windows 10)
- if you dump the config to a file, check the ascii coding afterwards, e.g. in Notepad++
- the .clang-format file has to be utf8 without BOM !!! (you can convert it in Notepadd++)
- otherwise you get an error like "YAML:1:4: error: Got empty plain scalar"
- place the .clang-format file in the same folder or in a parent directory of the code-file.c

A correct command line call to format the code-file.c would look like that:
clang-format.exe -style=file -i C:\path\code-file.c

Title: How do I specify a clang-format file?

Body:
I just built clang 5.0.0 on a Redhat 6 machine and tried to run clang-format. I'm unable to get the -style option to read in a style file. Here's an example of a set of commands that I think should work:

./clang-format -style=llvm -dump-config > .llvm-format
./clang-format -style=.llvm-format ~/myFile.cc

When I run this command I get the following error:

Invalid value for -style

It appears to find and use .clang-format when placed in a parent directory as expect. The built-in types also work:

./clang-format -style=Mozilla ~/myFile.cc

The problem, then, is that I can't specify explicitly a .clang-format file to use. Is this a problem with my build or am I misusing clang-format oir misunderstanding the documentation?


问:
Cloud function working locally but crashing in GCP (Function execution took 12681 ms, finished with status: 'crash')
Here is a super abbreviated version of my code (I'll put a link to everything in comments)

import ...

...

def main(data, context):
    log_client = logging.Client()

    log_name = 'cloudfunctions.googleapis.com%2Fcloud-functions'

    res = Resource(type="cloud_function",
                   labels={
                       "function_name": "refresh_classes",
                       "region": os.environ.get("FUNC_REGION")
                   })
    logger = log_client.logger(log_name.format(os.environ.get("PROJECT_ID")))

    db = sqlalchemy.create_engine(
        sqlalchemy.engine.url.URL(
            drivername="mysql+pymysql",
            username=os.environ.get("DB_USER"),
            password=os.environ.get("DB_PASS"),
            host=os.environ.get("DB_HOST"),
            port=3306,
            database=PRIMARY_TABLE_NAME
        ),
        pool_size=5,
        max_overflow=2,
        pool_timeout=30,
        pool_recycle=1800
    )
    start_time = perf_counter()

    check_if_table_exists(db)

    for i in range(START_IDX, END_IDX):
        print(i)
        logger.log_text(f"Checking class with id {i}", resource=res, severity="INFO")

        ...

    logger.log_text(f"Total seconds elapsed: {perf_counter() - start_time}", resource=res, severity="INFO")

if __name__ == '__main__':
    main('data', 'context')
```

<p>When I run the above cloud function locally, with my <code>GOOGLE_APPLICATION_CREDENTIALS</code> configured along with my local Cloud MySQL proxy set up, the verbose cloud logging comes through and the function finishes without a hitch, exactly as I would expect:</p>

<p><img src="https://i.stack.imgur.com/zZxb5.png" alt="enter image description here"></p>

<p>However, when I deploy the entire thing to GCP, and try to trigger it through the console (cloud messaging trigger), all I get is this in terms of logging:</p>

<p><img src="https://i.stack.imgur.com/vrXNk.png" alt="enter image description here"></p>

<p><strong>actual text</strong></p>

```{
 insertId: "******"
 labels: {
  execution_id: "******"
 }
 logName: "projects/******/logs/cloudfunctions.googleapis.com%2Fcloud-functions"
 receiveTimestamp: "2020-05-29T22:11:13.435688367Z"
 resource: {
  labels: {
   function_name: "******"
   project_id: "******"
   region: "us-central1"
  }
  type: "cloud_function"
 }
 severity: "DEBUG"
 textPayload: "Function execution started"
 timestamp: "2020-05-29T22:11:03.069889708Z"
 trace: "projects/******/traces/******"
}

{
 insertId: "******"
 labels: {
  execution_id: "******"
 }
 logName: "projects/******/logs/cloudfunctions.googleapis.com%2Fcloud-functions"
 receiveTimestamp: "2020-05-29T22:11:16.331311285Z"
 resource: {
  labels: {
   function_name: "******"
   project_id: "******"
   region: "us-central1"
  }
  type: "cloud_function"
 }
 severity: "DEBUG"
 textPayload: "Function execution took 12362 ms, finished with status: 'crash'"
 timestamp: "2020-05-29T22:11:15.430033249Z"
 trace: "projects/******/traces/******"
}
```

*i don't really know what's sensitive information and what's not, so I just starred some random things

As I'm writing this, I realize more logging could help, so I stuck a Google logger in between the logger setup, db setup, and the table check I run.

The function crashes before the Google logger is even set up.

So at this point I'm not really sure what could be breaking my function, and I don't know how to find out, seeing as Google Cloud logging is of no help. The error json has a trace property which looks really promising, because all I need at this point is a Python stack trace, but I don't know if there's a way to see that.

I should note that I have environment variables configured through GCP's Cloud Function console.

Principally, there are two things that would be helpful:

how to see python stack trace of crashing cloud function

what, specific to my application, could be causing it to exhibit this crashing behavior

答:
So I finally figured out that if, instead of triggering your cloud function via Cloud Scheduler, you run the function manually via Test Function

GCP will give you the raised exception. In my case, my Cloud MySQL connection was failing

```<code>Error: function terminated. Recommended action: inspect logs for termination reason. Details:
(pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on '**.***.**.***' (timed out)")
(Background on this error at: http://sqlalche.me/e/e3q8)
</code>```

so I simply had to introduce an environment variable to toggle between connecting via proxy and unix sockets like such:

if os.environ.get("ENV") == "local":
    db = sqlalchemy.create_engine(
        sqlalchemy.engine.url.URL(
            drivername="mysql+pymysql",
            username=os.environ.get("DB_USER"),
            password=os.environ.get("DB_PASS"),
            host=os.environ.get("DB_HOST"),
            port=3306,
            database=PRIMARY_TABLE_NAME
        ),
        pool_size=5,
        max_overflow=2,
        pool_timeout=30,
        pool_recycle=1800
    )
else:
    db = sqlalchemy.create_engine(
        sqlalchemy.engine.url.URL(
            drivername="mysql+pymysql",
            username=os.environ.get("DB_USER"),
            password=os.environ.get("DB_PASS"),
            database=PRIMARY_TABLE_NAME,
            query={"unix_socket": "/cloudsql/{}".format(os.environ.get("CLOUD_SQL_CONNECTION_NAME"))}
        ),
        pool_size=5,
        max_overflow=2,
        pool_timeout=30,
        pool_recycle=1800
    )
```

Body:
Here is a super abbreviated version of my code (I'll put a link to everything in comments)

import ...

...

def main(data, context):
    log_client = logging.Client()

    log_name = 'cloudfunctions.googleapis.com%2Fcloud-functions'

    res = Resource(type="cloud_function",
                   labels={
                       "function_name": "refresh_classes",
                       "region": os.environ.get("FUNC_REGION")
                   })
    logger = log_client.logger(log_name.format(os.environ.get("PROJECT_ID")))

    db = sqlalchemy.create_engine(
        sqlalchemy.engine.url.URL(
            drivername="mysql+pymysql",
            username=os.environ.get("DB_USER"),
            password=os.environ.get("DB_PASS"),
            host=os.environ.get("DB_HOST"),
            port=3306,
            database=PRIMARY_TABLE_NAME
        ),
        pool_size=5,
        max_overflow=2,
        pool_timeout=30,
        pool_recycle=1800
    )
    start_time = perf_counter()

    check_if_table_exists(db)

    for i in range(START_IDX, END_IDX):
        print(i)
        logger.log_text(f"Checking class with id {i}", resource=res, severity="INFO")

        ...

    logger.log_text(f"Total seconds elapsed: {perf_counter() - start_time}", resource=res, severity="INFO")

if __name__ == '__main__':
    main('data', 'context')

When I run the above cloud function locally, with my GOOGLE_APPLICATION_CREDENTIALS configured along with my local Cloud MySQL proxy set up, the verbose cloud logging comes through and the function finishes without a hitch, exactly as I would expect:

However, when I deploy the entire thing to GCP, and try to trigger it through the console (cloud messaging trigger), all I get is this in terms of logging:

actual text

{
 insertId: "******"
 labels: {
  execution_id: "******"
 }
 logName: "projects/******/logs/cloudfunctions.googleapis.com%2Fcloud-functions"
 receiveTimestamp: "2020-05-29T22:11:13.435688367Z"
 resource: {
  labels: {
   function_name: "******"
   project_id: "******"
   region: "us-central1"
  }
  type: "cloud_function"
 }
 severity: "DEBUG"
 textPayload: "Function execution started"
 timestamp: "2020-05-29T22:11:03.069889708Z"
 trace: "projects/******/traces/******"
}

{
 insertId: "******"
 labels: {
  execution_id: "******"
 }
 logName: "projects/******/logs/cloudfunctions.googleapis.com%2Fcloud-functions"
 receiveTimestamp: "2020-05-29T22:11:16.331311285Z"
 resource: {
  labels: {
   function_name: "******"
   project_id: "******"
   region: "us-central1"
  }
  type: "cloud_function"
 }
 severity: "DEBUG"
 textPayload: "Function execution took 12362 ms, finished with status: 'crash'"
 timestamp: "2020-05-29T22:11:15.430033249Z"
 trace: "projects/******/traces/******"
}

*i don't really know what's sensitive information and what's not, so I just starred some random things

As I'm writing this, I realize more logging could help, so I stuck a Google logger in between the logger setup, db setup, and the table check I run.

The function crashes before the Google logger is even set up.

So at this point I'm not really sure what could be breaking my function, and I don't know how to find out, seeing as Google Cloud logging is of no help. The error json has a trace property which looks really promising, because all I need at this point is a Python stack trace, but I don't know if there's a way to see that.

I should note that I have environment variables configured through GCP's Cloud Function console.

Principally, there are two things that would be helpful:

how to see python stack trace of crashing cloud function

what, specific to my application, could be causing it to exhibit this crashing behavior

Body:
So I finally figured out that if, instead of triggering your cloud function via Cloud Scheduler, you run the function manually via Test Function

GCP will give you the raised exception. In my case, my Cloud MySQL connection was failing

Error: function terminated. Recommended action: inspect logs for termination reason. Details:
(pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on '**.***.**.***' (timed out)")
(Background on this error at: http://sqlalche.me/e/e3q8)

so I simply had to introduce an environment variable to toggle between connecting via proxy and unix sockets like such:

if os.environ.get("ENV") == "local":
    db = sqlalchemy.create_engine(
        sqlalchemy.engine.url.URL(
            drivername="mysql+pymysql",
            username=os.environ.get("DB_USER"),
            password=os.environ.get("DB_PASS"),
            host=os.environ.get("DB_HOST"),
            port=3306,
            database=PRIMARY_TABLE_NAME
        ),
        pool_size=5,
        max_overflow=2,
        pool_timeout=30,
        pool_recycle=1800
    )
else:
    db = sqlalchemy.create_engine(
        sqlalchemy.engine.url.URL(
            drivername="mysql+pymysql",
            username=os.environ.get("DB_USER"),
            password=os.environ.get("DB_PASS"),
            database=PRIMARY_TABLE_NAME,
            query={"unix_socket": "/cloudsql/{}".format(os.environ.get("CLOUD_SQL_CONNECTION_NAME"))}
        ),
        pool_size=5,
        max_overflow=2,
        pool_timeout=30,
        pool_recycle=1800
    )