问:
Rewrite query with union in subquery by using gorm
I am trying to write sql query by using gorm. Here the query

```<code>SELECT *
FROM (
    SELECT unnest(tags) as tag_name FROM models
        union all
    SELECT unnest(system_tags) from models
left join projects on projects.id = models.project_id
WHERE (projects.is_public = true )) as tD
WHERE LOWER( tD.tag_name ) LIKE '%12%' ORDER BY tag_name
</code>```

I tried to create subquery. But cant figure out how to add union. As I understand select does not work this way. Is using Raw() my only option?

```<code>selectStr := "unnest(tags) as tag_name from models union select unnest(system_tags) from models"

subQuery = db.
    Model(&tagsGet).
    Select(selectStr).
    Joins(joinStrProjects).
    Where(whereClause, args...)
</code>```

Body:
I am trying to write sql query by using gorm. Here the query

SELECT *
FROM (
    SELECT unnest(tags) as tag_name FROM models
        union all
    SELECT unnest(system_tags) from models
left join projects on projects.id = models.project_id
WHERE (projects.is_public = true )) as tD
WHERE LOWER( tD.tag_name ) LIKE '%12%' ORDER BY tag_name

I tried to create subquery. But cant figure out how to add union. As I understand select does not work this way. Is using Raw() my only option?

selectStr := "unnest(tags) as tag_name from models union select unnest(system_tags) from models"

subQuery = db.
    Model(&tagsGet).
    Select(selectStr).
    Joins(joinStrProjects).
    Where(whereClause, args...)


来源: stackexchange

问:
Organizing family likes and favorites for advanced gift giving
I'm looking for a way to organize and share data with extended family members with excel or google sheets were I can open it up for everyone to contribute to the information.
Id like to have a list of the oldest family members like grandma and grandpa, under them the children's names and so on. like a family tree but not for genealogy... this is for taking information like favorite foods, clothing sizes, interest(information pertinent to gift giving)
I'm not good with excel so much but in the past this community has never let me down.
any ideas or templets that others have or have seen that could help me do this would be so great.

Ive attached a start of the idea i've had but i feel theres a better way

ContentLicense: CC BY-SA 4.0


问:
dovecot mail_crypt failed to initialize user,mail_crypt_global_private_key mail_crypt_global_private_key_password unset,no password to decrypt the key
I have been using postfix+dovecot successfully for a while now until I tried mail crypt plugin lately. I tried what is describe here https://doc.dovecot.org/configuration_manual/mail_crypt_plugin/ and I went for global-keys as described here: https://doc.dovecot.org/configuration_manual/mail_crypt_plugin/#global-keys
"A good solution for environments where no user folder sharing is needed is to generate per-user EC key pair and encrypt that with something derived from user’s password."

I am setting mail_crypt_global_private_key, mail_crypt_global_public_key, mail_crypt_save_version from user_query and userdb_mail_crypt_global_private_key_password from password_query. mail_crypt seems to work fine in imap (I saved a message as draft and it is stored encrypted on the disk), but lmtp complains about "mail_crypt_global_private_key_password unset, no password to decrypt the key" As you can see below in logs that it was able to set all other mail_crypt_ configurations successfully from user_query. However, the password is provided via password_query and I assume lmtp does not read password_query. How else can I provide a password in lmtp (Why do lmtp needs a password, can it not use public key to encrypt)? Is my approach correct to begin with?

```<code>-- Dovecot Configurations --
# using doveconf -n
# 2.3.19.1 (9b53102964): /etc/dovecot/dovecot.conf
# Pigeonhole version 0.5.19 (4eae2f79)
# OS: Linux 5.15.0-57-generic x86_64 Ubuntu 20.04.5 LTS
# Hostname: mailserver-dovecot-7c9ff7b94b-8ldrr
auth_mechanisms = plain login
auth_verbose = yes
auth_verbose_passwords = yes
debug_log_path = /dev/stdout
haproxy_trusted_networks = 192.168.0.0/16 10.10.10.0/24 10.10.30.0/24 172.17.0.1/16
hostname = imap.mailserver.k8s.local pop.mailserver.k8s.local
info_log_path = /dev/stdout
listen = *
log_path = /dev/stdout
mail_debug = yes
mail_gid = 1000
mail_home = /var/vmail/mailboxes/%d/%n
mail_location = maildir:~/:LAYOUT=fs
mail_plugins = quota mail_crypt
mail_privileged_group = mail
mail_uid = 1000
managesieve_notify_capability = mailto
managesieve_sieve_capability = fileinto reject envelope encoded-character vacation subaddress comparator-i;ascii-numeric relational regex imap4flags copy include variables body enotify environment mailbox date index ihave duplicate mime foreverypart extracttext imapsieve vnd.dovecot.imapsieve
namespace inbox {
  inbox = yes
  location =
  mailbox Drafts {
    auto = subscribe
    special_use = \Drafts
  }
  mailbox Sent {
    auto = subscribe
    special_use = \Sent
  }
  mailbox "Sent Messages" {
    special_use = \Sent
  }
  mailbox Spam {
    auto = subscribe
    autoexpunge = 30 days
    special_use = \Junk
  }
  mailbox Trash {
    auto = subscribe
    autoexpunge = 30 days
    special_use = \Trash
  }
  prefix =
}
passdb {
  args = /etc/dovecot/dovecot-sql.conf.ext
  driver = sql
}
plugin {
  imapsieve_mailbox1_before = file:/var/vmail/sieve/global/learn-spam.sieve
  imapsieve_mailbox1_causes = COPY APPEND FLAG
  imapsieve_mailbox1_name = Spam
  imapsieve_mailbox2_before = file:/var/vmail/sieve/global/learn-ham.sieve
  imapsieve_mailbox2_causes = COPY APPEND FLAG
  imapsieve_mailbox2_from = Spam
  imapsieve_mailbox2_name = *
  mail_crypt_save_version = 0
  quota = maildir:User quota
  quota_exceeded_message = User %u has exhausted allowed storage space.
  quota_rule = Junk:ignore
  quota_rule2 = Trash:storage=+100M
  quota_warning = storage=90%% quota-warning 90 %u %d
  quota_warning2 = storage=80%% quota-warning 80 %u %d
  sieve = file:~/sieve;active=~/.dovecot.sieve
  sieve_before = /var/vmail/sieve/global/spam-global.sieve
  sieve_global = /var/vmail/sieve/global/
  sieve_global_extensions = +vnd.dovecot.pipe +vnd.dovecot.debug
  sieve_pipe_bin_dir = /var/vmail/sieve/global
  sieve_plugins = sieve_imapsieve sieve_extprograms
}
protocols = " imap lmtp sieve pop3"
service auth {
  inet_listener {
    port = 25252
  }
}
service imap-login {
  inet_listener imap {
    haproxy = yes
  }
  inet_listener imaps {
    haproxy = yes
    ssl = yes
  }
}
service lmtp {
  executable = lmtp -L
  inet_listener lmtp {
    address = 0.0.0.0
    port = 24
  }
}
service managesieve-login {
  inet_listener sieve {
    port = 4190
  }
}
service pop3-login {
  inet_listener pop3 {
    haproxy = yes
  }
  inet_listener pop3s {
    haproxy = yes
  }
}
ssl = required
ssl_cert = </etc/dovecot/certs/tls.crt
ssl_client_ca_dir = /etc/ssl/certs
ssl_key = # hidden, use -P to show it
ssl_prefer_server_ciphers = yes
userdb {
  args = /etc/dovecot/dovecot-sql.conf.ext
  driver = sql
}
protocol lmtp {
  info_log_path = /dev/stdout
  log_path = /dev/stdout
  mail_plugins = quota mail_crypt sieve
  postmaster_address = <hidden>
}
protocol imap {
  mail_plugins = quota mail_crypt quota imap_quota imap_sieve
}
-- Dovecot Configurations Ends --

-- Password Query --
password_query = \
    SELECT username, domain, password, \
    '%{sha256:password}' AS userdb_mail_crypt_global_private_key_password \
    FROM mailbox \
    WHERE username='%u';
-- Password Query Ends--

-- User Query --
user_query = SELECT CONCAT('*:bytes=', 1024) as quota_rule, \
    private_key AS mail_crypt_global_private_key, \
    public_key AS mail_crypt_global_public_key, \
    mail_crypt_save_version AS mail_crypt_save_version \
    FROM mailbox \
    WHERE username='%u';
-- User Query Ends --

-- Debug Logs --
--- Load Inbox ---
imap-login: Info: Login: user=<someone@example.com>, method=PLAIN, rip=192.168.49.1, lip=192.168.49.2, mpid=241, TLS, session=<oaoI9sLxVKXAqDEB>
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Loading modules from directory: /usr/lib/dovecot/modules
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Module loaded: /usr/lib/dovecot/modules/lib10_mail_crypt_plugin.so
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Module loaded: /usr/lib/dovecot/modules/lib10_quota_plugin.so
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Module loaded: /usr/lib/dovecot/modules/lib11_imap_quota_plugin.so
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Module loaded: /usr/lib/dovecot/modules/lib95_imap_sieve_plugin.so
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Added userdb setting: plugin/mail_crypt_global_private_key=LS0tLS1CRUd.....LS0tLS0K
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Added userdb setting: plugin/mail_crypt_global_private_key_password=<hidden>
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Added userdb setting: plugin/mail_crypt_global_public_key=LS0tLS1CRUd.....LS0tCg==
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Added userdb setting: plugin/mail_crypt_save_version=2
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Added userdb setting: plugin/quota_rule=*:bytes=1024000000
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Effective uid=1000, gid=1000, home=/var/vmail/mailboxes/example.com/someone
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: mail_crypt_plugin: mail_crypt_curve setting missing - generating EC keys disabled
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Quota root: name=User quota backend=maildir args=
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Quota rule: root=User quota mailbox=* bytes=1024000000 messages=0
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Quota rule: root=User quota mailbox=Trash bytes=+104857600 messages=0
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Quota warning: bytes=921600000 (90%) messages=0 reverse=no command=quota-warning 90 someone@example.com example.com
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Quota warning: bytes=819200000 (80%) messages=0 reverse=no command=quota-warning 80 someone@example.com example.com
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Quota grace: root=User quota bytes=102400000 (10%)
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: open(/proc/self/io) failed: Permission denied
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Namespace inbox: type=private, prefix=, sep=, inbox=yes, hidden=no, list=yes, subscriptions=yes location=maildir:~/:LAYOUT=fs
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: fs: root=/var/vmail/mailboxes/example.com/someone, index=, indexpvt=, control=, inbox=/var/vmail/mailboxes/example.com/someone, alt=
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: quota: quota_over_flag check: quota_over_script unset - skipping
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Mailbox INBOX: Mailbox opened
--- Load Inbox Ends ---
--- Lmtp ---
lmtp(248): Info: Connect from 172.17.0.1
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: auth-master: userdb lookup(someone@example.com): Started userdb lookup
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: auth-master: conn unix:/var/run/dovecot/auth-userdb: Connecting
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: auth-master: conn unix:/var/run/dovecot/auth-userdb (pid=143,uid=0): Client connected (fd=18)
imap(someone@example.com)<247><WlggG8PxEOvAqDEB>: Debug: Mailbox Sent: Purging (new file_seq=1673195172): creating cache
imap(someone@example.com)<247><WlggG8PxEOvAqDEB>: Debug: Mailbox Sent: Purging finished, file_seq changed 0 -> 1673195172, size=0 -> 388, max_uid=0
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: auth-master: userdb lookup(someone@example.com): auth USER input: someone@example.com quota_rule=*:bytes=1024000000 mail_crypt_global_private_key=LS0tLS1CRUd.....LS0tLS0K mail_crypt_global_public_key=LS0tLS1CRUd.....LS0tCg== mail_crypt_save_version=2
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: auth-master: userdb lookup(someone@example.com): Finished userdb lookup (username=someone@example.com quota_rule=*:bytes=1024000000 mail_crypt_global_private_key=LS0tLS1CRUd.....LS0tLS0K mail_crypt_global_public_key=LS0tLS1CRUd.....LS0tCg== mail_crypt_save_version=2)
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: lmtp-server: conn 172.17.0.1:6376 [1]: rcpt someone@example.com: Added userdb setting: plugin/mail_crypt_global_private_key=LS0tLS1CRUd.....LS0tLS0K
imap(someone@example.com)<247><WlggG8PxEOvAqDEB>: Debug: duplicate db: Initialize
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: lmtp-server: conn 172.17.0.1:6376 [1]: rcpt someone@example.com: Added userdb setting: plugin/mail_crypt_global_public_key=LS0tLS1CRUd.....LS0tCg==
imap(someone@example.com)<247><WlggG8PxEOvAqDEB>: Debug: sieve: Pigeonhole version 0.5.19 (4eae2f79) initializing
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: lmtp-server: conn 172.17.0.1:6376 [1]: rcpt someone@example.com: Added userdb setting: plugin/mail_crypt_save_version=2
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: lmtp-server: conn 172.17.0.1:6376 [1]: rcpt someone@example.com: Added userdb setting: plugin/quota_rule=*:bytes=1024000000
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: lmtp-server: conn 172.17.0.1:6376 [1]: rcpt someone@example.com: Effective uid=1000, gid=1000, home=/var/vmail/mailboxes/example.com/someone
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: lmtp-server: conn 172.17.0.1:6376 [1]: rcpt someone@example.com: mail_crypt_plugin: mail_crypt_curve setting missing - generating EC keys disabled
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: lmtp-server: conn 172.17.0.1:6376 [1]: rcpt someone@example.com: Quota root: name=User quota backend=maildir args=
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: lmtp-server: conn 172.17.0.1:6376 [1]: rcpt someone@example.com: Quota rule: root=User quota mailbox=* bytes=1024000000 messages=0
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: lmtp-server: conn 172.17.0.1:6376 [1]: rcpt someone@example.com: Quota rule: root=User quota mailbox=Trash bytes=+104857600 messages=0
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: lmtp-server: conn 172.17.0.1:6376 [1]: rcpt someone@example.com: Quota warning: bytes=921600000 (90%) messages=0 reverse=no command=quota-warning 90 someone@example.com example.com
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: lmtp-server: conn 172.17.0.1:6376 [1]: rcpt someone@example.com: Quota warning: bytes=819200000 (80%) messages=0 reverse=no command=quota-warning 80 someone@example.com example.com
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: lmtp-server: conn 172.17.0.1:6376 [1]: rcpt someone@example.com: Quota grace: root=User quota bytes=102400000 (10%)
lmtp(248): Error: lmtp-server: conn 172.17.0.1:6376 [1]: rcpt someone@example.com: Failed to initialize user: mail_crypt_plugin: mail_crypt_global_private_key: mail_crypt_global_private_key_password unset, no password to decrypt the key
lmtp(248): Info: Disconnect from 172.17.0.1: Logged out (state=READY)
--- Lmtp Ends ---
-- Debug Logs Ends --

</code>```

Body:
I have been using postfix+dovecot successfully for a while now until I tried mail crypt plugin lately. I tried what is describe here https://doc.dovecot.org/configuration_manual/mail_crypt_plugin/ and I went for global-keys as described here: https://doc.dovecot.org/configuration_manual/mail_crypt_plugin/#global-keys
"A good solution for environments where no user folder sharing is needed is to generate per-user EC key pair and encrypt that with something derived from user’s password."

I am setting mail_crypt_global_private_key, mail_crypt_global_public_key, mail_crypt_save_version from user_query and userdb_mail_crypt_global_private_key_password from password_query. mail_crypt seems to work fine in imap (I saved a message as draft and it is stored encrypted on the disk), but lmtp complains about "mail_crypt_global_private_key_password unset, no password to decrypt the key" As you can see below in logs that it was able to set all other mail_crypt_ configurations successfully from user_query. However, the password is provided via password_query and I assume lmtp does not read password_query. How else can I provide a password in lmtp (Why do lmtp needs a password, can it not use public key to encrypt)? Is my approach correct to begin with?

-- Dovecot Configurations --
# using doveconf -n
# 2.3.19.1 (9b53102964): /etc/dovecot/dovecot.conf
# Pigeonhole version 0.5.19 (4eae2f79)
# OS: Linux 5.15.0-57-generic x86_64 Ubuntu 20.04.5 LTS
# Hostname: mailserver-dovecot-7c9ff7b94b-8ldrr
auth_mechanisms = plain login
auth_verbose = yes
auth_verbose_passwords = yes
debug_log_path = /dev/stdout
haproxy_trusted_networks = 192.168.0.0/16 10.10.10.0/24 10.10.30.0/24 172.17.0.1/16
hostname = imap.mailserver.k8s.local pop.mailserver.k8s.local
info_log_path = /dev/stdout
listen = *
log_path = /dev/stdout
mail_debug = yes
mail_gid = 1000
mail_home = /var/vmail/mailboxes/%d/%n
mail_location = maildir:~/:LAYOUT=fs
mail_plugins = quota mail_crypt
mail_privileged_group = mail
mail_uid = 1000
managesieve_notify_capability = mailto
managesieve_sieve_capability = fileinto reject envelope encoded-character vacation subaddress comparator-i;ascii-numeric relational regex imap4flags copy include variables body enotify environment mailbox date index ihave duplicate mime foreverypart extracttext imapsieve vnd.dovecot.imapsieve
namespace inbox {
  inbox = yes
  location =
  mailbox Drafts {
    auto = subscribe
    special_use = \Drafts
  }
  mailbox Sent {
    auto = subscribe
    special_use = \Sent
  }
  mailbox "Sent Messages" {
    special_use = \Sent
  }
  mailbox Spam {
    auto = subscribe
    autoexpunge = 30 days
    special_use = \Junk
  }
  mailbox Trash {
    auto = subscribe
    autoexpunge = 30 days
    special_use = \Trash
  }
  prefix =
}
passdb {
  args = /etc/dovecot/dovecot-sql.conf.ext
  driver = sql
}
plugin {
  imapsieve_mailbox1_before = file:/var/vmail/sieve/global/learn-spam.sieve
  imapsieve_mailbox1_causes = COPY APPEND FLAG
  imapsieve_mailbox1_name = Spam
  imapsieve_mailbox2_before = file:/var/vmail/sieve/global/learn-ham.sieve
  imapsieve_mailbox2_causes = COPY APPEND FLAG
  imapsieve_mailbox2_from = Spam
  imapsieve_mailbox2_name = *
  mail_crypt_save_version = 0
  quota = maildir:User quota
  quota_exceeded_message = User %u has exhausted allowed storage space.
  quota_rule = Junk:ignore
  quota_rule2 = Trash:storage=+100M
  quota_warning = storage=90%% quota-warning 90 %u %d
  quota_warning2 = storage=80%% quota-warning 80 %u %d
  sieve = file:~/sieve;active=~/.dovecot.sieve
  sieve_before = /var/vmail/sieve/global/spam-global.sieve
  sieve_global = /var/vmail/sieve/global/
  sieve_global_extensions = +vnd.dovecot.pipe +vnd.dovecot.debug
  sieve_pipe_bin_dir = /var/vmail/sieve/global
  sieve_plugins = sieve_imapsieve sieve_extprograms
}
protocols = " imap lmtp sieve pop3"
service auth {
  inet_listener {
    port = 25252
  }
}
service imap-login {
  inet_listener imap {
    haproxy = yes
  }
  inet_listener imaps {
    haproxy = yes
    ssl = yes
  }
}
service lmtp {
  executable = lmtp -L
  inet_listener lmtp {
    address = 0.0.0.0
    port = 24
  }
}
service managesieve-login {
  inet_listener sieve {
    port = 4190
  }
}
service pop3-login {
  inet_listener pop3 {
    haproxy = yes
  }
  inet_listener pop3s {
    haproxy = yes
  }
}
ssl = required
ssl_cert = </etc/dovecot/certs/tls.crt
ssl_client_ca_dir = /etc/ssl/certs
ssl_key = # hidden, use -P to show it
ssl_prefer_server_ciphers = yes
userdb {
  args = /etc/dovecot/dovecot-sql.conf.ext
  driver = sql
}
protocol lmtp {
  info_log_path = /dev/stdout
  log_path = /dev/stdout
  mail_plugins = quota mail_crypt sieve
  postmaster_address = <hidden>
}
protocol imap {
  mail_plugins = quota mail_crypt quota imap_quota imap_sieve
}
-- Dovecot Configurations Ends --

-- Password Query --
password_query = \
    SELECT username, domain, password, \
    '%{sha256:password}' AS userdb_mail_crypt_global_private_key_password \
    FROM mailbox \
    WHERE username='%u';
-- Password Query Ends--

-- User Query --
user_query = SELECT CONCAT('*:bytes=', 1024) as quota_rule, \
    private_key AS mail_crypt_global_private_key, \
    public_key AS mail_crypt_global_public_key, \
    mail_crypt_save_version AS mail_crypt_save_version \
    FROM mailbox \
    WHERE username='%u';
-- User Query Ends --

-- Debug Logs --
--- Load Inbox ---
imap-login: Info: Login: user=<someone@example.com>, method=PLAIN, rip=192.168.49.1, lip=192.168.49.2, mpid=241, TLS, session=<oaoI9sLxVKXAqDEB>
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Loading modules from directory: /usr/lib/dovecot/modules
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Module loaded: /usr/lib/dovecot/modules/lib10_mail_crypt_plugin.so
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Module loaded: /usr/lib/dovecot/modules/lib10_quota_plugin.so
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Module loaded: /usr/lib/dovecot/modules/lib11_imap_quota_plugin.so
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Module loaded: /usr/lib/dovecot/modules/lib95_imap_sieve_plugin.so
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Added userdb setting: plugin/mail_crypt_global_private_key=LS0tLS1CRUd.....LS0tLS0K
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Added userdb setting: plugin/mail_crypt_global_private_key_password=<hidden>
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Added userdb setting: plugin/mail_crypt_global_public_key=LS0tLS1CRUd.....LS0tCg==
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Added userdb setting: plugin/mail_crypt_save_version=2
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Added userdb setting: plugin/quota_rule=*:bytes=1024000000
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Effective uid=1000, gid=1000, home=/var/vmail/mailboxes/example.com/someone
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: mail_crypt_plugin: mail_crypt_curve setting missing - generating EC keys disabled
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Quota root: name=User quota backend=maildir args=
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Quota rule: root=User quota mailbox=* bytes=1024000000 messages=0
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Quota rule: root=User quota mailbox=Trash bytes=+104857600 messages=0
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Quota warning: bytes=921600000 (90%) messages=0 reverse=no command=quota-warning 90 someone@example.com example.com
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Quota warning: bytes=819200000 (80%) messages=0 reverse=no command=quota-warning 80 someone@example.com example.com
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Quota grace: root=User quota bytes=102400000 (10%)
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: open(/proc/self/io) failed: Permission denied
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Namespace inbox: type=private, prefix=, sep=, inbox=yes, hidden=no, list=yes, subscriptions=yes location=maildir:~/:LAYOUT=fs
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: fs: root=/var/vmail/mailboxes/example.com/someone, index=, indexpvt=, control=, inbox=/var/vmail/mailboxes/example.com/someone, alt=
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: quota: quota_over_flag check: quota_over_script unset - skipping
imap(someone@example.com)<241><oaoI9sLxVKXAqDEB>: Debug: Mailbox INBOX: Mailbox opened
--- Load Inbox Ends ---
--- Lmtp ---
lmtp(248): Info: Connect from 172.17.0.1
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: auth-master: userdb lookup(someone@example.com): Started userdb lookup
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: auth-master: conn unix:/var/run/dovecot/auth-userdb: Connecting
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: auth-master: conn unix:/var/run/dovecot/auth-userdb (pid=143,uid=0): Client connected (fd=18)
imap(someone@example.com)<247><WlggG8PxEOvAqDEB>: Debug: Mailbox Sent: Purging (new file_seq=1673195172): creating cache
imap(someone@example.com)<247><WlggG8PxEOvAqDEB>: Debug: Mailbox Sent: Purging finished, file_seq changed 0 -> 1673195172, size=0 -> 388, max_uid=0
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: auth-master: userdb lookup(someone@example.com): auth USER input: someone@example.com quota_rule=*:bytes=1024000000 mail_crypt_global_private_key=LS0tLS1CRUd.....LS0tLS0K mail_crypt_global_public_key=LS0tLS1CRUd.....LS0tCg== mail_crypt_save_version=2
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: auth-master: userdb lookup(someone@example.com): Finished userdb lookup (username=someone@example.com quota_rule=*:bytes=1024000000 mail_crypt_global_private_key=LS0tLS1CRUd.....LS0tLS0K mail_crypt_global_public_key=LS0tLS1CRUd.....LS0tCg== mail_crypt_save_version=2)
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: lmtp-server: conn 172.17.0.1:6376 [1]: rcpt someone@example.com: Added userdb setting: plugin/mail_crypt_global_private_key=LS0tLS1CRUd.....LS0tLS0K
imap(someone@example.com)<247><WlggG8PxEOvAqDEB>: Debug: duplicate db: Initialize
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: lmtp-server: conn 172.17.0.1:6376 [1]: rcpt someone@example.com: Added userdb setting: plugin/mail_crypt_global_public_key=LS0tLS1CRUd.....LS0tCg==
imap(someone@example.com)<247><WlggG8PxEOvAqDEB>: Debug: sieve: Pigeonhole version 0.5.19 (4eae2f79) initializing
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: lmtp-server: conn 172.17.0.1:6376 [1]: rcpt someone@example.com: Added userdb setting: plugin/mail_crypt_save_version=2
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: lmtp-server: conn 172.17.0.1:6376 [1]: rcpt someone@example.com: Added userdb setting: plugin/quota_rule=*:bytes=1024000000
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: lmtp-server: conn 172.17.0.1:6376 [1]: rcpt someone@example.com: Effective uid=1000, gid=1000, home=/var/vmail/mailboxes/example.com/someone
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: lmtp-server: conn 172.17.0.1:6376 [1]: rcpt someone@example.com: mail_crypt_plugin: mail_crypt_curve setting missing - generating EC keys disabled
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: lmtp-server: conn 172.17.0.1:6376 [1]: rcpt someone@example.com: Quota root: name=User quota backend=maildir args=
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: lmtp-server: conn 172.17.0.1:6376 [1]: rcpt someone@example.com: Quota rule: root=User quota mailbox=* bytes=1024000000 messages=0
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: lmtp-server: conn 172.17.0.1:6376 [1]: rcpt someone@example.com: Quota rule: root=User quota mailbox=Trash bytes=+104857600 messages=0
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: lmtp-server: conn 172.17.0.1:6376 [1]: rcpt someone@example.com: Quota warning: bytes=921600000 (90%) messages=0 reverse=no command=quota-warning 90 someone@example.com example.com
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: lmtp-server: conn 172.17.0.1:6376 [1]: rcpt someone@example.com: Quota warning: bytes=819200000 (80%) messages=0 reverse=no command=quota-warning 80 someone@example.com example.com
lmtp(someone@example.com)<248><e2dcD6TuumP4AAAALzF/Qw>: Debug: lmtp-server: conn 172.17.0.1:6376 [1]: rcpt someone@example.com: Quota grace: root=User quota bytes=102400000 (10%)
lmtp(248): Error: lmtp-server: conn 172.17.0.1:6376 [1]: rcpt someone@example.com: Failed to initialize user: mail_crypt_plugin: mail_crypt_global_private_key: mail_crypt_global_private_key_password unset, no password to decrypt the key
lmtp(248): Info: Disconnect from 172.17.0.1: Logged out (state=READY)
--- Lmtp Ends ---
-- Debug Logs Ends --


问:
Kotlin - The accelerometer sampling rate is not independent of the location update interval
I'm trying to make a sensor data collection app in Kotlin. However, I've been encountering a lot of issues when it comes to getting accelerometer data and location updates at different sampling rates. I need to set the accelerometer sampling rate at 4 Hz, and the location updates at 1 Hz.

Basically, changing the 'samplingPeriodUs' of the accelerometer's register listener has no impact on it, when I'm trying to get location updates. I'm able to get the location updates once every second just fine, but the accelerometer values are changing too rapidly and not accurately.

I've tested this as well. When I remove the location updates, and just check the accelerometer values, they are changing much more slowly and at a rate I want. When I try to get the location updates as well, the accelerometer sampling rate suddenly has no effect, and the values start changing too rapidly.

I've looked everywhere for a solution, but I cannot seem to find it. I would be very grateful if someone could help this very confused beginner!

Additionally, I am also attaching a snippet of the code:

```<code>class MainActivity : AppCompatActivity() {

    var latitude : Double = 0.0
    var longitude : Double = 0.0
    // start button flag
    private var resume = false

    private val locationCallback = object : LocationCallback() {
        override fun onLocationResult(locationResult: LocationResult?) {
            locationResult ?: return
            for (location in locationResult.locations) {

                if (resume)
                {
                    latitude = location.latitude
                    longitude = location.longitude
                    findViewById<TextView>(R.id.longt).text = longitude.toString()
                    findViewById<TextView>(R.id.lat).text = latitude.toString()
                }

            }
        }
    }

    private val accelerometerListener = object : SensorEventListener {
        override fun onSensorChanged(event: SensorEvent) {

            var sensor_label = ""
            var accelerometer_x = "0.0"
            var accelerometer_y = "0.0"
            var accelerometer_z = "0.0"

            var gyroscope_x = "0.0"
            var gyroscope_y = "0.0"
            var gyroscope_z = "0.0"

            if (event != null && resume)
            {
                if (event.sensor.type == Sensor.TYPE_ACCELEROMETER)
                {

                    val accX = event.values[0]
                    val temp01:Double = String.format("%.3f", accX).toDouble()
                    findViewById<TextView>(R.id.acc_X).text = temp01.toString()

                    val accY = event.values[1]
                    val temp11:Double = String.format("%.3f", accY).toDouble()
                    findViewById<TextView>(R.id.acc_Y).text = temp11.toString()

                    val accZ = event.values[2]
                    val temp21:Double = String.format("%.3f", accZ).toDouble()
                    findViewById<TextView>(R.id.acc_Z).text = temp21.toString()

                    accelerometer_x = temp01.toString()
                    accelerometer_y = temp11.toString()
                    accelerometer_z = temp21.toString()
               }

           }
        }

        override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {}
    }

    @SuppressLint("MissingPermission")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Request location updates
        val locationRequest = LocationRequest().apply {
            interval = 1000
            fastestInterval = 1000
            priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        }
        val locationClient = LocationServices.getFusedLocationProviderClient(this)
        if(CheckPermission()){
            if(isLocationEnabled()){
                locationClient.requestLocationUpdates(locationRequest, locationCallback, null)
            }else{
                Toast.makeText(this, "Location service not enabled", Toast.LENGTH_SHORT).show()
            }

        }else{
            RequestPermission()
        }

        // Register accelerometer sensor listener
        val sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
        val accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
        val desiredInterval = SensorManager.SENSOR_DELAY_NORMAL

        Timer().scheduleAtFixedRate( object : TimerTask() {
                override fun run() {
                    sensorManager.registerListener(accelerometerListener, accelerometer, 100000, )
                }
            }, 0, 1000)
    }

    override fun onPause() {
        super.onPause()
        // unregister the sensor listener
        val sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
        sensorManager.unregisterListener(accelerometerListener)
    }

    private fun CheckPermission() : Boolean {
        if( (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
            || (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) ){
            return true
        }

        return false
    }

    private fun RequestPermission() {

        ActivityCompat.requestPermissions(
            this,
            arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ), 1000
        )

    }

    private fun isLocationEnabled() : Boolean{
        val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        if (requestCode == 1000){
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                println("Permission granted")
            }
        }
    }

    // button start and stop
    fun resumeReading(view: View) {
        if (this.resume == true)
        {
            Toast.makeText(this, "Data collection has already been started!", Toast.LENGTH_SHORT).show()
        }
        else if (this.resume == false)
        {
            this.resume = true
            Toast.makeText(this, "Data collection has begun!", Toast.LENGTH_SHORT).show()

        }
    }

    fun pauseReading(view: View) {
        if (this.resume == false)
        {
            Toast.makeText(this, "Data collection has already stopped!", Toast.LENGTH_SHORT).show()
        }
        else if (this.resume == true)
        {
            this.resume = false
            Toast.makeText(this, "Data collection has stopped!", Toast.LENGTH_SHORT).show()
        }
    }

}

</code>```

Body:
I'm trying to make a sensor data collection app in Kotlin. However, I've been encountering a lot of issues when it comes to getting accelerometer data and location updates at different sampling rates. I need to set the accelerometer sampling rate at 4 Hz, and the location updates at 1 Hz.

Basically, changing the 'samplingPeriodUs' of the accelerometer's register listener has no impact on it, when I'm trying to get location updates. I'm able to get the location updates once every second just fine, but the accelerometer values are changing too rapidly and not accurately.

I've tested this as well. When I remove the location updates, and just check the accelerometer values, they are changing much more slowly and at a rate I want. When I try to get the location updates as well, the accelerometer sampling rate suddenly has no effect, and the values start changing too rapidly.

I've looked everywhere for a solution, but I cannot seem to find it. I would be very grateful if someone could help this very confused beginner!

Additionally, I am also attaching a snippet of the code:

class MainActivity : AppCompatActivity() {

    var latitude : Double = 0.0
    var longitude : Double = 0.0
    // start button flag
    private var resume = false

    private val locationCallback = object : LocationCallback() {
        override fun onLocationResult(locationResult: LocationResult?) {
            locationResult ?: return
            for (location in locationResult.locations) {

                if (resume)
                {
                    latitude = location.latitude
                    longitude = location.longitude
                    findViewById<TextView>(R.id.longt).text = longitude.toString()
                    findViewById<TextView>(R.id.lat).text = latitude.toString()
                }

            }
        }
    }

    private val accelerometerListener = object : SensorEventListener {
        override fun onSensorChanged(event: SensorEvent) {

            var sensor_label = ""
            var accelerometer_x = "0.0"
            var accelerometer_y = "0.0"
            var accelerometer_z = "0.0"

            var gyroscope_x = "0.0"
            var gyroscope_y = "0.0"
            var gyroscope_z = "0.0"

            if (event != null && resume)
            {
                if (event.sensor.type == Sensor.TYPE_ACCELEROMETER)
                {

                    val accX = event.values[0]
                    val temp01:Double = String.format("%.3f", accX).toDouble()
                    findViewById<TextView>(R.id.acc_X).text = temp01.toString()

                    val accY = event.values[1]
                    val temp11:Double = String.format("%.3f", accY).toDouble()
                    findViewById<TextView>(R.id.acc_Y).text = temp11.toString()

                    val accZ = event.values[2]
                    val temp21:Double = String.format("%.3f", accZ).toDouble()
                    findViewById<TextView>(R.id.acc_Z).text = temp21.toString()

                    accelerometer_x = temp01.toString()
                    accelerometer_y = temp11.toString()
                    accelerometer_z = temp21.toString()
               }

           }
        }

        override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {}
    }

    @SuppressLint("MissingPermission")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Request location updates
        val locationRequest = LocationRequest().apply {
            interval = 1000
            fastestInterval = 1000
            priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        }
        val locationClient = LocationServices.getFusedLocationProviderClient(this)
        if(CheckPermission()){
            if(isLocationEnabled()){
                locationClient.requestLocationUpdates(locationRequest, locationCallback, null)
            }else{
                Toast.makeText(this, "Location service not enabled", Toast.LENGTH_SHORT).show()
            }

        }else{
            RequestPermission()
        }

        // Register accelerometer sensor listener
        val sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
        val accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
        val desiredInterval = SensorManager.SENSOR_DELAY_NORMAL

        Timer().scheduleAtFixedRate( object : TimerTask() {
                override fun run() {
                    sensorManager.registerListener(accelerometerListener, accelerometer, 100000, )
                }
            }, 0, 1000)
    }

    override fun onPause() {
        super.onPause()
        // unregister the sensor listener
        val sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
        sensorManager.unregisterListener(accelerometerListener)
    }

    private fun CheckPermission() : Boolean {
        if( (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
            || (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) ){
            return true
        }

        return false
    }

    private fun RequestPermission() {

        ActivityCompat.requestPermissions(
            this,
            arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ), 1000
        )

    }

    private fun isLocationEnabled() : Boolean{
        val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        if (requestCode == 1000){
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                println("Permission granted")
            }
        }
    }

    // button start and stop
    fun resumeReading(view: View) {
        if (this.resume == true)
        {
            Toast.makeText(this, "Data collection has already been started!", Toast.LENGTH_SHORT).show()
        }
        else if (this.resume == false)
        {
            this.resume = true
            Toast.makeText(this, "Data collection has begun!", Toast.LENGTH_SHORT).show()

        }
    }

    fun pauseReading(view: View) {
        if (this.resume == false)
        {
            Toast.makeText(this, "Data collection has already stopped!", Toast.LENGTH_SHORT).show()
        }
        else if (this.resume == true)
        {
            this.resume = false
            Toast.makeText(this, "Data collection has stopped!", Toast.LENGTH_SHORT).show()
        }
    }

}


问:
I can't change row's background color in table
I can't change rows' background-color; I'd like to have one row red.

Here is my code:

table.cennik-table {
  font-size: 20px;
  border: 3px solid #555555;
  width: 80%;
  height: auto;
  text-align: center;
  border-collapse: collapse;
  margin: 0 auto;
}

table.cennik-table th {
  font-size: 22px;
  background-color: #888888;
}

table.cennik-table td {
  padding: 0.7rem;
}

table.cennik-table tr.rowB {
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <table class="cennik-table">
    <tr>
      <th>Ilość wejść</th>
      <th>Zajęcia grupowe</th>
      <th>Treningi personalne</th>
    </tr>

    <tr class="rowB">
      <td>1x tydzień</td>
      <td>20zł</td>
      <td rowspan="4">50zł</td>
    </tr>

    <tr class="rowA">
      <td>2x tydzień</td>
      <td>60zł</td>
    </tr>

    <tr class="rowB">
      <td>3x tydzień</td>
      <td>110zł</td>
    </tr>

    <tr class="rowA">
      <td>OPEN</td>
      <td>160zł</td>
    </tr>
  </table>
</div></code>```

I'm a beginner so I could have made some simple mistakes.

Body:
I can't change rows' background-color; I'd like to have one row red.

Here is my code:

table.cennik-table {
  font-size: 20px;
  border: 3px solid #555555;
  width: 80%;
  height: auto;
  text-align: center;
  border-collapse: collapse;
  margin: 0 auto;
}

table.cennik-table th {
  font-size: 22px;
  background-color: #888888;
}

table.cennik-table td {
  padding: 0.7rem;
}

table.cennik-table tr.rowB {
  background-color: red;
}

      Ilość wejść
      Zajęcia grupowe
      Treningi personalne

      1x tydzień
      20zł
      50zł

      2x tydzień
      60zł

      3x tydzień
      110zł

      OPEN
      160zł

I'm a beginner so I could have made some simple mistakes.


问:
How to resolve mismatch in argument error
Please, I have this code which computes the root of a nonlinear algebraic equation. When I compile the code for the written function(rtsafe) alone, it works, but when I call the function rtsafe using  y = rtsafe(0.01000000000,10.0000000000, 0.00000001) it complains about the argument input for 'x1', giving the error message:

```<code>
      y= rtsafe(0.01000000000,10.0000000000,0.00000001)
                1
Warning: Type mismatch in argument 'x1' at (1); passed REAL(4) to REAL(8)
</code>```

I don't understand how my 'X1 =0.01000000000' is REAL(4) because it has more than 8 decimal digits.
kindly find below the code:

```<code>
      program rootfinding
      real(8) :: rtsafe,y

      real(8) ::testroot

      y= rtsafe(0.01000000000,10.0000000000,0.00000001)

      testroot =(y**2 +0.25)**0.5-1
      print *, testroot,y

      end program

      function rtsafe(x1,x2,xacc)
      implicit none
      integer,parameter :: maxit = 200
      real(8) :: x1,x2
      real(8) :: rtsafe
      real(4) ::  xacc
      integer :: j
      real(4) :: df, dx, dxold, fh, fl, temp, xh, xl, f
      real(4):: func
      real(4):: funcd

      fl =  func(x1)
      fh = func(x2)
      if ((fl > 0 .and. fh > 0) .or. (fl < 0 .and. fh < 0)) then
         print *, 'root must be bracketed'
         return
      end if

      if (fl == 0) then
        rtsafe = x1
        return
      else if (fh == 0) then
        rtsafe = x2
        return

      c    orient the search so that f(x1) < 0

      else if (fl < 0) then
         xl = x1
         xh = x2
      else
         xh = x1
         xl = x2
      end if

      c    initialize  the guess for root,
         rtsafe = 0.5 * (x1+x2)

      c    the step size before last
         dxold = abs(x2 - x1)

      c    and the last step
         dx = dxold

      df = funcd(rtsafe)
      f = func(rtsafe)

      c    loop over allowed iterations

      do j = 1, maxit

      c    bisect if newton is out of range or not decreasing fast enough
          if (((rtsafe - xh)*df - f)*((rtsafe - xl)*df - f) > 0 .or.    &
     &           abs(2*f) > abs (dxold*df)) then
              dxold = dx
              dx = 0.5*(xh - xl)
              rtsafe = xl  + dx
              if (xl == rtsafe) return
          else
              dxold = dx
              dx = f/df
              temp = rtsafe
              rtsafe = rtsafe - dx
              if (temp == rtsafe ) return
          end if

      c     convergence criterion
         if (abs(dx) < xacc) return

         f = func(rtsafe)
         if (f < 0) then
              xl = rtsafe
         else
              xh = rtsafe
         end if

      end do
      print *, 'rtsafe exceeding maximum iterations'
      return
      end function rtsafe

      function func(x)
      implicit none
      real(4):: func
      real(8) :: x
      func = (x**2+ 0.25)**0.5-1.0
      end function

      function funcd(x)
      implicit none
      real(4):: funcd
      real(8) ::x
      funcd= x*(x**2 +0.25)**(-0.5)
      end function
</code>```

Body:
Please, I have this code which computes the root of a nonlinear algebraic equation. When I compile the code for the written function(rtsafe) alone, it works, but when I call the function rtsafe using  y = rtsafe(0.01000000000,10.0000000000, 0.00000001) it complains about the argument input for 'x1', giving the error message:

      y= rtsafe(0.01000000000,10.0000000000,0.00000001)
                1
Warning: Type mismatch in argument 'x1' at (1); passed REAL(4) to REAL(8)

I don't understand how my 'X1 =0.01000000000' is REAL(4) because it has more than 8 decimal digits.
kindly find below the code:

      program rootfinding
      real(8) :: rtsafe,y

      real(8) ::testroot

      y= rtsafe(0.01000000000,10.0000000000,0.00000001)

      testroot =(y**2 +0.25)**0.5-1
      print *, testroot,y

      end program

      function rtsafe(x1,x2,xacc)
      implicit none
      integer,parameter :: maxit = 200
      real(8) :: x1,x2
      real(8) :: rtsafe
      real(4) ::  xacc
      integer :: j
      real(4) :: df, dx, dxold, fh, fl, temp, xh, xl, f
      real(4):: func
      real(4):: funcd

      fl =  func(x1)
      fh = func(x2)
      if ((fl > 0 .and. fh > 0) .or. (fl < 0 .and. fh < 0)) then
         print *, 'root must be bracketed'
         return
      end if

      if (fl == 0) then
        rtsafe = x1
        return
      else if (fh == 0) then
        rtsafe = x2
        return

      c    orient the search so that f(x1) < 0

      else if (fl < 0) then
         xl = x1
         xh = x2
      else
         xh = x1
         xl = x2
      end if

      c    initialize  the guess for root,
         rtsafe = 0.5 * (x1+x2)

      c    the step size before last
         dxold = abs(x2 - x1)

      c    and the last step
         dx = dxold

      df = funcd(rtsafe)
      f = func(rtsafe)

      c    loop over allowed iterations

      do j = 1, maxit

      c    bisect if newton is out of range or not decreasing fast enough
          if (((rtsafe - xh)*df - f)*((rtsafe - xl)*df - f) > 0 .or.    &
     &           abs(2*f) > abs (dxold*df)) then
              dxold = dx
              dx = 0.5*(xh - xl)
              rtsafe = xl  + dx
              if (xl == rtsafe) return
          else
              dxold = dx
              dx = f/df
              temp = rtsafe
              rtsafe = rtsafe - dx
              if (temp == rtsafe ) return
          end if

      c     convergence criterion
         if (abs(dx) < xacc) return

         f = func(rtsafe)
         if (f < 0) then
              xl = rtsafe
         else
              xh = rtsafe
         end if

      end do
      print *, 'rtsafe exceeding maximum iterations'
      return
      end function rtsafe

      function func(x)
      implicit none
      real(4):: func
      real(8) :: x
      func = (x**2+ 0.25)**0.5-1.0
      end function

      function funcd(x)
      implicit none
      real(4):: funcd
      real(8) ::x
      funcd= x*(x**2 +0.25)**(-0.5)
      end function


问:
How can I connect my GCP bucket to my VM/DNS zone IP address?
I am trying to host a static website I created on GCP for a domain I bought on Namecheap. I have uploaded the static files into a cloud bucket, and set up a virtual machine and DNS zone, and used the VM's IP address to set up the DNS zone. I also have added the GCP name server's to my Namecheap domain. However, I get no response when I try to visit my site. What am I missing here?</p>


问:
How can I retrieve the top three amounts within a specific time interval?
I'm trying to retrieve the top 3 likes of this past week from the uploads table.  Ideally, I'm going to execute this query every Thursday at the end of day but for some reason, my query below is returning nothing but empty columns.

A screenshot's attached of the format of the timestamp

What am I doing wrong?

```<code>select `users`.`name`, `uploads`.`likes`, `uploads`.`url`, `uploads`.`UserID`, `users`.`email`, `uploads`.`timestamp`
from `uploads`
inner join `users`
on `users`.`UserID` = `uploads`.`UserID`
where `uploads`.`timeStamp` >= curdate() - INTERVAL DAYOFWEEK(curdate()) +6 DAY
and `uploads`.`timeStamp` < curdate() - INTERVAL DAYOFWEEK(curdate()) -1 DAY
order by `likes`
desc limit 3;
</code>```

Body:
I'm trying to retrieve the top 3 likes of this past week from the uploads table.  Ideally, I'm going to execute this query every Thursday at the end of day but for some reason, my query below is returning nothing but empty columns.

A screenshot's attached of the format of the timestamp

What am I doing wrong?

select `users`.`name`, `uploads`.`likes`, `uploads`.`url`, `uploads`.`UserID`, `users`.`email`, `uploads`.`timestamp`
from `uploads`
inner join `users`
on `users`.`UserID` = `uploads`.`UserID`
where `uploads`.`timeStamp` >= curdate() - INTERVAL DAYOFWEEK(curdate()) +6 DAY
and `uploads`.`timeStamp` < curdate() - INTERVAL DAYOFWEEK(curdate()) -1 DAY
order by `likes`
desc limit 3;


问:
ModelAssetPathNotFoundInStorage error when mlflow.sklearn.autolog() used to train within an Azure ML YAML Pipeline

YAML appears correct, there are no validation issues, and the pipeline can be seen in the Azure ML Studio GUI

I'm assuming the error is thrown by mlflow.sklearn.autolog() when the fit() method is called

Full stacktrace not available, the exception shown below is the full exception raised in Azue ML Studio GUI

I've commented out the function save_outputs() and the same error is raised, leading to my assumption regarding MLFlow SDK attempting to autolog the model

I haven't included the code below for the predict job in the pipeline, this step doesn't get to execute as the seep job in the pipeline fails first

Exception raised in Azure ML GUI

UserErrorException:
    Message: Model asset creation API failed with {'additional_properties': {'message': 'The request is invalid.', 'details': [{'code': 'ModelAssetPathNotFoundInStorage', 'message': 'No blobs found in storage at model asset path: azureml/HD_9b8798ab-c0cb-4c5d-8822-1411c01af249_0/model/'}], 'code': 'BadRequest', 'statusCode': 400}, 'error': <data_capability._restclient.model.models._models_py3.RootError object at 0x7f210407e310>, 'correlation': {'operation': '214b5eca2adce7f52fdba06fb5003437', 'request': '9515d04215048b81', 'RequestId': '9515d04215048b81'}, 'environment': '<REDACTED>', 'location': '<REDACTED>', 'time': datetime.datetime(2023, 1, 12, 23, 1, 27, 38782, tzinfo=<FixedOffset '+00:00'>), 'component_name': 'modelregistry'}
    InnerException None
    ErrorResponse
{
    "error": {
        "code": "UserError",
        "message": "Model asset creation API failed with {'additional_properties': {'message': 'The request is invalid.', 'details': [{'code': 'ModelAssetPathNotFoundInStorage', 'message': 'No blobs found in storage at model asset path: azureml/HD_9b8798ab-c0cb-4c5d-8822-1411c01af249_0/model/'}], 'code': 'BadRequest', 'statusCode': 400}, 'error': <data_capability._restclient.model.models._models_py3.RootError object at 0x7f210407e310>, 'correlation': {'operation': '214b5eca2adce7f52fdba06fb5003437', 'request': '9515d04215048b81', 'RequestId': '9515d04215048b81'}, 'environment': '<REDACTED>', 'location': '<REDACTED>', 'time': datetime.datetime(2023, 1, 12, 23, 1, 27, 38782, tzinfo=<FixedOffset '+00:00'>), 'component_name': 'modelregistry'}"
    }
} Marking the experiment as failed because initial child jobs have failed due to user error

```
<h4>CLI Command</h4>
<pre class="lang-bash prettyprint-override"><code>$ az ml job create --subscription <REDACTED> --resource-group <REDACTED> --workspace-name <REDACTED> --file /home/azureuser/cloudfiles/code/Users/<REDACTED>/repos/<REDACTED>/src/assets/pipeline_tune.yml --stream

RunId: quirky_bone_tf250gdlfg
Web View: https://ml.azure.com/runs/<REDACTED>?wsid=/subscriptions/<REDACTED>/resourcegroups/<REDACTED>/workspaces/<REDACTED>

Streaming logs/azureml/executionlogs.txt
========================================

[2023-01-12 22:58:42Z] Submitting 1 runs, first five are: <REDACTED>
[2023-01-12 23:03:46Z] Execution of experiment failed, update experiment status and cancel running nodes.

Execution Summary
=================
RunId: <REDACTED>
Web View: https://ml.azure.com/runs/<REDACTED>?wsid=/subscriptions/<REDACTED>/resourcegroups/<REDACTED>/workspaces/<REDACTED>
Exception :
 {
    "error": {
        "code": "UserError",
        "message": "Pipeline has some failed steps. See child run or execution logs for more details.",
        "message_format": "Pipeline has some failed steps. {0}",
        "message_parameters": {},
        "reference_code": "PipelineHasStepJobFailed",
        "details": []
    },
    "environment": "<REDACTED>",
    "location": "<REDACTED>",
    "time": "2023-01-12T23:03:45.982134Z",
    "component_name": ""
}
</code>```

Folder structure

src/
  assets/
    component_train.yml
    pipeline_tune.yml
  train.py
```
<h4><code>src/assets/pipeline_tune.yml</code></h4>
<pre class="lang-yaml prettyprint-override"><code># References
# ----------
# - How to create component pipelines
#   - https://learn.microsoft.com/en-us/azure/machine-learning/how-to-create-component-pipelines-cli
# - Pattern reference
#   - https://github.com/Azure/azureml-examples/tree/main/cli/jobs/pipelines-with-components/pipeline_with_hyperparameter_sweep
# - Pipeline schema
#   - https://learn.microsoft.com/en-us/azure/machine-learning/reference-yaml-job-pipeline
# - Sweep Job schema (hyperparameter tuning)
#   - https://learn.microsoft.com/en-us/azure/machine-learning/reference-yaml-job-sweep
# - Core Azure ML YAML syntax
#   - https://learn.microsoft.com/en-us/azure/machine-learning/reference-yaml-core-syntax#binding-inputs-and-outputs-between-steps-in-a-pipeline-job
$schema: https://azuremlschemas.azureedge.net/latest/pipelineJob.schema.json
type: pipeline

# -------------------------------------------------------------------
# Pipeline settings
# - Having inputs defined at the pipelione level, instead of the first
#  job, allows for parameterisation of the pipeline via both CLI/SDK
experiment_name: <REDACTED>
description: Tune hyperparemeters for training a scikit-learn SVM on the Iris dataset.
settings:
    default_compute: azureml:aml-compute-cpu
    default_datastore: azureml:workspaceblobstore
inputs:
  data:
    type: uri_file
    mode: ro_mount
    path: wasbs://datasets@azuremlexamples.blob.core.windows.net/iris.csv
outputs:
  predict:
    type: uri_folder
    mode: rw_mount
    path: azureml://datastores/workspaceblobstore/paths/<REDACTED>

# -------------------------------------------------------------------
# Jobs
jobs:

  # Tune job
  tune:
    type: sweep
    inputs:
      data: ${{parent.inputs.data}}
    outputs:
      model:
        type: mlflow_model
      test_data:
        type: uri_folder

    trial: ./component_train.yml

    search_space:
      c_value:
        type: uniform
        min_value: 0.5
        max_value: 0.9
      kernel:
        type: choice
        values:
          - rbf
          - linear
          - poly
      coef0:
        type: uniform
        min_value: 0.1
        max_value: 1

    sampling_algorithm: random

    objective:
      goal: minimize
      primary_metric: training_f1_score

    limits:
      max_total_trials: 20
      max_concurrent_trials: 10
      timeout: 7200

  # Score test data
  predict:
    type: command
    inputs:
      model: ${{parent.jobs.tune.outputs.model}}
      test_data: ${{parent.jobs.tune.outputs.test_data}}
    outputs:
      predictions: ${{parent.outputs.predict}}
    component: ./component_predict.yml
</code>```

src/assets/component_train.yml

# References
# ----------
# - How to create component pipelines
#   - https://learn.microsoft.com/en-us/azure/machine-learning/how-to-create-component-pipelines-cli
# - Command schema
#   - https://learn.microsoft.com/en-us/azure/machine-learning/reference-yaml-job-command
# - Core Azure ML YAML syntax
#   - https://learn.microsoft.com/en-us/azure/machine-learning/reference-yaml-core-syntax#binding-inputs-and-outputs-between-steps-in-a-pipeline-job
$schema: https://azuremlschemas.azureedge.net/latest/commandComponent.schema.json
type: command

# -------------------------------------------------------------------
# Command settings
version: 1
description: Training a scikit-learn SVM on the Iris dataset
environment: azureml:<REDACTED>:1
inputs:
  data:
    type: uri_file
  c_value:
    type: number
    default: 1.0
  kernel:
    type: string
    default: rbf
  coef0:
    type: number
    default: 0
outputs:
  model:
    type: mlflow_model
  test_data:
    type: uri_folder

# -------------------------------------------------------------------
# Job
code: ..
command: >-
  python train.py
  --data ${{inputs.data}}
  --C ${{inputs.c_value}}
  --kernel ${{inputs.kernel}}
  --coef0 ${{inputs.coef0}}
  --outputs_model ${{outputs.model}}
  --outputs_test_data ${{outputs.test_data}}

```
<h4>src/train.py</h4>
<pre class="lang-py prettyprint-override"><code>"""
Notes
-----
- Imports in this file must match the imports in `score.py` to allow
  pickle objects to be loaded correctly by `score.py`

References
----------
- Azure ML Environments and ScriptRunConfig for training
    - i.e How to execute this script against Azure ML compute cluster
    - https://docs.microsoft.com/en-us/azure/machine-learning/how-to-use-environments#use-environments-for-training
- Azure ML - Hyperparameter tuning
    - https://learn.microsoft.com/en-us/azure/machine-learning/how-to-tune-hyperparameters
- Azure ML - Hyperparameter tuning in Azure Machine Learning pipeline
    - https://learn.microsoft.com/en-us/azure/machine-learning/how-to-use-sweep-in-pipeline#how-to-do-hyperparameter-tuning-in-azure-machine-learning-pipeline
- Azure ML - Random, Grid, Bayesian sampling
    - https://learn.microsoft.com/en-us/azure/machine-learning/how-to-tune-hyperparameters#sampling-the-hyperparameter-space
- Azure ML - How to Train scikit-learn
    - https://learn.microsoft.com/en-us/azure/machine-learning/how-to-train-scikit-learn#prepare-the-training-script
- Azure ML - How to train Tesnorflow
    - https://learn.microsoft.com/en-us/azure/machine-learning/how-to-train-tensorflow
- Azure ML - How to train Keras
    - https://learn.microsoft.com/en-us/azure/machine-learning/how-to-train-keras
- Azure ML - How to train PyTorch
    - https://learn.microsoft.com/en-us/azure/machine-learning/how-to-train-pytorch
- Azure ML - Logging with MLFlow
    - https://learn.microsoft.com/en-us/azure/machine-learning/how-to-log-view-metrics?tabs=jobs#getting-started
- MLFlow - Autologging of frameworks
    - https://mlflow.org/docs/latest/tracking.html#automatic-logging
"""
import argparse

from distutils.dir_util import copy_tree
from pathlib import Path

import mlflow.sklearn
import pandas as pd

from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC

def get_data(data):
    """Get data and return train/test splits"""
    df = pd.read_csv(data)
    X = df.iloc[:, :-1]
    y = df.iloc[:, -1]
    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.2, random_state=0
    )

    # Return split data
    return X_train, X_test, y_train, y_test

def get_hyperparameters(**kwargs):
    """Set hyperparameters here

    References
    ----------
    - Understand how to pass hyperparameters to a sklearn pipeline
        - https://stackoverflow.com/questions/66388056/why-does-sklearn-pipeline-set-params-not-work
    """
    hyperparameters = {
        "estimator__C": kwargs.get("c_value"),
        "estimator__kernel": kwargs.get("kernel"),
        "estimator__coef0": kwargs.get("coef0"),
    }
    return hyperparameters

def save_outputs(model, model_dir, X_test, y_test, test_data_dir):
    """Save outputs of the training process"""
    # Save model
    local_dir = "model"
    mlflow.sklearn.save_model(model, local_dir)
    copy_tree(local_dir, model_dir)

    # Save test data
    X_test.to_csv(Path(test_data_dir) / "X_test.csv", index=False)
    y_test.to_csv(Path(test_data_dir) / "y_test.csv", index=False)

def train_model(hyperparameters, X_train, y_train):
    """Train the model with your chosen framework here"""
    # Model architecture
    model = Pipeline(
        steps=[
            ("scaler", StandardScaler()),
            ("estimator", SVC()),
        ]
    )

    # Set hyperparameters for training run
    model.set_params(**hyperparameters)

    # Train model
    model.fit(X_train, y_train)

    return model

def parse_args():
    """Parse args and hyperparameters"""
    parser = argparse.ArgumentParser()

    # Parse mandatory args
    parser.add_argument("data", help="Path to data for training", type=str)
    parser.add_argument("outputs_model", help="Name of the model", type=str)
    parser.add_argument("outputs_test_data", help="Path to data for testing", type=str)

    # Parse hyperparameter args
    parser.add_argument("c_value", help="Coeffiecient for the estimator", type=str)
    parser.add_argument("kernel", help="Kernel for the estimator", type=str)
    parser.add_argument("coef0", help="Coeffiecient for the estimator", type=str)

    # Get args
    args = parser.parse_args()

    return args

def main(**kwargs):
    """Train the model(s)

    Parameters
    ----------
    kwargs : dict
        Dictionary of all parsed arguments
    """
    # Logging
    # - Autologging works with (0.22.1 <= scikit-learn <= 1.1.3)
    # - See: https://www.mlflow.org/docs/latest/python_api/mlflow.sklearn.html#mlflow.sklearn.autolog
    mlflow.sklearn.autolog()

    # Setup
    X_train, X_test, y_train, y_test = get_data(kwargs.get("data"))
    hyperparameters = get_hyperparameters(**kwargs)

    # Train
    model = train_model(hyperparameters, X_train, y_train)

    # Output
    save_outputs(model, kwargs.get("outputs_model"), X_test, y_test, kwargs.get("outputs_test_data"))

if __name__ == "__main__":
    """Entrypoint for training the model(s)"""
    main(**vars(parse_args()))

</code>```

Body:
YAML appears correct, there are no validation issues, and the pipeline can be seen in the Azure ML Studio GUI

I'm assuming the error is thrown by mlflow.sklearn.autolog() when the fit() method is called

Full stacktrace not available, the exception shown below is the full exception raised in Azue ML Studio GUI

I've commented out the function save_outputs() and the same error is raised, leading to my assumption regarding MLFlow SDK attempting to autolog the model

I haven't included the code below for the predict job in the pipeline, this step doesn't get to execute as the seep job in the pipeline fails first

Exception raised in Azure ML GUI

UserErrorException:
    Message: Model asset creation API failed with {'additional_properties': {'message': 'The request is invalid.', 'details': [{'code': 'ModelAssetPathNotFoundInStorage', 'message': 'No blobs found in storage at model asset path: azureml/HD_9b8798ab-c0cb-4c5d-8822-1411c01af249_0/model/'}], 'code': 'BadRequest', 'statusCode': 400}, 'error': <data_capability._restclient.model.models._models_py3.RootError object at 0x7f210407e310>, 'correlation': {'operation': '214b5eca2adce7f52fdba06fb5003437', 'request': '9515d04215048b81', 'RequestId': '9515d04215048b81'}, 'environment': '<REDACTED>', 'location': '<REDACTED>', 'time': datetime.datetime(2023, 1, 12, 23, 1, 27, 38782, tzinfo=<FixedOffset '+00:00'>), 'component_name': 'modelregistry'}
    InnerException None
    ErrorResponse
{
    "error": {
        "code": "UserError",
        "message": "Model asset creation API failed with {'additional_properties': {'message': 'The request is invalid.', 'details': [{'code': 'ModelAssetPathNotFoundInStorage', 'message': 'No blobs found in storage at model asset path: azureml/HD_9b8798ab-c0cb-4c5d-8822-1411c01af249_0/model/'}], 'code': 'BadRequest', 'statusCode': 400}, 'error': <data_capability._restclient.model.models._models_py3.RootError object at 0x7f210407e310>, 'correlation': {'operation': '214b5eca2adce7f52fdba06fb5003437', 'request': '9515d04215048b81', 'RequestId': '9515d04215048b81'}, 'environment': '<REDACTED>', 'location': '<REDACTED>', 'time': datetime.datetime(2023, 1, 12, 23, 1, 27, 38782, tzinfo=<FixedOffset '+00:00'>), 'component_name': 'modelregistry'}"
    }
} Marking the experiment as failed because initial child jobs have failed due to user error

CLI Command

$ az ml job create --subscription <REDACTED> --resource-group <REDACTED> --workspace-name <REDACTED> --file /home/azureuser/cloudfiles/code/Users/<REDACTED>/repos/<REDACTED>/src/assets/pipeline_tune.yml --stream

RunId: quirky_bone_tf250gdlfg
Web View: https://ml.azure.com/runs/<REDACTED>?wsid=/subscriptions/<REDACTED>/resourcegroups/<REDACTED>/workspaces/<REDACTED>

Streaming logs/azureml/executionlogs.txt
========================================

[2023-01-12 22:58:42Z] Submitting 1 runs, first five are: <REDACTED>
[2023-01-12 23:03:46Z] Execution of experiment failed, update experiment status and cancel running nodes.

Execution Summary
=================
RunId: <REDACTED>
Web View: https://ml.azure.com/runs/<REDACTED>?wsid=/subscriptions/<REDACTED>/resourcegroups/<REDACTED>/workspaces/<REDACTED>
Exception :
 {
    "error": {
        "code": "UserError",
        "message": "Pipeline has some failed steps. See child run or execution logs for more details.",
        "message_format": "Pipeline has some failed steps. {0}",
        "message_parameters": {},
        "reference_code": "PipelineHasStepJobFailed",
        "details": []
    },
    "environment": "<REDACTED>",
    "location": "<REDACTED>",
    "time": "2023-01-12T23:03:45.982134Z",
    "component_name": ""
}

Folder structure

src/
  assets/
    component_train.yml
    pipeline_tune.yml
  train.py

src/assets/pipeline_tune.yml

# References
# ----------
# - How to create component pipelines
#   - https://learn.microsoft.com/en-us/azure/machine-learning/how-to-create-component-pipelines-cli
# - Pattern reference
#   - https://github.com/Azure/azureml-examples/tree/main/cli/jobs/pipelines-with-components/pipeline_with_hyperparameter_sweep
# - Pipeline schema
#   - https://learn.microsoft.com/en-us/azure/machine-learning/reference-yaml-job-pipeline
# - Sweep Job schema (hyperparameter tuning)
#   - https://learn.microsoft.com/en-us/azure/machine-learning/reference-yaml-job-sweep
# - Core Azure ML YAML syntax
#   - https://learn.microsoft.com/en-us/azure/machine-learning/reference-yaml-core-syntax#binding-inputs-and-outputs-between-steps-in-a-pipeline-job
$schema: https://azuremlschemas.azureedge.net/latest/pipelineJob.schema.json
type: pipeline

# -------------------------------------------------------------------
# Pipeline settings
# - Having inputs defined at the pipelione level, instead of the first
#  job, allows for parameterisation of the pipeline via both CLI/SDK
experiment_name: <REDACTED>
description: Tune hyperparemeters for training a scikit-learn SVM on the Iris dataset.
settings:
    default_compute: azureml:aml-compute-cpu
    default_datastore: azureml:workspaceblobstore
inputs:
  data:
    type: uri_file
    mode: ro_mount
    path: wasbs://datasets@azuremlexamples.blob.core.windows.net/iris.csv
outputs:
  predict:
    type: uri_folder
    mode: rw_mount
    path: azureml://datastores/workspaceblobstore/paths/<REDACTED>

# -------------------------------------------------------------------
# Jobs
jobs:

  # Tune job
  tune:
    type: sweep
    inputs:
      data: ${{parent.inputs.data}}
    outputs:
      model:
        type: mlflow_model
      test_data:
        type: uri_folder

    trial: ./component_train.yml

    search_space:
      c_value:
        type: uniform
        min_value: 0.5
        max_value: 0.9
      kernel:
        type: choice
        values:
          - rbf
          - linear
          - poly
      coef0:
        type: uniform
        min_value: 0.1
        max_value: 1

    sampling_algorithm: random

    objective:
      goal: minimize
      primary_metric: training_f1_score

    limits:
      max_total_trials: 20
      max_concurrent_trials: 10
      timeout: 7200

  # Score test data
  predict:
    type: command
    inputs:
      model: ${{parent.jobs.tune.outputs.model}}
      test_data: ${{parent.jobs.tune.outputs.test_data}}
    outputs:
      predictions: ${{parent.outputs.predict}}
    component: ./component_predict.yml

src/assets/component_train.yml

# References
# ----------
# - How to create component pipelines
#   - https://learn.microsoft.com/en-us/azure/machine-learning/how-to-create-component-pipelines-cli
# - Command schema
#   - https://learn.microsoft.com/en-us/azure/machine-learning/reference-yaml-job-command
# - Core Azure ML YAML syntax
#   - https://learn.microsoft.com/en-us/azure/machine-learning/reference-yaml-core-syntax#binding-inputs-and-outputs-between-steps-in-a-pipeline-job
$schema: https://azuremlschemas.azureedge.net/latest/commandComponent.schema.json
type: command

# -------------------------------------------------------------------
# Command settings
version: 1
description: Training a scikit-learn SVM on the Iris dataset
environment: azureml:<REDACTED>:1
inputs:
  data:
    type: uri_file
  c_value:
    type: number
    default: 1.0
  kernel:
    type: string
    default: rbf
  coef0:
    type: number
    default: 0
outputs:
  model:
    type: mlflow_model
  test_data:
    type: uri_folder

# -------------------------------------------------------------------
# Job
code: ..
command: >-
  python train.py
  --data ${{inputs.data}}
  --C ${{inputs.c_value}}
  --kernel ${{inputs.kernel}}
  --coef0 ${{inputs.coef0}}
  --outputs_model ${{outputs.model}}
  --outputs_test_data ${{outputs.test_data}}

src/train.py

"""
Notes
-----
- Imports in this file must match the imports in `score.py` to allow
  pickle objects to be loaded correctly by `score.py`

References
----------
- Azure ML Environments and ScriptRunConfig for training
    - i.e How to execute this script against Azure ML compute cluster
    - https://docs.microsoft.com/en-us/azure/machine-learning/how-to-use-environments#use-environments-for-training
- Azure ML - Hyperparameter tuning
    - https://learn.microsoft.com/en-us/azure/machine-learning/how-to-tune-hyperparameters
- Azure ML - Hyperparameter tuning in Azure Machine Learning pipeline
    - https://learn.microsoft.com/en-us/azure/machine-learning/how-to-use-sweep-in-pipeline#how-to-do-hyperparameter-tuning-in-azure-machine-learning-pipeline
- Azure ML - Random, Grid, Bayesian sampling
    - https://learn.microsoft.com/en-us/azure/machine-learning/how-to-tune-hyperparameters#sampling-the-hyperparameter-space
- Azure ML - How to Train scikit-learn
    - https://learn.microsoft.com/en-us/azure/machine-learning/how-to-train-scikit-learn#prepare-the-training-script
- Azure ML - How to train Tesnorflow
    - https://learn.microsoft.com/en-us/azure/machine-learning/how-to-train-tensorflow
- Azure ML - How to train Keras
    - https://learn.microsoft.com/en-us/azure/machine-learning/how-to-train-keras
- Azure ML - How to train PyTorch
    - https://learn.microsoft.com/en-us/azure/machine-learning/how-to-train-pytorch
- Azure ML - Logging with MLFlow
    - https://learn.microsoft.com/en-us/azure/machine-learning/how-to-log-view-metrics?tabs=jobs#getting-started
- MLFlow - Autologging of frameworks
    - https://mlflow.org/docs/latest/tracking.html#automatic-logging
"""
import argparse

from distutils.dir_util import copy_tree
from pathlib import Path

import mlflow.sklearn
import pandas as pd

from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC

def get_data(data):
    """Get data and return train/test splits"""
    df = pd.read_csv(data)
    X = df.iloc[:, :-1]
    y = df.iloc[:, -1]
    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.2, random_state=0
    )

    # Return split data
    return X_train, X_test, y_train, y_test

def get_hyperparameters(**kwargs):
    """Set hyperparameters here

    References
    ----------
    - Understand how to pass hyperparameters to a sklearn pipeline
        - https://stackoverflow.com/questions/66388056/why-does-sklearn-pipeline-set-params-not-work
    """
    hyperparameters = {
        "estimator__C": kwargs.get("c_value"),
        "estimator__kernel": kwargs.get("kernel"),
        "estimator__coef0": kwargs.get("coef0"),
    }
    return hyperparameters

def save_outputs(model, model_dir, X_test, y_test, test_data_dir):
    """Save outputs of the training process"""
    # Save model
    local_dir = "model"
    mlflow.sklearn.save_model(model, local_dir)
    copy_tree(local_dir, model_dir)

    # Save test data
    X_test.to_csv(Path(test_data_dir) / "X_test.csv", index=False)
    y_test.to_csv(Path(test_data_dir) / "y_test.csv", index=False)

def train_model(hyperparameters, X_train, y_train):
    """Train the model with your chosen framework here"""
    # Model architecture
    model = Pipeline(
        steps=[
            ("scaler", StandardScaler()),
            ("estimator", SVC()),
        ]
    )

    # Set hyperparameters for training run
    model.set_params(**hyperparameters)

    # Train model
    model.fit(X_train, y_train)

    return model

def parse_args():
    """Parse args and hyperparameters"""
    parser = argparse.ArgumentParser()

    # Parse mandatory args
    parser.add_argument("data", help="Path to data for training", type=str)
    parser.add_argument("outputs_model", help="Name of the model", type=str)
    parser.add_argument("outputs_test_data", help="Path to data for testing", type=str)

    # Parse hyperparameter args
    parser.add_argument("c_value", help="Coeffiecient for the estimator", type=str)
    parser.add_argument("kernel", help="Kernel for the estimator", type=str)
    parser.add_argument("coef0", help="Coeffiecient for the estimator", type=str)

    # Get args
    args = parser.parse_args()

    return args

def main(**kwargs):
    """Train the model(s)

    Parameters
    ----------
    kwargs : dict
        Dictionary of all parsed arguments
    """
    # Logging
    # - Autologging works with (0.22.1 <= scikit-learn <= 1.1.3)
    # - See: https://www.mlflow.org/docs/latest/python_api/mlflow.sklearn.html#mlflow.sklearn.autolog
    mlflow.sklearn.autolog()

    # Setup
    X_train, X_test, y_train, y_test = get_data(kwargs.get("data"))
    hyperparameters = get_hyperparameters(**kwargs)

    # Train
    model = train_model(hyperparameters, X_train, y_train)

    # Output
    save_outputs(model, kwargs.get("outputs_model"), X_test, y_test, kwargs.get("outputs_test_data"))

if __name__ == "__main__":
    """Entrypoint for training the model(s)"""
    main(**vars(parse_args()))


问:
How to manage Jetpack recomposition inside Fragment
I have integrated compose ui inside my fragment , but when i navigate and back again to the fragment that contain the compose function , the compose UI disappear.
Those images show my results :

Binding Compose View on fragment

```<code>binding.composeSeatsView.apply {
                setViewCompositionStrategy(
                    ViewCompositionStrategy.DisposeOnLifecycleDestroyed(viewLifecycleOwner)
                )
                setContent {
                    MaterialTheme {
                        SeatsUi()
                    }
                }
            }
</code>```

My Compose Func

```<code>@Composable
fun SeatsUi(){
     .......

    for (i in 0..44){
      //fill seats lists
    }

  Column(){

  //UI GridViews here
}
</code>```

I try to save UI compose shown or recompose when i back to it's fragment

Body:
I have integrated compose ui inside my fragment , but when i navigate and back again to the fragment that contain the compose function , the compose UI disappear.
Those images show my results :

Binding Compose View on fragment

binding.composeSeatsView.apply {
                setViewCompositionStrategy(
                    ViewCompositionStrategy.DisposeOnLifecycleDestroyed(viewLifecycleOwner)
                )
                setContent {
                    MaterialTheme {
                        SeatsUi()
                    }
                }
            }

My Compose Func

@Composable
fun SeatsUi(){
     .......

    for (i in 0..44){
      //fill seats lists
    }

  Column(){

  //UI GridViews here
}

I try to save UI compose shown or recompose when i back to it's fragment


问:
Nginx Docker stuck at "Configuration complete; ready for start up" after copying custom config
I'm trying to run a Docker image on a container, here's the Dockerfile:

```<code>FROM node:14-alpine AS builder
WORKDIR '/app'
COPY package.json .
RUN npm install
COPY . .
RUN npm run build

FROM nginxinc/nginx-unprivileged
COPY --from=builder /app/build /usr/share/nginx/html
COPY nginx.conf /etc/nginx/
</code>```

When I remove the line that copies the nginx.conf into the image, it works:

```<code>FROM node:14-alpine AS builder
WORKDIR '/app'
COPY package.json .
RUN npm install
COPY . .
RUN npm run build

FROM nginxinc/nginx-unprivileged
COPY --from=builder /app/build /usr/share/nginx/html
</code>```

I've already used the nginx default config and the problem persists, so the problem isn't my config file I think.

```<code>pid /tmp/nginx.pid;

events {}

http {
    server {
        location /api {
            proxy_set_header Host $host;
            proxy_set_header Cookie $http_cookie;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_http_version 1.1;

            proxy_pass http://#removed_for_privacy#;
        }

        location /socket.io/ {
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";
            proxy_set_header Host $host;
            proxy_pass #removed_for_privacy#;
        }

        location / {
            index  index.html;
            try_files $uri $uri/ /index.html;
        }
    }
}
</code>```

Nginx config file seems ok:

```<code>nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
</code>```

Any clues on this?

Body:
I'm trying to run a Docker image on a container, here's the Dockerfile:

FROM node:14-alpine AS builder
WORKDIR '/app'
COPY package.json .
RUN npm install
COPY . .
RUN npm run build

FROM nginxinc/nginx-unprivileged
COPY --from=builder /app/build /usr/share/nginx/html
COPY nginx.conf /etc/nginx/

When I remove the line that copies the nginx.conf into the image, it works:

FROM node:14-alpine AS builder
WORKDIR '/app'
COPY package.json .
RUN npm install
COPY . .
RUN npm run build

FROM nginxinc/nginx-unprivileged
COPY --from=builder /app/build /usr/share/nginx/html

I've already used the nginx default config and the problem persists, so the problem isn't my config file I think.

pid /tmp/nginx.pid;

events {}

http {
    server {
        location /api {
            proxy_set_header Host $host;
            proxy_set_header Cookie $http_cookie;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_http_version 1.1;

            proxy_pass http://#removed_for_privacy#;
        }

        location /socket.io/ {
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";
            proxy_set_header Host $host;
            proxy_pass #removed_for_privacy#;
        }

        location / {
            index  index.html;
            try_files $uri $uri/ /index.html;
        }
    }
}

Nginx config file seems ok:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Any clues on this?


问:
Get an email or text message when R stops working
I am running an infinite loop in R processing certain type of data that is collected in real time from the web. I know there are certain packages that can interface with email and text messaging to send alerts when an error occurred in R. However, I wonder if there is a way to know if R stopped altogether (say the electricity went out, and R cannot send a message).

I am planning to implement this functionality by having R send a message each loop to Discord via webhook, like shown here. and then having Discord monitor the time lapse, such that if more than one minute has lapse since the last email was received from R, it will trigger a message or text message.

Is there such a functionality in R. Given this fast moving wave of connectivity, I think this functionality should be of much use, but I have not yet fund much about it.


问:
generate different results using three columns
I'm trying to create an invoice based on Excel data (attached). I required a MySQL query that can generate different results using three columns. Functional requirement is as follows:

The Excel file has a column called KM (Kilometer), city and total_amount

If a person travel DXB (Dubai) the rates from total_amount column would be like this

```<code>1-3 Kms the rate is 9
4-5 Kms the rate is 11
6-7 Kms the rate is 13
</code>```

For AUH (Abu Dhabi) different rates but same process. So the query will count all the entries of 1-3, 4-5, 6-7 and vice-versa (see sample invoice).

So far, I wrote separate queries for Dubai. See below:

```<code>SELECT city, count(KM), sum(total_amount), total_amount*count(KM), total_amount*count(KM), round(total_amount*count(KM)*0.05,2), total_amount*count(KM)*0.05+(total_amount*count(KM)) FROM perorder where city like '%XB' and KM between 1 and 3 GROUP BY CITY

SELECT city, count(KM), sum(total_amount), total_amount*count(KM), total_amount*count(KM), round(total_amount*count(KM)*0.05,2), total_amount*count(KM)*0.05+(total_amount*count(KM)) FROM perorder where city like '%XB' and KM between 4 and 5 GROUP BY CITY

SELECT city, count(KM), sum(total_amount), total_amount*count(KM), total_amount*count(KM), round(total_amount*count(KM)*0.05,2), total_amount*count(KM)*0.05+(total_amount*count(KM)) FROM perorder where city like '%XB' and KM between 6 and 7 GROUP BY CITY
</code>```

I will repeat almost the same queries for Abu Dhabi, but is there a way to generate the attached invoice result by writing a single MySQL query?

Sample data in the Database

Required invoice result

Body:
I'm trying to create an invoice based on Excel data (attached). I required a MySQL query that can generate different results using three columns. Functional requirement is as follows:

The Excel file has a column called KM (Kilometer), city and total_amount

If a person travel DXB (Dubai) the rates from total_amount column would be like this

1-3 Kms the rate is 9
4-5 Kms the rate is 11
6-7 Kms the rate is 13

For AUH (Abu Dhabi) different rates but same process. So the query will count all the entries of 1-3, 4-5, 6-7 and vice-versa (see sample invoice).

So far, I wrote separate queries for Dubai. See below:

SELECT city, count(KM), sum(total_amount), total_amount*count(KM), total_amount*count(KM), round(total_amount*count(KM)*0.05,2), total_amount*count(KM)*0.05+(total_amount*count(KM)) FROM perorder where city like '%XB' and KM between 1 and 3 GROUP BY CITY

SELECT city, count(KM), sum(total_amount), total_amount*count(KM), total_amount*count(KM), round(total_amount*count(KM)*0.05,2), total_amount*count(KM)*0.05+(total_amount*count(KM)) FROM perorder where city like '%XB' and KM between 4 and 5 GROUP BY CITY

SELECT city, count(KM), sum(total_amount), total_amount*count(KM), total_amount*count(KM), round(total_amount*count(KM)*0.05,2), total_amount*count(KM)*0.05+(total_amount*count(KM)) FROM perorder where city like '%XB' and KM between 6 and 7 GROUP BY CITY

I will repeat almost the same queries for Abu Dhabi, but is there a way to generate the attached invoice result by writing a single MySQL query?

Sample data in the Database

Required invoice result


问:
Is there an alternative to the applyInPandas() method with accepts native PySpark Dataframes, instead of Pandas Dataframes?
I have a hybdrid PySpark-Pandas code which does a custom Pandas operation on a Pyspark dataframe:

```<code>a_values.groupby("dkey").applyInPandas(
        lambda psx: some_pandas_function(
            plan_req_columns, psx[req_columns + ["dkey"]], another_df_orc_location, **params_dict
        )
</code>```

Here a_values is a PySpark dataframe, and some_pandas_function() accepts a Pandas dataframe in parameter psx. I want to replace some_pandas_function() with a function that accepts a PySpark dataframe as input. Is there a way of doing this?

Body:
I have a hybdrid PySpark-Pandas code which does a custom Pandas operation on a Pyspark dataframe:

a_values.groupby("dkey").applyInPandas(
        lambda psx: some_pandas_function(
            plan_req_columns, psx[req_columns + ["dkey"]], another_df_orc_location, **params_dict
        )

Here a_values is a PySpark dataframe, and some_pandas_function() accepts a Pandas dataframe in parameter psx. I want to replace some_pandas_function() with a function that accepts a PySpark dataframe as input. Is there a way of doing this?


问:
How to get the good url with the api invision board power to doynload a file via curl
I block with the API Download/Files with IPB.

I have a json like that

```<code>{
    "page": 1,
    "perPage": 300,
    "totalResults": 180,
    "totalPages": 1,
    "results": [
        {
            "id": 2,
            "title": "my title file",
            "downloads": 8,
            "comments": 0,
            "reviews": 0,
            "views": 1737,
            "prefix": "shopping",
            "url": "https:\/\/www.example.com\//files\/file\/2-myfile\/",
            "hasPendingVersion": false
        }
    ]
}
</code>```

via a file_get_contents($file_url); // in this case url above I want to download the file. but it does not work.

If I go on the site I have my url like that : https://www.example.com/files/file/2-myfile/?do=download

the name of the file is : 2-myfile.zip
I do not find inside the json the zip

What is the good process to download via a file_get_contents in php.

invision documentation : https://invisioncommunity.com/developers/rest-api?endpoint=downloads/files/GETitem

My endpoint is like that : $curl = curl_init( $this->Url . 'api/downloads/files?id=' . $id . '&perPage=300');

Thank you

Body:
I block with the API Download/Files with IPB.

I have a json like that

{
    "page": 1,
    "perPage": 300,
    "totalResults": 180,
    "totalPages": 1,
    "results": [
        {
            "id": 2,
            "title": "my title file",
            "downloads": 8,
            "comments": 0,
            "reviews": 0,
            "views": 1737,
            "prefix": "shopping",
            "url": "https:\/\/www.example.com\//files\/file\/2-myfile\/",
            "hasPendingVersion": false
        }
    ]
}

via a file_get_contents($file_url); // in this case url above I want to download the file. but it does not work.

If I go on the site I have my url like that : https://www.example.com/files/file/2-myfile/?do=download

the name of the file is : 2-myfile.zip
I do not find inside the json the zip

What is the good process to download via a file_get_contents in php.

invision documentation : https://invisioncommunity.com/developers/rest-api?endpoint=downloads/files/GETitem

My endpoint is like that : $curl = curl_init( $this->Url . 'api/downloads/files?id=' . $id . '&perPage=300');

Thank you


问:
I want to push my branch in git in a other branch in remote . I tried git push origin@ .it hasn't worked for me.Could anyone help me?
I want to push my branch in git in a other branch in remote . I tried git push origin@ .it hasn't worked for me.Could anyone help me?

git push origin @ i expect to a push in a remote branch


问:
Run Tkinter and TikTokLiveClient in the same time
Can you please tell me, if there exists a solution to run a Tkinter Gui and a TikTok live Client in the same time, because when I run the program only first of them starts.</p>
```<code>import tkinter as tk
from TikTokLive import TikTokLiveClient

root = tk.Tk()
client = TikTokLiveClient(unique_id="<user_name>")

@client.on("like")
async def on_like(event):
    print(f"{event.user.nickname} liked the video")

if __name__ == "__main__":
    root.mainloop()
    client.run()
</code>```

Body:
Can you please tell me, if there exists a solution to run a Tkinter Gui and a TikTok live Client in the same time, because when I run the program only first of them starts.

import tkinter as tk
from TikTokLive import TikTokLiveClient

root = tk.Tk()
client = TikTokLiveClient(unique_id="<user_name>")

@client.on("like")
async def on_like(event):
    print(f"{event.user.nickname} liked the video")

if __name__ == "__main__":
    root.mainloop()
    client.run()


问:
Loop call in Postman
I need some help with Postman. I have a post method call where in the call I pass an account through the path and in the body I insert the id. However, with my method, I can only do the account, and I have more than 30,000 accounts to perform this procedure.

Given the situation above, I would like to know how I can resolve this situation, at first I thought of leaving an account variable in the call path and another for the id, and with that performing a loop, but I don't know how to perform this routine, especially from the loop. I don't know if it would be through the JS or through Postman itself.

I turned the account's path into a variable, but I didn't get past that part. I would like to loop passing a file with the id and the account and make the call run until the end of the file.

Title: Loop call in Postman


问:
Backspace does not work in neovim with that moving setup
I have mapped C-h for moving left in insert mode, but when i try to delete previous letter with backspace, it not works. I was looking around and BS is the same that C-h, someone know how to remap BS to delete previous letters and make i still use C-h for moving?

I tried remapping but no success