Server comunication fail on same IP block

Question: Good morning,
I own 7 servers in the same DC.
Of these, 4 of them are unable to communicate with each other: each of these 4 machines does not communicate with the other 3 via SSH and there is no response to ping ("Destination Host Unreachable").
These 4 servers are all identical, purchased on the same day.
Communication between these 4 machines and the other 3 machines that I own works regularly (ping, ssh, etc.).
Of course, there are no firewall blocks or anything else because, as I said, communication with other machines works and I tested on just-installed machines.
IMPORTANT: all 4 servers belong to the SAME IP block xx.xx.xx.* (example 126.96.36.199, 126.96.36.199, 126.96.36.199, etc.)
Some suggestion, please?
root@myserver [~] # ip link show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT qlen 1000
    link/ether 00:22:4d:7a:b7:c0 brd ff:ff:ff:ff:ff:ff

root@myserver [~] # ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:22:4d:7a:b7:c0 brd ff:ff:ff:ff:ff:ff
    inet 838.309.278.48/24 brd 838.309.278.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 2001:41d0:8:7830::1/128 scope global
       valid_lft forever preferred_lft forever
    inet6 fe80::222:4dff:fe7a:b7c0/64 scope link
       valid_lft forever preferred_lft forever

root@myserver [~] # ip route show
default via 838.309.278.254 dev eth0
838.309.278.0/24 dev eth0 proto kernel scope link src 838.309.278.48

iptables-save -c
root@myserver [~] # iptables-save -c
# Generated by iptables-save v1.4.21 on Tue Nov 21 08:53:14 2017
*mangle
:PREROUTING ACCEPT [697331:228627666]
:INPUT ACCEPT [697331:228627666]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [654668:238129552]
:POSTROUTING ACCEPT [627123:232560477]
COMMIT
# Completed on Tue Nov 21 08:53:14 2017
# Generated by iptables-save v1.4.21 on Tue Nov 21 08:53:14 2017
*nat
:PREROUTING ACCEPT [77156:3042292]
:INPUT ACCEPT [72516:2727270]
:OUTPUT ACCEPT [41719:6614113]
:POSTROUTING ACCEPT [14174:1045038]
COMMIT
# Completed on Tue Nov 21 08:53:14 2017
# Generated by iptables-save v1.4.21 on Tue Nov 21 08:53:14 2017
*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT DROP [0:0]
:ALLOWIN - [0:0]
:ALLOWOUT - [0:0]
:DENYIN - [0:0]
:DENYOUT - [0:0]
:INVALID - [0:0]
:INVDROP - [0:0]
:LOCALINPUT - [0:0]
:LOCALOUTPUT - [0:0]
:LOGDROPIN - [0:0]
:LOGDROPOUT - [0:0]
[0:0] -A INPUT -s 18.104.22.168/32 ! -i lo -p tcp -m tcp --dport 53 -j ACCEPT
[0:0] -A INPUT -s 126.96.36.199/32 ! -i lo -p udp -m udp --dport 53 -j ACCEPT
[0:0] -A INPUT -s 22.214.171.124/32 ! -i lo -p tcp -m tcp --sport 53 -j ACCEPT
[954:68688] -A INPUT -s 126.96.36.199/32 ! -i lo -p udp -m udp --sport 53 -j ACCEPT
[0:0] -A INPUT -s 184.108.40.206/32 ! -i lo -p tcp -m tcp --dport 53 -j ACCEPT
[0:0] -A INPUT -s 126.96.36.199/32 ! -i lo -p udp -m udp --dport 53 -j ACCEPT
[0:0] -A INPUT -s 22.214.171.124/32 ! -i lo -p tcp -m tcp --sport 53 -j ACCEPT
[7982:866312] -A INPUT -s 188.8.131.52/32 ! -i lo -p udp -m udp --sport 53 -j ACCEPT
[660785:221345203] -A INPUT ! -i lo -j LOCALINPUT
[27610:6347463] -A INPUT -i lo -j ACCEPT
[122886:73580584] -A INPUT ! -i lo -p tcp -j INVALID
[119005:73544720] -A INPUT ! -i lo -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
[0:0] -A INPUT ! -i lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 20 -j ACCEPT
[25:1216] -A INPUT ! -i lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 21 -j ACCEPT
[210:9016] -A INPUT ! -i lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 22 -j ACCEPT
[4098:231644] -A INPUT ! -i lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 25 -j ACCEPT
[7:344] -A INPUT ! -i lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 53 -j ACCEPT
[216:11384] -A INPUT ! -i lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 80 -j ACCEPT
[17:820] -A INPUT ! -i lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 110 -j ACCEPT
[17:848] -A INPUT ! -i lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 143 -j ACCEPT
[49:2176] -A INPUT ! -i lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 443 -j ACCEPT
[10:464] -A INPUT ! -i lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 465 -j ACCEPT
[21:1128] -A INPUT ! -i lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 587 -j ACCEPT
[9:400] -A INPUT ! -i lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 993 -j ACCEPT
[4:180] -A INPUT ! -i lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 995 -j ACCEPT
[42:2172] -A INPUT ! -i lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 2030 -j ACCEPT
[0:0] -A INPUT ! -i lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 2031 -j ACCEPT
[0:0] -A INPUT ! -i lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 2082 -j ACCEPT
[0:0] -A INPUT ! -i lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 2083 -j ACCEPT
[4:220] -A INPUT ! -i lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 2086 -j ACCEPT
[11:660] -A INPUT ! -i lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 2087 -j ACCEPT
[0:0] -A INPUT ! -i lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 2095 -j ACCEPT
[0:0] -A INPUT ! -i lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 2096 -j ACCEPT
[0:0] -A INPUT ! -i lo -p udp -m conntrack --ctstate NEW -m udp --dport 20 -j ACCEPT
[0:0] -A INPUT ! -i lo -p udp -m conntrack --ctstate NEW -m udp --dport 21 -j ACCEPT
[11:717] -A INPUT ! -i lo -p udp -m conntrack --ctstate NEW -m udp --dport 53 -j ACCEPT
[61724:2149570] -A INPUT ! -i lo -p icmp -m icmp --icmp-type 8 -m limit --limit 1/sec -j ACCEPT
[2:96] -A INPUT ! -i lo -p icmp -m icmp --icmp-type 0 -m limit --limit 1/sec -j ACCEPT
[5:320] -A INPUT ! -i lo -p icmp -m icmp --icmp-type 11 -j ACCEPT
[24:2583] -A INPUT ! -i lo -p icmp -m icmp --icmp-type 3 -j ACCEPT
[4627:313990] -A INPUT ! -i lo -j LOGDROPIN
[0:0] -A OUTPUT -d 220.127.116.11/32 ! -o lo -p tcp -m tcp --dport 53 -j ACCEPT
[954:68688] -A OUTPUT -d 188.8.131.52/32 ! -o lo -p udp -m udp --dport 53 -j ACCEPT
[0:0] -A OUTPUT -d 188.8.131.52/32 ! -o lo -p tcp -m tcp --sport 53 -j ACCEPT
[0:0] -A OUTPUT -d 184.108.40.206/32 ! -o lo -p udp -m udp --sport 53 -j ACCEPT
[0:0] -A OUTPUT -d 22.214.171.124/32 ! -o lo -p tcp -m tcp --dport 53 -j ACCEPT
[7982:581323] -A OUTPUT -d 22.214.171.124/32 ! -o lo -p udp -m udp --dport 53 -j ACCEPT
[0:0] -A OUTPUT -d 22.214.171.124/32 ! -o lo -p tcp -m tcp --sport 53 -j ACCEPT
[0:0] -A OUTPUT -d 18.104.22.168/32 ! -o lo -p udp -m udp --sport 53 -j ACCEPT
[618122:231132078] -A OUTPUT ! -o lo -j LOCALOUTPUT
[0:0] -A OUTPUT ! -o lo -p tcp -m tcp --dport 53 -j ACCEPT
[9:673] -A OUTPUT ! -o lo -p udp -m udp --dport 53 -j ACCEPT
[20:2011] -A OUTPUT ! -o lo -p tcp -m tcp --sport 53 -j ACCEPT
[11:2510] -A OUTPUT ! -o lo -p udp -m udp --sport 53 -j ACCEPT
[27610:6347463] -A OUTPUT -o lo -j ACCEPT
[132012:58252558] -A OUTPUT ! -o lo -p tcp -j INVALID
[193611:60395750] -A OUTPUT ! -o lo -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
[0:0] -A OUTPUT ! -o lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 20 -j ACCEPT
[0:0] -A OUTPUT ! -o lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 21 -j ACCEPT
[0:0] -A OUTPUT ! -o lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 22 -j ACCEPT
[4:240] -A OUTPUT ! -o lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 25 -j ACCEPT
[0:0] -A OUTPUT ! -o lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 53 -j ACCEPT
[130:7800] -A OUTPUT ! -o lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 80 -j ACCEPT
[0:0] -A OUTPUT ! -o lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 110 -j ACCEPT
[0:0] -A OUTPUT ! -o lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 113 -j ACCEPT
[27:1620] -A OUTPUT ! -o lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 443 -j ACCEPT
[0:0] -A OUTPUT ! -o lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 2030 -j ACCEPT
[0:0] -A OUTPUT ! -o lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 2031 -j ACCEPT
[0:0] -A OUTPUT ! -o lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 2082 -j ACCEPT
[0:0] -A OUTPUT ! -o lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 2083 -j ACCEPT
[0:0] -A OUTPUT ! -o lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 2086 -j ACCEPT
[0:0] -A OUTPUT ! -o lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 2087 -j ACCEPT
[0:0] -A OUTPUT ! -o lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 2095 -j ACCEPT
[0:0] -A OUTPUT ! -o lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 2096 -j ACCEPT
[0:0] -A OUTPUT ! -o lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 587 -j ACCEPT
[0:0] -A OUTPUT ! -o lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 993 -j ACCEPT
[0:0] -A OUTPUT ! -o lo -p tcp -m conntrack --ctstate NEW -m tcp --dport 995 -j ACCEPT
[0:0] -A OUTPUT ! -o lo -p udp -m conntrack --ctstate NEW -m udp --dport 20 -j ACCEPT
[0:0] -A OUTPUT ! -o lo -p udp -m conntrack --ctstate NEW -m udp --dport 21 -j ACCEPT
[0:0] -A OUTPUT ! -o lo -p udp -m conntrack --ctstate NEW -m udp --dport 53 -j ACCEPT
[0:0] -A OUTPUT ! -o lo -p udp -m conntrack --ctstate NEW -m udp --dport 113 -j ACCEPT
[5292:402192] -A OUTPUT ! -o lo -p udp -m conntrack --ctstate NEW -m udp --dport 123 -j ACCEPT
[0:0] -A OUTPUT ! -o lo -p icmp -m icmp --icmp-type 0 -j ACCEPT
[38:3192] -A OUTPUT ! -o lo -p icmp -m icmp --icmp-type 8 -j ACCEPT
[0:0] -A OUTPUT ! -o lo -p icmp -m icmp --icmp-type 11 -j ACCEPT
[0:0] -A OUTPUT ! -o lo -p icmp -m icmp --icmp-type 3 -j ACCEPT
[27545:5569075] -A OUTPUT ! -o lo -j LOGDROPOUT
[260880:81590254] -A ALLOWIN -s 126.96.36.199/32 ! -i lo -j ACCEPT
[222056:70086439] -A ALLOWOUT -d 184.108.40.206/32 ! -o lo -j ACCEPT
[0:0] -A DENYIN -s 126.96.36.199/32 ! -i lo -j DROP
[0:0] -A DENYOUT -d 22.214.171.124/32 ! -o lo -j LOGDROPOUT
[348:15236] -A INVALID -m conntrack --ctstate INVALID -j INVDROP
[0:0] -A INVALID -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -j INVDROP
[0:0] -A INVALID -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,SYN,RST,PSH,ACK,URG -j INVDROP
[0:0] -A INVALID -p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -j INVDROP
[0:0] -A INVALID -p tcp -m tcp --tcp-flags SYN,RST SYN,RST -j INVDROP
[0:0] -A INVALID -p tcp -m tcp --tcp-flags FIN,RST FIN,RST -j INVDROP
[0:0] -A INVALID -p tcp -m tcp --tcp-flags FIN,ACK FIN -j INVDROP
[0:0] -A INVALID -p tcp -m tcp --tcp-flags PSH,ACK PSH -j INVDROP
[0:0] -A INVALID -p tcp -m tcp --tcp-flags ACK,URG URG -j INVDROP
[13:1032] -A INVALID -p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -m conntrack --ctstate NEW -j INVDROP
[361:16268] -A INVDROP -j DROP
[660785:221345203] -A LOCALINPUT ! -i lo -j ALLOWIN
[190499:76290936] -A LOCALINPUT ! -i lo -j DENYIN
[618122:231132078] -A LOCALOUTPUT ! -o lo -j ALLOWOUT
[226687:66385063] -A LOCALOUTPUT ! -o lo -j DENYOUT
[1676:68728] -A LOGDROPIN -p tcp -m tcp --dport 23 -j DROP
[0:0] -A LOGDROPIN -p udp -m udp --dport 23 -j DROP
[0:0] -A LOGDROPIN -p tcp -m tcp --dport 67 -j DROP
[0:0] -A LOGDROPIN -p udp -m udp --dport 67 -j DROP
[0:0] -A LOGDROPIN -p tcp -m tcp --dport 68 -j DROP
[90:31050] -A LOGDROPIN -p udp -m udp --dport 68 -j DROP
[20:960] -A LOGDROPIN -p tcp -m tcp --dport 111 -j DROP
[4:272] -A LOGDROPIN -p udp -m udp --dport 111 -j DROP
[0:0] -A LOGDROPIN -p tcp -m tcp --dport 113 -j DROP
[0:0] -A LOGDROPIN -p udp -m udp --dport 113 -j DROP
[5:224] -A LOGDROPIN -p tcp -m tcp --dport 135:139 -j DROP
[10:780] -A LOGDROPIN -p udp -m udp --dport 135:139 -j DROP
[395:20388] -A LOGDROPIN -p tcp -m tcp --dport 445 -j DROP
[0:0] -A LOGDROPIN -p udp -m udp --dport 445 -j DROP
[0:0] -A LOGDROPIN -p tcp -m tcp --dport 500 -j DROP
[8:3424] -A LOGDROPIN -p udp -m udp --dport 500 -j DROP
[1:40] -A LOGDROPIN -p tcp -m tcp --dport 513 -j DROP
[0:0] -A LOGDROPIN -p udp -m udp --dport 513 -j DROP
[1:40] -A LOGDROPIN -p tcp -m tcp --dport 520 -j DROP
[2:104] -A LOGDROPIN -p udp -m udp --dport 520 -j DROP
[2022:84660] -A LOGDROPIN -p tcp -m limit --limit 30/min -j LOG --log-prefix "Firewall: *TCP_IN Blocked* "
[376:101298] -A LOGDROPIN -p udp -m limit --limit 30/min -j LOG --log-prefix "Firewall: *UDP_IN Blocked* "
[0:0] -A LOGDROPIN -p icmp -m limit --limit 30/min -j LOG --log-prefix "Firewall: *ICMP_IN Blocked* "
[2415:187980] -A LOGDROPIN -j DROP
[2:120] -A LOGDROPOUT -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -m limit --limit 30/min -j LOG --log-prefix "Firewall: *TCP_OUT Blocked* " --log-uid
[18149:3725921] -A LOGDROPOUT -p udp -m limit --limit 30/min -j LOG --log-prefix "Firewall: *UDP_OUT Blocked* " --log-uid
[0:0] -A LOGDROPOUT -p icmp -m limit --limit 30/min -j LOG --log-prefix "Firewall: *ICMP_OUT Blocked* " --log-uid
[27545:5569075] -A LOGDROPOUT -j REJECT --reject-with icmp-port-unreachable
COMMIT
# Completed on Tue Nov 21 08:53:14 2017

ip neigh show
root@myserver [~] # ip neigh show
fe80::da24:bdff:fe90:740 dev eth0 lladdr d8:24:bd:90:07:40 router STALE
2001:41d0:8:78ff:ff:ff:ff:ff dev eth0 lladdr 00:05:73:a0:00:00 router STALE
838.309.278.51 dev eth0  FAILED
838.309.278.64 dev eth0  FAILED
838.309.278.57 dev eth0  FAILED
838.309.278.250 dev eth0 lladdr 00:07:b4:00:00:01 STALE
838.309.278.254 dev eth0 lladdr 00:07:b4:00:00:01 REACHABLE

arptables & ebtables
root@myserver [~] # arptables-save
*filter
:INPUT ACCEPT
:OUTPUT ACCEPT
:FORWARD ACCEPT

root@myserver [~] # ebtables-save
# Generated by ebtables-save v1.0 on Tue Nov 21 10:59:44 CET 2017

Comment: Adding the result of these commands (for at least one if all are similar) in the question would certainly help: `ip link show` ,  `ip addr show` , `ip route show` , `iptables-save -c`
Comment: The `state UP` result from the output of `ip link show` show that at least a cable is plugged in and the switch port isn't shut. That's good.
Comment: And whatever you add to your question, do not redact it.  For this kind of question, the devil tends to be in the details, so we need to see them.
Comment: Good morning here the results of the suggested commands. I can also report result of "iptables-save -c" if needed, I skipped because quite long:
Comment: One last "silly" question. Do you have any rules visible beside the 3 builtins with the commands `arptables-save` or `ebtables-save` ? I really think it's PVLAN but just to be sure... Oh and are .51 .64 .57 the 3 other servers ? Also what's the role of .250 (which appears to be working) ?
Comment: Sorry, I don't know "what's the role of .250". Yes, the listed IP are of the other three servers! I updated the question with arptables and ebtables
Answer: According to the result of ip neigh show you can't reach the three other servers (IPs ending in .51 .57 .64) at the link layer level. This really looks like port isolation aka PVLAN.
Your Data Center doesn't want some of its client/customers managing to access some of its other clients/customers' servers just because they are in the same LAN, for liability reasons. So it's using this isolation method for simplicity. The result is the same as with "Client Isolation" on Wifi.
What you should do is contact the Data Center, prove you're the same owner for the 4 servers, and ask them some exception to the isolation rules so they can talk together. In the wikipedia link from above, that would be to have them put in the same "Community" secondary VLAN instead of simply "Isolated".
Of course there's no way to completely prove this is what happens beside asking them, but everything fits.


jenkins cant pull from git repository using windows batch command

Question: when i build my jenkins project i want to pull it first from my git repository so the code is up to date, i can see git status and git --version normally, but when it come to git pull the console output stuck on loading like this:

When i try the exact same command and same dir in command prompt i can pull successfully in less than 2 seconds

is there anything that make different between jenkins command and cmd command?
i use windows xp with ssh to authenticating with git repository.
Comment: Are you the same user (anonymous) in the console as well as in the Jenkins job?
Comment: no, how to change that anonymous in jenkins? i can only change the name but not the userid
Comment: Actually, 'anonymous' just means you are not login. What I meant is: is Jenkins run with the same user as in your console? Could you add a build step with "`set`" in it, in order to print the user environment variable? `ssh` looks for the keys in `%HOME%\.ssh`. Is `HOME` set in your console? Is it set in the context of the Jenkins job? (hence the request for a `set` in a build step in the Jenkins job).
Comment: isn't the way to print environment variable is by using `echo %PATH%`? i set it on the environment variable but i don't know about _set in the context of the Jenkins job_
Answer: If ssh is used, it is crucial to make sure HOME is set when the job is executed: ssh will look for id_rsa and id_rsa.pub (private and public keys) under %HOME%\.ssh.
In doubt, one can use the EnvInject plugin which will add environment variables for a given job.


Update statement that will update the "Active" field of an employee if the corresponding department is inactive

Question: I want to update my employee's Employee_Type: if the Department_Type is Inactive, then the Employee_Type must be updated to also be Inactive.
This is my code I don't know why isn't working. There is primary key in tblEmployees which is EmployeeID, and there is a foreign key in tblDepartment which also EmployeeID:
UPDATE tblEmployees
SET Employee_Type = t2.Department_Type
FROM dbo.tblEmployees AS t1
RIGHT JOIN dbo.tblDepartment AS t2 ON t1.Employee_Type = t2.Department_Type
WHERE t2.EmployeeID = '6';

The result is:
(1 row(s) affected)

But nothing happens actually.
Answer: Your written logic implies the following query:
UPDATE tblEmployees
SET Employee_Type = t2.Department_Type
FROM dbo.tblEmployees AS t1
RIGHT JOIN dbo.tblDepartment AS t2
    ON t1.Employee_Type = t2.Department_Type
WHERE
    t2.Department_Type = 'inactive'
 -- t2.EmployeeID = '6';    -- not sure about this requirement

I don't know why you were targeting a particular employee in the WHERE clause, but this is inconsistent with trying updated all employee types to inactive whose departments are also inactive.
Answer: Try this
update t1
set t1.Employee_Type = t2.Department_Type
from dbo.tblEmployees as t1
right join dbo.tblDepartment as t2
on t1.Employee_Type = t2.Department_Type
where t2.Department_Type = 'InActive'

This will update all employee type to InActive.
Answer: I found the solution to my problem.
UPDATE tblEmployees
SET Employee_Type = t2.Department_Type
FROM tblEmployees AS t1
LEFT JOIN tblDepartment AS t2
ON t1.EmployeeID = t2.EmployeeID
WHERE
t2.Department_Type = 'Inactive'

Comment: This is identical to the query I posted an hour ago, except that you used `Inactive` with a capital first letter as opposed to `inactive`.  Without seeing any data, would you expect us to be able to guess what is inside your table?


Reorganise svn folder structure Tortoise

Question: I have an SVN repository named 'Solution' (contains many projects) created without the default trunk, branch etc structure. I'd like to move this to the recommended structure.
I have created the new folder structure on the server where 'Team' is the root containing aforementioned trunk and branches. So should I relocate locally to Team/Trunk or copy locally and Add to the new repo folders? I'd like to maintain history in the process, if possible.
I have read a number of SO posts on this theme, but it seems there are many ways of getting this right or wrong, depending on circumstances.
Also, I'm new to SVN and development in general, hence I need GUI instructions as opposed to command line, please, sorry to be non-developer about it. Doing my best.
Illustration:
(Existing)
    Solution/
            Project folders/

(Proposed)
    Team/
            Trunk/
                 /Project folders
            Branches/

Comment: What is "Team"? is it a new repository or it created child of "Solution"
Comment: Thanks Olive. Team is a new repository - currently empty. Should I create the new structure within 'solution' and move all project folders into that
Comment: Why did you create another repository? You don't mind losing the commit history in the previous repo (though, there are ways to transfer the history over to the new one - not recommended)? I would create the new structure in the current repo and `svn move` the project folders into that, as you mentioned.
Answer: Firstly, you do not need to create an entirely new repo in order to reorganize your projects.
Secondly, if you can, checkout the entirety of your Solution repo somewhere, and create and svn add the branches, tags, trunk folders. Do NOT commit them yet; you will svn move every other folder (the project folders) into trunk and then commit everything in one go.
To illustrate, I created a SampleRepo, checked it out, then svn added and svn committed a few placeholder project folders:

Then, I created the branches, tags, and trunk folders at the root of the repo checkout, then svn added them using TortoiseSVN:

The repo checkout now looks like this:

Now, I select all of the project folders, and right-drag them over to the trunk folder, selecting SVN Move versioned item(s) here:

The root of the SampleRepo folder now contains just the branches, tags, and trunk folders. If you right-click any whitespace in the SampleRepo folder, and select TortoiseSVN -> SVN Check for modifications, you should see something like this:

Finally, I right-click any whitespace in the SampleRepo folder, and choose TortoiseSVN -> SVN Commit..., add a commit message, and click OK.
Now, if I right-click any whitespace in the SampleRepo folder -> TortoiseSVN -> SVN Show log I will see this:

All done!
NB: The reason I asked for a complete checkout of the repo is because then you can minimize the number of commits you'd have to make in order to achieve the restructuring you want. You can perform the restructure server-side using TortoiseSVN's Repo Browser, but then you'd need to commit every folder move, one at a time.
More reading:

Version Control with Subversion
TortoiseSVN's Help File, usually found here: %SYSTEMDRIVE%\Program Files\TortoiseSVN\bin\TortoiseSVN_en.chm
Comment: Sameer singh that's a clear answer and well explained, thank you.
Comment: @Rufyan Glad to help! :) Please remember to mark this as the answer once you're done with your restructure and don't require any further help.
Comment: Thanks. After doing that, I had to do a **TortoiseSNV -> Switch...** to the new /trunk/ folder on the original projects.
Comment: @kannas I'm glad this helped!
Comment: @J.A.Cado I added pictures when I first answered the question. Do you not see them?


Creating "Type" object of a class by Type.getType

Question: I am stuck here. In my vs solution we have 10 different projects.
DAL contains 2 EF 6.0 objects, Say EG and EL.
I have an API project. In which I have a function as follows, I am trying to return properties of an EF class:
public IEnumerable<PropertyInfo> GetGetProperties(string className, string instanceType)
    {
        Type thisType;

        if (instanceType.Contains("G"))
        {
            thisType = Type.GetType("E.DAL.EG." + className);
        }
        else
        {
            thisType = Type.GetType("E.DAL.EL." + className);
        }
        return thisType.GetType().GetProperties();
    }

But every time "thisType" returns null. Is this because of the AssemblyInformation? if so what would be the correct code. I have Assembly's fully qualified name in string.
Thanks-- Anirban
Comment: I believe the return should be return thisType.GetProperties();
Comment: Thats a typo mistake here, thanks , I rectified it. But still the problem remains.
Comment: I had a typo too, check the comment now
Comment: thisType is itself a null value. thisType is returning correctly if that is in the same assembly.
Comment: I just remembered that you can get the assembly first somehow, and from it you do GetType, I don't remember how, but my internet connection doesn't allow me now to search.. Try to find it. Assembly something with the path to the assembly..
Comment: Check the last line in the answer, that's what I meant I think
Answer: The problem is the last line. You are calling .GetType() on type Type (variable thisType) and that would return RuntimeType and not your type. The last line should be
return thisType.GetProperties();

and if your namespaces are correct, so you do have those namespaces (E.DAL.EL and E.DAL.EG) in the project, it will work.
If it doesn't check the namespaces and verify that those types are in the same assembly as your code! If they are in an external one you need to specify it for the GetType method.
Assuming those are in assembly named SharedAssembly then you need to load them this way
thisType = Type.GetType("E.DAL.EG." + className+ ", SharedAssembly");

Comment: Thanks Let me check


SQL query to find min and & max value for a user who has at least one day with a row count of > threshold

Question: I have records for a user base, and I am trying to identify a kind of user who has at least 100 records per day and then determine that user's life span by finding the user's max and min time stamp. I have not been able to do that in a single query. Here's how I identify users who meet the threshold:
SELECT COUNT(*) count, userid, recorddate::date
FROM data
WHERE datatype = 0
GROUP BY userid, recorddate::date
HAVING COUNT(userid) > 100

However, this only returns data for days where the count was > 100. I am interested in the max and min date for a user who had at least one day with the count > 100. Is there a way to modify this query above to get what I want or must I use a second query?
Answer: join the result to the original table to get the lifespan of those users who have more than 100 entries per day atleast once.
select d.user_id
,max(d.record_date::date) - min(d.record_date::date) as user_lifespan_in_days
from data d
join (SELECT COUNT(*) count, userid, recorddate::date
      FROM data
      WHERE datatype = 0
      GROUP BY userid, recorddate::date
      HAVING COUNT(*) > 100) t
on t.user_id = d.user_id
group by d.user_id

Answer: Note this is a comparison of 2 of the answers.  While the first section of this is written for sql-server, I also tried the windowed functions specifically in Postgres the code is below as well.  The bottom line is that this is a 2 step query for the questions desired results.  Step 1 find the UserIds meeting the criteria you want Step 2 joining that back to the table and getting the max and min from the entire dataset.
I truly wish it could be done in one step but the results are clear that the windowed functions when combined with GROUP BY will calculate their results based upon the result set of the GROUP BY NOT the entire table.
Here is some test Data so that we can see the actual results:
DECLARE @Data AS TABLE (UserId INT, RecordDate DATETIME)

INSERT INTO @Data (UserId, RecordDate)
VALUES (2,DATEADD(YEAR,-3,GETDATE())), (2,DATEADD(YEAR,3,GETDATE())), (4,DATEADD(YEAR,-6,GETDATE())), (4,DATEADD(YEAR,6,GETDATE()))

DECLARE @U INT = 1

WHILE @U < 5
BEGIN
    DECLARE @I INT = 1

    WHILE @I < 12
    BEGIN
       IF (@U IN (1,3) AND @I > 6)
       BEGIN
          BREAK
       END

       INSERT INTO @Data (UserId, RecordDate) VALUES (@U, DATEADD(MINUTE,-1,GETDATE()))

       SET @I += 1
    END

    SET @U += 1
END

Here is @Gordon Linoff's suggestion
SELECT
    UserId, RecordDate, COUNT(*) AS [count]
    ,MIN(RecordDate) OVER (PARTITION BY UserId) AS min_recorddate
    ,MAX(RecordDate) OVER (PARTITION BY UserId) AS max_recorddate
FROM
    @Data
GROUP BY
    UserId, RecordDate
HAVING
    COUNT(UserId) > 9

And here is @vkp's suggestion
SELECT
    t.UserId
    ,COUNT(*) AS [count]
    ,MIN(d.RecordDate) as min_recorddate
    ,MAX(d.RecordDate) as max_recorddate
FROM
    @Data d
    INNER JOIN
    (
       SELECT
          UserId
          ,RecordDate
          ,[count] = COUNT(*)
       FROM
          @Data
       GROUP BY
          UserId
          ,RecordDate
       HAVING
          COUNT(*) > 9
    ) t
    ON d.UserId = t.UserId
GROUP BY
    t.UserId

Note @Gordon's results:

@Vkp's resuls:

Image of UserId 2 from Test Date I generated

Adding Postgres Test Case with @Gordons suggestion:
CREATE TEMPORARY TABLE DATA (USERID INT, RECORDDATE TIMESTAMP)
ON COMMIT DELETE ROWS;

INSERT INTO DATA (USERID, RECORDDATE) VALUES (2,NOW() + INTERVAL '3 YEAR');
INSERT INTO DATA (USERID, RECORDDATE) VALUES (2,NOW() + INTERVAL '-3 YEAR');
INSERT INTO DATA (USERID, RECORDDATE) VALUES (4,NOW() + INTERVAL '6 YEAR');
INSERT INTO DATA (USERID, RECORDDATE) VALUES (4,NOW() + INTERVAL '-6 YEAR');

DO $$
    DECLARE
        i integer;
        u integer;
    BEGIN
        u := 1;
        WHILE (u < 5) LOOP
            i := 1;

            WHILE (i < 11) LOOP

                IF (u IN (1,3) AND i > 6) THEN
                    EXIT;
                END IF;

                INSERT INTO DATA (USERID, RECORDDATE) VALUES (u,NOW() + INTERVAL '-1 MINUTE');

            i = i + 1;

            END LOOP;

            u = u + 1;

        END LOOP;

    RAISE NOTICE 'value of i: %, and u: %', i, u;

END $$ ;

SELECT userid, recorddate::date, COUNT(*) as count,
       MIN(recorddate::date) OVER (PARTITION BY userid) as min_recorddate,
       MAX(recorddate::date) OVER (PARTITION BY userid) as max_recorddate
FROM data
GROUP BY userid, recorddate::date
HAVING COUNT(*) > 9;

Results
Answer: You mean that on a given day, the user has at least 100 records.  Here is one method:
SELECT userid, recorddate::date, COUNT(*) as count,
       MIN(recorddate::date) OVER (PARTITION BY userid) as min_recorddate,
       MAX(recorddate::date) OVER (PARTITION BY userid) as max_recorddate
FROM data
WHERE datatype = 0
GROUP BY userid, recorddate::date
HAVING COUNT(*) > 100;

Now, this will produce multiple records for the same user, if a user meets the criteria on multiple dates.  One solution is to use a subquery to filter down to the user level.  Another is to use DISTINCT ON:
SELECT DISTINCT ON (userid)
       userid, recorddate::date, COUNT(*) as count,
       MIN(recorddate::date) OVER (PARTITION BY userid) as min_recorddate,
       MAX(recorddate::date) OVER (PARTITION BY userid) as max_recorddate
FROM data
WHERE datatype = 0
GROUP BY userid, recorddate::date
ORDER BY userid, COUNT(*) DESC
HAVING COUNT(userid) > 100;

Now that I think about it . . . I haven't used window functions with DISTINCT ON.  So I think this will work.  A subquery or CTE definitely would work.
Comment: Perhaps I am reading it wrong but I believe he is asking for the MAX & MIN date of the User within the entire table not just the date he had 100 entries.  Which I know you know how to solve that looking at your reputation but for others it takes a 2 step query that can be done all in one swoop but step 1 find the userids by the group by having, step 2 relate it back to the original data set and get the max and min values
Comment: @Matt . . . This gets the `min()` and the `max()` over the whole table.  It wouldn't be very interesting if it got the min and max on a single date.  Do you understand how window functions work?
Comment: I use windowed functions pretty much every day though admittedly not usually in combination with aggregations.  However, I had tested the code block you wrote even before you answered the question because I was curious if it would work and it didn't.  Note, I posted an answer take a look at it for yourself.  Test data your way and the other answers.  Looks like some testing could have been done.
Comment: here is a quote from a website for you: "Note: You can't use window functions and standard aggregations in the same query. More specifically, you can't include window functions in a GROUP BY clause."  https://community.modeanalytics.com/sql/tutorial/sql-window-functions/ though I admit this is anonymous so I will look for more too because I would love to be able for the results to be driven by your query for some of the data warehouse stuff I do!
Comment: Matt . . . You can use analytic functions in aggregation queries.  I have been doing it for years and even have examples in "**Data Analysis Using SQL and Excel**" (which is not anonymous).  It is true that you cannot put them in the `GROUP BY` clause itself.
Comment: @Matt . . . The first code block should work.  The second I'm not so sure about.
Comment: look at the results for yourself they are below in my answer for you
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/114793/discussion-between-matt-and-gordon-linoff).


Would there be any issues with combining both a mixer (PV14AT) and an audio interface?

Question: I am currently looking to setup a home studio to record music with drums, bass, guitar, and vocals.The goal is to have up to 12 different microphones connected and ready for recording.
At the moment I have a PV14AT mixer and I am looking for an audio interface to possibly work in tandem. My idea is to use the audio interface for approximately 6-8 mic preamps with the mixer providing the remaining mic connections. One thing to note, the Mixer is able to provide individual line outs from all 8 mic preamps from the mixer. So the sound won't be summed into one output
My question is whether there would be any issues with connecting mixer outputs in combination with audio interface inputs in terms of latency or connections?
This is my first attempt at large scale recording and would like to minimize any potential issues
Comment: Are you saying you want to use the PV14AT mixer to pass a number of separate channels digitally into the computer over USB? Or just to use it to submix a number of channels and then plug that into the interface?
Answer: As long as the audio interface has enough inputs to accommodate all the microphones and the mixer outputs, connecting them should not result in significant latency issues. Make sure that the mixer and audio interface have compatible levels to prevent too low a signal, clipping, or distortion.
Answer: The manual of the PV 14AT says:

This impedance-balanced TRS output signal is taken after the mic
preamp, hi pass filter, and compressor, but before the EQ stage.

Additionally, the block diagram shows that the signal coming into the mixer remains analog on the entire signal path to the Direct Out ports, so you won't have any noticeable latency from analog-to-digital or digital-to-analog conversions. The audio interface will handle all analog-to-digital conversion internally, so you won't have separate clocks that would need to be synchronized. You should expect this to work as you propose.
If you intend to connect the mixer to your computer directly via USB rather than with analog cables to your audio interface, you might have issues. The manual does not list Windows 10 or 11 as compatible, suggesting any drivers they developed for the unit are already several years old. Latency will depend on the quality and compatibility of the driver. But if you only need the preamp function of the mixer, you should connect via analog connections.
Depending on the age, capability, and quality of your audio interface, you may wish to set up direct monitoring so you can listen back without noticeable latency. But such latency won't be the result of using the mixer.


Compare $A$ and $B$

Question: Compare $A$ and $B$ with:
$$A = \sqrt{2017} + \sqrt{2019} + \sqrt{2023}$$
$$B = \sqrt{2018} + \sqrt{2020} + \sqrt{2021}$$
I tried to prove $A^4 < B^4$ but it's too hard to do that.
Comment: [Quick beginner guide for asking a well-received question](https://math.meta.stackexchange.com/questions/35391) + [please avoid "no clue" questions](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question/27933#27933).
Comment: Nguyen, could you write your attempts and efforts in your post?
Answer: Well its enough to prove
$$A < B$$
since taking power to a positive number is operation that does not change sign. Easy to prove seems
$$A^2 < B^2$$
just by doing all of that products.
Quick guess without calculator would be also to use Taylor series
$$\sqrt{2017 + x} \approx \sqrt{2017} + \frac{x}{2\sqrt{2017}} - \frac{1}{8}\frac{x^2}{2017^{3/2}} $$
so only third term makes difference and you effectively want to compare $x^2$
$$2^2+6^2 > 1^2 + 3^2 + 4^2$$
so that
$$40 > 26$$
seems to hold.
Comment: This question goes against our [quality standard policy](https://math.meta.stackexchange.com/questions/33508/enforcement-of-quality-standards). Instead of posting an answer, you should encourage the person who posted the question to improve it.
Comment: In the same spirit : replace $2017$ by $x$ and use Taylor series for infintely large $x$ to get $$A-B=-\frac{7}{4 x^{3/2}}\left( 1-\frac{33}{7 x}+O\left(\frac{1}{x^2}\right)\right)$$
Comment: Thank you but I had done it already. I use the subtraction of A and B; it seems easier than yours.

Compare $A$ and $B$


Return value must be of type Collections array returned Doctrine / Symfony 6

Question: I have 2 order and line entities, with onetoMany / manytoOne relationship
I want to save a command with its lines, except I need to customize things, so I go through a datapersister function persist
If I don't try to save my lines it goes well, but as soon as I want to save the lines I get this message:
"App\Entity\DoRetourEntete::getRetALignes(): the return value must be of type Doctrine\Common\Collections\Collection, array returned
Basically I'm sending it an array while it's waiting for a collection.
But how to send it a collection in json?
In get everything works fine, I have my line detail when I call a command.
Here is my POST:
{
  "nomCommande": "2398",
  "cmdALignes": [
    {
      "ref": "maref1",
      "des1": "designation1",
      "qtt": 2
    },
    {
      "ref": "maref2",
      "des1": "designation2",
      "qtt": 2
    }

  ]
}

Here is a piece of my entities:
Commande:
/**
     * @ORM\OneToMany(targetEntity=lignes::class, mappedBy="ligneEntete")
     */
    private $cmdALignes;

    public function __construct()
    {
        $this->cmdALignes = new ArrayCollection();
    }

    /**
     * @return Collection|Post[]
     */
    public function getCmdALignes(): Collection
    {
        return $this->cmdALignes;
    }

    public function setCmdALignes(array $cmdALignes): self
    {
        $this->cmdALignes= $cmdALignes;

        return $this;
    }

and ligne :
/**
     *
     * @ORM\ManyToOne(targetEntity=Commande::class, inversedBy="cmdALignes")

     */
    private $ligneEntete;

    public function __construct()
    {
        $this->ligneEntete= new ArrayCollection();
    }

    public function getLigneEntete(): ?Commande
    {
        return $this->ligneEntete;
    }

    public function setLigneEntete(?Commande $ligneEntete): self
    {
        $this->ligneEntete= $ligneEntete;
        return $this;
    }

In my data persister :
$commande = new Commande();
$commande->setNomCommande($data->getNomCommande);

and in principle if I want to browse my lines, I do:
foreach ($data->getCmdALignes() as $ligne){ }

I know that I send an array in a collection but how to do?
thanks in advance
Guillaume
Comment: You ask an array in your setter, and return a collection in the getter. Have you tried setting "array" as return type for getCmdALignes() ? Or the other way around, but you'd need to ensure you send a collection in the hydrator
Comment: thank,
if I pass my get in array, my POST works, but my GET no longer works : Return value must be of type array, Doctrine\\ORM\\PersistentCollection returned
Comment: PersistentCollection has a "toArray()" method you could call it in your getter. I'm not saying it's the right way to do it, i don't know how symfony handles the hydration process
Answer: Collection and array are not the same thing. A collection is a class that is iterable and has methods for adding, removing, counting, etc.
Change
this
public function setCmdALignes(array $cmdALignes): self
    {
        $this->cmdALignes= $cmdALignes;

        return $this;
    }

to this
public function setCmdALignes(array $cmdALignes): self
    {
        foreach ($cmdALignes as $cmdALigne){
             $this->cmdALignes->add($cmdALigne);
        }

        return $this;
    }

or this
public function setCmdALignes(array $cmdALignes): self
    {
        $this->cmdALignes = new ArrayCollection($cmdALignes);

        return $this;
    }

I recommend reading the article
https://www.doctrine-project.org/projects/doctrine-collections/en/stable/index.html


$\mathbb{S}^1$-action on $\mathbb S^{2n+1}$

Question: I am trying to show $\mathbb{C}P^n$ is Hausdorff. I came across a proof that I would like to understand.

Let $[z],[w] \in \mathbb{C}P^{n}$ such that $[z]\ne [w]$ and $z,w \in \mathbb{S}^{2n+1}\subset \mathbb{C}^{n+1}$. Note that $\mathbb{S}^1 \subset \mathbb{C}$ is compact so we define $R = \min \{|sz - tw|: s,t \in \mathbb{S}^1\subset \mathbb{C}\} > 0$. Let $U = \{x \in \mathbb{S}^{2n+1}:|x-z| < \frac{R}{2}\}$ and $V = \{x \in \mathbb{S}^{2n+1}:|x-w| < \frac{R}{2}\}$. Note that $\lambda U = U$ and $\lambda V = V$ for all $\lambda \in \mathbb{S}^1$. So it follows that $\pi^{-1}(\pi(U)) = U$ and $\pi^{-1}(\pi(V))=V$. Thus, $\pi(U)$ and $\pi(V)$ are open and are disjoint, respectively containing $[z]$ and $[w]$. It follows that $\mathbb{C}P^n$ is Hausdorff.

Note that $\pi$ refers to the quotient map. I do not understand why both $U$ and $V$ are invariant under that action of $\mathbb{S}^1$, and to be honest, I do not understand the the aim behind defining $R$ as they have.
Comment: Is $\mathbb S^{n+1}$ supposed to be $S^{2n+1}$?
Comment: This is not true.  I suspect you have misstated something.
Comment: Maybe I'm a bit confused, but what is the definition of product between an element of $s\in\mathbb{S}^1$ and $z\in\mathbb{S}^{2n+1}$ being used here? Is it supposed to be the product with a 'unit' element of $[z]\in\mathbb{C}P^n$?
Comment: I dont think $\lambda \in \mathbb S^n$.
Comment: Yes, thank you.
Comment: Thank you for pointing that out, I've gone ahead and changed it.
Comment: My apologies, I did not clarify, $\mathbb{S}^{2n+1} \subset \mathbb{C}^{n+1}$. So complex scalar multiplication to each coordinate.
Comment: You're right, it is $\mathbb{S}^1$.
Answer: This is false. The scalar $-1$ is in $\mathbb{S}^1$, but of every $z\in\mathbb{S}^{2n+1}$, $ |z - (-1)z| = 2$. Thus, if $\varepsilon = 1$ for example, $U$ is not stable under the action of $\mathbb{S}^1$.
Comment: Thank you, I've changed my post.


Derivative of a composition of higher dimensional functions

Question: Let $A \subseteq \mathbb R^2$ be open and $f : A \to \mathbb R$ be a function whose all partial derivatives exist in A, and let $g = (g_1,g_2) : \mathbb R \to A$ be a differentiable function. Does the function $h : \mathbb R \to \mathbb R, h := f\circ g$ have a derivative, and if it does what is it.
Attempt:
So if we assume $f$ is also differentiable, then we get (from chain rule) that
$$h'(t)=\frac{\partial f}{\partial x}(g(t))g_1'(t)+\frac{\partial f}{\partial y}(g(t))g_2'(t),\quad t\in \mathbb R$$
So i assume that if there exists a derivative of $h$ in $t\in \mathbb R$ it is equal to that. Problem is, i can't prove that it exists since $f$ doesn't have to be differentiable.
Answer: I claim that $h$ is not necessarily differentiable. To see this, consider the functions $$f\colon\mathbb{R}^{2}\to\mathbb{R},\qquad f(x,y):=\begin{cases}0&(x,y)=(0,0)\\2xy/(x^{2}+y^{2})&(x,y)\neq(0,0)\end{cases}$$ and $$g\colon\mathbb{R}\to\mathbb{R}^{2},\qquad g(t):=(t,t).$$
Then $f$ is partially differentiable at $(0,0)$. Namely, if $e_{1}=(1,0)$ and $e_{2}:=(0,1)$, then
$$\frac{f(\xi e_{i})-f(0,0)}{\xi}=0\to0\qquad\text{as}\qquad\xi\to0\qquad\text{for}\qquad i\in\{1,2\}.$$
However, $f$ is not differentiable at $0$ (in fact not even continuous, check this!). Clearly $g$ is differentiable. Finally, $h:=f\circ g$ is not differentiable in $0$. Indeed, for $t\in\mathbb{R}$ we have $$h(t)=\begin{cases}0&t=0\\1&t\neq0\end{cases}.$$
Comment: Beat me to it. +1.
Comment: why does $\xi$ go to infinity shouldn't it go to 0 in definition of directional derivatives?
Comment: regardless partial derivatives should exist so the example holds
Comment: @Nasal, yes you're absolutely right. The map $f$ is not be differentiable in every direction. Nevertheless, as you pointed out,  $f$ is indeed still partially differentiable,. Edited it.


What tools are available to detect heap corruption in .NET/C# program?

Question: I know that I can use WinDbg+PageHeap+ApplicationVerifier - Microsoft tools.
I read there are many tools available for C++ and wonder if there is something similar exists for C#?
Answer: These are the kind of tools you use to troubleshoot mis-behaving native code.  Access violations, heap corruption, resource leaks, that sort of thing.  That just doesn't happen in pure managed code by virtue of the concept of safe code and the garbage collector.  If you have a dependency on native code in your managed project that misbehaves that way (Fatal Execution Engine Error for example) then you still use the same tools.  Diagnosing it is never easy.
Comment: Alone?  No.  Threading races don't cause heap corruption in .NET.
Comment: [here](http://stackoverflow.com/questions/7574153/net-4-can-the-managed-code-alone-cause-a-heap-corruption) people say that the managed code can corrupt the heap.
Comment: Yeah, sure, the Marshal class lets you break the rules.  That's what it is for.  If you haven't already scanned your code for Marshal, DllImport, unsafe and COM references then do make sure to ask help from a team member that knows the code base better.


Is there a way to get Eclipse's Open Resource dialog to search the middle of filenames automatically?

Question: Eclipse's Open Resource dialog lets you search for project files based on a typed query, but the default behavior is to return only those filenames that start with the given query. You have to prepend a * wildcard symbol if you want the query to be interpreted as an arbitrary filename substring.
I'd say that 95% of the time, I'd want to prepend the wildcard. The default behavior for analogous dialogs, e.g. those in Visual Assist or Komodo, is to assume the query can be any part of the filename. I'm wondering if there's a way to force Eclipse to work the same way.
Comment: There is https://bugs.eclipse.org/bugs/show_bug.cgi?id=531785 from 2018 which addresses this as a feature request, but it was not implemented yet.
Answer: 12+ years later, yes this is officially supported with Eclipse 4.27 (2023-03 release), from PR 12.

Open Resource dialog now defaults to "substring" search
By default, the search pattern input to the Open Resource dialog is now searched anywhere in the file name.
That means you no longer need to input a leading asterisk ("*") when searching from the middle of a file name.

If you want to enforce the old behavior, where "prefix-matching" search is expected, simply add a leading angle bracket (">") to the search pattern.
Answer: I don't think so.  The UI you're talking about uses the FileDialog class which isn't really configurable in the way you describe.  To me, that says that there's no preferences view that can alter that behavior.  I certainly don't know of any nor could I find one.


Find the first day of the x week of the x year

Question: Is there a way to find the first day of the x week of the x year with the package lubridate?
For example I have this data: week number in some year (e.g 33th week from the year 1988) and i would like to convert it into a data like: day/month/year (e.g 15/08/1988).
Missing_day <- c("33/1988", "37/1991", "37/1992",
             "41/1994", "15/1997", "18/2001",
             "50/2001", "16/2002", "35/2004",
             "5/2012", "50/2012", "8/2013",
             "36/2013", "51/2017")

thanks
Answer: You can attach the weekday and convert the data into Date. Using base R, you can do :
as.Date(paste0('1/', Missing_day), '%u/%U/%Y')

# [1] "1988-08-15" "1991-09-16" "1992-09-14" "1994-10-10" "1997-04-14"
# [6] "2001-05-07" "2001-12-17" "2002-04-22" "2004-08-30" "2012-01-30"
#[11] "2012-12-10" "2013-02-25" "2013-09-09" "2017-12-18"

Answer: Do note the discussion here about:

Specifying the day of the week
Ensuring you understand the different ways in which R enumerates weeks of a year

library(dplyr)
library(stringr)

# Using Lubridate per your request
library(lubridate)
tibble(week_year = Missing_day) %>%
  mutate(
    day_month_year = format(lubridate::parse_date_time(
      paste(
        str_extract(string = week_year, pattern = "^\\d+"),
        str_extract(string = week_year, pattern = "\\d*$"),
        'Mon',
        sep =
          "/"
      ), 'W/Y/a'
    ), "%d/%m/%Y")
  )

# A tibble: 14 x 2
# week_year  day_month_year
#    <chr>        <chr>
# 1 33/1988    15/08/1988
# 2 37/1991    16/09/1991
# 3 37/1992    14/09/1992
# 4 41/1994    10/10/1994
# 5 15/1997    14/04/1997
# 6 18/2001    30/04/2001
# 7 50/2001    10/12/2001
# 8 16/2002    22/04/2002
# 9 35/2004    30/08/2004
# 10 5/2012    30/01/2012
# 11 50/2012   10/12/2012
# 12 8/2013    25/02/2013
# 13 36/2013   09/09/2013
# 14 51/2017   18/12/2017

# Using Base R
tibble(week_year = Missing_day) %>%
  mutate(
    day_month_year = format(as.Date(
      paste(
        1,
        str_extract(string = week_year, pattern = "^\\d+"),
        str_extract(string = week_year, pattern = "\\d*$"),
        sep = "/"
      ), "%w/%W/%Y"
    ), "%d/%m/%Y")
  )

# A tibble: 14 x 2
# week_year  day_month_year
#    <chr>       <chr>
# 1 33/1988    15/08/1988
# 2 37/1991    16/09/1991
# 3 37/1992    14/09/1992
# 4 41/1994    10/10/1994
# 5 15/1997    14/04/1997
# 6 18/2001    30/04/2001
# 7 50/2001    10/12/2001
# 8 16/2002    22/04/2002
# 9 35/2004    30/08/2004
# 10 5/2012    30/01/2012
# 11 50/2012   10/12/2012
# 12 8/2013    25/02/2013
# 13 36/2013   09/09/2013
# 14 51/2017   18/12/2017


Maximization of $tr[U^HAU(U^HBU)^{-1}]$

Question: I am looking for the solution of
\begin{align*}
 \max_{{U}\in\mathbb{C}^{M\times P},\ {U}^H{U}={I}_P } &tr\left[ {U}^H{A}{U}\left({U}^H{B}{U}\right)^{-1}\right],
\end{align*}
where $P\leq M$, ${A} \in \mathbb{C}^{M\times M}$ and ${B} \in \mathbb{C}^{M\times M}$ are full-rank Hermitian matrices.
I wonder if the solution is a collection of the $P$ generalized eigenvectors associated to the $P$ maximal generalized eigenvalues of the matrix pencil $({A},{B})$. Alternatively, ${U}$ would be a collection of the $P$ eigenvectors associated to the $P$ maximal eigenvalues of the matrix ${B}^{-1}{A}$.
I can only prove it in the case $P=1$, in which case the problem becomes the well-known generalized Rayleigh quotient
\begin{align*}
 \max_{{u}\in\mathbb{C}^{M\times 1},\ {u}^H{u}=1 } & \frac{u^HAu}{u^HBu},
\end{align*}
which is maximized by using the dominant generalized eigenvector of $({A},{B})$.
What about the general case $P>1$?
Comment: Something that might help: WLOG you may assume one of $A$ or $B$ is diagonal.
Comment: Typo in ${U}\in\mathbb{C}^{P\times M},\ {U}^H{U}={I}_P$?
Comment: Indeed River Li, thanks for noticing, corrected!
Comment: Thanks eyeballfrog, indeed, but not sure to see how to use that. Rethinking about the problem, I do not think the eigenvectors I described are orthogonal given that $B^{-1}A$ is not necessarily Hermitian.
What is sure is that, in the case $P=1$, the dominant generalized eigenvector is optimal as the problem becomes a well-known generalized Rayleigh quotient.
Answer: We can solve this for real symmetric matrices, but I'm not sure if the method works all the way for Hermitian matrices. Anyway, we can use Lagrange multipliers method to solve this problem. So, in the real symmetric case the Lagrangian can be written as
$$L = tr\left[ {U}^T{A}{U}\left({U}^T{B}{U}\right)^{-1}\right] - tr \left[ \left(U^T U - I\right) \Lambda \right]$$
where $\Lambda \in \mathbb{R}^{P \times P}$ is symmetric and contains the Lagrange multipliers. To see where the second part comes from, consider the constraint equation $U^TU=I$, which has $P^2$ equations to be satisfied (of which $P^2 - P(P+1)/2$ are redundant). Multiplying each one with $\Lambda_{ij}$ and summing all of them yields
$$ \textbf{1}^T \left[ \left(U^T U - I\right) \circ \Lambda \right] \textbf{1} = tr \left[ \left(U^T U - I\right) \Lambda \right] $$
where $\circ$ is the Hadamard product and $\textbf{1}$ is the vector with all ones. We used the properties of Hadamard product to obtain the result.
We can use the differential form of $L$ w.r.t. $U$ to solve the problem as follows:
$$\begin{align}
dL &= tr\left[ d \left({U}^T{A}{U}\right) \left({U}^T{B}{U}\right)^{-1}\right] + tr\left[ {U}^T{A}{U} ~ d \left(\left({U}^T{B}{U}\right)^{-1}\right)\right] - tr \left[ d\left(U^T U \Lambda\right) \right] \\
&= 2 tr\left[\left({U}^T{B}{U}\right)^{-1} {U}^T{A}(dU)\right] - 2 tr \left[ \left({U}^T{B}{U}\right)^{-1} {U}^T{A}{U} \left({U}^T{B}{U}\right)^{-1} {U}^T{B}(dU)\right] \\
&\phantom{=}- 2 tr \left[ \Lambda U^T (dU) \right] \\
\frac{\partial L}{\partial U} &= 2\left({U}^T{B}{U}\right)^{-1} {U}^T{A} - 2\left({U}^T{B}{U}\right)^{-1} {U}^T{A}{U} \left({U}^T{B}{U}\right)^{-1} {U}^T{B} - 2\Lambda U^T \\
&= 0
\end{align}$$
Mutilplying with $U$ from right we get $\Lambda = 0$. So the constraint is not binding. Therefore, $U$ has to satisfy
$$ U^T A = {U}^T{A}{U} \left({U}^T{B}{U}\right)^{-1} {U}^T{B} $$
If $B$ has an inverse we get
$$ U^T A B^{-1} = {U}^T{A}{U} \left({U}^T{B}{U}\right)^{-1} {U}^T $$
or equivalently
$$ B^{-1} A U = U \left({U}^T{B}{U}\right)^{-1} {U}^T{A}{U} $$
Note that the image of the right side of the equation is the column space of $U$. This means image of $U$ must be an invariant subspace of $B^{-1} A$.
If there are finitely many invariant subspaces, an algorithm for finding $U$ can be given as follows:

Find all $P$-dimensional invariant subspaces $V_i$ of $B^{-1} A$.
Use Gram–Schmidt process to construct $U_i$ such that $Im(U_i) = V_i$ and $U_i^T U_i = I$.
Calculate $tr\left[ {U}_i^T{A}{U}_i\left({U}_i^T{B}{U}_i\right)^{-1}\right]$ for all $i$.
Take $U = U_i$ that maximizes the trace.

Of course there might be infinitely many invariant subspaces. In this case you can try to parameterize $U$ and find the parameters that maximizes the trace. For $P=1$, the eigenvector of the largest eigenvalue gives a solution, but there might be infinitely many $U$ that gives the same result.
In general, if $B^{-1} A$ has distinct eigenvalues, then there are finitely many invariant subspaces.
I believe this method also generalizes to Hermitian matrices but you need to be careful when calculating the derivative of the trace, since it changes with complex conjugate transpose operation.
Comment: @François2021 I give a complete-ish answer. Please see my edits.
Comment: Thank you for the edit. Why "can't we just multiply the derivative of the Lagrangian with $U$ from the right"? This seems a good idea and it seems intuitive, especially in the case $P=1$. It is well known that a (generalized) Rayleigh quotient is independent of scaling and thus a normalization constraint. Here this is kind of a generalization for $P>1$.
Comment: You were right. We can multiply with $U$ to show $\Lambda = 0$, so I deleted my comments.
Comment: Thanks obareey for all your inputs. The fact that the constraint is not binding was key to help finding the solution. I posted below a tentative solution. What do you think? Maybe this corresponds somewhat to your own. Any new input welcome.
I also deleted some of my previous comments for clarity.
Answer: Given previous inputs of obareey, I realized the constraint is not binding and can actually be forgotten. Indeed, $U$ can be multiplied from the right by any full rank/invertible matrix without changing the cost function. Hence, we can forget about the constraint, optimize for a general matrix $W$ and "orthogonalize" at the end to find $U$ as $U=W(W^HW)^{-1/2}$. The relaxed problem is thus
\begin{align*}
 \max_{{W}\in\mathbb{C}^{M\times P}} f(W)=tr\left[ {W}^H{A}{W}\left({W}^H{B}{W}\right)^{-1}\right].
\end{align*}
Now, we can write equivalent forms of the problem. Given that $W$ can be multiplied from the right arbitrarily, we can choose $W$ such that $W^HBW=I$. Indeed, consider for instance a given $\tilde{W}$. We can "normalize" it as $W=\tilde{W}(\tilde{W}^HB\tilde{W})^{-1/2}$, so that $W^HBW=I$ and this does not affect the value of $f(W)$. Hence the problem is equivalent to
\begin{align*}
 \max_{{W}\in\mathbb{C}^{M\times P}} f(W)=tr\left[ {W}^H{A}{W}\left({W}^H{B}{W}\right)^{-1}\right]\quad s.t.\ W^HBW=I,
\end{align*}
which is equivalent to
\begin{align*}
 \max_{{W}\in\mathbb{C}^{M\times P}} tr\left[ {W}^H{A}{W}\right]\quad s.t.\ W^HBW=I.
\end{align*}
This problem has (one of) the canonical form(s) of a generalized eigenvalue problem, see, e.g., Optimization Form 2 in [1]. Let us extend the methodology of [1] to the complex/Hermitian case. The Lagrangian can be written
\begin{align*}
L&= tr\left[ {W}^H{A}{W}\right] -  tr\left[\Lambda(W^HBW-I)\right],
\end{align*}
where $\Lambda$ is real and symmetric. $tr\left[\Lambda(W^HBW-I)\right]$ is then always real so that no real part should be taken. Moreover, using the same trick as in [Appendix B, 1], we can show that, without loss of generality, $\Lambda$ can be considered diagonal. Taking the Wirtinger derivative with respect to $W^*$ gives
\begin{align*}
\frac{dL}{dW^*}=\frac{1}{2}\left(\frac{dL}{d\Re(W)}+j\frac{dL}{d\Im(W)}\right)=AW-BW\Lambda,
\end{align*}
and setting it to zero gives the generalized eigenvalue problem
\begin{align*}
AW=BW\Lambda.
\end{align*}
Using this, the cost function becomes $tr\left[ {W}^H{A}{W}\left({W}^H{B}{W}\right)^{-1}\right]=tr\left[\Lambda\right]$. It is thus optimal to select maximal generalized eigenvalues.
The solution is thus given by choosing for $W$ the generalized eigenvectors of the pencil $(A,B)$, associated to its $P$ largest eigenvalues.
The final $U$, having orthogonal columns, can be obtained again by multiplying $W$ on the right as $U=W(W^HW)^{-1/2}$.
[1] B. Ghojogh, F. Karray, and M. Crowley, "Eigenvalue and Generalized Eigenvalue Problems: Tutorial." arXiv, May 23, 2022. Accessed: Jul. 28, 2022. [Online]. Available: http://arxiv.org/abs/1903.11240
Comment: This is a very nice and clear solution. Also +1 for the reference. But I think it needs a discussion on why this works for Hermitian / complex case.
Comment: Agreed. Actually, the extension of the proof given in [1] to the complex case seems straightforward to me. One can use the Wirtinger derivative ($\frac{dL}{dW^*}$) instead of the conventional one in the real case ($\frac{dL}{dW}$). If you are interested, I can draft it.
Comment: I would love that. I didn't know anything about Wirtinger derivatives until I searched something trying to answer this question. It could be useful to me in the future.
Comment: I added more details. I hope it is clear enough. In short, in the complex case, you can take the derivative of the Lagrangian with respect to real and imaginary parts of $W$, $\frac{dL}{d\Re(W)}$ and $\frac{dL}{d\Im(W)}$. Given that $L$ is real, these derivatives will be real as well. Hence, setting the two derivatives to zero is equivalent to setting $\frac{dL}{d\Re(W)}+j\frac{dL}{d\Im(W)}$ to zero, giving the above condition.
To go faster, you can take directly the Wirtinger derivative, see wikipedia. For this you can simply consider $W$ and $W^*$ as independent when taking derivatives.
Comment: Thank you for the explanation. It is very clear now.

Maximization of $tr[U^HAU(U^HBU)^{-1}]$


How can I force a re-render of a component in MainLayout?

Question: I know one answer is don't use MainLayout for this one page, but I prefer to not do that as we then have to keep 2 layout pages in sync on every change in them - and that's just asking for divergence.
Here's the problem. This is my MainLayout (simplified)
<ErrorBoundary>
    <ChildContent>

            <PopupMessageBox>

                    <PrimaryNav UserAvatarUrl="@UserAvatarUrl" IsManagerOrSysAdmin="@(Principal.IsManagerOrSysAdmin())" />

                    @Body

    </ChildContent>

For one @Body page we need to have <PrimaryNav> have a slightly different menu selection. In <PrimaryNav> we can determine what page is in @Body, but having the page change does not cause <PrimaryNav> to re-render.
Is there a way to force it to re-render on every page change?
Comment: On questions like this I wish I could conclude the question with "Or is this a bad idea?" But opinions cannot be asked for. (They can however be given.)
Comment: https://learn.microsoft.com/en-us/aspnet/core/blazor/components/sections?view=aspnetcore-8.0. Is now the more elegant way to do this. Your page can define its own menu.
Answer: @body is the current page component.  It's available in Routes in the Router as routeData.
Here I'm simply cascading the Type.
<Router AppAssembly="typeof(Program).Assembly">
    <Found Context="routeData">
        <CascadingValue Name="PageComponent" Value="routeData.PageType">
            <RouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)" />
            <FocusOnNavigate RouteData="routeData" Selector="h1" />
        </CascadingValue>
    </Found>
</Router>

The value will be refreshed with a render cascade on each navigation.
You can then capture the cascade in NavMenu.  Here's a demo that only shows the Weather nav link when you are on Home.

        BlazorApp1

<input type="checkbox" title="Navigation menu" class="navbar-toggler" />

            <NavLink class="nav-link" href="" Match="NavLinkMatch.All">
                 Home
            </NavLink>

            <NavLink class="nav-link" href="counter">
                 Counter
            </NavLink>

@if(_isHome)
        {

            <NavLink class="nav-link" href="weather">
                 Weather
            </NavLink>

        }

@code {
    [CascadingParameter(Name = "PageComponent")] private Type? RouteType { get; set; }

    private bool _isHome => RouteType == typeof(Home);
}

Comment: As always, thank you
Answer: You could firstly call a method in the Parent(MainLayout) from ChildComponent(@body). Then in the "MainLayout" call a method in the "nav" .
Try following sample which calling StateHasChanged(); in the "NavMenu" from Counter.razor.
Create a static Number which for render test of NavMenu.
    public static class Number
    {
       public static int value;
    }

NavMenu.cs (Add @number.value behind Counter for render test)
...
                Counter
               @Number.value
           </NavLink>
...

@code{
    public void RefreshState()
    {
        this.StateHasChanged();
    }
}

MainLayout.cs   (call methods 1.cascadingvalue: child->parent;  2.@ref: parent->child  )
...
 <NavMenu @ref="nav" />
...
            <CascadingValue Value="this">
                @Body
            </CascadingValue>
...
@code{
    NavMenu nav;
    public void CallMethodInNav()
    {
        nav.RefreshState();
    }
}

Counter.cs  (using cascading parameter to call method from parent)
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    [CascadingParameter]
    public MainLayout _mainLayout { get; set; }

    private void IncrementCount()
    {
        currentCount++;
        Number.value = currentCount;
        _mainLayout.CallMethodInNav();
    }
}

Test Result  (The @Number.value keep re-render when click counter)

You could using similar at "OnInitialized" for pages you want to trigger nav refresh.


How to relate two series(GP and AP) using a positive real number, who have nothing in common?

Question: Here is a question from my book:

Given a GP and an AP with positive terms $a,a_1,a_2,a_3...a_n$ and $b,b_1,b_2,b_3,...b_n$ respectively. The common ratio of the GP is different from $1$.
  Then there exists $x\in \Bbb R^+$, such that $\log_xa_n-\log_xa$ is equal to
(A) $a-b$
  (B) $a_n-b$
  (C) $b_n-b$
  (D) $a_n-b_n$

I asked for the solution from my teacher but he said that the question was wrong since there is no relation given between AP and GP. I told him that we can adjust $x$ according to our needs but he wasn't convinced. I hope there is a way to solve this question.
We just have to find out which options aren't possible for any value of $x$.
Above statement is my only progress(if the question is solved I indeed progressed further than my teacher XD).
Thanks for any hints or solution.
Answer: The only correct option is $(C)$.
$(A)$ is not correct since for $n=1,a=1,a_1=2,b=1,b_1=2$, there does not exist $x\in\mathbb R^+$ such that
$$\log_x2-\log_x1=0$$
$(B)$ is not correct since for $n=1,a=2,a_1=1,b=1,b_1=2$, there does not exist $x\in\mathbb R^+$ such that
$$\log_x1-\log_x2=0$$
For $(C)$, we see that $$\log_x a_n-\log_x a=b_n-b$$
is equivalent to
$$\ln x=\frac{\ln\left(\frac{a_n}{a}\right)}{b_n-b}\tag1$$
where we always have $b_n-b=nd\not=0$ assuming that the common difference $d$ is not $0$.
Note here that the range of the function $y=\ln x$ is $\mathbb R$. So, for every real number $c$, there exists $x\in\mathbb R^+$ such that $\ln x=c$. So, there exists $x\in\mathbb R^+$ such that $(1)$. Hence, the option $(C)$ is correct.
$(D)$ is not correct since for $n=1,a=1,a_1=2,b=1,b_1=2$, there does not exist $x\in\mathbb R^+$ such that
$$\log_x2-\log_x1=0$$
Comment: Thanks, I would accept your answer. But is there any way to prove that option C is correct. Well there is a fault that it is not mentioned that AP's common difference isn't 0. Leaving it aside can you prove option C.
Comment: @Love Invariants: I've added some explanations.


How to restore form values from $form_state['values']?

Question: I save the $form_sate['values'] in a data base. When my users come back to the form I want to show the values that they put before. Something like:
function my_form($form, &$form_sate) {
  $form_state_saved = get_form_state_values_from_db();

  $form['my_field'] = array(
    ...
    '#default_value' = $form_state_saved['my_field'];
    ...
  );

  return $form;
}

With a textfield seems that works fine, but I have some custom fields. Is there a way to set the default_value from db? Or should I implement the default_value independently for each field?
Comment: I think you've answered yourself the question. Every element in your form could be filled with the default value.
Comment: You should implement `default_value` independently for each field.
Answer: Use Form default value:
'#default_value' => variable_get('sitename_textfield', ''),

If you use system_settings_form() you don't need to manually save your variables using a custom form submit function. Note: The variable must have the same name as the form item.
Function details: https://api.drupal.org/api/drupal/modules!system!system.module/function/system_settings_form/7
/**
 * Creates/returns a form to configure the variables.
 *
 * @param array $form
 * @param array $form_state
 * @return array
 */
function sitename_custom_form($form, &$form_state) {
  $form['sitename_textfield'] = array(
    '#type' => 'textfield',
    '#title' => t('Custom Textfield'),
    '#default_value' => variable_get('sitename_textfield', ''),
  );

  // Use system_settings_form() to automate saving configuration variables.
  return system_settings_form($form);
}

Answer: You need to use variable_set() if you only want to set the previous value
There is no harm in storing independent values for each fiels element using variable_set()
  function my_form($form, &$form_sate) {
      $form['my_field'] = array(
        ...
        '#default_value' = variable_get('my_field','');
        ...
      );

  return $form;
}
function my_form_submit($form, &$form_sate) {

      variable_set('my_field',  $form['my_field']['#default_value']);

}

Answer: Finally, what my colleague did was a combination of field_default_form and field_form_set_state.
$field_state = array(
  'field' => $field,
  'instance' => $instance,
  'items_count' => $count,
  'array_parents' => array(),
  'errors' => array(),
);
field_form_set_state($parents, $field_name, $language, $form_state, $field_state);

$items is an array with the form values stored in a database.
$form_field = field_default_form('node', NULL, $field, $instance, $language, $items, $form, $form_state);

$form[$field_name] = $form_field[$field_name];


Do views filter plugins not apply to base field definitions?

Question: I created a custom entity type that has a base field definition like this:
$fields['start_date'] = BaseFieldDefinition::create('datetime')
  ->setLabel(t('Start Date'))
  ->setDescription(t('The date and time to start.'))
  ->setDisplayOptions('view', array(
    'type' => 'datetime_default',
    'weight' => 3,
  ))
  ->setDisplayOptions('form', [
    'type' => 'datetime_default',
    'weight' => 3,
  ])
  ->setRequired(TRUE);

When I create a view that displays entities of this type, and try to create a filter on this base field, I get the generic filter provided by views, instead of the one defined in Drupal\datetime\Plugin\views\filter\Date.
Why is that?
Comment: I'm guessing https://www.drupal.org/node/2489476#comment-11891454 is you, then you figured it out by now ;) As a workaround, you can specify the filter yourself for now
Comment: hah - yes. I'm working on a hook_views_data implementation now, then will post it as an answer here.
Answer: Looks like this is a known major issue. Here's the main "parent" issue where most of the work is going down: https://www.drupal.org/node/2337515
I think, by default, there is some basic views integration for all entities, but it's not that robust.
As a workaround, I was able to implement hook_views_data_alter to tell views to use the 'datetime' filter plugin instead of the default 'string' plugin it had.
function MY_MODULE_views_data_alter(array &$data) {
  $data['my_entity_type']['start_date']['filter']['id'] = 'datetime';
}

Comment: Can you specify what changes you made in the filter?
It seems that the MY_MODULE_run_views_data_alter does not exist, is an error and I have to use MY_MODULE_views_data_alter ?
Comment: Sorry, I that was a type in the hook name. Updated answer to fix that and removed the last bit about creating a custom filter. I think that was incorrect as well, it shouldn't have been required.
Comment: I tested and doesn't work for me, when I try to add a filter with this field, the popup window doesn't show me the options and reappear the add filter page. When I reload the edit view page, shows me this error "Notice: Undefined index: field_name in Drupal\datetime\Plugin\views\filter\Date->getFieldStorageDefinition() (line 56 of /var/www/.../core/modules/views/src/FieldAPIHandlerTrait.php)"
Answer: An entity type can be revisionable and translatable and in these cases, the table name will not be entity_type. Check the @ContentEntityType annotation on the entity class for data_table and revision_data_table keys.
Also, the ListField Views filter class needs field_name set.
Here's a working example for a base field set on media:
function sd8_media_views_data_alter(array &$data) {
  $data['media_field_data']['embed_status']['filter']['id'] = 'list_field';
  $data['media_field_data']['embed_status']['filter']['field_name'] = 'embed_status';
}

My field is not revisionable and so I didn't need to set the same on $data['media_field_revision'] but if your field is, then you need that too. xdebug is very much your friend, put a breakpoint inside the hook_views_data_alter function and look at $data.


String split and duplicate row in R?

Question: I have a database as follow:
col1 <-c("X1",";X2","X3;X4;X5","X6;X7")
[1] "X1"       ";X2"      "X3;X4;X5" "X6;X7"
col2 = col3 = col4 <- c("5","8","4","1")
[1] "5" "8" "1" "4"
dat <- data.frame(col1,col2,col3,col4)
 dat
      col1 col2 col3 col4
1       X1    5    5    5
2      ;X2    8    8    8
3 X3;X4;X5    4    4    4
4    X6;X7    1    1    1

I want to remove semi colon in column 1 and if column 1 which contains over one X, it will duplicate new rows.
Moreover, column 2 and 3 will duplicate values, column 4 will replace by value 0. I expect it will be:
dat
  col1 col2 col3 col4
1   X1    5    5    5
2   X2    8    8    8
3   X3    4    4    4
4   X4    4    4    0
5   X5    4    4    0
6   X6    1    1    1
7   X7    1    1    0

Comment: Please don't quote the numeric values.  It will be read as `factor/character` columns depending upon whether you specify the `stringsAsFactors=TRUE/FALSE`
Answer: This splits col1 by semicolon and uses tidyr's unnest to explode single rows into multiple rows as needed.   Next it uses filter to remove unwanted rows that were generated by leading (or trailing or multiple) semicolons.  tidyr puts col1 last so we rearrange using select. Alternately, if the column order does not matter just omit the select.
library(dplyr)
library(tidyr)

   dat %>%
       mutate(col1 = strsplit(as.character(col1), ";")) %>%
       unnest(col1) %>%
       filter(col1 != "") %>%
       select(col1, col2:col4)

giving:
Source: local data frame [7 x 4]

       col1   col2   col3   col4
      (chr) (fctr) (fctr) (fctr)
    1    X1      5      5      5
    2    X2      8      8      8
    3    X3      4      4      4
    4    X4      4      4      4
    5    X5      4      4      4
    6    X6      1      1      1
    7    X7      1      1      1

Comment: You could specify `fixed = TRUE` to speed it up a bit
Comment: Thanks Sir...
Just a update now, unnest need a cols parameter as:
unnest(cols = col1)
Answer: We can use cSplit
library(splitstackshape)
cSplit(dat, "col1", ";", "long")[col1!=""][duplicated(col4), col4 := as.numeric(0)][]
#    col1 col2 col3 col4
#1:   X1    5    5    5
#2:   X2    8    8    8
#3:   X3    4    4    4
#4:   X4    4    4    0
#5:   X5    4    4    0
#6:   X6    1    1    1
#7:   X7    1    1    0

data
col2 = col3 = col4 <- c(5,8,4,1)
 dat <- data.frame(col1,col2,col3,col4)

Comment: please help me, in case col1 contains only the letter like "" or NA, it will delete that row. How could I keep that rows? Thank you.
Comment: @MinhPhúcHuỳnh  Could you update your post with the new case and the expected output.

String split and duplicate row in R?


Why do we need a null terminator only in strings in C?

Question: I'm taking CS50X. I'm on week 2 now. my question is: why do we need a null character '\0' in strings (aka null terminated char arrays) to mark its end, while we don't need it in normal char arrays or a non-string data type array such as an int array , like while printing both arrays (the null terminated char array and the int array for example) what does mark the end of the second array?
I tried to demonstrate how strings are implemented for myself with some code:
this code worked printing "hi!" in the terminal
this also worked printing the three scores
Why in the first code did we need an additional place in the array for the null character? Couldn't we have used i < 3 instead as we did in the second code? A character array, like any other array, has a specific length, so what changed when we decided to treat string as a character array?
Comment: Could you paste the two code examples into your question as text? Screenshots of code are discouraged since we can't copy and paste them.
Comment: "Couldn't we have used i < 3 instead as we did in the second code?" - well, sure, if you only wanted to be able to deal with arrays of exactly 3 characters.
Comment: I'm sure there's a good duplicate, but I didn't find one
Comment: A `char[2]` is a different type from a `char[3]`, which is a different type from a `char[4]`, etc. If you want to have _just one_ string type that works for any length -- potentially without knowing the length ahead of time so arbitrary content can be handled -- the "just define it in your code so it's known at compile time" approach doesn't work at all; you need to either store the length in memory at runtime (which is the approach some other language use -- traditionally, we call those "Pascal strings"), or signify the end when a terminator is seen (which is how C strings do it).
Comment: See: https://en.wikipedia.org/wiki/Sentinel_value https://en.wikipedia.org/wiki/Null_character and https://en.wikipedia.org/wiki/Null-terminated_string The advantage is simplicity and flexibility (vs. "pascal strings"). In the 3rd link, note the 2nd paragraph of the history section.
Comment: The whole story is that back in ancient times when C was invented, one of the major changes from its predecessors was that arrays did not store their size together with the array data - you can read all the details here: https://www.bell-labs.com/usr/dmr/www/chist.html. At the same time as Unix moved over to C, it also moved away from "fixed length strings" to null terminated strings. For a while it supported both types of strings, until null terminated became the standard. A historical remain from this is the `strncpy` function, which is only to be used for these old fixed length strings.
Answer: The truth is that you don't need null terminators. They're just the convention that the C library chose to represent the end of the string.
For some purposes, it's a terrible choice. An example: when strings might contain nulls. Another: when string length must be computed often; the only way is to traverse the whole (potentially very long) string.
A method without these problems would be to represent a string as a char array (not null terminated) and an explicit length paired with it:
typedef struct string_s {
  char *text;
  size_t len;
} STRING;

And in fact you'll find systems written in C that do this.
The down side is that they can't use standard libraries for concatenation, i/o, etc. They need to supply their own. Also, size_t is up to 8 bytes while a terminating null is only one. When C was invented, that difference was a fairly big deal. In some applications (like very small embedded processors), it still is.
Comment: `char *text; size_t len;`, a pointer and size, is not quite comparable to C's _string_, an array-like entity (not a pointer) as the `struct` adds another level of indirection.  It is that memory management, that even today, adds significant complexity.   Pseudo code `size_t len; char text[len];` is a more comparable idea.
Answer:
Why do we need a null terminator

To indicate the length.

When using functions on 1) a string or 2) an array, the function cannot receive the string or the array.  It can receive a pointer to the string or the array.  It will be a pointer to the first character of the string or array.
Now how does the function know now long the string or array is?

With strings, the function knows the length by inspecting the data and when it detects a null character, it knows that is the end of the string.  No additional parameter was needed to be sent to the function.
foo_string(pointer_to_string_beginning);

With arrays, the caller needs to send the element count of the array to the function in addition to the pointer (in either prescribed order).  The function can not use the data of the array to know the end as no value is reserved to indicate the "end".
foo_array(element_count_of_the_array, pointer_to_array_beginning);

If sending 2 parameters is OK, use arrays and size.  Else for text, use 1 parameter for a string.
For text, strings are the common approach used since the 1970s.

How to return values to indicate a a string or array in the next concern, not yet addressed here.
Answer: Short answer: To be able to store short strings in a bigger array.
Explanation:
Assume you have (one way or another) allocated a memory area capable of holding M characters and you want to store a string into that memory.
If the string has exactly M characters you can print it like:
for (i = 0; i < M; ++i) putchar(str[i]);

In principle it's not problem... You know the value M from the size of the memory area (note: this is only true in some cases but for now let's assume that).
But what if you want to store and later print a string with N (N < M) characters in that memory?
When printing it, you could of cause do:
for (i = 0; i < N; ++i) putchar(str[i]);

But from where do you get the value N?
Sometimes N is 5 (e.g. the string "Hello"), sometimes N is 13 (e.g. the string "stackoverflow"), and so on.
One solution would be to keep N in a seperate variable that you update whenever you change the string.
Another solution would be to use a sentinel value to indicate "End of string" and store that special value as part of the string.
There are pros and cons of both solutions.
The designers of C decided to go with the second solutions. So consequently we must always make sure to include the sentinel (the NUL) when dealing with strings in C.
The print can now be written:
for (i = 0; str[i] != '\0'; ++i) putchar(str[i]);

and it will work no matter what length the string has.
BTW:
Interresting read: https://stackoverflow.com/a/1258577/4386427


Update values of multiple value field programmatically? (Rules action)

Question: I'm trying to create a rule to populate a multiple value order reference field in Drupal Commerce, on checkout complete.
I haven't been able to achieve this through Rules UI, so instead I'm trying to programmatically create the action but can't figure out how to set the actual value.
I simply want to add a reference of the newly created order to the purchased product, while keeping the references already set (in this particular case an order will never contain more than one product).
I have added an order_reference_field (Commerce Order Reference module) to my product, showing checkboxes with multiple values allowed.
Below my code:
function example_rules_action_info() {
  $actions = array();

  $actions['commerce_set_product_order_ref'] = array(
    'label' => t('Link an order to the purchased product'),
    'group' => t('Custom action'),
    'parameter' => array(
      'commerce_line_item' => array(
        'type' => 'commerce_line_item',
        'label' => t('Line item'),
      ),
    ),
  );

  return $actions;
}

function commerce_set_product_order_ref($line_item, $order) {
  if (in_array($line_item->type, commerce_product_line_item_types())) {

    $sku = $line_item->line_item_label;
    $product = commerce_product_load_by_sku($sku);
    $orderID = $line_item->order_id;

    $wrapper = entity_metadata_wrapper('commerce_product', $product);

    $wrapper->field_order_reference /***** What to do here? *******/

    $result = $wrapper->save();

  }
}

EDIT:
I have gotten a little further with the code below.. It works the first time an order reference is set, but the second time i get the following error "The website encountered an unexpected error. Please try again later."
Found the example a bit down this page: https://drupal.org/node/1021556
function example_rules_action_info() {
  $actions = array();

  $actions['commerce_set_product_order_ref'] = array(
    'label' => t('Link an order to the purchased Product'),
    'group' => t('Custom action'),
    'parameter' => array(
      'commerce_line_item' => array(
        'type' => 'commerce_line_item',
        'label' => t('Line item'),
      ),
    ),
  );

  return $actions;
}

function commerce_set_product_order_ref($line_item, $order) {
  if (in_array($line_item->type, commerce_product_line_item_types())) {

    $sku = $line_item->line_item_label;
    $product = commerce_product_load_by_sku($sku);
    $orderID = $line_item->order_id;
    $wrapper = entity_metadata_wrapper('commerce_product', $product);
    $curr_list = $wrapper->field_order_reference->value();

    if (!$curr_list){
        $curr_list = array();
    }

    $curr_list[] = $orderID;
    $wrapper->field_order_reference->set($curr_list);

    $result = $wrapper->save();

  }
}

Comment: Please MOVE the content of your last "edit" to a separate answer, so that you can also mark that answer as "accepted". That way you question will no longer be considered as "unanswered".
Answer: DOH! - Seconds after adding my previous edit i realised what was wrong. Below the final code :)
function example_rules_action_info() {
  $actions = array();

  $actions['commerce_set_product_order_ref'] = array(
    'label' => t('Link an order to the purchased product'),
    'group' => t('Custom group'),
    'parameter' => array(
      'commerce_line_item' => array(
        'type' => 'commerce_line_item',
        'label' => t('Line item'),
      ),
    ),
  );

  return $actions;
}

function commerce_set_product_order_ref($line_item, $order) {
  if (in_array($line_item->type, commerce_product_line_item_types())) {

    $sku = $line_item->line_item_label;
    $product = commerce_product_load_by_sku($sku);
    $orderID = $line_item->order_id;
    $wrapper = entity_metadata_wrapper('commerce_product', $product);
    $curr_list = $wrapper->field_order_reference->value();
    $new_ref = commerce_order_load($orderID);

    if (!$curr_list){
        $curr_list = array();
    }

    $curr_list[] = $new_ref;
    $wrapper->field_order_reference->set($curr_list);

    $result = $wrapper->save();

  }
}


Ordinal variables: integers versus "polynomial contrasts"

Question: By default, R encodes ordinal variables (factor(..., ordered=TRUE)) with "polynomial contrasts". I have read at several places that these are only useful for evenly spaced ordered levels, so this contradicts the very idea of an ordinal varaible (ordered, but no specified spacing).
Moreover, evenly spaced levels can much simpler be encoded as consecutive integers. Is there any use case where an encoding as "polynomial contrasts" makes sense and what is the advantage over an integer representation, e.g., in regression?
Answer: Ultimately all (standard) contrast codings allow to use all degrees of freedom, meaning that polynomial contrasts, as all other standard choices for contrasts, allow a fully flexible modelling of the effects of every single category. Mathematically, at least as far as the fit is concerned, all such contrast choices are equivalent, the difference concerns the interpretation of the estimated coefficients and the standard hypotheses tested.
If you just represent your ordered categories by integers, a linear model will assume that they affect the $y$ linearly, whereas polynomial contrasts allow for all kinds of nonlinear impact (if I'm not mistaken, you can emulate the mathematically same thing by using linear representation and then incorporate a squared, cubic, etc. term). What polynomial contrasts allow for is to test a model in which the impact is just linear against a more complex relationship involving higher order polynomial terms, and then to go on further and test a squared model against one having cubic and maybe even higher order terms.
I wouldn't say that "these are only useful for evenly spaced ordered levels". This is a subtle issue though. On one hand it is true that as a basis for the polynomials the levels are treated as equally spaced. On the other hand, as explained above, this does not restrict the modelling flexibility. The question of interest addressed by polynomial contrasts is what functional form can describe the connection of the ordinal levels with the outcome. One could argue that if a linear term turns out to be enough, the regression behaves as if an even spacing of the ordinal categories makes sense. In this vein, a use could be if it is of interest whether categories work in an evenly spaced linear way, rather than saying that we have to assume in advance that they do. One could for example be interested in the relation between a patient's assessment of their well-being on a scale between 1 and 10 and some measured indicators. One may suspect that the patient's scoring is meant to be in some sense evenly spaced (they are asked for integer numbers after all), but of course there is no calibration, and the score is not in any well defined sense interval-scaled. Using polynomial coding, it may or may not turn out that the relationship between these scores and the measurements is roughly linear, and if this is so, it looks like the evenly spaced integer numbers express well how the patients have used the scale (at least if this isn't very noisy, i.e., low $R^2$).
If, however, a linear term is not enough, in most cases I'd take the polynomial contrasts just as one representation of a flexible categorial model, rather than interpreting them as a squared, cubic etc. relationship between evenly spaced categories. The best thing beyond interpreting a "linear only" relationship is probably to make some qualitative statements about the fitted function (monotonicity, number of local optima, minimum where etc.). Such interpretations do not require categories to be evenly spaced, although I don't want to exclude that in some situations one can come up with a meaningful interpretation of a squared relationship, say.
I should also say that if only qualitative interpretations are given, I don't think that the polynomial coding is more useful than other standard codings, e.g., those that allow to interpret category effects relative to the grand mean or the lowest category, unless the number of categories is high (e.g., a 1-100 rating scale), in which case it may be informative that a low degree polynomial can fit the data well even if nonlinear.
Comment: @frank-harrell `ordSmooth` allows for a mixture of ordinal, categorial (parameter `u`) and metric (parameter `z`) predictors. Moreover it also supports logistic regression, so in principle it should also work for ordinal respones, but I do not see that this is already builtin.
Comment: Thanks for the answer. Just tested this with a linear regression mpg ~ cyl on the R builtin dataset mtcars, and verified that indeed applying "polynomial contrast" to cyl is indeed identical to treating it as a category. And treating cyl as numeric instead leads to a (slightly) smaller $R^2$ and thus a poorer fit, because a linear link is assumed.
Comment: In the frequentist world we don't have many methods tailored for ordinal predictors (unlike the case for ordinal Y).  There are elegant Bayesian solutions.  The R `brms` package's `brm` function automatically properly handles an ordered factor predictor by putting priors on the spacings of the coefficients of the $k-1$ indicator variables for $k$ levels.
Comment: @frank-harrell Thanks for the hint to `brms`. Is the R package `ordPens` not also specifically written to address ordinal predictors?
Comment: It does. Thanks for letting me know about that package. The question I have is whether it handles mixtures of ordinal and non ordinal variables.  Also how can you do regression in general with it, e.g. ordinal Y model or survival analysis?


Kotlin - Array property in data class error

Question: I'm modelling some JSON - and using the following lines
data class Metadata(
        val id: String,
        val creators: Array<CreatorsModel>
)

along with:
data class CreatorsModel (
        val role: String,
        val name: String
)

However keep seeing the error: Array property in data class error.
Any ideas why this is?
FYI, the JSON looks like:
{
"id": "123",
"creators": [{
   "role": "Author",
    "name": "Marie"
    }
  ]
}

Comment: maybe you should try List instead of Array?
Answer: In Kotlin you should aim to use List instead of Array where possible. Array has some JVM implications, and although the compiler will let you, the IDE may prompt you to override equals and hashcode manually. Using List will make things much simpler.
You can find out more about the difference here: Difference between List and Array types in Kotlin
Comment: what about `ByteArray`? I plan to use Entity with image field to save it for the Room
Comment: @user924 Your best bet is to wrap the `ByteArray` in a wrapper and use that wrapper in the data class. That will overcome this limitation.


Limit with terms of convergent series problem

Question: Prove that if a positive series $\sum_{\nu =1}^\infty a_\nu$ is convergent and the sequence $(\nu a_\nu)_{\nu =1}^\infty$ is decreasing, then $\lim_{\nu\to\infty}(\nu\log\nu)a_\nu=0$.
I've been trying to prove this for days, but so far I've only managed to prove that if the limit exists, it is equal to 0.
Could someone give me a hint?
Comment: apanpapan3, thanks for commenting, but why did you delete your comment in https://math.stackexchange.com/questions/2867643 ?
Answer: Suppose $na_n\log n$ does not tend to $0$.
 There exists $n_k$ increasing to $\infty $ such that $a_{{n_k}} n_k \log n_k \geq a$ for all $k$ for some $a>0$. Further, replacing $\{n_k\}$ be  a subequence if necessary we may assume that $$ \log (n_{k+1}-1) -\log n_k >\frac 1 2 \log n_{k+1}$$ for all $k$. Now $$\sum_n a_n=\sum_k \sum_{n_k \leq n <n_{k+1}} \frac 1 n (na_n)\geq \sum_k  \sum_{n=n_{k}}^{n_{k+1}-1} \frac 1 n (n_{k+1}a_{n_{k+1}})>\sum_k ({\log (n_{k+1}-1) -\log n_k}) (n_{k+1}a_{n_{k+1}}) $$. The general term of this series exceeds $\frac a 2$. This makes $\sum a_n$ divergent.
Comment: If you estimate the sum $\displaystyle \sum_{n=n_k}^{n_{k+1}-1} \frac{1}{n}$ by an integral the usual way, you get $\log(n_{k+1}) - \log(n_k)$ which looks nicer, although yours is also correct.
Comment: I mentioned in my answer that this can be ensured by going to a subsequence. We can make $n_{k+1}$ 'much larger' than $n_k$ by going to a subsequence.
Comment: @apanpapan3 Explicitly, $\frac {\log (n-1) -\log n_k} {\log n} \to 1$ so we can make this greater than $\frac 1 2$.
Comment: @apanpapan3 What equivalence are you talking about?
Answer: First notice that $(a_n)_n$ is also decreasing:
$$na_n \ge (n+1)a_{n+1} \implies a_n \ge \frac{n+1}{n} a_{n+1} \ge a_{n+1}$$
Since $\sum_{n=1}^\infty a_n$ converges, by Cauchy condensation test $\sum_{n=1}^\infty 2^na_{2^n}$ also converges.
Also, $(2^na_{2^n})_n$ is decreasing because it is a subsequence of $(na_n)_n$.
Now use this lemma:

Let $(x_n)_n$ be a decreasing sequence of positive numbers such that $\sum_{n=1}^\infty x_n$ converges. Then $\lim_{n\to\infty} nx_n = 0$.

We conclude that $\lim_{n\to\infty} n2^na_{2^n} = 0$.
By scaling, we can assume that $\log = \log_2$.
We have  $\log n \le 2\lfloor \log n\rfloor$ and $n \ge 2^{\lfloor \log n\rfloor}$ so $na_n \le 2^{\lfloor \log n\rfloor} a_{2^{\lfloor \log n\rfloor}}$. Therefore
$$0 \le (n\log n) a_n \le \log n\cdot 2^{\lfloor \log n\rfloor} a_{2^{\lfloor \log n\rfloor}}\le 2\lfloor \log n\rfloor\cdot 2^{\lfloor \log n\rfloor} a_{2^{\lfloor \log n\rfloor}}$$
The right hand side converges to $0$ because it is a constant times a subsequence of $(n2^na_{2^n})_n$ with some repeated terms because $n\mapsto \lfloor \log n\rfloor$ is not strictly increasing.
The squeeze theorem gives $\lim_{n\to\infty} (n\log n) a_n = 0$.
Comment: 1. How do you know that $a_n$ is decreasing so that we can use the Cauchy condensation test? 2. The inequality $n a_n \leqslant 2^n a_{2^n}$ should go the other way.
Comment: @Adayah You are right, of course. I tried to fix the issues, can you have a look now?
Comment: $\mbox{}$Seems fine.
Answer: Preliminaries
The Mean Value Theorem guarantees that
$$
\frac1n\ge\log(n+1)-\log(n)\tag1
$$
we have
$$
\begin{align}
\sum_{k=\left\lfloor\sqrt{n}\right\rfloor}^n\frac1k
&\ge\log(n+1)-\log\left(\left\lfloor\sqrt{n}\right\rfloor\right)\\
&\ge\frac12\log(n)\tag2
\end{align}
$$

The Answer
Suppose that $n a_n\searrow0$ and $\sum\limits_{n=0}^\infty a_n$ converges.
Assume that $\limsup\limits_{n\to\infty}n\log(n)\,a_n\gt0$; that is,
$$
\exists\epsilon\gt0:\forall N\gt0,\exists\,n_N\ge N:n_N\log(n_N)\,a_{n_N}\ge\epsilon\tag3
$$
Since $na_n$ is decreasing, we have that for $k\le n_N$,
$$
\begin{align}
ka_k
&\ge n_Na_{n_N}\\[6pt]
&\ge\frac{\epsilon}{\log(n_N)}\tag4
\end{align}
$$
Therefore, combining $(2)$ and $(4)$, we get
$$
\begin{align}
\sum_{k=\left\lfloor\sqrt{n_N}\right\rfloor}^{n_N}a_k
&\ge\sum_{k=\left\lfloor\sqrt{n_N}\right\rfloor}^{n_N}\frac{\epsilon}{k\log(n_N)}\\
&\ge\frac\epsilon2\tag5
\end{align}
$$
If we choose $N_{j+1}\ge\left(n_{N_j}+1\right)^2$, then
$$
\left\lfloor\sqrt{n_{N_{j+1}}}\right\rfloor\ge n_{N_j}+1\tag6
$$
and so the ranges $\left[\left\lfloor\sqrt{n_{N_j}}\right\rfloor,n_{N_j}\right]$ are disjoint. Thus, by $(5)$,
$$
\begin{align}
\sum_{n=1}^\infty a_n
&\ge\sum_{j=1}^\infty\sum_{k=\left\lfloor\sqrt{n_{N_j}}\right\rfloor}^{n_{N_j}}a_k\\
&\ge\sum_{j=1}^\infty\frac\epsilon2\tag7
\end{align}
$$
Therefore, if $(3)$ is true, the sum in $(7)$ diverges. The contrapositive says that if the sum converges, then
$$
\lim\limits_{n\to\infty}n\log(n)\,a_n=0\tag8
$$


Copy Excel Worksheet from one Workbook to another with twapi

Question: I am trying to combine multiple excel files from one folder one file, copy all sheets from all files to single with below code, But no luck. Can someone help here please....
set file1 {D:\Temp\CombineExcel\Work\1240676493.xlsm}
set file2 {D:\Temp\CombineExcel\Work\1735749199.xlsm}

set xl [ ::twapi::comobj Excel.Application ];
set wb [$xl Workbooks];
set wb1 [$wb Open $file1];
set wb2 [$wb Open $file2];
set f1w1s1 [$str_fil1 WorkSheets]
set f2w2s2 [$str_fil2 WorkSheets]

Comment: Curious. I'd expect `[$wb1 WorkSheets]` so that it's at least using an existing likely-looking variable… and you don't need to put `;` at the end of the line in Tcl (though it's harmless). Can't really say much else though, not enough to answer properly; I'm on the wrong platform so I can't test anything at all and I don't know TWAPI, COM or Excel's object model well enough.
Comment: all sheets or just one ?
Comment: Hi Mkn, I want to keep that option open (Some times some specific sheets, sometime all)
Answer: Assuming you want to copy the sheet1 of file2 in file1 you can do like this :
# Open COm Excel
set excel [twapi::comobj Excel.Application]
$excel DisplayAlerts [expr 0]
set workbooks [$excel Workbooks]

set wb2 [$workbooks Open $file2] ; # Open file2
set wb1 [$workbooks Open $file1] ; # Open file1

# Second file
set ws2 [$wb2 Worksheets]
set worksheetId [$ws2 Item [expr 1]] ; # First sheet of file2
$worksheetId Activate
set range [$worksheetId Cells] ; # select all...
$range Copy

# First file
set ws1 [$wb1 Worksheets]
set lastWsId [$ws1 Item [$ws1 Count]]
set worksheetId [$ws1 -callnamedargs Add After $lastWsId]
$worksheetId Activate

$worksheetId Paste ; # Paste the result in file1 after the last sheet

$wb1 Save ; # Save file1
$excel Quit

# Destroy all objects...
foreach obj [twapi::comobj_instances] {
    $obj -destroy
}

If you want copy an specific sheet you can work with the name [$worksheetId Name]
Comment: Thanks you for your valuable inputs, it solved 90% of problem, but after copying cell excel messing up with formatting, is there any option to preserve source formatting?
Comment: it's works for me , but i tried with simple example (border , background , font) maybe you may contact with the author...
Comment: Is there a way to copy the worksheet instead of the range? I think that might resolve the issue if yes. I don't know enough of the twapi package to give suggestions :(