text:
Q: How does UEFI work? I was studying about bootloaders when exactly came upon the term UEFI. I can understand some things about UEFI. But still, In what mode(Real,Protected,Long) does a system with UEFI start? If normal boot loaders cant work with UEFI, Then what is the alternate of boot loader while dealing with UEFI? And do I need any other programming to create one, than assembly?

A: Here's a good answer to this question:

Other modern 64-bit machines have new EFI firmwares. These don't load a bootstrap program from sector #0 of a disc at all. They bootstrap by the EFI Boot Manager loading and running an EFI boot loader application. Such programs are run in protected mode. This is the EFI bootstrap process.
EFI firmwares in general switch to protected mode within a few instructions of exiting processor reset. Switching to protected mode is done early on in the so-called "SEC Phase" of EFI firmware initialization. Technically, 32-bit and greater x86 processors don't even start in real mode proper, but in what is colloquially known as unreal mode. (The initial segment descriptor for the CS register does not describe the conventional real mode mapping and is what makes this "unreal".)
As such, it could be said that those EFI systems never enter real mode proper at all, when bootstrapping natively to an EFI bootloader (i.e. when they don't employ a compatibility support module), since they switch from unreal mode directly to protected mode and stay in protected mode from then on.

A: When you asked "In what mode(Real,Protected,Long) does a system with UEFI start?", what do you mean?  The processor starts executing in a mode that is similar to the mode of the 80386 of the past.  But do you really care.  Don't you really care about the mode of the processor when your OS loader code is given control?  And you care about what services are provided to your OS loader code.
The environment is defined in the UEFI spec.  Latest Versions of the UEFI Specifications
As for which language you use, assembly is good to start with.  It's probably easier to use C or some other high level language after a bit.
Other background:
There are a lot of terms here that we are not always careful about using correctly.
The code that executes when the processor comes out of reset is system firmware that does a lot of initialization of various hardware in the system.
In the old days on a x86 PC system before the UEFI Forum existed, the system firmware was called BIOS.  The BIOS in those days executed all of its initialization code, then loaded some code off of a floppy diskette or the hard drive and jumped into the code.  The BIOS also provided some interfaces between the hardware and the operating system to help isolate the OS from hardware differences.  Nothing was standardized though.  The only standards were the OS and applications level software that used the BIOS interfaces.
If the OS and apps functioned correctly then the BIOS was considered correct.  But you could only prove correctness by lack of failure.  Thus new OSs or applications would work on one correct system yet fail on a different correct system.
Today we've tried to provide some actual standardization of those interfaces.  They are defined by the UEFI Forum.  Today I can prove that my system is correct according to meeting the UEFI specifications.
When people say things like the UEFI, they are usually referring to the actual system firmware installed on the system that is executed before the OS starts executing.  But a lot of us still toss around these terms like we've spilled alphabet soup.
The boot loader is actually OS owned code that is loaded in memory by the system firmware and the system firmware gives control of the hardware to the boot loader.  One could say that the end of the system firmware is the UEFI Boot Loader.  Or you could just say BDS uses the system policy to find the OS.  And you could still find someone that disagreed with the words.

A: If you wish to know more about how UEFI works then the post UEFI boot: how does that actually work, then? by Adam Williamson is highly recommended.
He answers the questions you have and its a good read:

Now let's look at how booting works on a UEFI system. Even if you
  don't grasp the details of this post, grasp this: it is completely
  different. Completely and utterly different from how BIOS booting
  works. You cannot apply any of your understanding of BIOS booting to
  native UEFI booting. You cannot make a little tweak to a system
  designed for the world of BIOS booting and apply it to native UEFI
  booting. You need to understand that it is a completely different
  world.

The Wikipedia page Unified Extensible Firmware Interface is also a useful resource.

A: UEFI firmware runs in 64 bit long mode for 64 bit platforms and flat mode for 32 bit platforms; Unlike BIOS, UEFI features its own architecture, independent of the CPU, and its own device drivers. UEFI can mount partitions and read certain file systems.
When an x86 computer equipped with UEFI, the interface searches the system storage for a partition labeled with a specific globally unique identifier (GUID) that marks it as the EFI System Partition (ESP). BTW Windows doesn't mount this partition and you cannot see it in the OS. But there is a trick, you simply change the partition type (using HexWorkshop) in VBR to regular FAT32 code and it will be mounted into the OS.
This partition contains applications compiled for the EFI architecture. In general you don't have to deal with assembler to write a UEFI application/loader, it's just a regular C code. By the default it is located at "EFI/BOOT/BOOTX64.EFI". When a bootloader is selected, manually or automatically, UEFI reads it into the memory and yields control of the boot process to it.

A: In the following, some sentences are a copy, amalgamation and wording improvement of the best sources I've seen, and then I improve on and correct their unknowns / errors by using my own hardware case study.
Boot Guard
Intel Boot Guard is a technology introduced by Intel in the 4th Intel Core generation (Haswell) to verify the boot process. This is accomplished by flashing the public key of the BIOS signature into the field programmable fuses (FPFs), a one-time programmable memory inside Intel ME (in the PCH), during the manufacturing process; in this way it has the public key of the BIOS and it can verify the correct signature during every subsequent boot. Once enabled by the manufacturer, Intel Boot Guard can't be disabled anymore.
Boot Guard has two separate modes, according to Intel. Typical PC OEMs configure it to  "Verified Boot" mode. The PC manufacturer fuses their public key into the hardware itself. If the UEFI firmware isn't signed by the OEM—i.e., created by the OEM—the computer will halt and refuse to boot. That's why you can't modify the UEFI firmware. There's also a second option: "Measured Boot" mode, where the hardware uses Intel TXT to secure stores information about the boot process (in a trusted platform module (TPM)) or Intel Platform Trust Technology (PTT) with the aid of SMX. The operating system could then examine this information, and—if there was a problem—present an error to the user.
Secure Boot
When enabled and fully configured, Secure Boot helps a computer resist attacks and infection from malware. Secure Boot detects tampering with boot loaders, key operating system files, and unauthorized option ROMs by validating their digital signatures. Detections are blocked from running before they can attack or infect the system. UEFI Secure Boot assumes the OEM platform firmware is a Trusted Computing Base (TCB) (i.e. that it's been initialised with BootGuard technologies and trusts it implicitly).

Verified Boot Process
Pre-UEFI stage
When the OEM receives the PCH, the ME is still in "Manufacturing Mode" and runs a special part of the firmware that will copy the "OEM Public Key Hash" and "Boot Guard Profile Configuration" policy values from its section of the flash ROM into the field programable fuses (FPFs) so that they are permanent and unchangable. It then sets a fuse to indicate that it has exited from manufacturing mode so that this portion of the firmware will not run again. These values can be adjusted in the flash image with the Intel Flash Image Tool (FITC), but unless you have a way to force the ME into manufacturing mode then the values in the flash image are ignored.
The Bootguard profile is as follows:

Protect BIOS Environment Enabled: if set, this possibly means that the ACM will copy the IBB segments into the CPU cache so that it runs in a cache-as-RAM (CAR) mode and has all DMA disabled to prevent devices from being able to modify it.
As soon as power is available, the ME CPU boots up from its on-die boot ROM, checks some straps and fuses to determine its configuration, and typically then copies the flash partition table (FPT) from the ME region of the SPI flash (which is typically below the BIOS region) to its on-die SRAM. It locates the ME region by using the flash descriptor at the lowest address of the SPI flash.

The boot ROM locates the FTPR partition using the FPT and copies it from the SPI flash into the on-die SRAM. It then checks that the SHA-1 hash of the key stored in the partition manifest matches the one in its on-die ROM and validates the RSA signature on the rest of the partition manifest. The partition table contains hashes of each of the modules in the partition, allowing the modules to be validated after they are copied into the on-die SRAM for execution.

When the ME boots the x86 CPU, possibly in bup.met. The BIST and then the BSP MP Initialisation algorithm takes place. The legacy reset vector at CS:FFF0 (where CS is 0xF000 and the segment descriptor cache contains the base 0xFFFF0000) is no longer the first instruction the x86 CPU executes on reset. Instead, on-die microcode fetches the FIT pointer at 0xFFFFFFC0 (using 0xF000:FFC0 with the unreal mode segment descriptor hack – because this is the initial state of the registers), which points to the FIT table somewhere in the SPI flash BIOS region.

This image shows the 16 byte FIT entries with their modes 3 bytes from the end.
#pragma pack (1)
typedef struct {
  UINT64     Address;
  UINT8      Size[3];
  UINT8      Rsvd;
  UINT16     Version;
  UINT8      Type:7;
  UINT8      C_V:1;
  UINT8      Checksum;
} FIRMWARE_INTERFACE_TABLE_ENTRY;

On my system, there is a FIT pointer at FFFFFFC0 to FFD90100

The FIT table points to microcode updates, ACMs, the BootGuard Boot Policy Manifest (which contains an IBBS) and BootGuard Key manifest etc.
My FIT does not contain any 0x7 entries. Record Types 7 is used by legacy Intel® TXT FIT boot only and is not needed, if latter is not used.
The BootGuard Boot Policy (IBBM) contains:
Intel BootGuard Boot Policy Manifest found at base FD3C00h
Tag: ACBP Version: 10h HeaderVersion: 01h
PMBPMVersion: 10h PBSVN: 00h ACMSVN: 02h NEMDataStack: 0010h

Initial Boot Block Element found at base FD3C28h
Tag: IBBS       Version: 10h         Unknown: 0Fh
Flags: 00000000h    IbbMchBar: FED10000h VtdBar: 00000000h
PmrlBase: FED90000h PmrlLimit: 00000000h  EntryPoint: 00100000h

Post IBB Hash:
0000000000000000000000000000000000000000000000000000000000000000

IBB Digest:
B9CCC06B77AEACC51768981D07CBE9E43D34DB6795752C4B998312241B26F874

IBB Segments:
Flags: 0000h Address: FFE10000h Size: 001C3C00h
Flags: 0000h Address: FFFD4C00h Size: 00000080h
Flags: 0000h Address: FFFD5C80h Size: 0000A380h
Flags: 0000h Address: FFFE8000h Size: 00018000h

Boot Policy Signature Element found at base FD3CDDh
Tag: PMSG Version: 10h

Boot Policy RSA Public Key (Exponent: 10001h):
....
Boot Policy RSA Public Key Hash:
....
Boot Policy RSA Signature:
....

The Key Manifest contains:
Intel BootGuard Key Manifest (KEYM) found at base FD4C80h
Tag: KEYM Version: 10h KmVersion: 10h KmSvn: 00h KmId: 0Fh

Key Manifest RSA Public Key Hash:
...
Boot Policy RSA Public Key Hash:
...
Key Manifest RSA Public Key (Exponent: 10001h):
...
Key Manifest RSA Signature:
... //it does actually contain a signature, I just removed these for space

Cache as RAM (CAR) (aka. AC-RAM, No fill mode and No evict mode) is then set up by the microcode. The FIT is then searched for microcode updates that match the CPU ID. The current microcode copies them linearly from flash into L3 cache and decrypts with an on-die symmetric AES key, then validates with (on-die?) RSA key. It's likely that these microcode updates also contain the key hashes for the ACM. The microcode update is then applied by writing to the UCODE MSR and the CPU reads it out I assume through normal memory accesses. The FIT absolutely has to contain a microcode patch and it patches the microcode SRAM to complement the already existing microcode ROM. [1]
Next, the microcode goes back to the FIT to find the Startup ACM (aka BIOS or Bootguard ACM) and does an odd copy of it into L3 (looks like multiple hyperthreads are copying 4KB chunks? -- according to that source). The ACM contains an RSA public key; the microcode compares it against either an on-die key or one stored in the microcode update and halts the CPU if it does not match. The microcode  then checks the signature on the ACM and again halts if it does not match.
The Startup ACM runs entirely out of L3. The ACM receives the OEM public key hash (the Key Hash that verifies the Key Manifest) and Bootguard Profile from the ME via MSR.
The ACM reads the BootGuard Key Manifest from the SPI flash (pointed to by the FIT and identified by __KEYM__) into L3 and hashes the RSA public key stored in it. If it doesn't match the OEM public key hash or if the OEM public key signature on the Key Manifest or if the stored KmSvn isn't right, the ACM takes action based on the Bootguard Profile bits. If it does match, it locates the Bootguard Policy in the FIT (and identified by __ACBP__) and copies it into L3. The ACM then computes the hash of the RSA public key in the Policy and compares it to the SHA256 hash stored in the Key Manifest. If that fails to match, or if the RSA signature on the Policy doesn't match, then the ACM again takes action based on the Profile settings.
The ACM uses the now validated Bootguard Policy structure to read the Initial Boot Block (IBB) segments into L3, hashing them as they are copied. If this computed hash doesn't match the "IBB Digest" in the Policy, the ACM takes action based on the Profile settings. The 4th IBB segment contains the reset vector, so it prevents that from being modified. It's unclear whether it leaves the CPU in CAR mode or whether it just leaves them cached in the L3 but without eviction disabled i.e. without CAR mode left enabled. SEC however needs to (disable) and set up a new CAR mode.

Taking a dump of physical memory using RwEverything, or downloading CSME System Tools for your ME version and then performing fptw64 -d -me -bios dump.bin will dump the flash (and often you will only be able to dump the BIOS region and not the ME region). The dump is now analysable in UEFITool NE Alpha 58, and the FIT shows the EntryPoint of the ACM in the body. So if you right click, extract it and open it up in IDA as 32 bit, the entry point will be at 3BB1h + 18h = 3BC9h
3BC9   mov     ax, ds
3BCC   mov     ss, ax
3BCF   mov     es, ax
3BD2   mov     fs, ax
3BD5   mov     gs, ax
3BD8   mov     esp, ebp
3BDA   add     esp, 1000h
3BE0   mov     eax, ebp
3BE2   add     eax, 4C8h
3BE7   lidt    fword ptr [eax]
3BEA   push    ebp
3BEB   call    sub_392A
3BF0   mov     ebx, eax
3BF2   mov     edx, 0
3BF7   mov     eax, 3
3BFC   getsec

The startup ACM is always the final ACM and it GETSEC[EXITAC]s to the IBBS base + entry point address (0xFEE90000, which falls in the first IBB) in the bootguard policy manifest, which appears to be in the ME region and presumably contains code to switch the CPU back to unreal mode and jump to the legacy reset vector in the 4th IBB segment. GETSEC can only be executed in protected mode, so clearly the CPU is in protected mode in the startup ACM, so must be enabled by the microcode before entry. The legacy reset vector is at 0xFFFFFFF0, which on my system is a relative jump to FFFFFFF5 - 3BD = FFFFFC38, which is the SEC core entry point.
SEC

The SEC core is a Raw section from FFFFCA14 - FFFFCA17, a PE32 image from FFFFCA18 - FFFFFFBB, a raw section from FFFFFFBC - FFFFFFBF, and a raw section from FFFFFFC0-FFFFFFFF (which contains the reset vector).
The entry point of the PE32 Image in the SEC Core that is jumped to by the reset vector contains:
0x00:  DB E3                      fninit
0x02:  0F 6E C0                   movd   mm0, eax   //move BIST value to mm0
0x05:  0F 31                      rdtsc
0x07:  0F 6E EA                   movd   mm5, edx
0x0a:  0F 6E F0                   movd   mm6, eax  //save tsc
0x0d:  66 33 C0                   xor    eax, eax //clear eax

0x10:  8E C0                      mov    es, ax
0x12:  8C C8                      mov    ax, cs
0x14:  8E D8                      mov    ds, ax
0x16:  B8 00 F0                   mov    ax, 0xf000
0x19:  8E C0                      mov    es, ax
0x1b:  67 26 A0 F0 FF 00 00       mov    al, byte ptr es:[0xfff0]
0x22:  3C EA                      cmp    al, 0xea
0x24:  74 0E                      je     0x34   //if ea is at ffff0h then jump to the 0xf000e05b check

0x26:  BA F9 0C                   mov    dx, 0xcf9
0x29:  EC                         in     al, dx    //read port 0xcf9
0x2a:  3C 04                      cmp    al, 4
0x2c:  75 25                      jne    0x53
0x2e:  BA F9 0C                   mov    dx, 0xcf9 //perform warm reset since if CPU only reset is issued not all MSRs are restored to their defaults
0x31:  B0 06                      mov    al, 6
0x33:  EE                         out    dx, al

0x34:  67 66 26 A1 F1 FF 00 00    mov    eax, dword ptr es:[0xfff1]
0x3c:  66 3D 5B E0 00 F0          cmp    eax, 0xf000e05b
0x42:  75 0F                      jne    0x53      //if it isn't, move to notwarmstart

0x44:  B9 1B 00                   mov    cx, 0x1b //if it is equal, read bsp bit from apic_base msr
0x47:  0F 32                      rdmsr
0x49:  F6 C4 01                   test   ah, 1
0x4c:  74 41                      je     0x8f   //if the and operation with 00000001b produces a zero result i.e. it's an AP then jump to cli, hlt

0x4e:  EA F0 FF 00 F0             ljmp   0xf000:0xfff0 //if it's the BSP, exit unreal mode by far jumping to 0xffff0 which reloads the segment descriptor cache with a 0 base

notwarmstart:
0x53:  B0 01                      mov    al, 1
0x55:  E6 80                      out    0x80, al  //send 1 as a debug POST code
0x57:  66 BE 68 FF FF FF          mov    esi, 0xffffff68
0x5d:  66 2E 0F 01 14             lgdt   cs:[si] //loads 32&16 GDT pointer (not 16&6, due to 66 prefix) at 16bit address fff68 in si into GDTR (base:ffffff28 limit:003f); will be accessing alias and not shadow ROM

//enter 16 bit protected mode//
0x62:  0F 20 C0                   mov    eax, cr0
0x65:  66 83 C8 03                or     eax, 3   //Set PE bit (bit #0) & MP bit (bit #1)
0x69:  0F 22 C0                   mov    cr0, eax  //Activate protected mode
0x6c:  0F 20 E0                   mov    eax, cr4
0x6f:  66 0D 00 06 00 00          or     eax, 0x600 //Set OSFXSR bit (bit #9) & OSXMMEXCPT bit (bit #10)
0x75:  0F 22 E0                   mov    cr4, eax

//set up selectors for 32 bit protected mode entry
0x78:  B8 18 00                   mov    ax, 0x18 //segment descriptor at 0x18 in GDT is (raw): 00cf93000000ffff
0x7b:  8E D8                      mov    ds, ax
0x7d:  8E C0                      mov    es, ax
0x7f:  8E E0                      mov    fs, ax
0x81:  8E E8                      mov    gs, ax
0x83:  8E D0                      mov    ss, ax
0x85:  66 BE 6E FF FF FF          mov    esi, 0xffffff6e
0x8b:  66 2E FF 2C                ljmp   cs:[si]   //transition to flat 32 bit protected mode and jump to address at 0x0:0xffffff6e aka. 0xffffff6e which is fffffcd8. CS contains 0 remember (it's the base that is 0xffff) so it will load the first entry.  This address is also in the SEC Core PE32 Image

0x8f:  FA                         cli
0x90:  F4                         hlt
.
.
.


text:
Q: Android BootReceiver does not work I'm trying to listen for reboot event.
I'v created the following class:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class OnBootReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("MYBOOTRECEIVER", "HELLO!");
    }
}

and then in the manifest file I've putted the following xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mypackage"
    android:installLocation="internalOnly"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="3"
        android:targetSdkVersion="8" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <application android:label="@string/app_name" >
        <receiver android:name=".OnBootReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
                <category android:name="android.intent.category.HOME" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

However, after I've installed this app and rebooted the device, nothing happens. (I'm using a galaxy tab 8.9 with android 3.2 on it).
As you can see from the manifest I've installed the app on internal memory (like suggested on similar questions here on stackoverflow) ... I've also putted a Quickboot_poweron action (to see if galaxy tab have similar behaviour of htc devices) ... but nothing. I hope that someone can help me!

A: The problem is that with Honeycomb and beyond, broadcast signals do not automatically start an application which has not been otherwise started. There is a flag that can be used to change this however the BOOT_COMPLETED broadcast does not carry that flag. You need to be installed on the system partition in order to overcome this nuance.
If you're not able to be installed on the system partition, you'll need to find some other way to be started -- either by convincing the user to start you manually, or having the user install a widget you provide, etc.

A: The action mention in your manifest is correct except the category part, this can be exclude if you just want to receive for boot complete. And in Receiver file this will work fine, but you should always use an if-else statement to distinguish between actions received.
    if (action.equals(android.intent.action.BOOT_COMPLETED)) {
       Log.i("MYBOOTRECEIVER", "BOOT COMPLETED RECEIVED");
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to stop Google Chrome from refreshing tabs that fail to load Note: This is not memory pressure (I have 40GB of RAM on a 64-bit system) or tab discarding. Please read on for full details. Both flags also no longer exist and I cannot turn them off anyway. Installing an extension that disables tab discarding does not do anything (because this isn't discarding).

When a tab fails to load (i.e. I am offline, the server is not running, some other network error), visiting that tab later causes Chrome to try to refresh it. Sometimes this will result in the same error, sometimes a different error, and sometimes the error will disappear and be replace by a working website.
Whatever the case is, I do not like having Chrome automate these actions for me. Even if a tab failed to load and is showing an error, I would not like it to be refreshed automatically even if I click on the tab.
I have checked and there do not seem to be any flags under the traditional search terms. Searching "refresh", "auto", "error", and so on doesn't reveal anything. How do I disable this auto-refresh?


text:
Q: Mongo query Not giving the expected result I have following document in my collection.
{
 "state": "approved",
 "applicants": [
],
 "user": "54a62c8bd334c57300d63af5",
 "nonapplicants": [
  {
  "id": "54a630d7d334c59501d63afd"
  }
 ]
}

I'm performing following query to get the documents that have either nonapplicants id "54a630d7d334c59501d63afd" or applicants id "54a630d7d334c59501d63afd" but it wont show any results.
{"$or":[{"applicants.id":"54a630d7d334c59501d63afd","nonapplicants.id":"54a630d7d334c59501d63afd"}]}

A: You have an error in your query: your $or has only one argument, which is {"applicants.id":"54a630d7d334c59501d63afd","nonapplicants.id":"54a630d7d334c59501d63afd"}. What you want is:
{"$or":[{"applicants.id":"54a630d7d334c59501d63afd"}, {"nonapplicants.id":"54a630d7d334c59501d63afd"}

and not:
{"$or":[{"applicants.id":"54a630d7d334c59501d63afd", "nonapplicants.id":"54a630d7d334c59501d63afd"}


text:
Q: how to get the table2 information using hibernate concept I have 2 tables in my database

*

*table1--> id, name, address

*table2--> id, tb1id
How can I get the table2 information using hibernate framework?

A: you can use  ResultsetMetaData in spring/hibernate.
Check this answer..
Use annotations for getting ResultsetMetaData.
Thanks..


text:
Q: Is it possible to obtain orthogonal (but not normalized) vectors after QR factorization? After QR decomposition of a matrix, $M$, the columns of Q are orthonormal. Is it possible after obtaining Q, we recover unnormalized column vectors from $Q$? For example, the matrix M has the following $Q$ matrix.
$M=
  \begin{bmatrix}1&-1&4\\1&4&-2\\1&4&2\\1&-1&0
  \end{bmatrix}$
The $Q$ matrix is
$Q=\begin{bmatrix}0.5&  -0.5&   0.5\\0.5&   0.5&    -0.5\\0.5&  0.5&    0.5\\0.5&-0.5&-0.5  \end{bmatrix}$
This is for a certain application in spectroscopy. The process is as follows using Gram-Schmidt method.
The raw data is an experimental spectroscopy data. In general, we will have background signals, call them v1, v2, v3 as column vectors. Now measure the spectrum of the molecule of interest. This vector is m. Orthonormalize v1,v2 and v3 to obtain e1, e2 and e3. The magnitude of e1,e2,and e3 is 1. I am following the notation of Wikipedia's article on Gram-Schmidt Wiki.
Then here comes the key step: After an orthonormal basis set of e1, e2, and e3 has been obtained, from the background spectra, measure the spectrum of molecule of interest. This vector is $m$.
Now orthogonalize $m$, with respect to e1,e2, and e3 to obtain another vector $u$. In other words, the dot product u.e1=u.e2=u.e3 = 0.
Since $u$ has not been normalized, i.e., it has a length given by sqrt($u.u$). The length of $u$ is of interest for measurement purposes.
I wanted to know if this is possible by QR method or not?

A: It looks like you want $m - QQ^Tm$, is that correct?


text:
Q: SSRS 2008 Datediff for Working Days I have seen this question asked a lot  and I cannot seem to find one clear answer about
"how to calculate business days only between two dates?"
The expression below will give me the total days but I am looking to exclude Saturday and Sunday.
=DateDiff("d",Parameters!STARTDATE.Value,Parameters!ENDDATE.Value)

I would appreciate specific help about how to accomplish this.
Thank you in advance.

A: This code is not exactly correct. A year can start or end with either a Saturday or a Sunday. For example, 2011 starts on a Saturday and ends on a Saturday. January 1st & 2nd, 2011 are Saturday and Sunday respectively and Dec 31st, 2011 is also a Saturday. The above code does not account for this scenario. The code below is correct:
= (DateDiff(DateInterval.day,Parameters!BeginDate.Value,Parameters!EndDate.Value)+1)
- (DateDiff(DateInterval.WeekOfYear,Parameters!BeginDate.Value,Parameters!EndDate.Value)*2)
- IIF(Weekday(Parameters!BeginDate.Value,1) = 1,1,0)
- IIF(Weekday(Parameters!BeginDate.Value,1) = 7,1,0)
- IIF(Weekday(Parameters!EndDate.Value,1) = 1,1,0)
- IIF(Weekday(Parameters!EndDate.Value,1) = 7,1,0)

A: The SQL in the link (Number of working days between two dates) translated for SSRS: Hopefully this will give you a good place to start. Type this into the expression for the textbox.
=(DateDiff(DateInterval.day,Parameters!STARTDATE.Value,Parameters!ENDDATE.Value)+1)
-(DateDiff(DateInterval.WeekOfYear,Parameters!STARTDATE.Value,Parameters!ENDDATE.Value)*2)
-(iif(Weekday(Parameters!STARTDATE.Value) = 7,1,0)
-(iif(Weekday(Parameters!ENDDATE.Value) = 6,1,0))-1)

A: The easy way getting workingdays between two dates is:
DateDiff(DD, BeginDate, EndDate) - DateDiff(WK, Begindate, EndDate)*2

A: Below code worked for me properly in all the scenarios
= (DateDiff(DateInterval.day,Parameters!BeginDate.Value,Parameters!EndDate.Value)+1)
- (DateDiff(DateInterval.WeekOfYear,Parameters!BeginDate.Value,Parameters!EndDate.Value)*2)
- IIF(Weekday(Parameters!BeginDate.Value,1) = 1,1,0)
- IIF(Weekday(Parameters!EndDate.Value,1) = 7,1,0)


text:
Q: Test private component in unit test So I have a class like this:
public class Person {
   private List<String> list = new ArrayList<String>();

   public addPerson(String s) {
        this.list.add(s);
   }
}

public class TestPerson extends TestCase {
     private Person person;

     public testAddPerson() {
        this.person.addPerson("John");
     }
}

My question is how can I test that John was added in the list.
I woulod like to do some tests like list.size() == 1 or list.get(0).equals("John")
Any suggestions?

A: You can use Reflection to test private variables.
But it might not be a good idea. It is recommended to test private properties trough public interfaces instead.

A: for this code testing makes no sense, it would actually test that the list implementation does what it supposed to be doing and that should not be part of your test.
The question is - where is your list used, where is any public access to it, and what behavior is there expected. This what you should test.
Overall, this sounds like test-after where you try to add tests for the sake of testing and not for verification.

A: There is a very useful tool for this called shazamcrest. It serializes actual and expected objects to json and does String comparison. You don't have to modify your production code (no annotations, no getters needed, fields can be private).
assertThat(actualPerson, sameBeanAs(expectedPerson));

And it throws ComparisonFailure so you get very good diagnostics like this:


text:
Q: How to execute the command after each javascript statement in a block? I want to remove some connection from a Social Media account using JavaScript. If I execute the statements line by line, it works perfectly, but when I execute them in a block of code, it doesn't work.
THE BLOCK CODE
function sleep(delay) {
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
}

for(var i=0;i<5;i++) {
    //Click on connection
    sleep(1000);
    document.getElementsByClassName('reusable-search__entity-result-list list-style-none')[0].getElementsByClassName('entity-result__title-text t-16')[1].getElementsByClassName('app-aware-link')[0].click();
    sleep(1000);
    //Remove connection button
    document.getElementsByClassName('ivm-view-attr__img--centered EntityPhoto-circle-3 lazy-image ember-view')[1].click();
    sleep(1000);
    document.getElementsByClassName('artdeco-dropdown__content-inner')[0].getElementsByTagName('li')[6].getElementsByClassName('pvs-profile-actions__action display-flex align-items-center artdeco-dropdown__item artdeco-dropdown__item--is-dropdown ember-view')[0].click();
    //Back
    sleep(1000);
    history.back();
}

I get every time the following error: TypeError: undefined is not an object (evaluating 'document.getElementsByClassName('artdeco-dropdown__content-inner')[0].getElementsByTagName')
It seems that after Click on connection part, the page is not loading, and it does only after the block is done. (I tried also without for loop, only those statements, but it happened the same like in the loop).


text:
Q: jsdom and Contextify error My node application works fine on my macbook, but when I publish to our servers on Rackspace I get the following error which I've never seen before (sensitive paths replaced with [...]):
[...]/node_modules/jsdom/node_modules/contextify/lib/contextify.js:7
    var ctx = new ContextifyContext(sandbox);
              ^
TypeError: undefined is not a function
    at Contextify ([...]/node_modules/jsdom/node_modules/contextify/lib/contextify.js:7:15)
    at Object.createWindow ([...]/node_modules/jsdom/lib/jsdom/browser/index.js:303:3)
    at Object.windowAugmentation ([...]/node_modules/jsdom/lib/jsdom/browser/index.js:63:24)
    at Object.parentWindow ([...]/node_modules/jsdom/lib/jsdom/browser/index.js:605:28)
    at Object.<anonymous> ([...]/node_modules/jsdom/lib/jsdom.js:81:15)
    at [...]/node_modules/jsdom/lib/jsdom.js:170:52
    at Request._callback ([...]/node_modules/jsdom/lib/jsdom.js:275:9)
    at Request.callback ([...]/node_modules/request/node_modules/request/main.js:119:22)
    at Request.<anonymous> ([...]/node_modules/request/node_modules/request/main.js:525:16)
    at Request.emit (events.js:67:17)

A: Contextify needs to be compiled to create .node binaries. These come prebuilt with jsdom. It worked fine on my mac, but not on the ubuntu server I was publishing to. Rebuilding contextify  on the server according to the instructions on the github page fixed the problem for me.


text:
Q: How to create conditional configuration sections in zc.buildout? I am trying to create a section in version.cfg file defining different versions of Jinja2 egg-package (1.8.1 and 2.9.6) to be installed for different OS versions (Fedora 25/Fedora 26). Unfortunately, official documentation lacks examples and contains only the following explanation how to create conditional configuration sections:

You can define environment-specific options by providing conditional sections:
[ctl]
suffix =
[ctl:windows]
suffix = .bat
In this tiny example, we've defined a ctl:suffix option that's .bat on Windows and an empty string elsewhere.
A conditional section has a colon and then a Python expression after the name. If the Python expression result is true, the section options from the section are included. If the value is false, the section is ignored.

Accordingly, I expected the version.cfg with
[versions]
Jinja2 = 1.8.1

[versions:platform.release().split('-')[1].split('.')[1]=='fc26']
Jinja2 = 2.9.6

would solve my problem but it doesn't. How to fix my versions.cfg?
UPDATE
Actually, it works. More concise way is
[versions:platform.linux_distribution()[:2] == ('Fedora', '26')]
Jinja2 = 2.9.6


text:
Q: DTD Validation on XML Files I started learning XML yesterday but I cant get around the concept of DTD.
My thinking is that, this will cause an error since my picture tag contains a whitespace character and I explicitly mention in my DTD that this should contain only EMPTY element.
As per my understanding, empty element does not contain any character at all.  Whitespace is a character I think.
But I am not sure why my eclipse editor is not displaying an error related to this?
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE person [
<!ELEMENT person (picture) >
<!ELEMENT picture  EMPTY >
]>
<person>

 <picture></picture>

</person>

Any thoughts?

A: The XML you've posted doesn't actually include any whitespace which is why it validates just fine. If you had something like this:
<person>
     <picture> </picture>
</person>

you would have whitespace. An empty element can be written as either <picture/> or <picture></picture>. They are equivalent.

A: You may want to format the XML like
<person>
   <picture />
</person>

I don't think there is any whitespace in your picture element in your example which is why Eclipse won't throw an error.


text:
Q: Tensorflow Serving Model Server continuously re-adding the same models when polling s3 for config file I am using Tensorflow Serving to run models which are stored in an s3 bucket. I am also keeping the model config file in a separate s3 bucket. My use case is that in order to dynamically add models without needing to restart the server I will poll this config file for changes periodically.
In order to do this I have used the following setup:

*

*tensorflow/serving:1.15.0 image deployed into a Kubernetes cluster using helm.

*In the helm chart for the deployment the following lines define the run command and args used for polling s3 for the config

command:
 - "/usr/bin/tensorflow_model_server"
args:
 - --model_config_file={path to config file}
 - --model_config_file_poll_wait_seconds=60

*The helm chart also sets environment variables for AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION, S3_ENPOINT and AWS_LOG_LEVEL=3

The model config file has contents:
model_config_list: {
    config: {
        name: "mlp",
        base_path: "s3://bucketname/mlp",
        model_platform: "tensorflow",
        model_version_policy: {
            specific: {
                versions: 20200130
            }
        }
    }
}

Everything seems to be working as expected with Tensorflow loading the correct models and running them properly. The issue I am seeing is that everytime the server polls for the config file in S3 it is readding models even if they are the same.
This results in regular logs as below.
2020-02-06 07:07:01.930476: I tensorflow_serving/model_servers/server_core.cc:462] Adding/updating models.
2020-02-06 07:07:01.930495: I tensorflow_serving/model_servers/server_core.cc:573]  (Re-)adding model: mlp
2020-02-06 08:07:01.965518: I tensorflow_serving/model_servers/server_core.cc:462] Adding/updating models.
2020-02-06 08:07:01.965548: I tensorflow_serving/model_servers/server_core.cc:573]  (Re-)adding model: mlp
2020-02-06 09:07:01.967228: I tensorflow_serving/model_servers/server_core.cc:462] Adding/updating models.
2020-02-06 09:07:01.967259: I tensorflow_serving/model_servers/server_core.cc:573]  (Re-)adding model: mlp

My concern is that this will be impacting performance of the model if the polling frequency is too high. I am wondering though whether there are actually any changes going on or if this is just additional logging.

A: This all looks normal.
Looking at the code (server_core.cc), it seems that these messages are displayed when reading the model.config file rather than when loading the models... which would have to happen after reading the model.config file. Although I don't understand the code clearly, I think we can conclude that these messages are not displayed when loading the models themselves; but are displayed at an earlier point in the workflow.
It only tries to figure out which models are new after these messages have been displayed.
 You can see the comparison happening here.

There is one strange thing about your question. From the timestamps of your messages, it seems that your models.config file is being read every 60 minutes instead of every 60 seconds.


text:
Q: Windows Forms Databound Control Accessing Getters For All Properties I have several bound controls on a Windows Form that link to properties on another class.  When ANY ONE of the controls' values is changed, ALL bound properties' Getters are accessed.
Class code:
Public Class Student

    Private _Name As String
    Public Property Name As String
        Get
            Return _Name
        End Get
        Set(value As String)
            _Name = value
        End Set
    End Property

    Private _Grade As String
    Public Property Grade As String
        Get
            Return _Grade
        End Get
        Set(value As String)
            _Grade= value
        End Set
    End Property

    Private _Age As Integer
    Public Property Age As Integer
        Get
            Return _Age
        End Get
        Set(value As Integer)
            _Age = value
        End Set
    End Property

End Class

Form Code:
Public Class Main

    Public ThisStudent As New Student

    Private Sub Main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.Name_TextBox.DataBindings.Add("Text", Me.ThisStudent, "Name")
        Me.Grade_TextBox.DataBindings.Add("Text", Me.ThisStudent, "Grade")
        Me.Age_TextBox.DataBindings.Add("Text", Me.ThisStudent, "Age")
    End Sub

End Class

When I type into the "Name" texbox only, the Getters for Name, Grade, and Age are ALL being accessed (I'm actually not even sure why the Getter is being accessed for "Name" itself, since it should just be Setting the name).  In my actual use-case, the Getters are doing some extra validation, which makes the Databinding VERY slow whenever a control value changes and it then checks the Getters of 30+ other properties that are unrelated, but are bound to entirely different controls.
Is there a way for me to Databind multiple controls to properties in the same object, but only access the properties that are actually bound to that specific control?

A: When you bind to an object and change the value of bound property of a data-bound control, all bound controls will reload their values by default and it calls the getter of the properties.
To stop this behavior, you can to set ControlUpdateMode property of Binding class to Never:
Me.Name_TextBox.DataBindings.Add("Text", Me.ThisStudent, "Name") _
    .ControlUpdateMode = ControlUpdateMode.Never
Me.Grade_TextBox.DataBindings.Add("Text", Me.ThisStudent, "Grade") _
    .ControlUpdateMode = ControlUpdateMode.Never
Me.Age_TextBox.DataBindings.Add("Text", Me.ThisStudent, "Age") _
    .ControlUpdateMode = ControlUpdateMode.Never

This way you are saying, never reload Name_TextBox, Grade_TextBox and Age_TextBox.
If for any reason you want to reload value of the data source into control, you can force a control update by calling the ReadValue method on the related Binding.
For example to reload all values of ThisStudent into the related TextBox controls, you can use the following code:
BindingContext(ThisStudent).Bindings.Cast(Of Binding) _
    .ToList().ForEach(Sub(x) x.ReadValue())


text:
Q: Transforming puzzle to graph theory? I am trying to solve the puzzle below and am thinking that there ought to be some way of formulating it as a problem about counting matchings, but I can not make it work. I would appreciate a hint or a different strategy.
N premier league footballers, all with different birth dates, and a single female, Natasha, are to be seated at a round table. To avoid any footballers getting ignored, each footballer must either sit next to a younger footballer or to Natasha. In how many ways can the footballers and Natasha be seated?

A: Let's elaborate the hint of Michael Ulm:

*

*We first seat Natasha, there are $N+1$ possibilities.

*The youngest footballer cannot sit next to a younger footballer, so we must seat him next to Natasha. There are two possibilities.

*The second youngest footballer can either sit next to Natasha or next to the youngest footballer. There are two possibilities.

*The third youngest footballer must sit next to Natasha or to one the two youngest footballers. Since those three are already seated in a row, there are again two possibilities (the two empty seats next to them).

Going on like this, we have 2 possibilities for all footballers up to the second oldest one. The oldest footballer goes to the last empty seat.
So the total number of possibilities is
$$
(N+1)\cdot 2^{N-1}.
$$


text:
Q: Single quotes on Quarkus examples, error or not? I've seen this example in the Quarkus guide, and the single quotes gives error on Windows SO. Are they to indicate what exactly that should be written or is it that it should be written literally like that?
Example on Quarkus Guide

A: It could be possible that it is written for a Linux environment. Apparently, Windows handles single quotes differently. It is possible that double quotes (") would work.
You also need to have access to this quarkus command. So if it tells you that the command cannot be found, that might be the issue.


text:
Q: How to get extended data type in AX [X++] I am using the following code to get type of a field. How do I get "extended type"
tID = dict.tableName2Id('CustTable');
dt = new DictTable(tID);
if (dt)
{
    fId = dt.fieldName2Id('CustGroup');
    df = dt.fieldObject(fId);
    if (df)
    {
        t = df.type(); // Need to get extended data type
        print enum2str(t);
        pause;
    }

}

Kindly help.

A: Use typeId() instead of type() to get the ID of the extended data type. With extendedTypeId2Name() you can then find its name.

A: If you really want to do "reflection" over the extended data types, then the correct Class is DictType:
http://msdn.microsoft.com/en-us/library/gg804354.aspx


text:
Q: How to align an Angular grid in CSS? How is a grid to be aligned in the center of the page with css in an Angular component
.grid-container {
display: grid;
grid-gap: 20px;
grid-template-columns: repeat(3, 1fr);
}

I tried margin-left and margin-right in percentage but it doesn't work very elegant.
<main>
 <div class="grid-container col-md-9 text-center center">
 <card class="grid-item" [data]="topic"><card>
<ng-container *ngFor="let o of os">
    <card class="grid-item" [data]="o"></card>
</ng-container>
</div>
</main>

A: you can do that in css :
main {
  display: flex;
  justify-content: center;
}


text:
Q: Lagging/Differences in Pig Is there a way to generate "column" lags or differences in Pig? Here's an example of what I'm trying to do, transcribed from R:
         Value           Value.Diff
1        0.209                NA
2        0.198            -0.011
3        0.187            -0.011
4        0.176            -0.011
5        0.168            -0.008
6        0.159            -0.009

I realize this might be tricky given the (presumably) distributed nature of Pig's data storage, but thought it might be possible given that Pig 0.11+ allows you to rank tuples.

A: Something like this should work:
values = rank values by some_field;
values = foreach values generate $0 as this_rank, $0 - 1 as prev_rank, value;
copy   = foreach values generate *;
pairs  = join values by this_rank, copy by prev_rank;
diffs  = foreach pairs generate this_rank, values::value - copy::value as diff;


text:
Q: how many questions did the answer in each round? yolanda went on a quiz show. the question in the first round were worth 6 points. the questions in second round were worth 10 points. yolanda answered a total of 5 questions and earned 34 points. how many questions did the answer in each round?

A: Let $x$ be the number of questions answered in the first round, and $y$ be the number of questions in the second round. Now, she answered $5$ questions, thus $$x+y=5.$$ Also, she had a total of $34$ points, thus $$6x+10y=34.$$ We include the second equation based on the points for each question. Solving the first equation: $$x=5-y,$$ and substituting it into the second: $$6(5-y)+10y=34$$ $$\Longrightarrow 30-6y+10y=34 \Longrightarrow y=1. $$ Putting this value into the first equation yields $x=4$. Thus, she answered $4$ in the first round and $1$ in the second round.


text:
Q: Calling Kendo UI DatePicker using prototype We use prototype.js for javascript but we are now implementing the Kendo UI DatePicker and I am confused on how to approach an issue. Given the following:
function MyClass()
{
 this.Name = $('inputName');
 this.LastName $('inputLastName');
 this.GridViewInputs;
}

MyClass.prototype.init = function()
{
  //some event observe methods here
}

MyClass.protype.setUpDatePickers = function()
{
   //grab all input values from a gridview and attach a date picker to each
   this.GridViewInputs = $$('.Dates');

   //HERE IS MY PROBLEM, I AM NOT SURE HOW TO CALL THE FUNCTION BELOW FROM HERE
   //AND PASSING IT EACH INPUT
}

 $j(document).ready(function() {
                // create DatePicker from input HTML element
                $(myInput passed here).kendoDatePicker();
      });

The problem i have is that I cant really use this.GridViewInputs inside the $j function because it would say its not recognized, I believe because it's outside the object.

*

*Can I include this call inside my MyClass object so that I can pass my values and how would i do that?

A: Why don't you call the setUpDatePickers method inside the document ready function?
2 ways to call it - either after you have created an instance of MyClass
var t = new MyClass();
t.setupDatePickers();

or directly from the prototype
MyClass.protype.setUpDatePickers()

If you call it directly from the prototype you do not have this available - so it might not be the best way
Also inside of MyClass.protype.setUpDatePickers to put the date pickers on the inputs you'll need to do one of the following - I'm not exactly sure if the first one will work as I haven't used kendo before - but the 2nd one will work.
$$('.Dates').invoke('kendoDatePicker');
//
//OR
//
$$('.Dates').each(function(input){
    input.kendoDatePicker();
});


text:
Q: Convert 2 images to numpy arrays and compare pixel by pixel I'm using Pillow to load 2 images (apparently black and white, however in RGB format) and convert to grayscale. I can't use opencv.
aImage = Image.open(imageA.visualFilename).convert("L")
bImage = Image.open(imageB.visualFilename).convert("L")

I convert them to numpy arrays.
aArray = np.array(aImage)
bArray = np.array(bImage)

What I ultimately want to do is (1) count all the black pixels in each array and (2) compare aArray to bArray pixel by pixel and count the number of matching black pixels.
What's currently confusing me is when I print one of the arrays print aArray.shape , I don't understand what i'm looking at. I'm using np.set_printoptions(threshold='nan') to print the full array but it appears to be a series of elements with way too many values than I would expect. I would think each element would contain either a single 255 or 0?
Am I doing this the correct way in order to work with a black and white pixels? When I attempted to convert to binary "1", I got "True"/"False" results which confused me a little more.
Also, assuming aArray and bArray look identical, but are actually off by a few pixels, what is the best way to incorporate a 'fuzzy logic' to the pixel by pixel comparison of the two?
Just for additional information, aImage.size and aImage.mode return
(184, 184)
L

A: For starters the L mode in the Image.open(visualFilename).convert("L") does not convert a image to Black&White, rather it converts the image to a gray scale using the following formula:

L = R * 299/1000 + G * 587/1000 + B * 114/1000

Being R, G and B, red, green and blue respectively
This formula goes throughout the image and change a 3 (RGB) channel pixel to a 1 (gray scale) channel pixel that best approximates the 3 channel color scheme. And that is why at the end you don't get only the values 0 and 255. Instead you get a pixel with values ranging from 0 to 255.
To compare all the black pixels between two gray scale images first you have to define what black really means. Is a value like 10 black enough or 25 is already black for you? You got to remember that color is not absolute, and its meaning can change depending what you are doing.
Therefore a way around this is to set a threshold in which you will define "what is black for you". Using a simple Threshold function would do. So, I think this simple code might solve your problem:
import numpy as np

def threshold(array, th=50, above_to_max = False):
  #check type numpy
  if type(array) is np.ndarray:
    #Creates a copy to not mess with original
    array = array.copy()
     #set all values below threshold to 0
    array[array<=th] = 0
    if above_to_max:
      #set all values above threshold to 0
      array[array>th] = 255
    return array
  else:
    raise Exception("Array must be a numpy array")

#Example images
image1 = [[ 0,  5, 10, 15, 20],
          [ 25, 30, 35, 40, 45],
          [ 50, 55, 60, 65, 70],
          [175,180,185,190,195],
          [200,210,215,240,255]]

image2 = [[ 5,  5, 110,  5,  0],
          [ 25, 30, 35,  0, 15],
          [150, 55, 60, 65, 70],
          [275,280,285,290,295],
          [ 20, 10, 15,240,255]]

#Transform to array
array1 = np.asarray(image1, dtype=np.uint8)
array2 = np.asarray(image2, dtype=np.uint8)

#Apply threshold
tsh_array1 = threshold(array1)
tsh_array2 = threshold(array2)

print(' Array1\n', array1, '\n', 'Thresholded1\n',tsh_array1,'\n' )
print(' Array2\n', array2, '\n', 'Thresholded2\n',tsh_array2,'\n' )
equals = (tsh_array1==0)[tsh_array2==0]

print("Number of pixels in the same position equal to zero: {}".format(sum(equals)))

This code renders the following:
Array1
[[  0   5  10  15  20]
 [ 25  30  35  40  45]
 [ 50  55  60  65  70]
 [175 180 185 190 195]
 [200 210 215 240 255]]
Thresholded1
[[  0   0   0   0   0]
 [  0   0   0   0   0]
 [  0  55  60  65  70]
 [175 180 185 190 195]
 [200 210 215 240 255]]

Array2
[[  5   5 110   5   0]
 [ 25  30  35   0  15]
 [150  55  60  65  70]
 [ 19  24  29  34  39]
 [ 20  10  15 240 255]]
Thresholded2
[[  0   0 110   0   0]
 [  0   0   0   0   0]
 [150  55  60  65  70]
 [  0   0   0   0   0]
 [  0   0   0 240 255]]

Number of pixels in the same position equal to zero: 9

EDIT:
Let's take a better look at the following line: (tsh_array1==0)[tsh_array2==0]

*

*(tsh_array1==0) returns an array with the same shape as tsh_array1 with value True in the position of a 0 value and False otherwise

*[tsh_array2==0] is the same as a where clausule. It filters the previous item where tsh_array2==0
The result is an array that looks like that:
[ True True True True True True True True True False False False False False False False False]

Since True is the same as 1, the sum of this array will return the number of zeros in the same position in the two arrays
I hope it helped!

A: Sounds like you want Numpy arrays to me.
When I do that I load the images to array by using cv2, with
img = cv2.imread(filepath, cv2.IMREAD_UNCHANGED)
using a demo img of mine I get
>>> img.shape
(2576, 4592, 3)
>>> img.max()
255
>>> img.min()
0
Comparing it to a second img results in a Boolean for each pixel which says if these pixels are identical. See
>>> (img == img2).shape
(2576, 4592, 3)
You can determine if the images are the same, by checking if all pixels compared to True:
>>> (img == img2).all()
False
Counting black pixels by:
>>> sum(sum(sum((img == 0).astype(int))))
6136
Here you sum three times for each axis once. You can also do it fast by using:
>>> ((img == 0).astype(int)).sum()
6136
EDIT:
second part of your question is a bit tougher.
1) offset in x y direction.
Then you probably could try to find that by embedding both images in larger arrays.
Now you could work with clustering approaches to find key areas which you then try to connect.
This should result in a shifting and maybe rotation, which should be the translation between the two images.
2) An offset in color on the other hand would require something like a subtraction of both images.
Now you could use the sum and calculate ratios to extreme cases like black and white images.
3) Fuzzy logic.
You could move away from the idea of comparing index to index, but sliding a window over each image and compare the sets that are shown in the windows.
EDIT 2:
for not using cv2:
you can skip the cv2 load and just use np.array(aArray) like you did in your question. I just used cv2 because i had no PIL installed and wanted to show you demo.


text:
Q: Analogous versus analogue: why the extra "o" after the "g"? Why does the word analogous have an extra letter o after the g in comparison to the word analogue?
How is their origin related to one another?
According to The American Heritage Dictionary of the English Language, 4th edition, analogue has the following origin:

French, analogous, analogue, from Medieval Latin analogus, from Greek analogos, proportionate; see analogous. (see wordlink.)

And analogous has similar origins:

From Latin analogus, from Greek analogos, proportionate : ana-, according to; see ana- + logos, proportion; see leg- in Indo-European roots. (see wordlink.)

A: It's not an "extra" o. It's there because the English suffix is ‑ous not ‑us.
The OED notes the following as part of a very much longer etymological note:

Classical Latin stressed long ō /oː/ passed, via close /o/, into a
  diphthong /ou/ in early Old French, which was variously written o or u,
  less commonly ou; hence Latin adjectives in -ōsus, which either came down
  in popular use, or were adopted at an early date, had in Old French forms
  in -os, or -us (-ous), e.g. coveitos, coveitus, doleros, dolerus,
  envios, envius, glorios, glorius, religios, religius.
In the 12th
  cent. the vowel-sound changed in Central French (via 11th-cent. /eu/ and
  later /øu/) to /ø/, written eu, so that the suffix had now the form -eus
  (covoiteus, dolereus, envieus, glorieus, etc.); and this still later
  was written in the masculine -eux (convoiteux, envieux, glorieux, with
  feminine however in -euse), as still in modern French.
In Anglo-Norman the
  forms were the same as in early Old French (coveitos, coveitus, envios,
  envius, glorios, glorius), but in English the vowel was soon identified
  with Old English and Middle English long ū, and like it written ou
  (covetous, envious, glorious), the spelling ever since retained, though
  the sound has passed through /uːs/, /us/, /ʊs/ to /ʌs/, /əs/ (there is some
  evidence from early modern English orthoepists that where secondary stress
  fell on the suffix, Middle English long ū was sometimes retained as the
  diphthong /ʌu/, and that under low stress the final -s could be voiced to
  /z/: see E. J. Dobson Eng. Pronunc. 1500–1700 (ed. 2, 1968) II. §281,
  §363).
This -ous, having thus become the form of the suffix in all words
  from Norman French, became the established type for all those of later
  introduction, whether adaptations of French adjectives in -eus, -eux, or
  Latin adjectives in -ōsus (but see -ose suffix¹), or new formations on the
  analogy of these, from French, Latin, or other elements.

And later also:

This tendency to represent a Latin adjective by an English form in -ous may have been strengthened by the fact that the canonical form of the Latin adjective entered in dictionaries is the nominative singular masculine, and that this in the majority of adjectives ends in -us, the English pronunciation of which is the same as that of the English word in -ous, so that the latter to the cursory observer appears to be merely an English spelling of the Latin.

So all such words have the -ous; it's not just analogous that merits is and so it somehow special.

A: The two terms entered the English languages in different periods, analogue,  retained the French spelling from which the different suffixes.
Analogous:

*

*"corresponding (to some other) in particulars," 1640s, from Latin analogus, from Greek analogos "proportionate, according to due proportion," from ana "throughout; according to" (see ana-) + logos "ratio, proportion," a specialized use (see Logos). Used with to or with.

Ethymonline
Analogue:

*

*The newer [analogue came directly from French around 1800, bearing the word's French sense and spelling. The newer spelling, analog, developed in the U.S. around the early 20th century and is now preferred in the U.S. and to a lesser extent in Canada.

The Grammarist
As for the use of the suffix -ous of terms like analogous:

*

*a suffix forming adjectives that have the general sense "possessing, full of" a given quality (covetous; glorious; nervous; wondrous); -ous, and its variant -ious, have often been used to Anglicize Latin adjectives with terminations that cannot be directly adapted into English (atrocious; contiguous; garrulous; obvious; stupendous).  As an adjective-forming suffix of neutral value, it regularly Anglicizes Greek and Latin adjectives derived without suffix from nouns and verbs; many such formations are productive combining forms in English, sometimes with a corresponding nominal combining form that has no suffix.

(Random House Dictionary)


text:
Q: calculating program's runtime for each iteration using Unix program time I wish to calculate runtime of my program which approximates PI using Monte Carlo Method. I have written a unix shell script which feeds the program No of points, N = 10^{k} , for K = 1,2, ...7.
Now I wish to find the execution time for Each N in Unix program time. My unix shell script looks as follows:
#!/bin/bash

k=1
N=10
while [[ k -le 7 ]]
do
    echo "$k N" | ./pi $N

    ((k = k + 1))
    ((N = N * 10))
done

Now when I type: $ time ./pi.sh , it returns me the total execution time
        10                 3.6            0.1459155902616465
       100                3.08           0.01960555055392467
      1000               3.104           0.01196611328551369
     10000              3.1284          0.004199352062629202
    100000              3.1432         0.0005116342528909465
   1000000            3.139704         0.0006011771092076384
  10000000            3.141432         5.113762588206346e-05

real    0m0.583s
user    0m0.560s
sys     0m0.012s

I was wondering if I have to write a bash script to get execution time for Each N input or I have to do something in my code.

A: By writing $ time ./pi.sh you are measuring time needed to execute pi.sh, which has a loop in it. So you measure total time for all iterations. If you want to measure every iteration independently, you have to put time in invocation of the iteration:
echo "$k N" | time ./pi $N


text:
Q: How to add input to a database in netbeans I'm trying to add input to a bookings table for a fictitious company in Netbeans.
When the user comes to the bookings page they're prompted to a form where they add some details and click the button leading the details to be added and saved to the bookings table
This is what I've used to create the table
<h:form>
    <h:panelGrid columns = "2" border = "1" cellpadding = "0" cellspacing = "2">
     <f:facet name="header">
         <h:outputText value="Fill the form to complete booking"/>
     </f:facet>
           <h:outputText value="Enter your name"/>
           <h:inputText value="#{training4uBean.name}"/>
           <h:outputText value="Enter your phone number"/>
           <h:inputText value="#{training4uBean.phone}"/>
           <f:facet name="footer">
           <h:commandButton id="submitBtn" value="Book" action="#{training4uBean.addBooking}"/>
            </f:facet>
         </h:panelGrid>
       </h:form>

and in the bean ive put ....
 public String getName(){
    return name;
}
public void setName(String name){
    this.name = name;
}
public Integer getPhone(){
    return phone;
}
public void setPhone(Integer phone){
    this.phone = phone;
}

public void addBooking (){

}

}
and I'm lost as to what to put in the bean method addBooking, nothing I have done seems to work!
Any help would be very appreciated!


text:
Q: Was cleavage first used for Jane Russell? While trying to understand when and why the term cleavage was first used to refer to a woman neckline I've found that:

The sense of "cleft between a woman's breasts in low-cut clothing" is first recorded 1946, defined in a "Time" magazine article [Aug. 5] as the "Johnston Office trade term for the shadowed depression dividing an actress' bosom into two distinct sections;"

But they also say that:

traditionally first used in this sense by U.S. publicist Joseph I. Breen (1888-1965), head of the Production Code Administration (replaced 1945 by Eric Johnston), enforcers of Hollywood self-censorship, in reference to Jane Russell's costumes and poses in "The Outlaw." (Etymonline)

The story about J.I.Breen is reported also in History of cleavage

In the 1940s, Joseph Breen, head of the U.S. Production Code Administration (PCA), applied the term to breasts in reference to actor Jane Russell's costumes and poses in the 1941 movie The Outlaw.

So apparently the term was not first used in 1946 by magazine Time, but in the early 40s given that the movie was released two years later, in 1943, because of PCA censorship.
I could not find evidence that the term was actually used in those years. Was it actually cooked up the the imaginative mind of a censor? Is there evidence of its earliest usage?

A: Searches of the Google Books and Elephind (newspaper) databases yields more than a dozen matches for cleavage (in the revealing physique sense) from the year 1946, a couple of which date directly or indirectly to August 4, 1946—one day earlier than the August 5 Time magazine article cited in the posted question and in TaliesinMerlin's excellent answer.
Here is the full text of "'Wicked Lady' Too Wicked: Scenes Reshot for America," in the [Sydney, New South Wales] Truth (August 4, 1946):

NEW YORK, Saturday.—British producers are resentfully reshooting several costly scenes of 'The Wicked Lady' because Hollywood's self-imposed censorship considers actresses' half-covered bosoms far more sexy than yards of uncovered legs.
'The Wicked Lady', is only one of three films which will have to be altered to meet the Johnson Office morality code.
It is a very interesting example of the length to which the American film industry goes to keep half-baked censors like the unofficial League of Decency out of its hair.
'The Wicked Lady' is a film of the Restoration period, and beauteous Margaret Lockwood and Patricia Roc wear low-cut, half-bosom-exposing costumes which, according to Joe Breen, United States interpreter of the Hollywood morality code, now in London, 'expose too much cleavage.'
'Cleavage' is Hollywood's own delicate term for the shadowed depression dividing an actress's bosom.
English-produced 'The Rake's Progress' will have its title changed to 'The Notorious Gentleman' before American distributors show it.
Mr. Breen fears that the American public would think from the title that it was a documentary film on gardening.

And from a brief item in Newsweek (August [?] 1946) [combined snippets]:

Amazed: Prof. Cyril E. M. Joad, of London University and author of "A Guide to Modern Wickedness," denounced the censoring of motion pictures in the United States and said he was amazed at American insistence upon banning the "cleavage . . . the top end of the little ravine that runs down between and separates women's breasts. In an article in The London Sunday Dispatch on Aug. 4, he also complained that American films bar the words "damn" and "bastard," and asked: "Does nobody in America ever swear and are there no illegitimate children?"

Since Newsweek claims to be quoting comments by Professor Joad that were first reported in an article published in the London Sunday Dispatch of August 4, 1946, the latter source would seem to have a nominal one-day advantage over the August 5, 1946, issue Time magazine—but as Sydney is several time zones ahead of London, the Truth may have an even stronger claim to having the earliest published occurrence of the term in the relevant sense.
From Earl Wilson's column in the Los Angeles [California] Daily News (August 13, 1946):

Look! There's Diana Lynn, beautiful young Paramount actress, wearing a low-cut white dress that shows much cleavage.
"Diana, why are you so un-dressed-up tonight?" I ask her.

Earl Wilson was a smart-alecky, gossipy, night-life journalist who wrote a nationally syndicated column for decades, operating out of New York City and based at the New York Post. I remember that he was still going strong (and his column was still appearing regularly in my hometown newspaper, the Houston Post) in the late 1970s.
From Mary Armitage, "Liaison Lack on Movie Morality," in the [Adelaide, South Australia] Mail (August 31, 1946):

Forty scenes of Gainsborough's "Wicked Lady" have been reshot at a cost of L5,000, and a great number of man-hours, because America's production code censor, Joseph I. Breen, decided that Margaret Lockwood's period gowns were too low-cut to be seen by American audiences.
This is not the first time that a British movie has been rejected by America through "chest trouble," or what film people call "cleavage." The same thing happened over the release of the British-made "Scarlet Pimpernel." American production code officials then considered Merle Oberon's eighteenth century gowns were too revealing for twentieth century American audiences.

From "Here She's Wicked; Here She Isn't" in the [Sydney, New South Wales] Daily Telegraph (September 15, 1946):

U.S. film censors were upset by the "cleavage" in the low-bosomed gowns, of Margaret Lockwood in the British film, The Wicked Lady (left), and of the supporting actress, Patricia Roc.
They demanded the re-shooting of 40 close-ups before passing the film for the American public.

From "Josephine O'Neill's Reviews," in the same issue of [Sydney, New South Wales] Daily Telegraph

A more dashing leading man than Russell Wade could have made this fleeting frivol [The Bamboo Blonde] more fun. But Russell is a Sad Sack of a hero; and Miss [Frances] Langford, in spite of that blonde hair, and those cleavage gowns, is oddly prim.

From Earl Wilson's column in the Los Angeles [California] Daily News (September 27, 1946):

Ginger Rogers shows excess "cleavage" In "Magnificent Doll" and the Johnston office insists on covering her ...

From "'Breast Line' War Is Now On: British-U.S. Battle Front,"in the [Sydney, New South Wales] Sun (October 20, 1946):

Another British film held up here [in Hollywood] by censorship trouble is "Pink String and Sealing Wax."
Breen's office is objecting to the "cleavage" shown by Googie Withers' evening gowns.

From "Royalty Censored a Wedding Gown," in the [Sydney, New South Wales] Daily Telegraph (October 27, 1946):

A "cleavage" had become a matter of concern to the Ladies of the Royal Household.
At Buckingham Palace, Her Majesty Queen Elizabeth and the two Princesses held strong opinions about the propriety of the wedding gown chosen by their cousin, 22-year-old Patricia Edwina Victoria Mountbatten.
This week she was marrying 21-year-old John Ulick Knatchbull, seventh Baron Brabourne.
It was a beautiful gown of beaten gold Indian brocade. It had been designed in Paris by the famous couturier Captain Edward Molyneux. So had the blue bridesmaids' frocks.
That was the trouble. They were all "too, too Parisian" for the Regal taste, too daringly cut, and exposed rather too much bosom.
On the dresses at they stood, a Royal veto was placed. Like the costumes in the movie, "Wicked Lady," they had to be remade.

From "Movie Censorship: It Confuses British Movie Makers but U.S. Producers Get Around It," in Life magazine (October 28, 1946):

The thing that annoys British film-makers most about the [U.S.] Production Code is the highly legalistic way it works, especially regarding sex. To remove any symptom of sex from the traditional symbol of a happy marriage, a double bed is never shown on the screen except with only one person in it.  "Indecent exposure" is prohibited, but any bathing suit passes so long as it has a high bodice. "Cleavage" is banned, but a tight sweater is permissible (see top picture, opposite [of Diana Lynn in The Bride Wore Boots]). Brutality and drunkenness are prohibited except "when essential to the plot." Very often producers insist that such things are essential. ...
...
[Caption:] Cleavage between women's breasts forced revision of forthcoming British historical movie The Wicked Lady, starring Patricia Roc (above). For U.S., distributors had to substitute close-up shots for revealing ones like this.

From "US Censors Were Snubbed," in the [Sydney, New South Wales] Daily Telegraph (November 10, 1946):

LONDON, Sat.—British censors gave a subtle snub to their US fellows this week.
That Howard Hughes-Jane Russell film, The Outlaw, came up for review.
American censors banned the film for over three years, passed it, and then clamped down the ban again.
Reason: The "cleavage" in the bosomy shots of the heroine, Jane Russell.
The British film censors saw The Outlaw, and, after asking for one tiny cut, passed it for General Exhibition.

From Earl Wilson's column in the Los Angeles [California] Daily News (November 23, 1946):

NEW YORK.—Paulette Godard now wears a frog in her bust.
I guess I'd better clarify that.
When Ingrid Bergman was upsetting Broadway at the opening of the stage show "Joan of Lorraine"—which dumb showgirl Taffy Tuttle calls "Joan of Fontaine"—there sat practical Paulette wearing this wee gold frog hanging down in what the English would call her "cleavage."
"Look!" said Paulette to me, superfluously.

From an unidentified item in Negro Digest (1946) [combined snippets]:

. . . Nudist magazine, Sunshine & Health, court-testing Post Office department's ban on nude white breasts but okay of nude Negro breasts. Which reminds of longstanding N. Y. state film censorship rule which allows movies to expose Negro women's breasts full view but turns thumbs down on just a wee too much cleavage on white girls . . .

From Gordon Gilmour, "London Diary: Ernest Bevin May Be on His Way Out," in the [Sydney, New South Wales] Sun (December 4, 1946):

Critics argue that to spend £17,000.000 a year on films like the currently-showing, much-panned "The Outlaw" is throwing money down the sink—an action which not even Jane Russell's ample "cleavage" can justify.

And from a caption accompanying "London Letter: A Night at Picadilly's Beau Geste Club," in the [Hobart, Tasmania] Mercury (December 17, 1946):

New Cleavage Necklines: These two pastel-shaded afternoon frocks by Frederick Starke show you the cleavage necklines and elaborately draped bodices that are the very newest things in London. The one on the left is in pink, and a further feature to note is the heart-shaped bodice. The frock on the right is in dove grey.

Conclusions
The use of cleavage to refer to a certain kind of physiological negative space seems to have arisen in the U.S. movie industry in connection with the Motion Picture Production Code of 1934 and its latter-day enforcers.
The earliest cited mentions of cleavage in this sense seems to have come from three different periodicals on three different continents within a day of each other: an article in a Sydney newspaper on August 4, 1946; an article in a London newspaper on the same day; and an article in a U.S. news weekly dated August 5, 1946. (Note that the third instance may actually have come out earliest, depending on whether Time magazine was already engaged in the misleading practice of dating its periodicals by their sell-by date—the date when they get pulled from newsstands—rather than their actual first day on sale.)
All three articles focus on the fallout from a decision by U.S. censors to ban a British film (The Wicked Lady) for exposing too much of the actresses' skin, leading the studio to reshoot numerous close-ups—at considerable additional expense—after making wardrobe adjustments to placate the censors. Given that Joe Breen of the U.S. Production Code Administration had, according to the August 5 Time magazine account, been in London "for the past fortnight" making his case for banning the film, British newspapers may have been exposed to (and reported on) the term cleavage as early as late July 1946.
In this regard it is noteworthy that, whereas the August 5 U.S. and August 4 Australian articles referring to cleavage focus on Joe Breen, the August 4 London article quotes to it in an interview with Professor Cyril Joad, whose familiarity with the term may well have resulted from his having encountered it in an earlier article in the British press. If I had an subscription to the British Newspaper Archive, I would check its collection from July and early August 1946 for possible earlier mentions of cleavage—but I don't.
All three of the August 4 and 5 articles noted above treat the term cleavage as contemporaneous jargon among U.S. film industry executives and censors—but I haven't found any evidence that the term had appeared in the press or in published books prior to August 4, 1946. Mention of cleavage in the relevant sense in a private letter that one U.S. Production Code executive sent to another in 1935 (as cited by TaliesinMerlin) offers persuasive evidence that the expression was in use within the film industry more than a decade earlier, but there is no reason to suppose that it had escaped that narrow zone of use before Breen's visit to London in the summer of 1946.
Although the initial flurry of articles about the Wicked Lady kerfuffle undoubtedly played a major role in propagating the term, other sources subsequently helped spread it beyond the context of film industry censorship. In the United States, one such source was the widely read syndicated columnist and bon vivant Earl Wilson, who used the term three times in columns published in the second half of 1946. Curiously, in the last of those three columns, Wilson presents cleavage as a British English term, presumably because he picked up on it (as so many others did) in the wake of the Wicked Lady controversy.
That British English speakers were, from a fairly early date, familiar with the term outside the context of film industry usage is evident from the commercial appearance of garments with "cleavage necklines" in England in late 1946—a fashion development that an Australian newspaper characterizes as "the very newest things in London."
In Australia, early mentions of cleavage in the relevant sense are peculiarly concentrated in Sydney newspapers, with instances unrelated to the film industry appearing as early as October 1946.

A: Yes, the 1946 Time article itself claims that the PCA used cleavage as its own trade term. However, I have since found evidence of usage as early as 1935. What follows is first the explanation consistent with Etymonline and then the new evidence.
The Word First Appeared in Publication in 1946
The Oxford English Dictionary gives the first usage of "cleavage, n." as the cleft between a woman's breasts in 1946, referring to the same Time article:

1946   Time 5 Aug. 98   Low-cut Restoration costumes..display too much 'cleavage' (Johnston Office trade term for the shadowed depression dividing an actress' bosom into two distinct sections).

I tracked down the full text in an academic database, EBSCOhost. The full title of the article is "Cleavage & the Code." The intro to the article mentions Joseph Breen by name (as Joe Breen) as someone working in the "Johnston Office" to explain American film codes to British audiences:

Which is more sexy—an actress' half-covered bosom or her uncovered legs?
British moviemakers, puzzled by U.S. cinemorality, want a serious answer to this question. For the past fortnight, the man who knows all anyone needs to know about U.S. censorship has been in London trying to explain it in simple English. It is a tough job—even for the Johnston Office's jowly, jolly Joe Breen. No. 1 U.S. "interpreter" of the Hollywood morality Code.

The film being described in the OED quote is Wicked Lady (Wikipedia link). Here is that quote in full:

Wicked Lady, a 1945 picture starring Margaret Lockwood, James Mason and Patricia Roc, was a big moneymaker in England. But the U.S. will have to wait to see it. Low-cut Restoration costumes worn by the Misses Lockwood and Roc (see cut) display too much "cleavage" (Johnston Office trade term for the shadowed depression dividing an actress' bosom into two distinct sections). The British, who have always considered bare legs more sexy than half-bare breasts, are resentfully reshooting several costly scenes.

So it's the 1946 article itself that claims cleavage is a "Johnston Office trade term," that is, that the term was very likely invented by the PCA to refer to an indecent showing of the breasts in what then functioned as a euphemism.
However, I can find no direct reference to The Outlaw, even though the film was infamous for riling up the PCA about bosoms. All the sources I'm finding point back to the 1946 article or gesture generally to The Outlaw. For example, this excerpt from Thomas Doherty's book Hollywood's Censor : Joseph I. Breen and the Production Code Administration (2007, p. 254) summarizes the earlier affair without any actual evidence of the usage of cleavage at the time:

When Breen and his staff sat down to review The Outlaw and beheld Jane Russell—bouncing on horseback, strutting in clinging blouses, and leaning over in plunging necklines to spill out the upper portions of her 38D–25–36 figure—the vista inspired the most goggle-eyed of all Breen outbursts over mammary excess. "In my more than ten years of critical examination of motion pictures, I have never seen anything quite so unacceptable as the shots of the breasts of the character of Rio [Russell]," he sputtered. "Throughout almost half the picture the girl's breasts, which are quite large and prominent, are shockingly emphasized, and, in almost every instance are very substantially uncovered." Without cuts—or more covering—the Breen Office absolutely refused to grant The Outlaw lawful passage.

Prior Evidence of Cleavage in the PCA in 1935
There is textual evidence of the PCA / MPPDA using the word as early as 1935. In a December 31, 1935 letter from foreign representative Frederick Herron to Joseph Breen (in Margaret Herrick Library Digital Collections), Herron speculates on the strategy for appearing consistent to Londoners in applying censorship policy to Captain Blood:

I saw "Captain Blood" the other day and in the scene in Blood's cabin where the girl [Olivia de Havilland] is talking to him [Errol Flynn], she has her dress pulled down in front until the cleavage is just about that in Nell Gwyn. The same dress in other shots is perfectly all right.
What I am afraid of is that when this picture is shown in England and this low neck is shown that the newspapers will again take up the Nell Gwyn cleavage campaign. Some one in the studio must have deliberately done this because it is the only scene where there could be any criticism at all.

Herron suggests letting the depiction of cleavage go through untouched to avoid a big scene. The "Nell Gwyn cleavage campaign" is reference to an earlier rough reception for the 1934 film Nell Gwynn (see this Vanity Fair excerpt alluding to the censorship). In any case, the letter illustrates much earlier in-house use than Etymonline supposed.


text:
Q: How to reflect the entire CARTESIAN co-ordinate system to a line. I want to reflect every point possible in $R^2$ onto the line x+2y=0
Clearly we have a line equation with gradient :$ M= -1/2$
How do i find a suitable matrix to reflect all points to this line.
I'd appreciate any method, the more the better, thank you.

A: Hint More or less by definition, the reflection matrix fixes vectors parallel to the line and maps vectors orthogonal to the line to their negatives. These facts together give you geometric description of the eigenspaces along with their corresponding eigenvalues, and one can immediately reconstruct the matrix from these.

A: If a map is linear, a smart way to figure out its matrix is to figure out where the matrix takes the standard basis.  That is, with $v_1 = (1,0)^T, v_2 = (0,1)^T$ the standard basis and $M$ the matrix, we want to know, by whatever method, what are $Mv_1$ and $Mv_2$.  Since we don't know $M$ yet, we have to use other ways to find these two results.  Once we do, however, we can recover $M$ as $\left( Mv_1 ~ Mv_2 \right)$.  That is, the first column is $Mv_1$ and the second column is $Mv_2$.  A way to remind yourself that this works is to simulate (in your mind) what happens when we mutiply this matrix by $v_1$:  from the first row, it picks out the element in the first column.  From the second row, it picks out the element in the first column, et c...  It picks out the first element from each row and collects those into a vector.  Thus, we get the first column as output; we get $Mv_1$, as required.  Similarly, multiplication with $v_2$ picks out the second column and further, multiplication with $v_k$ picks out the $k^\text{th}$ column.
So, by any means we like we want to know where this reflection takes $v_1$ and $v_2$.  The line $x + 2y = 0$ can be written in slope-intercept form as $y = \frac{-1}{2}x + 0$.  When a point is reflected through a line, it starts and ends on a perpendicular to that line.  The slope of a line perpendicular to $y = \frac{-1}{2}x + 0$ has slope $\frac{-1}{-1/2} = 2$.  So the point at the end of $v_1$ is mapped somewhere on the line $y-0 = 2 (x-1) = 2x-2$.  The distance of the point from the line of reflection is the same before and after the reflection, so we should find this distance.  For this point, this is the distance between it and the point where the two lines intersect.  The line of reflection satisfies $x = -2y$, which we substitute to find $y-0 = 2(-2y)-2$, or $5y = -2$, which gives $y = -2/5$ and backsubstituting, $x=4/5$.  The distance is then $\sqrt{(1-4/5)^2 + (0--2/5)^2}$.  Finding the reflected point is then straightforward.  Repeat for the point at the end of $v_2$ and you have the two columns of your desired matrix.


text:
Q: validate alphanumeric value in UITextField I want alphanumeric value in textfield.If user enter only character or number then sending massage.Even no special characters acceptable.
        NSString *str = askIdTxt.text;
        NSCharacterSet *alphanumericSet = [NSCharacterSet alphanumericCharacterSet];
        NSCharacterSet *numberSet = [NSCharacterSet decimalDigitCharacterSet];
        BOOL isAlphaNumericOnly = [[str stringByTrimmingCharactersInSet:alphanumericSet] isEqualToString:@""] && ! [[str stringByTrimmingCharactersInSet:numberSet] isEqualToString:@""];
        if (isAlphaNumericOnly) {
             NSLog(@"isAplhaNumericOnly: %@",(isAlphaNumericOnly? @"Yes":@"No"));
        }

This is always returning true. I am not getting what is wrong in this.

A: How about using regular expression:
-(BOOL)isAlphaNumericOnly:(NSString *)input
{
    NSString *alphaNum = @"[a-zA-Z0-9]+";
    NSPredicate *regexTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", alphaNum];

    return [regexTest evaluateWithObject:input];
}

and then use it
if([self isAlphaNumeric:str])
{
    NSLog(@"IT IS ALPHA NUMERIC STRING");

}

edit
The same technique can be used to validate passwords, you need only better regex:
-(BOOL)isPasswordStrong:(NSString *)password {
/*
8-20 chars
at least one letter
at least one number OR special character
no more than 3 repeated characters
*/
        NSString *strongPass= @"^(?!.*(.)\\1{3})((?=.*[\\d])(?=.*[A-Za-z])|(?=.*[^\\w\\d\\s])(?=.*[A-Za-z])).{8,20}$";;
        NSPredicate *regexTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", strongPass];

        return [regexTest evaluateWithObject:password];
}

using the regular expression you can create different rules but this can give you a headstart,

A:  Call this Method and modify it accordingly .....

   -(BOOL) isPasswordValid:(NSString *)pwd
     {

       if ( [pwd length]<4 || [pwd length]>20 ) return NO;  // too long or too short
       NSRange rang;
       rang = [pwd rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]];
       if ( !rang.length ) return NO;  // no letter
       rang = [pwd rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]];
       if ( !rang.length )  return NO;  // no number;
       return YES;

     }

A: I guess the problem is in the alphanumericCharacterSet, here is a part from doc:

Informally, this set is the set of all characters used as basic units
  of alphabets, syllabaries, ideographs, and digits.

So, I am expecting it would allow the unwanted characters to you.
You may also try using Regex:
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[a-z\\d]+$" options:NSRegularExpressionCaseInsensitive error:&error];
NSUInteger matches = [regex numberOfMatchesInString:str options:NSMatchingReportCompletion range:NSMakeRange(0, [str length])];

BOOL hasMatches = (matches > 0) && !error;

A: Try this
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

        NSCharacterSet *charactersToBlock = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
        return ([string rangeOfCharacterFromSet:charactersToBlock].location == NSNotFound);
}

A: Try this :
NSCharacterSet *blockedCharacters = [[[NSCharacterSet alphanumericCharacterSet] invertedSet] retain];

- (BOOL)textField:(UITextField *)field shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)characters
{
    return ([characters rangeOfCharacterFromSet:blockedCharacters].location == NSNotFound);
}


text:
Q: Definition of an invariant differential form on a formal group These lecture notes define an invariant differential form on a formal group as follows:
My question concerns the statement

Equivalently, this can be restated as
  $$
P(F(T,S))F_X(T,S) = P(T).
$$

However from the definition
$$
\omega \circ F(T,S) = \omega(T),
$$
one only gets that
$$
P(F(T,S))F_X(T,S)dT = P(T)dT.
$$
It isn't clear to be how they are able to drop the $dT$ from the above statement.
To be clear on definitions, the space of formal differential forms on a ring of power series $R\left[\left[T\right]\right]$ is the quotient of the $R\left[\left[T\right]\right]$-module spanned by the symbols $df$ for $f \in R\left[\left[T\right]\right]$, by the submodule generated by elements of the form $f'dT - df$ for $f \in R\left[\left[T\right]\right]$.
I would appreciate if anyone was able to help clear this up for me.

A: I think I have managed to see why this is true formally now. I will provide my solution but leave the question open for the meantime.
Let $M$ be the $R\left[ \left[ T \right]\right]$-module of formal differential forms on a formally group $F$. Then $M$ is the quotient of the free $R\left[ \left[ T \right]\right]$-module $F$ on the set
$$
\left\{df \mid f \in R\left[ \left[ T \right]\right] \right\},
$$
by the submodule $S$ generated by
$$
\left\{f'dT - df \mid f \in R\left[ \left[ T \right]\right]  \right\}.
$$
Thus if $P,Q \in R\left[ \left[ T \right]\right]$ satisfy $PdT = QdT$ in $M$, then $(P-Q)dT = 0$ in $M$, or equivelently when we view $(P-Q)dT$ as an element of $F$ we get $(P-Q)dT \in S$. There thus exists
$$
f_1, \dots, f_\ell, g_1, \dots, g_{\ell} \in R\left[ \left[ T \right]\right],
$$
such that
$$
(P-Q)dT = \sum_i g_i(f'_idT - df_i).
$$
We may assume, without loss of generality, that the $f_i$ are distinct, and that the $g_i$ are non-zero. Then since $F$ is free we must have $g_i = 0$ unless $f_i = T$, and so we must have $\ell = 1$, and $f_1 = T$. But then
$$
(P-Q)dT = g_1(dT - dT) = 0,
$$
and so $P = Q$ since $F$ is free.

A: I think the answer is that if $\, f'dT - df = g'dT - dg \,$ then
$\, (f'-g')dT = (df - dg)\,$ and thus $\, df = dg\,$ iff $\, f'=g'\,$ and this is equivalent to $\, f=g+c\,$ where $\,c\,$ is a constant.
Since we assume that $\,P(0)=1\,$ then the constant must be $0$.


text:
Q: Why does calling code as a function take longer than calling it directly in Clozure Common lisp? I have around 900000 RECORDS:
(defparameter RECORDS
  '((293847 "john menk" "john.menk@example.com" 0123456789 2300 2760 "CHEQUE" 012345 "menk freeway" "high rose")
    (244841 "january agami" "j.a@example.com" 0123456789 2300 2760 "CHEQUE" 012345 "ishikawa street" "fremont apartments")
    ...))

(These are read from a file. The above code is provided only as an example. It helps show the internal structure of this data.)
For quick prototyping I use aliased names for selectors:
(defmacro alias (new-name existing-name)

  "Alias NEW-NAME to EXISTING-NAME. EXISTING-NAME has to be a function."

  `(setf (fdefinition ',new-name) #',existing-name))

(progn
  (alias account-number first)
  (alias full-name second)
  (alias email third)
  (alias mobile fourth)
  (alias average-paid fifth)
  (alias highest-paid sixth)
  (alias usual-payment-mode seventh)
  (alias pincode eighth)
  (alias road ninth)
  (alias building tenth))

Now I run:
(time (loop for field in '(full-name email)
        append (loop for record in RECORDS
                 when (cl-ppcre:scan ".*?january.*?agami.*?"
                                     (funcall (symbol-function field) record))
                 collect record)))

The repl outputs:
...
took 1,714 milliseconds (1.714 seconds) to run.
During that period, and with 4 available CPU cores,
     1,698 milliseconds (1.698 seconds) were spent in user mode
         9 milliseconds (0.009 seconds) were spent in system mode
 40 bytes of memory allocated.
...

Define a function doing the same thing:
(defun searchx (regex &rest fields)
  (loop for field in fields
    append (loop for record in RECORDS
             when (cl-ppcre:scan regex (funcall (symbol-function field) record))
             collect record)))

And then call it:
(time (searchx ".*?january.*?agami.*?" 'full-name 'email))

The output:
...
took 123,389 milliseconds (123.389 seconds) to run.
         992 milliseconds (  0.992 seconds, 0.80%) of which was spent in GC.
During that period, and with 4 available CPU cores,
     118,732 milliseconds (118.732 seconds) were spent in user mode
       4,569 milliseconds (  4.569 seconds) were spent in system mode
 2,970,867,648 bytes of memory allocated.
 501 minor page faults, 0 major page faults, 0 swaps.
...

It's almost 70 times slower ?!!
I thought maybe it's a computer specific issue. So I ran the same code on two different machines. A macbook air, and a macbook pro. The individual timings vary, but the behaviour is consistent. Calling it as a function takes much longer than calling it directly on both machines. Surely the overhead of a single function call should not be that much slower.

Then I thought it might be that Clozure CL is responsible. So I ran the same code in SBCL and even there the behaviour is similar. The difference isn't as big, but it's still pretty big. It's about 22 times slower.
SBCL output when running direct:
Evaluation took:
  1.519 seconds of real time
  1.477893 seconds of total run time (0.996071 user, 0.481822 system)
  97.30% CPU
  12 lambdas converted
  2,583,290,520 processor cycles
  492,536 bytes consed

SBCL output when running as a function:
Evaluation took:
  33.522 seconds of real time
  33.472137 seconds of total run time (33.145166 user, 0.326971 system)
  [ Run times consist of 0.254 seconds GC time, and 33.219 seconds non-GC time. ]
  99.85% CPU
  56,989,918,442 processor cycles
  2,999,581,336 bytes consed

Why is calling the code as a function so much slower? And how do I fix it?

A: The difference is probably due to the regular expression.
Here the regex is a literal string:
 (cl-ppcre:scan ".*?january.*?agami.*?"
                (funcall (symbol-function field) record))

The cl-ppcre:scan function has a compiler macro that detects this case and generates a (load-time-value (create-scanner ...)) expression (since the string cannot possibly depend on runtime values, this is acceptable).
The compiler-macro might be applied in your test too, in which case the load-time-value is probably executed only once.
In the following code, however, the regular expression is a runtime value, obtained as an input of the function:
(defun searchx (regex &rest fields)
  (loop for field in fields
    append (loop for record in RECORDS
             when (cl-ppcre:scan regex (funcall (symbol-function field) record))
             collect record)))

In that case, the scanner object is built when evaluating scan, i.e. each time the loop iterates over a record.
In order to test this hypothesis, you may want to do the following:
(defun searchx (regex &rest fields)
  (loop
    with scanner = (cl-ppcre:create-scanner regex)
    for field in fields
    append (loop for record in RECORDS
             when (cl-ppcre:scan scanner (funcall (symbol-function field) record))
             collect record)))

Alternatively, do not change the function but give it a scanner:
(time (searchx (cl-ppcre:create-scanner
                 ".*?january.*?agami.*?")
              'full-name
              'email))


text:
Q: Conversão de data para o oracle Estou com um problema, eu estou tentando salvar uma data no oracle com o formatado dd/MM/yyyy, porém, no banco ele apresenta a data no formato dd/MM/yy.
Então, me surgiu a dúvida, se o tipo que eu usei na tabela não é adequado, ou, se a data que eu passo para o banco que esta errada.
bom, no meu DAO (no java), para incluir a data, eu converto ela com os seguintes métodos:
    public static java.sql.Date converteParaBanco(Date data) {
            return new java.sql.Date(data.getTime());
    }

   public static Date converteDoBanco(java.sql.Date data) {
            return new Date(data.getTime());
   }

aplicando o método no DAO:
ps.setDate(5, ConverteData.converteParaBanco(pojoCompra.getDataCompra()));
dando um system.out na linha acima, percebi, que meu método faz a data ficar no formato de 2017-09-22.
Meu atributo no banco, está do tipo DATE.
O que eu poderia fazer para que a data seja salva e também retornada com o formato de dd/MM/yyyy ?

A: 1º somente na sessao do usuário alterar o formato
sql> ALTER SESSION SET NLS_DATE_FORMAT = 'DD/MM/YYYY';
sql> select sysdate from dual;
SYSDATE

SQL> ALTER SESSION SET NLS_DATE_FORMAT = 'DD/MM/YY HH24:MI:SS';
--Sessão alterada.
SQL> select sysdate from dual;
SYSDATE

NLS_DATE_FORMAT = 'DD/MM/YY HH24:MI:SS' esse é o formato da  strings  date  do oracle.
Pode alterar o padrão se estiver usando o SQLDeveloper
Segundo o seguintes passos:

*

*Tools > Preferences.

*Na janela que abrir Seleciona Database > NLS

*No Date Format coloque o formato desejado