How to lock Files to avoid deletion using NIO package

Question: I am using NIO File Channel to manage files, and locking them.  So far it works, however when I lock a File using NIO File Lock it locks the file so the file Content cannot be changed. As for example if I try to edit a text file on notepad it will show me the following error message:

And that is the expected result, however if I try to delete the file from windows explorer(I haven't tested on other OS likely will be possible as well) it will allow me, and this is undesired, I would like to know if it is possible to Open a File Handle
Code Used:
private static final byte[] MessageBytes;
static {
    byte tmp[];
    try {
        tmp = "Hello World".getBytes("UTF-8");
    } catch (UnsupportedEncodingException ex) {
        //if fail get the bytes in whatever the java VM charset sets as default
        tmp = "Hello World".getBytes();
    }
    MessageBytes = tmp;
}
private static final String Filename = "Lock_test.txt";

 private static void createFileandLock() {
    Path FilePath = Paths.get(Filename);
    FileChannel OpenFCh;
    try {
        OpenFCh = FileChannel.open(FilePath, StandardOpenOption.CREATE,
                StandardOpenOption.READ, StandardOpenOption.WRITE
        //                    ,StandardOpenOption.APPEND
        );
        System.out.println("File Channel is Open.");
    } catch (IOException err) {
        OpenFCh = null;
    }
    if (OpenFCh != null) {
        FileLock Lock = null;
        try {
            Lock = OpenFCh.lock();
        } catch (IOException err) {
            System.out.println("Unable To Lock the File.");
        }
        try {
            OpenFCh.write(ByteBuffer.wrap(MessageBytes));
            OpenFCh.force(false);
            System.out.println("Message Recorded");
        } catch (IOException ex) {
            System.out.println("Unable To write data into file");
        }
        try {
            // at this point file still locked and open.
            //lets wait for input and meanwhile ask to delete the file.
            System.out.print("Please Try to delete file at: ");
            System.out.println(FilePath.toString());
            System.out.println("Press Enter to Continue");
            System.in.read();
        } catch (IOException ex) {
        }
        if (Lock != null) {
            try {
                Lock.close();
            } catch (IOException ex) {
            }
        }
        try {
            OpenFCh.close();
        } catch (IOException ex) {
        }
    }
}

After further research I notice that using RandomAccessFile Will lock the file avoiding deletion as it creates a  File Descriptor that basically open a Handle on the underline Operative system.
So using the RAF does provide the desired result:

Code Used:
private static void createRAFileandLock() {
    RandomAccessFile RAf;
    try {
        RAf = new RandomAccessFile(Filename, "rw");
    } catch (FileNotFoundException ex) {
        //since is open as RW shold not trigger.
        RAf = null;
    }
    if (RAf != null) {
        FileChannel OpenFCh = RAf.getChannel();
        FileLock Lock = null;
        try {
            Lock = OpenFCh.lock();
        } catch (IOException err) {
            System.out.println("Unable To Lock the File.");
        }
        try {
            OpenFCh.write(ByteBuffer.wrap(MessageBytes));
            OpenFCh.force(false);
            System.out.println("Message Recorded");
        } catch (IOException ex) {
            System.out.println("Unable To write data into file");
        }
         // at this point file still locked and open.
        //lets wait for input and meanwhile ask to delete the file.
        try {
            System.out.print("Please Try to delete file at: ");
            System.out.println(Filename);
            System.out.println("Press Enter to Continue");
            System.in.read();
        } catch (IOException ex) {
        }
        if (Lock != null) {
            try {
                Lock.close();
            } catch (IOException ex) {
            }
        }
        try {
            OpenFCh.close();
            RAf.close();
        } catch (IOException ex) {
        }
    }
}

However I would like to know if it is possible to archive this using only NIO. As Random Access File is on IO package.
Comment: just out of curiosity: what is the problem with using a class that is found in IO package?
Comment: there is no problem, however i would like to avoid using(and or Importing) Other package besides NIO.
Using 'FileChannel.open' open the file channel and using this class also can provide me a lock, however missing the option to open a handle with a 'FileDescriptor' so is more about if is possible to do using only nio, or if is possible to code so it open a handle and avoid a user or other application from deleting the file, other than using RAF or any class within IO package.
Answer: FileLock isn't specified to prevent deletion. It's only specified to interact with other file locks, so you're already deep into platform-dependent behaviour. If RandomAccessFile somehow does what you want you may be stuck with it, but you can't rely on it.
NB of course FileChannel.open() uses a FileDescriptor, handle, etc.
Comment: thanks for your answer.

I am aware that FileLock will not prevent deletion. but it was used as it also provide a wanted feature and behavior.

I fear as much, that there might no be way around this, however is there a option to ensure the FileDescriptor or a handle keep the File "Open" to ensure the file cannot be deleted?, Also hoped that maybe a Special Open Option could be use on this case... hmm maybe I should request as a new feature for JRE? as it might prove to be useful.
Comment: There is nothing except platform dependence that says an open file can't be deleted  in the first place, so it has nothing to do with any API implementation in any language. Every system derived from Unix permits it. So you quest is ill-formed before it starts
Comment: Not everyone using Java cares about crossplatform behavior.
Comment: @NateS It's not just about cross-latform behaviour. *The plaform the OP is presently running on* may not support what he wants.


Windows Server 2008 R2 drops packets

Question: I seem to be having strange problems with my WS2008R2 Active Directory + DNS + DHCP + NAT configuration. It look to be some sort of an issue between DNS, NAT and LDAP.
The first consequence is some sort of packet dropping problem. Every once in a while, the server (acting as default gateway) will drop packets and command will return 'Destination host unreachable'. I have yet to figure out the cause. This seems unrelated to DNS.
C:\Users\Administrator>ping serverfault.com

Pinging serverfault.com [220.127.116.11] with 32 bytes of data:
Reply from 10.0.0.1: Destination host unreachable.
Reply from 220.127.116.11: bytes=32 time=113ms TTL=49
Request timed out.
Reply from 126.96.36.199: bytes=32 time=113ms TTL=49

C:\Users\Administrator>ping 220.127.116.11

Pinging 22.214.171.124 with 32 bytes of data:
Reply from 10.0.0.1: Destination host unreachable.
Reply from 126.96.36.199: bytes=32 time=39ms TTL=49
Reply from 184.108.40.206: bytes=32 time=37ms TTL=49

C:\Users\Administrator>ping 18.104.22.168

Pinging 220.127.116.11 with 32 bytes of data:
Reply from 184.108.40.206: bytes=32 time=36ms TTL=49
Reply from 184.108.40.206: bytes=32 time=36ms TTL=49

So the DNS resolves fine ... but then sometimes 10.0.0.1 drops packets .. just because? Happens intermittently. This was a test done on the server itself, but the clients exhibit pretty much the same behavior, except even DNS fails with them sometimes.
C:\Users\[user]>ping google.com
Ping request could not find host google.com. Please check the name and try again.

C:\Users\[user]>ping google.com

Pinging google.com [18.104.22.168] with 32 bytes of data:
Request timed out.
Reply from 22.214.171.124: bytes=32 time=37ms TTL=49
Reply from 18.104.22.168: bytes=32 time=36ms TTL=49

This will cause HTTP 404 errors, applications complaining about no internet connection, complaining about servers being offline, etc.
It's also reporting, for example
_ldap._tcp.Default-First-Site-Name._sites.[server].ad.[domain].net
No such name

Any help or tips would be very appreciated. :)
Update:
Some server info.
C:\Users\Administrator>ipconfig /all

Windows IP Configuration

   Host Name . . . . . . . . . . . . : [server]
   Primary Dns Suffix  . . . . . . . : ad.[domain].net
   Node Type . . . . . . . . . . . . : Mixed
   IP Routing Enabled. . . . . . . . : Yes
   WINS Proxy Enabled. . . . . . . . : No
   DNS Suffix Search List. . . . . . : ad.[domain].net

PPP adapter RAS (Dial In) Interface:

   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : RAS (Dial In) Interface
   Physical Address. . . . . . . . . :
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes
   IPv4 Address. . . . . . . . . . . : 10.0.0.12(Preferred)
   Subnet Mask . . . . . . . . . . . : 255.255.255.255
   Default Gateway . . . . . . . . . :
   NetBIOS over Tcpip. . . . . . . . : Enabled

Wireless LAN adapter Wireless Network Connection:

   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Linksys WMP600N Wireless-N PCI Adapter wi
th Dual-Band
   Physical Address. . . . . . . . . : 00-25-9C-FF-C1-FC
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes
   IPv4 Address. . . . . . . . . . . : 192.168.1.100(Preferred)
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.1.1
   DNS Servers . . . . . . . . . . . : 10.0.0.1
                                       127.0.0.1
   NetBIOS over Tcpip. . . . . . . . : Enabled

Ethernet adapter Local Area Connection:

   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Realtek RTL8168C(P)/8111C(P) Family PCI-E
 Gigabit Ethernet NIC (NDIS 6.20)
   Physical Address. . . . . . . . . : 00-19-66-88-6A-1F
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes
   IPv4 Address. . . . . . . . . . . : 10.0.0.1(Preferred)
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 0.0.0.0
   DNS Servers . . . . . . . . . . . : 10.0.0.1
                                       127.0.0.1
   NetBIOS over Tcpip. . . . . . . . : Enabled

Tunnel adapter isatap.{B84CD253-70D3-49E5-88F9-102C6B7FCEC0}:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Microsoft ISATAP Adapter
   Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes

Tunnel adapter Local Area Connection* 11:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Teredo Tunneling Pseudo-Interface
   Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes

Tunnel adapter isatap.{D7DFBDDF-7295-43E8-AAD4-4910D79202A9}:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Microsoft ISATAP Adapter #2
   Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes

Tunnel adapter isatap.{6E06F030-7526-11D2-BAF4-00600815A4BD}:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Microsoft ISATAP Adapter #3
   Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes

C:\Users\Administrator>route print
===========================================================================
Interface List
 26...........................RAS (Dial In) Interface
 15...00 25 9c ff c1 fc ......Linksys WMP600N Wireless-N PCI Adapter with Dual-Band
 11...00 19 66 88 6a 1f ......Realtek RTL8168C(P)/8111C(P) Family PCI-E GigabitEthernet NIC (NDIS 6.20)
  1...........................Software Loopback Interface 1
 12...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter
 13...00 00 00 00 00 00 00 e0 Teredo Tunneling Pseudo-Interface
 14...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter #2
 16...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter #3
===========================================================================

IPv4 Route Table
===========================================================================
Active Routes:
Network Destination        Netmask          Gateway       Interface  Metric
          0.0.0.0          0.0.0.0         On-link          10.0.0.1    266
          0.0.0.0          0.0.0.0      192.168.1.1    192.168.1.100    276
         10.0.0.0    255.255.255.0         On-link          10.0.0.1    266
         10.0.0.1  255.255.255.255         On-link          10.0.0.1     11
        10.0.0.12  255.255.255.255         On-link         10.0.0.12    306
       10.0.0.255  255.255.255.255         On-link          10.0.0.1    266
        127.0.0.0        255.0.0.0         On-link         127.0.0.1    306
        127.0.0.1  255.255.255.255         On-link         127.0.0.1    306
  127.255.255.255  255.255.255.255         On-link         127.0.0.1    306
      192.168.1.0    255.255.255.0         On-link     192.168.1.100    276
    192.168.1.100  255.255.255.255         On-link     192.168.1.100    276
    192.168.1.255  255.255.255.255         On-link     192.168.1.100    276
        126.96.36.199        240.0.0.0         On-link         127.0.0.1    306
        220.127.116.11        240.0.0.0         On-link          10.0.0.1    266
        188.8.131.52        240.0.0.0         On-link     192.168.1.100    276
        188.8.131.52        240.0.0.0         On-link         10.0.0.12    306
  255.255.255.255  255.255.255.255         On-link         127.0.0.1    306
  255.255.255.255  255.255.255.255         On-link          10.0.0.1    266
  255.255.255.255  255.255.255.255         On-link     192.168.1.100    276
  255.255.255.255  255.255.255.255         On-link         10.0.0.12    306
===========================================================================
Persistent Routes:
  Network Address          Netmask  Gateway Address  Metric
          0.0.0.0          0.0.0.0      192.168.1.1  Default
===========================================================================

IPv6 Route Table
===========================================================================
Active Routes:
 If Metric Network Destination      Gateway
  1     51 ::1/128                  On-link
  1    306 ff00::/8                 On-link
===========================================================================
Persistent Routes:
  None

Comment: Are you testing from a workstation or from the server itself ? You should post `ipconfig /all` and `route PRINT`. By the output of nslookup it seems you do have a problem with your DNS.
Comment: As mentioned, the first part (Administrator) is server, the second ([user]) is client. I've removed a part on DNS because `nslookup google.com.` resolves correctly, it just assumes by default that you're searching inside the domain if you don't specify the absolute path. I've added the extra info.
Comment: I don't think you should be looking at [tag:dns], [tag:active-directory], [tag:Windows-server-2008-r2] or [tag:ldap] for the source of the problem, it sounds to me like you need to be looking at [tag:networking] problems.
Comment: Well, I've added the tags to imply what kind of a setup it was. It's most likely some Windows Server problem though, since it worked just fine before I added the server on the network. I've added networking.
Comment: My thought was that the subject and tags might scare off people with a bias towards networking skills, which I believe is where your problem lies. Do you have a non domain connected Windows PC/laptop or a Linux or Mac you can connect to the network and test the same issue. It just doesn't seem like a configuration issue that could be anyway related to Active Directory in my opinion.
Answer: The routing shows two gateways, both are used for external connections (network destination 0.0.0.0). If one is not responding then the other one is used. That's why some random packets get dropped.
Try to remove the default gateway from your wired interface (10.0.0.1), this way the routing should always use the other gateway.
Otherwise, you could check the route from the client to 0.0.0.0 and the dns servers on the client.
Comment: Well, I've `route delete 0.0.0.0 10.0.0.1` and now `route print 0.0.0.0` on the server only shows the correct one. The thing is, WS2008 *GUI* for the wired interface doesn't display the gateway, but apparently it persisted in the server configuration after I had removed it there. I'll run some tests to see if the issue disappeared.
Comment: Well, after playing around with some services and applications and restarting the whole thing, it looks like the loss is gone. It would appear that the `Reply from 10.0.0.1: Destination host unreachable.` part really was caused by the bogus route. I thought that removing the gateway from the UI would do it, so I completely forgot to check `route`s. Thanks for the tips! :)

Windows Server 2008 R2 drops packets


Repassar um array de um formulário para PHP através de AJAX

Question: Tenho este formulário:
jQuery
(function($) {
  AddTableRow = function() {

    var newRow = $("
");
    var cols = "";

    cols += '<input type="text" name="dados[][nome]" id="dados[][nome]" class="form-control" value="">	';
    cols += '<input type="text" name="dados[][nome]" id="dados[][nome]" class="form-control" value="">	';
    cols += '<input type="text" name="dados[][nome]" id="dados[][nome]" class="form-control" value="">	';
    cols += '<input type="text" name="dados[][nome]" id="dados[][nome]" class="form-control" value="">	';
    cols += '';
    cols += '<button onclick="RemoveTableRow(this)" type="button"></button></button>';
    cols += '	';

    newRow.append(cols);
    $("#convidados-table").append(newRow);

    return false;
  };
})(jQuery);

Para entender melhor, modifiquei o código... Como eu faria este ajuste para array?
Comment: O ID você pode tirar, ele nunca pode se repetir na página. Quando você clona a linha vai duplicar o ID.
Answer: Você pode fazer assim, com um contador no JS
<input type="text" name="dados[][nome]" class="form-control" value="">
<input type="text" name="dados[][faixaetaria]" class="form-control" value="">
<input type="text" name="dados[][telefone]" class="form-control" value="">
<input type="text" name="dados[][email]" class="form-control" value="">

E no jQuery você pode fazer igual no HTML, sem ID e com os name iguais do formulário.
var cont = 1;
$("#adicionar_convidado").click(function() {
   cont++;
   var campos_novos = "\

 \

 \

 \
            <input type='text' name='dados[nome]["+cont+"]' placeholder='Nome' class='form-control'>
 \

<input type='text' name='dados[faixaetaria]["+cont+"]' placeholder='Faixa Etária' class='form-control'>
 \

<input type='text' name='dados[telefone]["+cont+"]' placeholder='Telefone' class='form-control'>
 \

<input type='text' name='dados[email]["+cont+"]' placeholder='E-mail'  class='form-control'>
 \

<button class='btn btn-default remove' type='button'></button>
 \

 \

 \

";
   $("#dep").append(campos_novos);
});

No meu caso iria retornar:
"dados" => array:4 [
    "nome" => array:2 [
      0 => "A"
      1 => "E"
    ]
    "faixaetaria" => array:2 [
      0 => "B"
      1 => "F"
    ]
    "telefone" => array:2 [
      0 => "C"
      1 => "G"
    ]
    "email" => array:2 [
      0 => "D"
      1 => "H"
    ]
]

Daí o PHP seria:
foreach($dados['nome'] as $key => $value){
    $fe       = $dados['faixaetaria'][$key];
    $email    = $dados['email'][$key];
    $telefone = $dados['telefone'][$key];
    $nome     = $value;
}

Comment: Entendi. EEEEE Code Igniter, só dando dor de cabeça.
Comment: Assim não dará certo, preciso que o retorno seja: array ( 0 ( nome = nome, email = email, telefone = telefone, idade = idade) (1 (nome = nome, email = email, telefone = telefone, idade = idade) ) e assim por diante
Comment: Do jeito que você quer terá que criar um contador. Se for do meu jeito você vai receber no PHP com um Foreach apenas em um campo e utilizará o indíce para pegar os outros.
Comment: Como iria retornar? Neste seu caso
Comment: Nessa sua útima edição, ele vai retornar em arrays separados por isso preciso criar o contador dentro das divs, ou seja, a primeira linha é 0, as outras, 1, 2, 3... ai daria certo, note que é tabela e não div. Por isso modifiquei minha questão
Comment: Eu fiz do jeito que você precisa, com um contador.
Comment: Fiz um pouco diferente, mas usei a logica do cont =1, cont++, pra fazer a contagem na hora de incluir a row, deu certo, obrigado! :) Um próspero 2017 pra você.
Comment: Neste caso fica mais fácil pra inserir usando o codeigniter:     [dados] => Array
        (
            [0] => Array
                (
                    [nome] => teste1
                    [faixaetaria] => 33
                    [telefone] => email@example.com
                    [email] => (41) 99 99999999
                )


call a function and return result to existing data frame

Question: ## Import airport data
airports <- read.csv("https://raw.githubusercontent.com/jpatokal/openflights/master/data/airports.dat", header = F)

library(geosphere)
## Calculate matrix of differences in km
distance.matrix <- distm(x = airports[,c("V8", "V7")],  y = airports[,c("V8", "V7")])/1000
## This may take a while, and will generate a matrix 8107 by 8107, about 0.5gb in size.

## Rename dimensions to airport codes
rownames(distance.matrix) <- airports$V5
colnames(distance.matrix) <- airports$V5

## Example: km between Gatwick and Heathrow
distance.matrix['LGW', 'LHR']

al_route <- read.csv("https://raw.githubusercontent.com/jpatokal/openflights/master/data/routes.dat", header = F)
#Example 2B,410,LGW,2965,LHR,2990,0,CR2

I am trying to pass 4th column (LGW) and 6th column (LHR) of each row in al_route and add the result (distance btw LGW and LHR) to the new column of al_route.  I am having trouble figuring out, I would expect my al_route will be like
v1, v2, v3, v4, v5, v6, v7, v8, v9 (new col)
2B,410,LGW,2965,LHR,2990,0,CR2, distance

Comment: Other than `V8`, all columns are strings. Try `grep("\\D", al_route$V4)` to see how many rows have a non-number in the `V4` field, and then `al_route[39 + -2:2,]` (where `39` is the first when I ran it) to see that `al_route$V4[39]` is the string `\N` (and in fact all non-number `V4` are the same).
Comment: You need to [merge/join](https://stackoverflow.com/q/1299871/3358272) (also https://stackoverflow.com/q/5706437/3358272, https://stackoverflow.com/q/34598139/3358272) the lat/lon from your `airports` object into your `al_routes` data. I suggest before you go too far that you name your columns, keeping them the obscure `V#` names will drive you crazy and open you up to many ways of "off-by-one".
Answer: You need to merge/join your data so that you can get the longitude/latitude from airports into your al_route frame. For guidance on this, see How to join (merge) data frames (inner, outer, left, right), What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?, (data.table) Left join using data.table.
To really do all of this right, though, we need to fix a couple of other things here. All together:

Name your columns using https://openflights.org/data. It is certainly possible to go without this step, but not doing so really opens you up to choosing incorrect columns for something.
Fix the airports ID field (column 1), it should be character (to match the al_route source/dest airport IDs) but is loaded as integer.
Merge/join the data. Twice, once to get the lon/lat of the source airport, once for the destination.
Do the calc, but ... don't use distm, it will calculate every possible distance between ever set of pairs in the whole frame. On my system with 64GB of RAM, it crashed me hard due to the over-allocation of memory. You only want row-wise distances (which R and geosphere do quickly/efficiently in a vectorized fashion), so we'll switch from distm to distHaversine. (If you want more accurate, there's also distVincentyEllipsoid. If you don't know the difference, it's really unlikely you'll need it.)

Base R
Steps:
# 0. Download
airports <- read.csv("https://raw.githubusercontent.com/jpatokal/openflights/master/data/airports.dat", header = F)
al_route <- read.csv("https://raw.githubusercontent.com/jpatokal/openflights/master/data/routes.dat", header = F)

# 1. Name them
names(airports) <- c("AirportID", "Name", "City", "Country", "IATA", "ICAO", "Lat", "Lon", "Alt", "Timezone", "DST", "Tz", "Type", "Source")
names(al_route) <- c("Airline", "AirlineID", "S_Airport", "S_AirportID", "D_Airport", "D_AirportID", "Codeshare", "Stops", "Equipment")

# 2. Ints to strings
airports$AirportID <- as.character(airports$AirportID)

# 3. Merge/join and 4. Calculate the distance between source/dest airports.
al_route <- al_route |>
  merge(setNames(airports[, c("AirportID", "Lon", "Lat")], c("S_AirportID", "S_Lon", "S_Lat")),
        by = "S_AirportID", all.x = TRUE, sort = FALSE) |>
  merge(setNames(airports[, c("AirportID", "Lon", "Lat")], c("D_AirportID", "D_Lon", "D_Lat")),
        by = "D_AirportID", all.x = TRUE, sort = FALSE) |>
  transform(Dist = geosphere::distHaversine(cbind(S_Lon, S_Lat), cbind(D_Lon, D_Lat)))
head(al_route)
#   D_AirportID S_AirportID Airline AirlineID S_Airport D_Airport Codeshare Stops Equipment    S_Lon    S_Lat   D_Lon   D_Lat      Dist
# 1        3964        2975      QN       426       SVX       EVN               0       735 60.80270 56.74310 44.3959 40.1473 2196701.4
# 2        3964        2975      U6      5234       SVX       EVN               0       320 60.80270 56.74310 44.3959 40.1473 2196701.4
# 3        3964        2964      SU       130       ROV       EVN               0       319 39.92472 47.49389 44.3959 40.1473  892801.9
# 4        3964        1613      UA      5209       VIE       EVN         Y     0   320 321 16.56970 48.11030 44.3959 40.1473 2377245.8
# 5        3964        4078      S7      4329       OVB       EVN               0       320 82.65070 55.01260 44.3959 40.1473 3257169.1
# 6        3964        4330      EP      2923       IKA       EVN               0       100 51.15220 35.41610 44.3959 40.1473  793735.0

The results are in meters.
dplyr
(After naming and int-to-string.)
library(dplyr)
al_route <- tibble(al_route) %>%
  left_join(select(airports, S_AirportID = AirportID, S_Lon = Lon, S_Lat = Lat), by = "S_AirportID") %>%
  left_join(select(airports, D_AirportID = AirportID, D_Lon = Lon, D_Lat = Lat), by = "D_AirportID") %>%
  mutate(Dist = geosphere::distHaversine(cbind(S_Lon, S_Lat), cbind(D_Lon, D_Lat)))

Comment: many thanks for your help !!! r2evans.  much appreciated!!!


The "on $\left\{ \tau <\infty \right\}$" in the Strong Markov Property

Question: The strong Markov property is often formulated as $$P[\theta _{\tau}X\in  A\mid \mathscr
F_{\tau}]\overset{\text {a.s on }\left\{ \tau <\infty \right\}
}{=}P_{X_\tau}(X\in A)$$

What exactly does "on $\left\{ \tau <\infty \right\}$" mean? Intuitively it seems we're conditioning on this event, but I'm unsure.
Is there a way to restate the strong Markov property as a conditional independence?

Edit: Since, as Did points out, the questions are unrelated, I'll ask the second one separately.
Answer: Two unrelated questions, for the first one, the assertion that "$X=Y$ almost surely on $A$" means that the event $[X\ne Y]\cap A$ has probability zero.


How to expose TypeORM Repository to other modules in NestJS

Question: I moved all database related operations into a standalone module:
@Module({
  imports: [
    TypeOrmModule.forFeature([
      PostRepository,
      UserRepository,
      CommentRepository,
    ]),
  ],
  exports: [PostRepository, UserRepository, CommentRepository],
  providers: [PostsDataInitializer],
})
export class DatabaseModule {}

But in other modules, when I imported the DatabaseModule and tried to inject PostRepository in service class, I got the following error.
Nest cannot export a provider/module that is not a part of the currently processed module (DatabaseModule).
Please verify whether the exported PostRepository is available in this particular context.

Comment: @ErangaHeshan Of course, it can take an array of *custom* Repository classes, see [Nestjs docs database#custom-repository](https://docs.nestjs.com/techniques/database#custom-repository).
Comment: How did you import Repositories directly? For example, from where did you import `PostRepository`? AFAIK `TypeOrmModule.forFeature` method takes an array of entity classes as the first param, not an array of repositories.
Comment: @ErangaHeshan Resolved it myself, see below.
Comment: Wow... I didn't know that you can import repositories directly.
Answer: Resolved it myself after reading some of my Angular codes, just need to export the TypeOrmModule in the DatabaseModule.
@Module({
  imports: [
    TypeOrmModule.forFeature([
      PostRepository,
      UserRepository,
      CommentRepository,
    ]),
  ],
  exports: [TypeOrmModule],
  providers: [PostsDataInitializer],
})
export class DatabaseModule {}


Question about Sui Zhen Lin's proof for inequality $\sqrt{\frac{a^2}{9b^2-8b+4}}+\sqrt{\frac{4b}{a+4}}\leq 1$ with positive numbers $a,b$ so $a+b=1$

Question: given two positive numbers $a, b$ so that $a+ b= 1$

Sui Zhen Lin ; @szl6208 gave a very beautiful proof for the following inequality
$$\sqrt{\frac{a^{2}}{9b^{2}- 8b+ 4}}+ \sqrt{\frac{4b}{a+ 4}}\leq 1$$
Source: AoPS/@szl6208_ on.AoPS

Proof. We have
$$\sqrt{\frac{a^{2}}{9b^{2}- 8b+ 4}}\leq\frac{\sqrt{a\left ( 9b^{2}- 8b+ 4 \right )\cdot a\left ( a+ 1 \right )^{2}}}{\left ( a+ 1 \right )\left ( 9b^{2}- 8b+ 4 \right )}\leq\frac{a\left ( 9b^{2}- 8b+ 4 \right )+ a\left ( a+ 1 \right )^{2}}{2\left ( a+ 1 \right )\left ( 9b^{2}- 8b+ 4 \right )}$$
$$\sqrt{\frac{4b}{a+ 4}}\leq\frac{\sqrt{4b\left ( a+ 4 \right )\cdot\left ( 2b+ 2 \right )^{2}}}{\left ( a+ 4 \right )\left ( 2b+ 2 \right )}\leq\frac{4b\left ( a+ 4 \right )+ \left ( 2b+ 2 \right )^{2}}{2\left ( a+ 4 \right )\left ( 2b+ 2 \right )}$$
Hence, we need to prove that
$$\frac{a\left ( 9b^{2}- 8b+ 4 \right )+ a\left ( a+ 1 \right )^{2}}{2\left ( a+ 1 \right )\left ( 9b^{2}- 8b+ 4 \right )}+ \frac{4b\left ( a+ 4 \right )+ \left ( 2b+ 2 \right )^{2}}{2\left ( a+ 4 \right )\left ( 2b+ 2 \right )}\leq 1$$
$$\Leftrightarrow RHS- LHS= \frac{a\left ( ab+ 11a+ 1 \right )\left ( a- b \right )^{2}}{\left ( a+ 1 \right )\left ( 9b^{2}- 8b+ 4 \right )\left ( a+ 4 \right )\left ( b+ 1 \right )}\geq 0$$
wait a minute, actually
$$RHS- LHS- \frac{a\left ( ab+ 11a+ 1 \right )\left ( a- b \right )^{2}}{\left ( a+ 1 \right )\left ( 9b^{2}- 8b+ 4 \right )\left ( a+ 4 \right )\left ( b+ 1 \right )}= \left ( a+ b- 1 \right )f\left ( a, b \right )= 0$$
but how.. why is that so perfect ? I think there maybe are solutions constructed by substitutions like $g\left ( a \right )- g\left ( 1- b \right )\!, g\left ( 2a \right )- g\left ( a+ 1- b \right )\!= \left ( a+ b- 1 \right )f\left ( x \right ).$ What's the best perfect substitution here ? Someone teaching me, huh ?
Comment: First of all, you copied the inequality wrong.
Comment: @haidangel Yes, I saw similar things before. But I forget the examples.
Comment: @haidangel Let $F = \mathrm{numer}(\mathrm{RHS} - \mathrm{LHS})$. Then let $G = quo(F, a+b-1, b)$ and $H = rem(F, a + b - 1, b)$. Then $F = H + (a+b-1)G$. Here $H = 2a(-a^2 +12a + 1)(-1+2a)^2 = 2a(ab + 11a + 1)(a-b)^2$.
Comment: @WhatsUp, my fault, I edited it, thanks for your comment.
Comment: @RiverLi, thanks for your valuable comment.
Answer: Using algebra.
From the constraint $b=1-a$. So, we face
$$f(a)=\sqrt{\frac{a^2}{9 a^2-10 a+5}}+2 \sqrt{\frac{1-a}{a+4}}$$
$$f'(a)=\frac{5-5 a}{(9 a^2-10 a+5)^{3/2}}-\frac{5}{\sqrt{1-a} (a+4)^{3/2}}$$
Square and factor; the numerator is just
$$(2 a-1) (5 a-1) \left(a^2-a+1\right) \left(73 a^2-118 a+61\right)$$ So, the derivative only cancels for $a=\frac 15$ and $a=\frac 12$. The second derivative test shows the the first is a minimum and the second a maximum. So, we have
$$f\left(\frac{1}{5}\right)=\frac 32\sqrt{\frac{3}{7}} \qquad \text{and} \qquad f\left(\frac{1}{2}\right)=1$$
Around $a=\frac 12$, we have
$$f(a)=1-\frac{20}{27} \left(a-\frac{1}{2}\right)^2-\frac{1480}{729}
   \left(a-\frac{1}{2}\right)^3+O\left(\left(a-\frac{1}{2}\right)^4\right)$$
Comment: I see, thank U.


What may cause TCP / HTTP request's delay / lag

Question: We have a device that sends POST requests or TCP messages in fixed intervals, with a JSON payload, through the internet to our server running a node application, on another location.
The JSON payload has a timestamp and some other values. We compare that timestamp to the server's timestamp to calculate the time difference, that we call lag.
The interval is 100ms. What we experience, is that initially, the lag is under 200ms.
We let the system run for a few days and we observe the lag is increasing, after 2-3 days it is 2000 - 3000ms, and increasing further .. after 6 days around 6000ms.
Once we restart the server process the lag is back to normal, so I assume the sender is OK. This happens with both, the POST requests implementation, and the TCP messages implementation.
Does anyone have any idea why this may happen, or how to narrow down the problem?
Comment: As AlexD indicates server and client clocks can be different. To check timings it's best to take begin/end times on the same machine.
Comment: Could you try manually triggering/timing the message on day 1 vs day 3 and comparing the performance? You'd be running it manually, so you'd want to ignore the timestamps/logging in favor of visually watching the performance.  This would help narrow down whether the problem is due to synchronization (if manual run is fast) vs. actual lag (if manual run is slow)?
Comment: If possible, setup a test device-server pair in a controlled environment, close to each other and see if the problem persists. It will let you eliminate the network aspect of the problem and should help narrow down the issue if you suspect that the routing over the Internet contributes to the problem.
Comment: You should also measure the round-trip time, since this takes two measurements from a single clock source, any clock mismatch / error / skew cannot be confused with delay / latency.
Comment: The client is a device that has it's own OS.
I have tried to emulate the device, but was not able to reproduce the problem.
Round trip time is fairly low, usually under 20ms.

Sine the reproduction takes days, the process of finding this is relative slow.
Answer: Do you have clocks on both server and sender synchronized?
1 second per day isn't unusual clock drift.
Comment: @rtaft it is possible that they are using some imprecise clock (`setInterval` ?) within their service process which drifts over time. Or they are restarting the process by restarting the server which does `ntpdate` at the boot but doesn't run `ntpd` service.
Comment: `Once we restart the server process the lag is back to normal` suggests otherwise.
Comment: @AlexD: It shouldn't be due to imprecise interval, since they're sending the server timestamp in the payload.  Interval drift would also drift the included timestamp.  However, clock drift is a very real possibility, especially if OP is using a virtual/cloud server rather than a dedicated machine.
Comment: @Brian, we don't know how they are calculating their timestamps. They can get system time once at the start and then add intervals.
Comment: We get the date via javascript `new Date()` on the server.
Clock drifting is unlikely, but I'll keep it in mind.
Answer: This would indicate what's known as a resource leak. Something in your application is slowing down processing over time as a queue or memory or some other resource builds up.
I'd recommend adding instrumentation to your NodeJS code to track any internal queues, memory allocated, database lookups, etc. Log all the things so you can start to identify where the bottleneck is.
If you're running in the cloud there are good tools to help instrument code, such as AWS X-Ray.
Comment: Thanks.
I will double-check my code.


Wordpress 'Failed to write wp-config' I've done all the Chowns

Question: I am on a mission to install wp-deploy on my local installation of linux mint. I had a wordpress working in xampp via the bitnami plugin but wp-deploy needed to go to htdocs.  I began getting permission errors like crazy.  I am in day 4 of complete madness which last night resulted in me somehow accidentally corrupting my system files (maybe I chowned myself out of them but i dont think I touched anything besides the lampp folders) and having to reinstall mint so all further actions are taking place on a blank slate.
What I tried before the wipe:

install wp-deploy in xampp htdocs: Fought permissions so long I forgot all of what I tried but ended up wondering if maybe the issue was xampp so..
gutted xampp and installed mysql, php, apache2 and phpmyadmin individually. After much debugging it ran and I was able to serve an html file. However when I set up wordpress it did not have access to it's own directory. Spent a bunch of time Chowning around and it seemed if I got one thing access I denied another thing. Then it all blew up and I got the blue login screen and went into recovery/wipe mode.

NEW INSTALL ATTEMPTS
To reduce the number of variables I decided I would install regular old wordpress as I do not think the issue is related to wp-deploy.
This is what I've done today:
-Installed Xampp and dragged wordpress into htdocs/myprojectname/
After navigating to localhost/myprojectname/wordpress/wp-admin I was presented with the setup form. Got error 'failed to write wp-config'
-Chown -R www-data:myuser ./lampp/
Caused mySql to get permission denied error in the xampp control panel
-Gut Xampp, try again
Again, failed to write wp-config so this time I..
-Chowned only the wordpress folder using www-data
-still fails so I restart xampp
-Chowned only the wordpress folder using www-data:myuser
-still I get failed to write wp-config
-Chowned the directory containing the site just inside htdocs as my user
-same error
All of my google-fu takes me to posts that resolve when someone chowns the directory. Either I am experiencing a different error or I am doing something wrong.  I am desperate. Help me obi-wan kenobi. You are my only hope.
-------UPDATE-------
Some other posts recommend building wp-config manually. The reason I haven't been doing this is because the underlying issue I want to solve is that wordpress has not been able to write to it's own folder and therefore cannot install plugins or do anything besides sit there.  I was making the assumption that the wp-config error indicated the same permissions fight I had been in since before the wipe. I decided to manually build wp-config and it was as I thought, wordpress cannot install plugins.
-------UPDATE-------
I have chmod 777ed the directory and still no go.
Comment: I sympathize,  but we can't help you without technical details.   You could start with an `ls -l` on the directories or sample files in question and the desired owner and permissions.
Comment: Two things: are you certain www-data is the name of the server group? In my Mac XAMPP install, it is daemon. Second, you should be chowning user:group and the directory will need to be writeable by group, so myuser:www-data instead of the other way around. Give that a whirl....
Comment: i used a grep to be certain that www-data was indeed the name apache2 was running under.
Comment: Dan Farrell,  drwxr-xr-x  5 root :root is the default permissions of htdocs. Above I explain that I have chowned and chmodded them into many configurations so im not sure what information you are looking for. I took screenshots that I didnt post verifying each of the permissions configurations that I tried. But wouldn't chmod 777 effectively bypass this as a potential problem despite being bad practice for production?
Answer: Best to Used LAMP stack instead of XAMMP
Comment: Thank you for the response but I did try that. I was running Xampp -it failed, so I installed LAMP and it failed in the same way.
Comment: what version of WP are you trying to install?
Comment: the most recent one. I went and pulled the zip from wordpress.com.  I've tried several downloads and experienced the same issue with the wp-deploy Installation I pulled from git
Comment: Im curious though, can you be more specific about Lamp over Xampp? I tried both because I thought maybe Xampp had custom magic happening that was making the problem harder to predict, but switching to Lamp did not fix it. It was during the Lamp phase that I somehow killed my install and had to start over and I just went back to Xampp for the ease of it. But understanding the difference might help me tease this apart.
Answer: Change ownership and group of your project folder
This will help you to solve the write problem in wp_config.php
<code> 1.sudo chown daemon /opt/lampp/htdocs/[project_name]
 2.sudo chgrp daemon /opt/lampp/htdocs/[project_name]
</code>


Material-ui Table Server side Pagination in Reactjs

Question: I need material-ui pagination sorting and filtering using server side. Can anyone help ?
Answer: Can't build a solution from scratch for you - please consider providing some code you have written that we can look at.

Below is a example of what your request can look like, your backend will then need to
A simple way to achieve this is to shape your request like this:
<code>// This is a sample structure - don't just copy and paste. Adjust it to your needs
{
    "page" : 1,
    "pageSize" : 25,
    "filters" : [
        {
            "field" : "anyFieldName",
            "direction" : "ASC"
        }
    ],
    "sortBy" : "date"
}
</code>
And your server which will talk to your data store will parse and use the above qualifiers to sort, filter, and limit the size.
Comment: mui-datatables Solved the issue thank you


Por que essa calculadora em php não está funcionando?

Question:
<form role="form" action="pratica_fazer_calculadora.php" method="get">
    <input type="number" placeholder="Digite um número" name="primeiro_numero"/>
    <select>
        <option value="1">Soma</option>
        <option value="2">Subtração</option>
        <option value="3">Divisão</option>
        <option value="1">Multiplicação</option>
    </select>
    <input type="number" placeholder="Digite um número" name="segundo_numero"/>
    <button type="submit">Ver resultado</button>
</form>

    <?php
      $num_1 = $_GET ['primeiro_numero'];
      $num_2 = $_GET ['segundo_numero'];

      $operacao[1] = 1;
      $operacao[2] = 2;
      $operacao[3] = 3;
      $operacao[4] = 4;

      $resultado = null;

      if($operacao[1]){
          $resultado = ($num_1 + $num_2);
      }
      echo $resultado;

    ?>

O interessante é que não aparece nenhuma mensagem de erro.
Comment: "_É como se ele pegasse os dados e sumisse com eles._".. rachei! rs :D
Comment: O que exatamente não está funcionando? Que erro retorna?
Comment: Ai está o problema. Simplismente não aparece nenhuma mensagem de erro. É como se ele pegasse os dados e sumisse com eles.
Comment: A soma está acontecendo, se vc quer que as outras operações funcionem, vc precisa definir condições para elas tb
Comment: Não sei quanto a você. Mas aqui o resultado não é impresso na tela. Na sua ele aparece?
Comment: Aqui funcionou, mas tem algumas coisas estranhas nessa calculadora, não sei se é apenas um teste, mas há muita coisa desnecessária que pode ser simplificada, vou postar um exemplo
Comment: @Bacco eu testei o codigo dele aqui, e a soma(unica operação) funcionou
Comment: @Shinchila_Matadora funciona no sentido de que vai somar incondicionalmente, pois o valor do item 1 do array é 1. Na prática "parece que funciona" apenas. Seria como você fazer um `echo 3` e dizer que funciona sempre que você testa com 1 + 2 ...
Answer: Não funciona por não ter sido programada para funcionar.
Antes de mais nada, vamos por um nome no select e consertar o item 4:
<select name="operacao">
    <option value="1">Soma</option>
    <option value="2">Subtração</option>
    <option value="3">Divisão</option>
    <option value="4">Multiplicação</option>
</select>

Depois, no PHP:
<?php
  $num_1    = $_GET ['primeiro_numero'];
  $num_2    = $_GET ['segundo_numero'];
  $operacao = $_GET ['operacao'];           // recuperamos a operação

  if ($operacao == 1) {                     // e comparamos para ver qual usar
      $resultado = ($num_1 + $num_2);
  } else if ($operacao == 2) {
      $resultado = ($num_1 - $num_2);
  } else if ($operacao == 3) {

     // ... vai repetindo o elseif e fazendo as operações corretas ...
  }
  echo $resultado;

?>

Não troquei o if por switch por que entendo que está aprendendo, mas recomendo usar no futuro.
Answer: Então, fiz algumas alterações no código e finalizei o arquivo.
Coloquei uma validação para o $_GET para não dar erro quando você entra na página.
E adicionei um switch para realizar as operações, está funcionando normalmente.

<form role="form" action="pratica_fazer_calculadora.php" method="get">
    <input type="number" placeholder="Digite um número" name="primeiro_numero"/>
    <select name="operacao">
        <option value="1">Soma</option>
        <option value="2">Subtração</option>
        <option value="3">Divisão</option>
        <option value="4">Multiplicação</option>
    </select>
    <input type="number" placeholder="Digite um número" name="segundo_numero"/>
    <button type="submit">Ver resultado</button>
</form>

<?php
if (isset($_GET) && !empty($_GET)) {
   $num_1 = (double)isset($_GET ['primeiro_numero']) ? $_GET ['primeiro_numero'] : 0;
   $num_2 = (double)isset($_GET ['segundo_numero']) ? $_GET ['segundo_numero'] : 0;

    $resultado = null;

switch ($_GET['operacao']) {
    case 1:
        $resultado = ($num_1 + $num_2);
        break;
    case 2;
        $resultado = ($num_1 - $num_2);
        break;
    case 3;
        $resultado = ($num_1 / $num_2);
        break;
    case 4;
        $resultado = ($num_1 * $num_2);
        break;
}

    echo 'O Resultado é : ' .$resultado;
}
?>

Answer: Fiz de uma forma diferente dos companheiros acima só por desencargo de consciência, e mostrar outras possibilidades também.
Ao invés de definir um value direto no <option>, definir que a operação aconteça de acordo com o nome que esta dentro dos <option> disponíveis:

<form role="form" action="teste2.php" method="get">
    <input type="number" placeholder="Digite um número" name="primeiro_numero"/>
    <select name="operacao">
        <option>Soma</option>
        <option>Subtração</option>
        <option>Divisão</option>
        <option>Multiplicação</option>
    </select>
    <input type="number" placeholder="Digite um número" name="segundo_numero"/>
    <button type="submit">Ver resultado</button>
</form>

    <?php
      $num_1 = $_GET ['primeiro_numero'];
      $num_2 = $_GET ['segundo_numero'];
      $operacao = $_GET['operacao'];

      if($operacao == "Soma"){
          $resultado = ($num_1 + $num_2);
          echo $resultado;

      } else if($operacao == "Subtração"){
          $resultado = ($num_1 - $num_2);
          echo $resultado;

      } else if($operacao == "Divisão"){
          $resultado = ($num_1 / $num_2);
          echo $resultado;

      } else if($operacao == "Multiplicação"){
          $resultado = ($num_1 * $num_2);
          echo $resultado;
      }
    ?>


Is there a tool that can tell me how a subset is different from a whole (in terms of features)

Question: Is there a tool/technique where we can specify a subset of tuples (of feature values that are real numbers) from an overall set and ask how this subset could be anomalous? (i.e., what are the key feature values that distinguishes this subset, and how)
For example: Feature average F1 in subset is 2 stddev higher than in overall set
Another exmaple: 40% of F2 values are non-zero in subset, but only 10% are non-zero in overall set.
etc. ...
Answer: If your data is numerical, you can judge based on mean,median,stdev, etc.
You can also use clustering algorithms such as K-means and compare the average distance for both datasets.
You can also use Hierarchical Clustering and compare the datasets visually. Here is a good python code to visualize the dendograms.
SciPy Hierarchical Clustering and Dendrogram Tutorial


Further terms of Taylor expansion for improved inequalities?

Question: Background: We know the classical exponential inequality
\begin{align*}
1 + x \le e^x \qquad \text{or} \qquad x \le e^{x - 1}
\end{align*}
Taking $x_i = y_i/\overline{y}$, where $y_i \ge 0$ and $\overline{y}$ is the arithmetic mean, and multiplying out the second form, we yield
\begin{align*}
\frac{\prod_{i=1}^{n}y_i}{\overline{y}^n} \le \exp\left(\frac{\sum_{i=1}^{n}y_i}{\overline{y}} - n\right) = 1
\end{align*}
And this yields a proof of the arithmetic-means and geometric-means (AM-GM) inequality.
An improved exponential inequality: We also have the exponential inequality
\begin{align*}
1 + x + \frac{x^2}{2} + \frac{x^3}{6} \le e^x
\end{align*}
If we substitute $y = 1 + x + \frac{x^2}{2} + \frac{x^3}{6}$, we get the equivalent form
\begin{align*}
y \le e^{g(y)}
\end{align*}
where
\begin{align*}
g(y) = \left(\sqrt{9y^2 - 6y + 2} + 3y - 1\right)^\frac{1}{3} - \left(\sqrt{9y^2 - 6y + 2} + 3y - 1\right)^{-\frac{1}{3}} - 1
\end{align*}
is the inverse function expressing $x$ in terms of $y$.
Can we derive other inequalities? From here, there are many directions we may take with our given inequality, but due to the non-linear nature of $g(y)$, a direct trick of normalization as in the AM-GM proof will yield no immediate discoveries.
This post is meant to be very open to discuss possible inequality sharpenings from the cubic-Taylor expansion inequality above. Some observations:

$(g(y) + 1)^3 = -3(g(y) + 1)$
$[6y-2]_+^\frac{1}{3} - [6y-2]_+^{-\frac{1}{3}} - 1 < g(y) \le ([6y-2]_+ + 1)^\frac{1}{3} - ([6y-2]_+ + 1)^{-\frac{1}{3}} - 1$, where $[x]_+ = \max(x, 0)$.

Have fun!
Answer: By your idea we can get for example the following inequality.

Let $a$, $b$ and $c$ be positive numbers such that $abc=1$.
Prove that:
$$(a+b)^{a+b}+(b+c)^{b+c}+(c+a)^{c+a}\geq4(a+b+c).$$


Save a format for a node body

Question: How do I save the format used for a node body?
I am using the following code, but it doesn't work.
$article = Node::create(array('type' => 'article'));
$article->setTitle($node->title);
$article->set('body', "My body...");
$article->setPublished(TRUE);
$article->body->format = 'full_html';
$article->save();

How can I achieve this?
EDIT:
Fixed:
Right code:
$article = Node::create(array('type' => 'article'));
$article->setTitle($node->title);
$article->body->value = $node->body;
$article->body->format = 'full_html';
$article->setPublished(TRUE);
$article->save();

Comment: Clarify "does not work", what did you expect and what happens? this looks fine to me, setting the body twice, once with set() and once directly is a bit strange, I'd suggest either pass both value and format to set() or use body->vlue = 'My body'..
Comment: Please don't incorporate the answer into the question. Please add a full answer and mark it as accepted.
Comment: I would also not use the `Node` class directly. The class handling the node entity could be different. There is `entity_create()`.
Comment: @Berdir My Post was edited :( the line what does not work is `$article->body->format = 'full_html';` when I save the node everything were saved except body->format.
Comment: have a look at this link will answer your question http://stackoverflow.com/questions/24172791/how-to-programmatically-create-a-node-in-drupal-8
Answer: // $node is supposed to be previously defined node object.
$article = Node::create(array(
  'type'     => 'article',
  'langcode' => 'en,
  'title'    => $node->title->value,
  'body'     => ['value' => $node->body->value, 'format' => 'full_html'],
  'status'   => 1,
));
$article->save();

This is the code if in case, anyone wants it.
Answer: You left out ->value: it should be $article->setTitle($node->title->value); but also $node->body->value I think. This likely throws an exception as a result and then something it eats it up so you don't get an error but it's not working indeed.
Comment: `$node` is a object stdClass that I created.
Answer: For an existing node, you can set the body with format simply as follows:
$node->body = array('format' => 'full_html', 'value' => $body);
$node->save();

Save a format for a node body


one item for 5 positions

Question: I have a table. And an item.
How can I use only one Item to fill part of the table?
If I set item to one position and then take item, I lose text at that position.
And use lots of items is not comfortable.
QTableWidgetItem *Type = new QTableWidgetItem;
if( line.contains("some"))
{
     Type->setText("some");
     ui->tableWidget->setItem(i, 0, Type);
}
else if( line.contains("shi"))
{
     Type->setText("shi");
     ui->tableWidget->setItem(i, 0, Type);
}
ui->tableWidget->takeItem(i, 0);

Comment: You opened 3 topics for almost the same subject. I saw that you're a beginner in Qt. I advise you to read some documentation and example, understand why it is written like this before trying your own custom implementation such as using only one item to initialize an entire tableWidget.
Comment: I read documentation about QTableWidget and QtableWidgetItem. It didn't help me in this question.
Comment: I admit that it's not clear. In fact it is more in the model/view Qt's spirit to have one (and a unique one) item in each box of a tableWidget. Each item can have detect if you click on it for example. If you had two pointers in different boxes pointing to the same item, this property would have absolutely no sense.
Answer: You can create copies of the item to insert at different cells. This can be done using clone :
QTableWidgetItem *Type1 = new QTableWidgetItem;

Type1->setText("some");
ui->tableWidget->setItem(row1, col1, Type1);

QTableWidgetItem *Type2 = Type1->clone(); // create a copy
Type2->setText("shi");
ui->tableWidget->setItem(row2, col2, Type2);

one item for 5 positions


Error when running a .net core web app with React.js on IIS 10

Question: I have a web app based on .net core v2.1 with a React.js front-end, which I'm trying to host on IIS 10.  The app runs fine via Visual Studio (2017), however when I publish the app and host via IIS, I get the following error:
Error image
HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.
Error Code     0x8007000d
The web.config file was generated during the publish; I have not modified it:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\SkillsMatrix.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
    </system.webServer>
  </location>
</configuration>

This same error happens if I start a brand new project via VS, do not add any code, and publish it to IIS...
I have tried:

Giving access to the folder/file to the IIS_IUSRS user group
Removing app.UseHttpsRedirection(); in StartUp.cs

Does anyone have any suggestions for how I can clear this error and host my app?
Answer: You could try the below steps to resolve the issue:
1)Make sure you download and install the .net core hosting bundle and runtime.
https://dotnet.microsoft.com/download/dotnet-core/3.1
2)Make sure that the Application Pool > Process Model > Identity is set to ApplicationPoolIdentity or your custom identity has the correct permissions to access the application's deployment folder.
3)Set the application pool set the .NET CLR version to No Managed Code:

4)Confirm that you have enabled the proper server role. See IIS Configuration.
you could the below link for more detail:
https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/?view=aspnetcore-3.1
Comment: Thanks, needed to install the hosting bundle.  Also, needed to update the Modules parameter in the web.config as per https://stackoverflow.com/questions/51336791/asp-net-core-hosting-error-internal-server-error-handler-aspnetcore-has-a-ba


Spectrum perturbation

Question: Let $A$ be a self-adjoint (not necessarily bounded) operator on a Hilbert space $\mathscr{H}$ and $B$ be self-adjoint bounded. Then how would one show that $\sigma (A+B) \subseteq \sigma(A) +\sigma(B)$? It seems that we would need a Neumann series argument, but I'm not sure of the details.
EDIT:
@Jake28 Thanks for the counterexample. In that case, my question should be that how would you prove that $\sigma(A+B) \subseteq \sigma(A) + [-||B||,||B||]$? This was the original statement, but I though it would've been possible to extend it a little.
Answer: It might very well be that I misunderstand your question but if "self-adjoint bounded" means "self adjoint and bounded" then I think you need more assumptions on $A$ and $B$. If we consider the Hilbert space $\mathbb{R}^2$ and the  operators
\begin{align}A=
\begin{pmatrix}
0 &1\\
1&0
\end{pmatrix}, \qquad
B=\begin{pmatrix}
1 &0\\
0&0
\end{pmatrix}
\end{align}
then it's easy to check that $\sigma(A)=\{\pm1\}$ and $\sigma(B)=\{1,0\}$ whereas $\sigma(A+B)=\{\frac{1\pm \sqrt{5}}{2}\}$

Spectrum perturbation


If $f:R^n\to R$ is differentiable,then $df=D_1f.dx^1+...+D_nf.dx^n$

Question: From Calculus on Manifold Spivak,chapter 4.
If $f:R^n\to R$ is differentiable,then $df=D_1f.dx^1+...+D_nf.dx^n$
Proof:
$df(p)(v_p)$
=$Df(p)(v)$
=$\sum_{i=1}^{n}v^i.D_if(p)$
=$\sum_{i=1}^{n}dx^i(p)(v_p).D_if(p)$
I understood the proof,but my question is how from $df(p)(v_p)=\sum_{i=1}^{n}dx^i(p)(v_p).D_if(p)$
,we conclude $df=D_1f.dx^1+...+D_nf.dx^n$.My question may be very basic. please help.
Answer: If $f$ and $g$ are two functions with $f(x)=g(x)$ for all $x$ then $f=g$. In the case at hand we have
$$df(p).v=\sum_{i=1}^n D_if(p)\> dx^i.v\quad\forall v\in T_p\ .$$
It follows that the maps
$$df(p):\ T_p\to{\mathbb R},\qquad \sum_{i=1}^n D_if(p)\>dx^i :\ T_p\to{\mathbb R}$$
are equal. Here the $D_if(p)={\partial f\over\partial x_i}(p)$ are numbers.


$\binom{54}{5}+\binom{49}{5}+\binom{44}{5}+\cdots+\binom{9}{5}$

Question: How to calculate the sum
$$\binom{54}{5}+\binom{49}{5}+\binom{44}{5}+\cdots+\binom{9}{5}$$

I wrote this as $$\sum_{r=2}^{11}\binom {5r-1}{5}$$
$$=\frac{1}{120}\sum_{r=2}^{11}(5r-1)(5r-2)(5r-3)(5r-4)(5r-5)$$
I'm stuck after this. Any help is greatly appreciated.
Comment: Do you have any reason to believe that a nice combinatorial interpretation exists?  The generic sum of $\sum\limits_{k=2}^n \binom{5k-1}{5}$ does simplify to a degree six polynomial in $n$, but it does not look very pretty.  If this is an isolated problem, there are only finitely many terms... you can just add them and be done with it.
Comment: If you're just interested in the answer, I think it's $7184430$
Comment: @JMoravitz my friend asked me this question...i suppose that there exists one as in my opinion she wouldn't just prank me...but im not sure
Comment: If your goal is to just evaluate the sum, then I'm sure it equals some huge number since you can just calculate it manually. But if your goal is to find a nicer expression, then the only expressions I can think of is what you wrote and write it as a polynimial.
Comment: @Accelerator I am looking for  nicer expression
Answer: For a combinatorial interpretation of the sum, consider $6$-subsets of $\{1,\dots,55\}$ such that the largest element is a multiple of $5$.  The sum conditions on the largest element $5r$; the remaining $5$ elements are then chosen from among $\{1,\dots,5r-1\}$.
Without the "multiple of $5$" restriction, this approach yields a combinatorial proof that
$$\sum_{k=6}^{55} \binom{k-1}{5} = \binom{55}{6}.$$
Comment: This is hockeystick identity imo
Answer: $$f:\mathbb Z \rightarrow \text{any commutative ring}$$$$\text {forward difference notation  }\Delta f(x)=f(x+1)-f(x)$$ $$\sum_{x=a}^b \Delta f(x)=f(b+1)-f(a)$$ $$\text {falling power notation } x^{(k)}=x(x-1)…(x-k+1)$$ $$\text {fact:  } x^{(k)}=(\Delta x^{(k+1)})/(k+1)$$ Your sum is $(1/5!)\sum_{x=9}^{54}x^{(5)}=(1/(5! \times 6))\sum_{x=9}^{54}\Delta x^{(6)}$ $$=(1/6!)(55^{(6)}-9^{(6)})$$ $$={55 \choose 6}-{9 \choose 6}$$
Comment: This yields $28989591$, which is not the same value as the OP's sum ($7184430$).
Comment: Yeah...both expressions are not same


MySQL Assembly C#. Update problem

Question: my project has a dependency from the mysql assembly, and it looks like I strictly linked to the mysql assembly version. Few days ago I made an update of the assembly (5.x) and put the latest one (6.x) and as a result all related to my project projects thrown error that the mysql assembly (5.x) couldn't be found
How I can avoid it? I can't just recompiled depended projects.
Regards,
Cyril
Answer: i guess what you did is add a reference to the dll itself.
which the project now is looking for.
you can remove the reference from the project,
create a bin directory, and put the files there.
then you can reference the mysql lib.

MySQL Assembly C#. Update problem


Is there a way to implement chart-js-plugin-waterfall as a react component

Question: I'm facing a situation here, including React use coupled with the additionnal plugin from the chart.js library : chartjs-plugin-waterfall.
I have to develop a personalised dashboard for my client, and until now I've been able to implement every type of charts needed with the library chartjs and its react components : react-chartjs-2.
But I'm now struggling for hours with the last one I have to implement -and which is not available as a "react-chart component"- : the Waterfall chart.
For this I decided to add chartjs-plugin-waterfall and to implement it as a new Chart (here a code sample) :
const WaterFallType = () => {
    let chart = false
    useEffect(() => {
        if(chart instanceof Chart) {
            chart.destroy();
        }
        let ctx = document.getElementById("myChart").getContext('2d')

        chart = new Chart(ctx, {
            type: "bar",
            plugins: [waterFallPlugin],
            data :{
                datasets: [
                  {
                    label: 'Closing Costs',
                    data: [50],
                    backgroundColor: '#e8cdd7',
                    stack: 'stack 1',
                  },
                  {
                    label: 'Purchase Price',
                    data: [700],
                    backgroundColor: '#d29baf',
                    stack: 'stack 1',
                  },
                  {
                    data: [200],
                    waterfall: {
                      dummyStack: true,
                    },
                    stack: 'stack 2',
                  },
                  {
                    label: 'Opening Loan Balance',
                    data: [550],
                    backgroundColor: '#bb6987',
                    stack: 'stack 2',
                  },
                  {
                    label: 'Initial Cash Investment',
                    data: [200],
                    backgroundColor: '#a53860',
                    stack: 'stack 3',
                  },
                ],
            },
            options: {
                plugins: {
                  waterFallPlugin: {
                    stepLines: {
                      enabled: true,
                      startColorStop: 0,
                      endColorStop: 0.6,
                      startColor: 'rgba(0, 0, 0, 0.55)',
                      endColor: 'rgba(0, 0, 0, 0)',
                      diagonalStepLines: true,
                    },
                  },
                },
            }

        })
    }, [chart])

    return

        <canvas id="myChart" width="400px" height="400px"></canvas>

}
export default WaterFallType

Unfortunatly This code does not render the component, instead it throws me several errors :
First one : "Uncaught Error: Canvas is already in use. Chart with ID '2' must be destroyed before the canvas can be reused."
Second one : "Uncaught TypeError: Cannot set properties of undefined (setting 'filter')"
Could anyone help me with this battle?
Thank you very much for your help.
Benjamin
Answer: Finally found a solution without any plugin need.
Chart.js allows floating bars :
https://www.chartjs.org/docs/3.2.1/samples/bar/floating.html
Which makes it a lot more easier!
Have an excellent day!


Mono c# console app, create standalone with mkbundle errors

Question: Trying to create a standalone app for console that will work on Linux, working environment is on Mac os x 10.7.
1.) Open Monodevelop and create new solution, a "C# Console Project".
2.) Build the app, the exe will be created in bin/Release folder
3.) In mac os x open terminal, goto folder and type:
mkbundle -o HelloTest HelloWorld.exe --deps
This will happen:
<code>OS is: Darwin
Sources: 1 Auto-dependencies: True
   embedding: /Users/fredrickbacker/Documents/Mono/HelloWorld/HelloWorld/bin/Release/HelloWorld.exe
   embedding: /Library/Frameworks/Mono.framework/Versions/2.10.9/lib/mono/4.0/mscorlib.dll
Compiling:
as -arch i386 -o temp.o temp.s
cc -arch i386 -g -o HelloTest -Wall temp.c `pkg-config --cflags --libs mono-2`  temp.o
temp.c:2:39: error: mono/metadata/mono-config.h: No such file or directory
temp.c:3:36: error: mono/metadata/assembly.h: No such file or directory
temp.c:6: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'assembly_bundle_HelloWorld_exe'
temp.c:8: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'assembly_bundle_mscorlib_dll'
temp.c:10: error: expected '=', ',', ';', 'asm' or '__attribute__' before '*' token
temp.c:22: error: 'NULL' undeclared here (not in a function)
temp.c: In function 'mono_mkbundle_init':
temp.c:26: warning: implicit declaration of function 'mono_register_bundled_assemblies'
temp.c:26: error: 'bundled' undeclared (first use in this function)
temp.c:26: error: (Each undeclared identifier is reported only once
temp.c:26: error: for each function it appears in.)
temp.c: In function 'main':
temp.c:118: warning: implicit declaration of function 'mono_set_dirs'
[Fail]
</code>
Any suggestions on what I'm doing wrong? Want a standalone linux app, developed from osx. Pulling my hair for hours.
Answer: You cannot build a binary that will be used on a Linux platform from an OSX one. Remember that mkbundle builds native platform code, not intermediate/JIT-compilable/MSIL code.
That does not solve the errors you have on OSX (I have no idea about what's going wrong), but if you want your app to run on Linux, install Mono on a Linux box and run mkbundle from there.


Retornar formatação original TextBox

Question: Tenho um método, que verifica se um TextBox esta preenchido, caso positivo segue normal, caso esteja em branco, ele exibe uma mensagem na tela, e pinta fundo do TextBox de amarelo, Ai que vem minha duvida, como faço para retornar para a cor padrão?
No momento, para voltar, estou usando:
 public void limparCorBoxes(Control.ControlCollection controles)
    {
        //Faz um laço para todos os controles passados no parâmetro
        foreach (Control ctrl in controles)
        {
            //Se o contorle for um TextBox...
            if (ctrl is TextBox)
            {
                ((TextBox)(ctrl)).BackColor = System.Drawing.Color.White;
            }
        }
    }

Porém, esse método, me traz problemas, pois tenho alguns TextBox que tem o parâmetro ReadOnly = true, que quando utilizado deixa o TextBox com a cor de fundo cinza, e quando executo o método a cima, todos os Textbox ficam com o fundo branco.
Answer: Você também pode utilizar as cores do sistema para melhor padronização:
public void limparCorBoxes(Control.ControlCollection controles)
{
    //Faz um laço para todos os controles passados no parâmetro
    foreach (Control ctrl in Controls)
    {
        //Se o contorle for um TextBox...
        if (ctrl is TextBox)
        {
            ctrl.BackColor = ((TextBox)ctrl).ReadOnly
                    ? System.Drawing.SystemColors.Control
                    : System.Drawing.SystemColors.Window;
        }
    }
}

Comment: Isso mesmo @Julio Borges, o uso das cores do sistema é sempre mais adequada, desde que não seja preciso uma cor específica, pois com as cores do sistema a aplicação vai acompanhar o tema de cores do ambiente em que está sendo executada. +1
Comment: Com certeza, respondi para enriquecer o conteúdo da sua resposta sem editá-la.
Comment: Julio e Emerson, Perfeito. Muito obrigado.. testei aqui e funciona perfeitamente. Obrigado
Answer: Você pode adicionar mais um teste na sua rotina, para alterar a cor de fundo apenas do TextBox que não está com a propriedade ReadOnly configurada para true.
Veja se funciona:
 public void limparCorBoxes(Control.ControlCollection controles)
    {
        //Faz um laço para todos os controles passados no parâmetro
        foreach (Control ctrl in controles)
        {
            //Se o contorle for um TextBox...
            if (ctrl is TextBox)
            {
                if (!((TextBox)(ctrl)).ReadOnly) {
                   ((TextBox)(ctrl)).BackColor = System.Drawing.Color.White;
                }

            }
        }
    }

Comment: Desta forma funciona, mais vc também pode utilizar 'System.Drawing.SystemColors.Window' para TextBoxes normais e 'System.Drawing.SystemColors.Control' para TextBoxes  Readonly, pois desta forma se houver alguma alteração de tema do usuário a cor do sistema será utilizada de forma padronizada.
Comment: Amigo, obrigado pela resposta, agora uma duvida, pq utiliza o ! na frente do ((TextBox)(ctrl)).ReadOnly) ?
Comment: Thomas, o ! é o operador de negação, o *not* de outras linguagens. Como `ReadOnly` é uma propriedade _boolean_ podemos usar seu valor para testar uma condição de um `if`, por exemplo. Para ficar mais claro poderíamos fazer assim: `if (((TextBox)(ctrl)).ReadOnly!=true)` ou assim `if (((TextBox)(ctrl)).ReadOnly==false)`.
Comment: Perfeito. Muito obrigado. =D

Retornar formatação original TextBox


Confusing rhythms/tuplets in Le Sacre du Printemps?

Question: I've been studying Igor Stravinsky's Le Sacre du Printemps, a wonderful piece known for being quite strange. Of course, there are numerous usages of tuplets, and they confuse me greatly, so I'm not entirely sure how to interpret them. For example, here's a small excerpt from the first part when the flute comes in:

The rhythms here make absolutely no sense. I mean you first have three 16th notes and then four 32nd notes in the Flute II part, which goes beyond one whole beat, and could only logically fit there if the first three 16th notes were a triplet, which I guess the notation wants the reader to assume. And then Flute I comes in with that beast of a triplet on beat 2, and if you count the notes in the triplet, they add up to 8, which isn't even divisible by three, so I have no idea what to get from this. The only logical explanation I can come up with is that maybe the first 8th note takes up the first third of the triplet, and then the next eighth note (the one the first one is tied to) with the consecutive 16th note is "implied" to be a 16th note triplet, which takes up the second third of the entire triplet, and then the last three 16th notes are another 16th note triplet which takes up the last third of the entire triplet. Honestly, what is happening here? It would've made things so much easier if they'd add the necessary notation to have it, you know, make sense. And then there are other places in the entire piece where these things ARE specified, such as with the beginning bassoon solo when the clarinets first come in:

See, here, the tuplet-within-a-tuplet is specified, but it's not in other places? Can anyone explain to me why it's written like this, and how to interpret the many other confusing tuplets seen throughout Le Sacre du Printemps???
Answer: The numbers and brackets are often omitted on tuplets where it is "obvious" to a professional musician what the notation means.
In your first bar, the player has a quarter note rest. The small notes are "cue" played by someone else, shown in the part as a check that the player hasn't miscounted - presumably this is after a long rest for the flute.
The second beat has two nested triplets (of 16th-notes) inside the 8th-note triplet that is marked. Presumably, there were some similar rhythms earlier in the flute part so there is no need to clutter up the score by spelling out every detail.
That said, the original (1929) score of "The rite of spring" does have rather a lot of typos, if you are looking at that, or a reprint of it! B&H published a corrected edition in 1948. And the Kalmus edition published in 2000 claims to have 21,000 corrections made by an orchestra librarian in the USA!!!
Comment: Well yeah, I know those are cue notes from Flute 2 (that exerpt is from the Flute 1 part, that's what I'm playing after all!)  And yeah, that's what I originally thought, just a bunch of nested 16th note triplets, the OCD in me just loves seeing all those little details being spelled out for me, even if it does create a bunch of clutter, because if not, I tend to second guess myself much more than I should.
Comment: @Sam I'm not a mind reader, and your question didn't give any clues how much you knew already - though phrases like "makes absolutely no sense" might suggest "I don't know much" (not knowing much isn't a problem, of course). Mark up your part any way you prefer, but for *most* people, repeating the same low-level-detail marking over and over again doesn't add any value.
Comment: Am I not allowed to correct you? And I never intended to speak on behalf of *most* people.


Alternative proof why $\overline B(0, 1)$ in $C[0, 1]$ is not compact and a question about this problem.

Question: Let $C[0, 1]$ be the set of continuous functions on $[0, 1]$ with the supremum metric $d(f, g) = sup_{x \in [0, 1]} |f(x) - g(x)|$.
The exercise asks to prove that the closed ball $\overline B(0, 1)$ defined as { $f | sup_{x \in [0, 1]} |f(x)| \leq 1$ } is not compact.
I have a few questions about this:
1) The definition of a compact set $S$ says: "if a collection of open sets $V_a$ satisfies $\cup{V_{a}} = S$, then we can take a finite sub-collection..."
So now how can we find a collection {$V_{a}$} satisfying $\cup{V_{a}} = \overline B(0, 1)$? Some open set $V_{a}$ must cover a constant function $1$, but then the set $V_{a}$ will include many functions f satisfying {f | $sup_{x \in [0, 1]}{f(x)} \gt 1$}, and so $\cup{V_{a}}$ will be larger than $\overline B(0, 1)$.
2) Thus I am going to assume that $\overline B(0, 1)$ is the whole space we have. Then consider a union $\cup_{f \in \overline B(0, 1)}{B(f, \frac{1}{2})}.$ It equals $\overline B(0, 1)$ but no finite sub-union covers the whole $\overline B(0, 1)$. Is this a reasonable proof?
Comment: If you are talking about a subspace, it is fine for a cover consisting of open sets in the ambient space to be larger than the subspace. That is pretty much inevitable in fact. When you restrict to the subspace, this goes away while the resulting intersections become open in the subspace topology.
Comment: I would not say your proof is complete because it is not clear to me, based on it, what the difference is between this case and the case of $[-1,1]$. In particular, why does no finite sub-union cover the whole ball?
Comment: @Ian, suppose you take an infinite number of open intervals to cover [-1, 1], most of them will be contained in one or a union of a few of those intervals. But that is not the case for the "intervals" $V_a$ that I defined.
Comment: Why? What makes this ball so different from $[-1,1]$ and even $[-1,1]^d$?
Answer: It's a question that why the union you give has no finite sub-union covers $\bar B(0,1)$.
And there is a more general result:

A normed  space $E$ is finite dimensional if and only if the closed unit ball is compact.

So it is sufficient and necessary to prove that $C[0,1]$ is infinite dimensional.


Confusion about abbreviating map

Question: I would have thought the following code:
val a = Array(1, 2, 3, 4, 5)
println(a.map(n => "x"))

Could be abbreviated to:
val a = Array(1, 2, 3, 4, 5)
println(a.map("x"))

But the latter gives me the exception below. Why is this?

java.lang.StringIndexOutOfBoundsException: String index out of range:
  1 java.lang.StringIndexOutOfBoundsException: String index out of
  range: 1  at java.lang.String.charAt(String.java:658)     at
  scala.collection.immutable.StringLike$class.apply(StringLike.scala:52)
    at
  scala.collection.immutable.WrappedString.apply(WrappedString.scala:33)
    at
  scala.collection.immutable.WrappedString.apply(WrappedString.scala:33)
    at
  scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:245)
    at
  scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:245)
    at
  scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:33)
    at
  scala.collection.mutable.ArrayOps$ofInt.foreach(ArrayOps.scala:234)
    at
  scala.collection.TraversableLike$class.map(TraversableLike.scala:245)
    at scala.collection.mutable.ArrayOps$ofInt.map(ArrayOps.scala:234)
Answer: Strings are also functions Int => Char which fetches the char at the given index into the string. Therefore
a.map("x")

is equivalent to
a.map(i => "x".charAt(i))

The first element of a is 1 so this will try to find the char at index 1 in the string x which is out of range, hence the exception.
If you want a function that always returns "x" then you can use Function.const:
import Function.const
a.map(const("x"))

Comment: Or you can also do `a.map(_ => "x")`. It's kind of like the debate between whether to use `identity` or  `x => x`.
Answer: In scala String is just a placeholder type for java.lang.Strings.
All instances of String are implicitly converted to scala.collection.immutable.StringOps which extends trait StringLike[ String ] which in-turn extends trait IndexedSeqOptimized[Char, String].
Now, trait IndexedSeqOptimized[Char, String] defines an abstract apply method  apply(index: Int): Char which is implemented by trait StringLike[ String ].
Hence each String instance like val s = "A String" can be used as a function of type Int => Char like this - val c = s( 0 ).
Now, your a.map( "x" ) is equivalent to a.map( i => "x".apply( i ) ) or a.map( "x".apply( _ ) ) or a.map( i => ( "x" )( i ) ) or simply a.map( "x".apply ).

Confusion about abbreviating map


EM-algorithm for two clusters (when one of the distributions is uniform)

Question: I am having a hard time with the EM-algorithm. Here's the problem that I am trying to solve.

Dealing with noisy annotations is a common problem in computer vision, especially when using crowdsourcing tools, like Amazon's Mechanical Turk. For this
  problem, you've collected photo aesthetic ratings for 150 images. Each image is
  labeled 5 times by a total of 25 annotators (each annotator provided 30 labels).
  Each label consists of a continuous score from 0 (unattractive) to 10 (attractive).
  The problem is that some users do not understand instructions or are trying
  to get paid without attending to the image. These "bad" annotators assign a
  label uniformly at random from 0 to 10. Other "good" annotators assign a label
  to the i-th image with mean µi and standard deviation σ (σ is the same for all
  images). Your goal is to solve for the most likely image scores and to figure out
  which annotators are trying to cheat you.
Derive the EM algorithm to solve for each $\mu_i$
  , each $\mu_j$ , $\sigma$, and $\beta$. Show the
  major steps of the derivation and make it clear how to compute each variable
  in the update step.

https://courses.engr.illinois.edu/cs543/sp2012/hw/hw4_assignment.pdf
(here's a link to the complete task, see p.2)
I know that mixtures of Gaussians are often used where you first initialize $k$ Gaussian distributions the parameters of which it is necessary to optimize.
With regard to this problem, I cannot understand how to work with the two distributions. Apparently, we have some prior knowledge that the behavior of bad annotators follows the uniform distribution. On the other hand, it seems that all books and articles I have seen so far consider mixtures of Gaussians.
I would appreciate any kind of guidance and advice with this problem.
Answer: Since this is a homework problem, I will provide hints and relevant resources to get you started.
For your problem you have the following variables,
$$
x_{ij} \in [0, 10] \: [ \text{available data, annotation for image (i) by annotator (j)} ] \\
m_j \in \{0, 1\} \: [\text{indicates good or bad annotator}] \\
p(x_{ij} \mid m_j=0) = \frac{1}{10} \: [\text{distribution for bad annotator data}] \\
p(x_{ij} \mid m_j=1) \sim \mathcal{N}(\mu_i, \sigma) \: [\text{distribution for good annotator data}] \\
\beta: [\text{prior probability for good annotator}]
$$
Based on this information you can formulate the log-likelihood for your problem as follows,
$$
\text{ln}\:p(\textbf{X} \mid \mu , \sigma , \beta ) = \sum_{i=1}^{N}\:\text{ln}\:[\:p(x_{ij}\mid m_j=0) \times p(m_j=0) + p(x_{ij}\mid m_j=1) \times p(m_j=1)\:] \\
= \sum_{i=1}^{N}\:\text{ln}\: [ \frac{1}{10}\times(1-\beta)\: + \: \mathcal{N}(\mu_i, \sigma) \times \beta \:]
$$
The EM algorithm is a maximum likelihood solution, which means you need to find expressions for $\mu_i, \sigma, \beta$ by taking the derivative of above equation and setting it to zero.
Pattern recognition and Machine learning [ pages 435 - 439 ] by Bishop gives very detailed steps on how to derive the relevant equations for the EM algorithm. Once you derive the equations you can use the chart on pages. 438-439 of the book to estimate the parameters.
Hope this helps!
Comment: thank you very much. Do I understand correctly, we do not really need the information about image ids?
I will definitely read PRML carefully since it's very difficult to implement such algorithms without a proper understanding.
Comment: The only information you need to solve this is $x$. Is it possible to share the data?
Comment: Sure. Here's the data: https://gofile.io/?c=TLgwSi
Comment: I am able to open the link, but when I try to download I get "You are not authorized to download this file.". Alternatively you can try to use Google Drive or Dropbox.
Answer: You likely don't want to cluster, but rather test for uniformity.
There are many tests for that, such as KS tests.
But I doubt that "cheaters" will exhibit anything like uniform behavior. Humans are notoriously bad at this.
Comment: Unfortunately, this is a problem where we have to use the EM algorithm. Can you please give a few hints on how to apply it to a mixture OF Gaussian and Uniform? Is there any value in image ids?


representation of a convolutional layer as a fully connected one (matrix representation)

Question: I'm surprised this isn't a duplicate, but Google seems to confirm that this is indeed the case.
What is the representation of a convolutional layer as a fully connected layer? A convolutional layer is nothing else than a discrete convolution, thus it must be representable as a matrix$\times$vector product, where the matrix is sparse with some well-defined, cyclic structure. However, what are neurons in this case? In the usual FC layer representation, each neuron has a vector input and a scalar output. But $\mathbf{M}\cdot\mathbf{v}$ is a vector, not a scalar. I must be missing something obvious.
PS of course $\mathbf{M}$ is not the input image - if the input is RGB, $\mathbf{M}$ must be some matricial representation of three matrices (R, G and B). If instead we're talking about a hidden layer, then $\mathbf{M}$ is a representation as a matrix of dozens or hundreds of matrices (channels).
Comment: "In the usual FC layer representation, each layer has a vector input and a scalar output." -- isn't the output of an FC layer a vector?
Comment: @shimao yes, of course - I put the blame on autocompletion! Fixed.
Comment: @shimao Actually, I think a scalar output is the right word because it's a "one" neuron he is talking about.
Comment: @DeltaIV  ⋅ is not an output of an single neuron. It's an output of a single layer...
Answer: For the 1D, 1-channel case, you may be interested in a related question and answer here.
In the 2D case*, if we flatten the input to the convolution $x \in \mathbb{R}^{C\times H\times W}$ into a vector $x' \in \mathbb{R}^{CHW}$ in the usual manner (such that $x'_{iHW+jW+k} = x_{i,j,k}$), and we have a convolutional kernel $K \in \mathbb{R}^{D\times C\times P\times Q}$ ($D$ is the out dimension and each filter has receptive field $P$ by $Q$) then we can define a weight matrix $M \in \mathbb{R}^{DH'W' \times CHW}$ ($H'=H-P+1, W'=W-Q+1$)such that the flattened version of $y = \text{conv}(K,x)$ can be written as $y' = Mx'$ as follows:
$$
M_{s,t} = \begin{cases} K_{s,i,v-j,w-k} &\text{if } 0 \leq v-j < P \text{ and } 0 \leq w-k < Q\\ 0 &\text{otherwise } \end{cases}
$$
Where $i,j,k$ are defined by $t = iHW+jW+k$ and $j<H$, $k<W$. and $u,v,w$ are defined by $s = uH'W'+vW'+w$ and $v < H'$ and $w < W'$.
You can see in each row of $M$, corresponding to a single entry in the output feature map, the only nonzero entries of that row are in the columns corresponding to the appropriate input receptive field.
*well I'm not masochistic enough to deal with strides, dilation, padding, separable filters, etc in this answer.

However, what are neurons in this case?

A neuron in a convolutional network (although I think it's usually not useful to think in terms of neurons), is a single entry in a feature (which is a vector) in a feature map (which is a 2D grid of features -- a 3D tensor).

Ok I agree the indexing notation is rather dense, here I'll write out an explicit example:
Our input $x$ is 1 by 3 by 3:
<code>[
    [
        [1 2 3]
        [4 5 6]
        [7 8 9]
    ]
]
</code>
Each single value such as "1" or "5" here is a neuron.
We flatten this into the vector $x'$:
<code>[1 2 3|4 5 6|7 8 9]
</code>
(to keep things sane, here and later, i use | to delimit every 3 elements, so you can see how they map onto the 1x3x3 input)
Meanwhile our kernel $K$ is 2 by 1 by 2 by 2:
<code>[
    [
        [
            [a b]
            [c d]
        ]
    ]
    [
        [
            [e f]
            [g h]
        ]
    ]
]
</code>
We arrange this into the matrix $M$, which is 8 by 9:
<code>[
    [a b 0|c d 0|0 0 0]
    [0 a b|0 c d|0 0 0]
    [0 0 0|a b 0|c d 0]
    [0 0 0|0 a b|0 c d]
    [e f 0|g h 0|0 0 0]
    [0 e f|0 g h|0 0 0]
    [0 0 0|e f 0|g h 0]
    [0 0 0|0 e f|0 g h]
]
</code>
Then $Mx' = y'$ computes
<code>[1a+2b+4c+5d, 2a+3b+5c+6d, 4a+5b+7c+8d, 5a+6b+8c+9d, 1e+2f+4g+5h, 2e+3f+5g+6h, 4e+5f+7g+8h, 5e+6f+8g+9h]
</code>
Again as before, each scalar value here such as "1a+2b+4c+5d" is a single neuron.
We reshape this to 2 by 2 by 2 to recover $y$:
<code>[
    [
        [1a+2b+4c+5d, 2a+3b+5c+6d]
        [4a+5b+7c+8d, 5a+6b+8c+9d]
    ]
    [
        [1e+2f+4g+5h, 2e+3f+5g+6h]
        [4e+5f+7g+8h, 5e+6f+8g+9h]
    ]
]
</code>
And you can see by inspection this is what we'd get by sliding the filter $K$ over the original $x$.
Comment: @DeltaIV I wrote out an explicit example -- hope it helps
Comment: yeah, it's not.
Comment: "I think it's usually not useful to think in terms of neurons" - it's actually indispensable if you want to understand the literature on visualization CNN hidden layers, because [the term is routinely used in that literature](https://distill.pub/2018/building-blocks/), pheraps unfortunately. Your answer is not clear to me - what is a neuron (or if you prefer, what are its inputs and output) in a CNN? In your notation, is the input $x'$ and the output $m_i\cdot x'$, i.e., one component of $y'$? Or to be more precise, is the neuron output $ReLU(y_i')=ReLU(m_i\cdot x')$?
Comment: it's a bit difficult (for me) to follow your notation. As an example, can you please write explicitly one or two (consecutive) rows of $M$? A simple case is fine - for example,  $K \in \mathbb{R}^{3\times 1\times 3\times 3}$, and each of the 3 kernels is actually the same, for example, a sharpen kernel $[[0, -1, 0];[-1, 5, -1];[0, -1, 0]]$
Comment: Ps I'm  % with you about not dealing with strides, padding, etc. the basic 2D case is fine.
Comment: interesting - thus in the nD case with $n>1$, $M$ is not even Toeplizt, right?


Método correto para pegar valor ComboBox populado por DataTable

Question: Qual a maneira correta para pegar o valor de um ComboBox populado por um DataTable?
Estou utilizando os seguinte código:
private void ComboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
    Consulta_cidade cidade = new Consulta_cidade();

    var dataRowView = this.comboBox3.SelectedItem as DataRowView;
    var valor = dataRowView.Row.ItemArray[1];

    int a = Convert.ToInt32(valor);

    comboBox2.DataSource = cidade.consulta_cidade(a);
    comboBox2.ValueMember = "descricao";
    comboBox2.DisplayMember = "descricao";
    comboBox2.Update();
}

Comment: Pode usar a propriedade `SelectedItem` para pegar o valor do display e a propriedade `SelectedValue` para pegar o código associado a valor do Display.
Comment: É WPF ou Winforms?
Comment: Onde o valor é retornado como um objeto?
Comment: Basta converter para inteiro: `int valor = Convert.ToInt32(comboBox3.SelectedValue);`
Comment: Dener, este metodo, não pode ser aplicado aqui, pois quando utilizamos um dataTable para popular um comboBox, os valores retornam como objeto, e não como string. Por isso tive a necessidade da utilização de um DataRowVIew. Me corriga se stiver errado. Obrigado
Comment: Dener estou trabalhando com WinForms
Comment: Dener, perfeito, refiz o código conforme você disse. e resolvi o problema. não sei pq, ontem não estava conseguindo. não consegui identificar o erro. Obrigado.
Comment: @DenerCarvalho Poste isso como resposta.
Comment: @zekk sim vou postar
Answer: Basta fazer a conversão para inteiro usando o método ToInt32() veja:
int valor = Convert.ToInt32(comboBox3.SelectedValue);


How to change buttons layout from horizontal to vertical?

Question: I'm translating a chinese app and I want to change the bottom buttons layout from horizontal to vertical in order to fit correctly the translations. I've been playing with the orientation and gravity from the LinearLayout and CheckedTextView but the buttons stay always in horizontal.
This is the xml code,
<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:orientation="vertical"
android:background="@drawable/homepage_ground"     android:layout_width="fill_parent"     android:layout_height="fill_parent"     xmlns:android="http://schemas.android.com/apk/res/android" xmlns:nav_stick="http://schemas.android.com/apk/res-auto">
<include layout="@layout/title_bar_transparent_white" />
<RelativeLayout android:layout_width="fill_parent" android:layout_height="0.0px" android:layout_weight="1.0">
    <com.rockrobo.ui.RRNavigateStick android:id="@id/navigate_stick" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" />
    <TextView android:id="@id/rc_starting" android:visibility="gone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10.0dip" android:text="@string/rc_starting_up" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" />
</RelativeLayout>
<LinearLayout android:layout_gravity="center" android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="@dimen/rc_bot_margin">
    <CheckedTextView android:textColor="@color/rc_button_text_color" android:gravity="center" android:id="@id/spot_clean" android:background="@drawable/rc_button_bg" android:clickable="true" android:layout_width="@dimen/rc_button_width" android:layout_height="@dimen/rc_button_height" android:layout_marginRight="@dimen/rc_bot_bar_gap" android:text="@string/rr_spot" />
    <CheckedTextView android:textColor="@color/rc_button_text_color" android:gravity="center" android:id="@id/clean" android:background="@drawable/rc_button_bg" android:clickable="true" android:layout_width="@dimen/rc_button_width" android:layout_height="@dimen/rc_button_height" android:layout_marginRight="@dimen/rc_bot_bar_gap" android:text="@string/rr_clean" />
    <CheckedTextView android:textColor="@color/rc_button_text_color" android:gravity="center" android:id="@id/charge" android:background="@drawable/rc_button_bg" android:clickable="true" android:layout_width="@dimen/rc_button_width" android:layout_height="@dimen/rc_button_height" android:text="@string/rr_charge" />
</LinearLayout>
</code>

Could anybody help? Thanks.
Comment: Can you attach screenshot
Answer: Hi try changing linear layout width to match parent and orientation to vertical
Comment: Please try writing such answer as a comment.


Como mudo o local da importação dos módulos no python?

Question: import pygame

O programa da esse erro, dizendo que não tem nenhum modulo

Só funciona quando mostro o local para o programa
Estou iniciando meu estudos na linguagem.
Meu python e vscode estão instalado no disco D:, não estou entendo pq os módulos estão sendo importados no disco C:.
Gostaria de mudar o local da importação, para não ficar mostrando todo vez o local do arquivo
Comment: quantas versões do python estão  instaladas ?
Comment: Duas, uma que eu instalei no disco D: e outra que foi instalada pelo aplicativo da microsoft Store no disco C:
Comment: pode ter acontecido que as instalações estão vinculadas a instalação no C e não ao D. Tera que especificar qual versão sera usada no IDE. como vscode pode criar mv para gerenciar a versão em uso. como esta o path, esta para a versão que quer usar ?
Comment: nas opções do vscode. File Preferences Settings ..  escolhe qual interprete do python sera usando.. só procurar "python" e a opção "Default Interpreter Path
Path to Python, you can use a custom version of Python by modifying this setting to include the full path."
Comment: Consegui resolver meu problema. Muito obrigado
Comment: Nas próximas perguntas, evite colocar código ou dados como imagens. Isso impede a busca no site, impede que pessoas possam copiar e colar trechos do seu código como exemplo, e atrapalha mais um monte de coisas.
Answer: Você tem que aprender sobre "virtual environments": são um recurso usado pela linguagem para cada projeto ter suas próprias bibliotecas, sem que haja problemas de conflitos no sistema.
Assim, se você tem um jogo que depende do pygame 1.8, e outro que depende do pygame 2.0, pode ter os dois instalados no PC.
Além disso, usando os virtualenvs, todas as dependencias do projeto são encontradas automaticamente.
Em geral as IDEs e editores mais avançados, como o vscode oferecem suporte a virtualenv - mas claro, é um mecanismo que não depende de IDEs - apenas da linguagem, e pode ser ativado via terminal, ou especificado em um atalho pra rodar seu programa, se criar um link pra ele rodar direto.
O que um virtualenv faz é colocar cópias e atalhos para o Python e as bibliotecas do sistema dentro de uma pasta - que em geral mantemos junto com o projeto (mas pode ficar em qualquer lugar). Antes de trabalhar com o projeto, ou executar ele, "ativamos" o virtualenv. Aí, você instala qualquer dependencia do seu projeto direto dentro do virtualenv (mesmo se já tiver instalado no Python do sistema, instale de novo). Depois, conforme você for entendendo dos projetos, especifica essa dependência nos arquivos de configuração do próprio projeto - assim, o Python pode instalar automaticamente as dependencias pra qualquer pessoa que for instalar o seu projeto.
Para fazer na linha de comando: abra o computador, e vá com o cmd até a pasta do seu projeto (com o comando "cd"). Chegando lá, digite python -m venv env - o Python vai criar uma pasta "env" com tudo lá dentro. Na sequencia, ative o virtualenv: env\scripts\activate.bat no Windows ou  source env\bin\activate no Linux/Mac.  Aí pode digitar pip install pygame que ele será instalado.
Paa trabalhar com virtuaenv no vscode, tem um guia aqui: https://code.visualstudio.com/docs/python/environments