问:
Get USB port of plugged in device in node
I'm using node-detection to be notify when a USB device was plugged in. However I can't seem to find out how to know to which port was it plugged in to, e.g. sdb1, sdc1, etc. Is there a simple way of doing it?

Body:
I don't know about node.js bindings, but using external udevadm tool the info is exposed:

$ udevadm monitor
monitor will print the received events for:
UDEV - the event which udev sends out after rule processing
KERNEL - the kernel uevent

KERNEL[766928.886896] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1 (usb)
KERNEL[766928.888766] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0 (usb)
UDEV  [766929.091194] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1 (usb)
KERNEL[766930.777996] add      /module/usb_storage (module)
UDEV  [766930.780203] add      /module/usb_storage (module)
KERNEL[766930.781054] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4 (scsi)
KERNEL[766930.781241] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/scsi_host/host4 (scsi_host)
KERNEL[766930.781370] add      /bus/usb/drivers/usb-storage (drivers)
UDEV  [766930.782320] add      /bus/usb/drivers/usb-storage (drivers)
KERNEL[766931.092511] add      /module/uas (module)
UDEV  [766931.092584] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0 (usb)
KERNEL[766931.092608] add      /bus/usb/drivers/uas (drivers)
UDEV  [766931.093550] add      /module/uas (module)
UDEV  [766931.094000] add      /bus/usb/drivers/uas (drivers)
UDEV  [766931.094305] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4 (scsi)
UDEV  [766931.095737] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/scsi_host/host4 (scsi_host)
KERNEL[766931.807635] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0 (scsi)
KERNEL[766931.807770] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0 (scsi)
KERNEL[766931.807901] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/scsi_disk/4:0:0:0 (scsi_disk)
KERNEL[766931.807995] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/scsi_device/4:0:0:0 (scsi_device)
KERNEL[766931.809543] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/scsi_generic/sg2 (scsi_generic)
KERNEL[766931.809605] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/bsg/4:0:0:0 (bsg)
UDEV  [766931.811736] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0 (scsi)
KERNEL[766931.812771] add      /devices/virtual/bdi/8:16 (bdi)
UDEV  [766931.815246] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0 (scsi)
UDEV  [766931.815908] add      /devices/virtual/bdi/8:16 (bdi)
UDEV  [766931.818228] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/scsi_disk/4:0:0:0 (scsi_disk)
UDEV  [766931.819748] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/bsg/4:0:0:0 (bsg)
UDEV  [766931.821506] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/scsi_device/4:0:0:0 (scsi_device)
UDEV  [766931.821894] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/scsi_generic/sg2 (scsi_generic)
KERNEL[766931.895701] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/block/sdb (block)
KERNEL[766931.895807] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/block/sdb/sdb1 (block)
KERNEL[766931.895879] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/block/sdb/sdb2 (block)
UDEV  [766933.474661] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/block/sdb (block)
UDEV  [766933.566443] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/block/sdb/sdb2 (block)
UDEV  [766933.658413] add      /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/block/sdb/sdb1 (block)

KERNEL[766942.802911] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/bsg/4:0:0:0 (bsg)
KERNEL[766942.804048] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/scsi_generic/sg2 (scsi_generic)
KERNEL[766942.804163] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/scsi_device/4:0:0:0 (scsi_device)
KERNEL[766942.804246] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/scsi_disk/4:0:0:0 (scsi_disk)
KERNEL[766942.804338] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/block/sdb/sdb2 (block)
KERNEL[766942.804426] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/block/sdb/sdb1 (block)
KERNEL[766942.804518] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/block/sdb (block)
KERNEL[766942.804590] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0 (scsi)
UDEV  [766942.806838] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/bsg/4:0:0:0 (bsg)
UDEV  [766942.807543] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/scsi_generic/sg2 (scsi_generic)
UDEV  [766942.809181] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/scsi_disk/4:0:0:0 (scsi_disk)
UDEV  [766942.809410] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/scsi_device/4:0:0:0 (scsi_device)
UDEV  [766942.812382] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/block/sdb/sdb1 (block)
UDEV  [766942.812545] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/block/sdb/sdb2 (block)
UDEV  [766942.814711] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0/block/sdb (block)
UDEV  [766942.815300] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0/4:0:0:0 (scsi)
KERNEL[766942.816341] remove   /devices/virtual/bdi/8:16 (bdi)
KERNEL[766942.816384] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0 (scsi)
UDEV  [766942.817716] remove   /devices/virtual/bdi/8:16 (bdi)
UDEV  [766942.819175] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/target4:0:0 (scsi)
KERNEL[766942.864803] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/scsi_host/host4 (scsi_host)
KERNEL[766942.864891] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4 (scsi)
KERNEL[766942.865168] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0 (usb)
KERNEL[766942.866960] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1 (usb)
UDEV  [766942.867670] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4/scsi_host/host4 (scsi_host)
UDEV  [766942.868469] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0/host4 (scsi)
UDEV  [766942.869291] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1/5-1:1.0 (usb)
UDEV  [766942.870791] remove   /devices/pci0000:00/0000:00:10.0/usb5/5-1 (usb)

Some notes:

There can be more than one partition on a USB stick, or it may have a filesystem directly without partitions.

You probably don't need to monitor for USB devices specifically, just any block device perhaps?

This isn't doing any filtering, you'll get a lot of unrelated events yet.


来源: stackexchange

问:
Changing MAIL FROM Domain in Amazon AWS SES
I'm using a marketing email application called Mautic to use AWS SES to send emails.  I'm receiving the emails successfully but they're all from the domain amazonses.com.  I followed the AWS SES documentation to verify ownership of my domain, I enabled SPF and DKIM successfully, and I put the proper MX records into my GoDaddy DNS.  Everything is 'verified' in the AWS Console, but I'm not sure how to get it to use the "MAIL FROM" domain I've setup.  Mautic has no settings with respect to the "MAIL FROM" domain so I'm pretty sure I'm just missing the last step on the SES in order to get it to actually use the 'from' domain I've setup.

Please let me know if I can provide any more details that might be helpful.  Thanks for your time in advance!

答:
AWS also has a Custom Mail From domain setup option.  Here is the doc:
http://docs.aws.amazon.com/ses/latest/DeveloperGuide/mail-from.html

Follow the directions very carefully and don't forget you need an SPF record for the new subdomain you create for the Mail From - otherwise SES won't pass it in the header.

ContentLicense: CC BY-SA 3.0


问:
How do I get the name of the current executable in C#?
I want to get the name of the currently running program, that is the executable name of the program. In C/C++ you get it from args[0].

答:
On .Net Core (or Mono), most of the answers won't apply when the binary defining the process is the runtime binary of Mono or .Net Core (dotnet) and not your actual application you're interested in. In that case, use this:</p>

```<code>var myName = Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location);
</code>```

Body:
On .Net Core (or Mono), most of the answers won't apply when the binary defining the process is the runtime binary of Mono or .Net Core (dotnet) and not your actual application you're interested in. In that case, use this:

var myName = Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location);


问:
Binary Tree Delete Node function not working
```<code>public void removeNode(int data) {
    deleteNode(root, data);
}

public Node deleteNode(Node focus, int data) {
    if(focus == null) {
        System.out.println("Tree empty");
        return null;
    }
    else if(data < focus.data) {
        deleteNode(focus.leftchild, data);
    }
    else if(data > focus.data) {
        deleteNode(focus.rightchild, data);
    }
    else {
        // No child
        if(focus.leftchild == null && focus.rightchild == null) {
            focus = null;
        }
        // one child
        else if(focus.leftchild == null) {
            focus = focus.rightchild;
            System.out.println("here");
        }
        else if(focus.rightchild == null) {
            focus = focus.leftchild;
        }
        // 2 children
        else {
            Node temp = findMin(focus.rightchild);
            focus.data = temp.data;
            deleteNode(focus.rightchild, temp.data);
        }
    }
    return focus;
}

public Node findMin(Node focus) {
    while(focus.leftchild != null) {
        focus = focus.leftchild;
    }
    return focus;
}
</code>```

I have written the above code to delete a node in Binary Search Tree. However for some reason when I run preordertraversal function to print all the nodes, I see that the node is not getting deleted. Can someone please tell me why a node is not getting deleted. The function seems to be right.

答:
I figured it! The problem was that I wasn't traversing the tree the right way. Also I did a mistake in the condition of having two children. I didn't set the right focus.rightchild. Here is the updated code</p>

```<code>public Node deleteNode(Node focus, int data) {
    if(focus == null) {
        System.out.println("Tree empty");
        return null;
    }
    else if(data < focus.data) {
        focus.leftchild = deleteNode(focus.leftchild, data);
    }
    else if(data > focus.data) {
        focus.rightchild = deleteNode(focus.rightchild, data);
    }
    else {
        // No child
        if(focus.leftchild == null && focus.rightchild == null) {
            focus = null;
        }
        // one child
        else if(focus.leftchild == null) {
            focus = focus.rightchild;
            System.out.println("here");
        }
        else if(focus.rightchild == null) {
            focus = focus.leftchild;
        }
        // 2 children
        else {
            Node temp = findMin(focus.rightchild);
            focus.data = temp.data;
            focus.rightchild = deleteNode(focus.rightchild, temp.data);
        }
    }
    return focus;
}
</code>```

Body:
public void removeNode(int data) {
    deleteNode(root, data);
}

public Node deleteNode(Node focus, int data) {
    if(focus == null) {
        System.out.println("Tree empty");
        return null;
    }
    else if(data < focus.data) {
        deleteNode(focus.leftchild, data);
    }
    else if(data > focus.data) {
        deleteNode(focus.rightchild, data);
    }
    else {
        // No child
        if(focus.leftchild == null && focus.rightchild == null) {
            focus = null;
        }
        // one child
        else if(focus.leftchild == null) {
            focus = focus.rightchild;
            System.out.println("here");
        }
        else if(focus.rightchild == null) {
            focus = focus.leftchild;
        }
        // 2 children
        else {
            Node temp = findMin(focus.rightchild);
            focus.data = temp.data;
            deleteNode(focus.rightchild, temp.data);
        }
    }
    return focus;
}

public Node findMin(Node focus) {
    while(focus.leftchild != null) {
        focus = focus.leftchild;
    }
    return focus;
}

I have written the above code to delete a node in Binary Search Tree. However for some reason when I run preordertraversal function to print all the nodes, I see that the node is not getting deleted. Can someone please tell me why a node is not getting deleted. The function seems to be right.

Body:
I figured it! The problem was that I wasn't traversing the tree the right way. Also I did a mistake in the condition of having two children. I didn't set the right focus.rightchild. Here is the updated code

public Node deleteNode(Node focus, int data) {
    if(focus == null) {
        System.out.println("Tree empty");
        return null;
    }
    else if(data < focus.data) {
        focus.leftchild = deleteNode(focus.leftchild, data);
    }
    else if(data > focus.data) {
        focus.rightchild = deleteNode(focus.rightchild, data);
    }
    else {
        // No child
        if(focus.leftchild == null && focus.rightchild == null) {
            focus = null;
        }
        // one child
        else if(focus.leftchild == null) {
            focus = focus.rightchild;
            System.out.println("here");
        }
        else if(focus.rightchild == null) {
            focus = focus.leftchild;
        }
        // 2 children
        else {
            Node temp = findMin(focus.rightchild);
            focus.data = temp.data;
            focus.rightchild = deleteNode(focus.rightchild, temp.data);
        }
    }
    return focus;
}


问:
XAMPP installation on Win 8.1 with UAC Warning
I am trying to install Xampp win32-1.8.2 on Windows 8.1. I get a message saying

Because an activated user account User Account on your system some functions of XAMPP are possibly restricted.

I've tried to change the user account control settings but still the warning is there. And the APACHE does not start. I've also disabled my IIS but still, its not working. What should I do? enter image description here

答:
To disable UAC (as an administrator), from Control Panel:

Type UAC in the search button in your windows the upper right corner.
Click the (Change User Account Control settings) in the search results.
Drag the slider down and select  Never notify and click OK.it will work.

ContentLicense: CC BY-SA 4.0


问:
Faster way to build text file in python
I have two 3d numpy arrays, call them a and b, 512x512x512. I need to write them to a text file:

```<code>a1 b1
a2 b2
a3 b3
...
</code>```

This can be accomplished with a triple loop:

```<code>lines = []
for x in range(nx):
    for y in range(ny):
        for z in range(nz):
            lines.append('{} {}'.format(a[x][y][z], b[x][y][z])
print('\n'.join(lines))
</code>```

But this is brutally slow (10 minutes when I'd prefer a few seconds on a mac pro).

I am using python 3.6, latest numpy, and am happy to use other libraries, build extensions, whatever is necessary. What is the best way to get this faster?

Title: Faster way to build text file in python

Body:
I have two 3d numpy arrays, call them a and b, 512x512x512. I need to write them to a text file:

a1 b1
a2 b2
a3 b3
...

This can be accomplished with a triple loop:

lines = []
for x in range(nx):
    for y in range(ny):
        for z in range(nz):
            lines.append('{} {}'.format(a[x][y][z], b[x][y][z])
print('\n'.join(lines))

But this is brutally slow (10 minutes when I'd prefer a few seconds on a mac pro).

I am using python 3.6, latest numpy, and am happy to use other libraries, build extensions, whatever is necessary. What is the best way to get this faster?

Body:
you could use flatten() and dstack(), see example below

a = np.random.random([5,5,5]).flatten()
b = np.random.random([5,5,5]).flatten()
c = np.dstack((a,b))
print c

will result in

[[[ 0.31314428  0.35367513]
  [ 0.9126653   0.40616986]
  [ 0.42339608  0.57728441]
  [ 0.50773896  0.15861347]
....


问:
I can't install npm not matter what I do
So I'm trying to get myself a good Discord Selfbot and one of them requires nodejs, then it said to do npm install. But it gave me an error. I tried again again again and again but nothing worked. The latest thing I did was installing nodejs via scoop but I get this error trying to install npm. Is there a way to do this manually or something? I've tried installing different versions but nothing. I believe scoop installed the latest version.
Here's the image. (the red squares cover up just names)</p>

答: You already have npm installed! npm is a package manager for installing nodejs packages.  Try running some nonsense command (like "lkajshdflhsf") and you'll see what it looks like if you actually didn't have npm installed.  What npm install does is install some package.  So, for example, if you want to install a node package called Blah, you would run npm intall blah.


问:
how to print current user's ip address in php 7.1.1
I am trying to get current users ip address using {$_SERVER['REMOTE_ADDR']} or {getenv('REMOTE_ADDR')}, in both of the cases i am getting ::1 .
I am using php 7.1.1, can any one help how i can get current ip address of current user.</p>

答: $_SERVER['REMOTE_ADDR'] or $_SERVER['REMOTE_HOST'] look to Get the client IP address using PHP


问:
shell - compare files and update matching string awk/sed/diff/grep/csv
I need to compare 2 csv files and make modifications to the second column. I wrote out the logic out of how I would want to achieve this however, it seems to confuse the thread a lot more than I wanted too so I'll just write out the example.

Any help would be appreciated. Thanks in advance.

file1

```<code>user1,distinguishedName1
user2,distinguishedName2
user3,distinguishedName3
user4,distinguishedName4
user5,distinguishedName5
</code>```

file2

```<code>user1,distinguishedName1
user3,distinguishedName13
user5,distinguishedName12
user6,distinguishedName4
</code>```

desired outcome:

```<code>user1,distinguishedName1
user2,distinguishedName2
user3,distinguishedName13
user4,distinguishedName4
user5,distinguishedName12
user6,distinguishedName4
</code>```

答:
The solution using join command combined with awk command:

```<code>join -t',' -j1 -a1 -a2  file1 file2 | awk -F',' '{if(NF==3) $0=$1FS$3}1'
</code>```

The output:

```<code>user1,distinguishedName1
user2,distinguishedName2
user3,distinguishedName13
user4,distinguishedName4
user5,distinguishedName12
user6,distinguishedName4
</code>```

Explanation:

-- for join command:

-t',' - defines field separator

-j1 - tells to join on first field 1

-a FILENUM - print unpairable lines coming from file FILENUM, where FILENUM is 1 or 2, corresponding to FILE1 or FILE2

-- for awk command:

NF - contains a total number of fields

FS - field separator(i.e. ,)

if(NF==3) $0=$1FS$3 - the condition, checks if there's a complement third field(as result of joining the files on lines with common first field) to perform the replacement

https://linux.die.net/man/1/join

Body:
I need to compare 2 csv files and make modifications to the second column. I wrote out the logic out of how I would want to achieve this however, it seems to confuse the thread a lot more than I wanted too so I'll just write out the example.

Any help would be appreciated. Thanks in advance.

file1

user1,distinguishedName1
user2,distinguishedName2
user3,distinguishedName3
user4,distinguishedName4
user5,distinguishedName5

file2

user1,distinguishedName1
user3,distinguishedName13
user5,distinguishedName12
user6,distinguishedName4

desired outcome:

user1,distinguishedName1
user2,distinguishedName2
user3,distinguishedName13
user4,distinguishedName4
user5,distinguishedName12
user6,distinguishedName4

Body:
The solution using join command combined with awk command:

join -t',' -j1 -a1 -a2  file1 file2 | awk -F',' '{if(NF==3) $0=$1FS$3}1'

The output:

user1,distinguishedName1
user2,distinguishedName2
user3,distinguishedName13
user4,distinguishedName4
user5,distinguishedName12
user6,distinguishedName4

Explanation:

-- for join command:

-t',' - defines field separator

-j1 - tells to join on first field 1

-a FILENUM - print unpairable lines coming from file FILENUM, where FILENUM is 1 or 2, corresponding to FILE1 or FILE2

-- for awk command:

NF - contains a total number of fields

FS - field separator(i.e. ,)

if(NF==3) $0=$1FS$3 - the condition, checks if there's a complement third field(as result of joining the files on lines with common first field) to perform the replacement

https://linux.die.net/man/1/join


问:
Why does working java app not create 1 of 22 .class files after one more line of code is added?
I am running Netbeans IDE 8.1 on Windows 10 and my application (697 kb) runs fine until the MarketData3.java file grows to 404 kb and one more line of code (even a simple print statement) is added tot he MarketData3.java file. Once coded added, I get the following Exception since the MarketData3.class file is not created on a successful compilation. This Exception occurs in ReadYahooStockPricess.startChart which creates an instance of MarketData3 but the MarketData3.class is not created upon save/compile or at runtime causing the following Exception.

```<code>Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: stockentrygui/MarketData3 at stockentrygui.ReadYahooStockPrices.startChart(ReadYahooStockPrices.java:1141)
</code>```

The project is large and proprietary so I have included the pertinent code where the Exception occurs since it runs successfully until MarketData3 grows above a specific size. To help understand flow, the application creates a stockentrygui to select a specific stock and then creates an instance of ReadYahooStockPrices (RYSP) to get specific stock price data and thereafter calls its startChart method below stockentrygui.ReadYahooStockPrices.startChart to create an instance of the MarketData3 class, which calculates technical data, followed by an instance of Chart3 to chart prices and technical. Chart3 gets all data it displays (prices and technical analysis data) from MarketData3.

Below is the pertinent ReadYahooStockPrices.startChart method that creates the MarketData3 object (mdata= new MarketData3) for the selected stock followed by creating the Chart3 class instance (c3= new Chart3).

startChart method in ReadYahooStockPrices called by its Constructor.

```<code>public void startChart(){
        //TechnicalAnalyzer ta;
        MarketData3 mdata;
        //Charter c;
        int range=12;
        String startDate=null;

        //new MarketData class - send stock, HLC arrays
        //ta= new TechnicalAnalyzer(stock,startDate,range,date,data,totalDays);

        mdata= new MarketData3 (stock,startDate,range,date,data,totalDays,alert);

        //new Chart - send MarketData identifier, stock and fix range
        MarketCommentary mc = new MarketCommentary(mdata);
        c3 = new Chart3(stock,range,mdata,mc,companyName);
        //c3 = new Chart3(stock,range,mdata);
        c3. setBackground(Color.white);
        //c3.requestFocus();
        //create a JFrame to put Chart3 Canvas and market commentary
        //JFrame f = new JFrame();
        setTitle("Technical Analysis (Press -> arrow to Forward, "+
        "<- arrow to Reverse, and up arrow for more options.)");
       GridBagLayout layout = new GridBagLayout();

        Container c=getContentPane();
        c.setLayout(layout);
        c.add(c3);
        c.add(mc);
        pack();
        show();
        //setVisible(true);
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }//end startChart
</code>```

The project works fine until the MarketData3 java file grows to 404 kb. The added code is in the formula method that is called below in the MarketData3 constructor. So it seems that the MarketData3.class file is not created after save/compile or run causing the above Exception at runtime. This seems be related to file size.

MarketData3 Constructor:

```<code>public MarketData3(String stk, String sdate, int r, String date1[], double data1[][], int tDays,TradeAlerts alert)
        //throws AccessControlException, SQLException, Exception
        //throws Exception
    {//Market Data Constructor
        super("MARKET TRACKER");

        //if MarketData3 initiated form MarketAnalyzer3 or ReadYahooStockPrices (rysp)
        stock=stk;//fixed in MarketData3, variable in rysp
        startDate=sdate;//start date fixed to 0
        range=r;//range fixed to 12
        this.alert=alert;//multiple file trade alert
//System.out.println("135 Start MarketData3");

        //if MarketData3 (MD3) initiated from ReadYahooStockPrices
        if(tDays>0){
            //create new arrays
            date= new String [tDays];
            data= new double[41][tDays];
            displayData = new double[41][tDays];
            trend= new int[tDays];
            trendLT= new int[tDays];
            trendTest=new int[7][tDays];
            stop12Date= new String[tDays];
            stop6Date= new String[tDays];
            stop6DateTest=new String[tDays]; //v6 stop test 110809
            stop6DateTestRT=new String[2][tDays];
            stop48DateTestRT=new String[4][tDays];
            stop6CaptureHiDate= new String[tDays];
            stop6CaptureLoDate= new String[tDays];
            side= new String[tDays];
            momSw= new int[tDays];
            trade= new String[tDays];
            deltaStoch = new double[7][tDays];
            dataTest=new double[10][tDays];
            //load date
            date=date1;
            //load H, L, C prices into array
            for(int x=0; x<tDays;x++){
                data[0][x]=data1[0][x];
                data[1][x]=data1[1][x];
                data[2][x]=data1[2][x];
            }
            totalDays=tDays;
        }//end tDays>0

        Date now=new Date();
        DateFormat df=DateFormat.getDateInstance();
        System.out.println("MD3 205 Today's date is "+ df.format(now));

        System.out.println("MD3 207 Connect to "+stock+" stockprices");
        //con=new DBConnection(driver, url).getConnection();
        //stmt=con.createStatement();

        // store prices and dates in data arrays if MD3 initiates
        if(totalDays==0){
            //readStockData(); // read from mysql database
            try{
                if(date[0]==null)
                readStockDataFile(); // read from existing csv files
            }
            catch(Exception e){
                System.out.println("readStockData Exeption "+ e.getMessage());
            }

        }

        // Calculate and store indicators in data array
        formula();//Rev7
        //getStop12();
        //Find startCell

        startCell = searchDates(date, startDate);

       //dateData(0);// Rev4: Store dates - shift=0 initialization

        //marketData();//Rev4: Store prices
        //getIndicators();//Rev7
        //formula();//Rev6: calculate ma, mom, vel
        //trendLogic();

        System.out.println("Stock Prices Read");

    }// end MarketData3 Constructor
</code>```

Does anyone know why this happens?

Is there an IDE or JRE interpreter size limit when compiling application and creating .class files?

Do you have to break a class into two classes when it grow too large?

Can this be because my formula method in MarketData3 is too large?

答: I believe I found my problem. I found that a method cannot be larger than 64 KB with Java (Maximum size of a method in Java 7 and 8), and my formula method has grown quite large due to various technical analysis tests. I assume when the JRE interpreter tried to create the marketData3.class, the formula method was too large and the above Exception was thrown. So, I created two methods, formula and technicalAnalysis, and it solved my problem. Of course when I stop testing technical analysis logic, I will remove most of the unused logic and the method will get much smaller. I hope this helps someone facing the same type of problem - allowing your method to grow too large. Keep it small.</p>

Body:
I am running Netbeans IDE 8.1 on Windows 10 and my application (697 kb) runs fine until the MarketData3.java file grows to 404 kb and one more line of code (even a simple print statement) is added tot he MarketData3.java file. Once coded added, I get the following Exception since the MarketData3.class file is not created on a successful compilation. This Exception occurs in ReadYahooStockPricess.startChart which creates an instance of MarketData3 but the MarketData3.class is not created upon save/compile or at runtime causing the following Exception.

Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: stockentrygui/MarketData3 at stockentrygui.ReadYahooStockPrices.startChart(ReadYahooStockPrices.java:1141)

The project is large and proprietary so I have included the pertinent code where the Exception occurs since it runs successfully until MarketData3 grows above a specific size. To help understand flow, the application creates a stockentrygui to select a specific stock and then creates an instance of ReadYahooStockPrices (RYSP) to get specific stock price data and thereafter calls its startChart method below stockentrygui.ReadYahooStockPrices.startChart to create an instance of the MarketData3 class, which calculates technical data, followed by an instance of Chart3 to chart prices and technical. Chart3 gets all data it displays (prices and technical analysis data) from MarketData3.

Below is the pertinent ReadYahooStockPrices.startChart method that creates the MarketData3 object (mdata= new MarketData3) for the selected stock followed by creating the Chart3 class instance (c3= new Chart3).

startChart method in ReadYahooStockPrices called by its Constructor.

public void startChart(){
        //TechnicalAnalyzer ta;
        MarketData3 mdata;
        //Charter c;
        int range=12;
        String startDate=null;

        //new MarketData class - send stock, HLC arrays
        //ta= new TechnicalAnalyzer(stock,startDate,range,date,data,totalDays);

        mdata= new MarketData3 (stock,startDate,range,date,data,totalDays,alert);

        //new Chart - send MarketData identifier, stock and fix range
        MarketCommentary mc = new MarketCommentary(mdata);
        c3 = new Chart3(stock,range,mdata,mc,companyName);
        //c3 = new Chart3(stock,range,mdata);
        c3. setBackground(Color.white);
        //c3.requestFocus();
        //create a JFrame to put Chart3 Canvas and market commentary
        //JFrame f = new JFrame();
        setTitle("Technical Analysis (Press -> arrow to Forward, "+
        "<- arrow to Reverse, and up arrow for more options.)");
       GridBagLayout layout = new GridBagLayout();

        Container c=getContentPane();
        c.setLayout(layout);
        c.add(c3);
        c.add(mc);
        pack();
        show();
        //setVisible(true);
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }//end startChart

The project works fine until the MarketData3 java file grows to 404 kb. The added code is in the formula method that is called below in the MarketData3 constructor. So it seems that the MarketData3.class file is not created after save/compile or run causing the above Exception at runtime. This seems be related to file size.

MarketData3 Constructor:

public MarketData3(String stk, String sdate, int r, String date1[], double data1[][], int tDays,TradeAlerts alert)
        //throws AccessControlException, SQLException, Exception
        //throws Exception
    {//Market Data Constructor
        super("MARKET TRACKER");

        //if MarketData3 initiated form MarketAnalyzer3 or ReadYahooStockPrices (rysp)
        stock=stk;//fixed in MarketData3, variable in rysp
        startDate=sdate;//start date fixed to 0
        range=r;//range fixed to 12
        this.alert=alert;//multiple file trade alert
//System.out.println("135 Start MarketData3");

        //if MarketData3 (MD3) initiated from ReadYahooStockPrices
        if(tDays>0){
            //create new arrays
            date= new String [tDays];
            data= new double[41][tDays];
            displayData = new double[41][tDays];
            trend= new int[tDays];
            trendLT= new int[tDays];
            trendTest=new int[7][tDays];
            stop12Date= new String[tDays];
            stop6Date= new String[tDays];
            stop6DateTest=new String[tDays]; //v6 stop test 110809
            stop6DateTestRT=new String[2][tDays];
            stop48DateTestRT=new String[4][tDays];
            stop6CaptureHiDate= new String[tDays];
            stop6CaptureLoDate= new String[tDays];
            side= new String[tDays];
            momSw= new int[tDays];
            trade= new String[tDays];
            deltaStoch = new double[7][tDays];
            dataTest=new double[10][tDays];
            //load date
            date=date1;
            //load H, L, C prices into array
            for(int x=0; x<tDays;x++){
                data[0][x]=data1[0][x];
                data[1][x]=data1[1][x];
                data[2][x]=data1[2][x];
            }
            totalDays=tDays;
        }//end tDays>0

        Date now=new Date();
        DateFormat df=DateFormat.getDateInstance();
        System.out.println("MD3 205 Today's date is "+ df.format(now));

        System.out.println("MD3 207 Connect to "+stock+" stockprices");
        //con=new DBConnection(driver, url).getConnection();
        //stmt=con.createStatement();

        // store prices and dates in data arrays if MD3 initiates
        if(totalDays==0){
            //readStockData(); // read from mysql database
            try{
                if(date[0]==null)
                readStockDataFile(); // read from existing csv files
            }
            catch(Exception e){
                System.out.println("readStockData Exeption "+ e.getMessage());
            }

        }

        // Calculate and store indicators in data array
        formula();//Rev7
        //getStop12();
        //Find startCell

        startCell = searchDates(date, startDate);

       //dateData(0);// Rev4: Store dates - shift=0 initialization

        //marketData();//Rev4: Store prices
        //getIndicators();//Rev7
        //formula();//Rev6: calculate ma, mom, vel
        //trendLogic();

        System.out.println("Stock Prices Read");

    }// end MarketData3 Constructor

Does anyone know why this happens?

Is there an IDE or JRE interpreter size limit when compiling application and creating .class files?

Do you have to break a class into two classes when it grow too large?

Can this be because my formula method in MarketData3 is too large?


问:
JavaScript Ajax URL 'post' data not received by PHP file
I was wondering if you'd be able to help me with this issue please?

I'm looking to pass variable length HTML (or any data in fact) to a PHP file via POST in a JavaScript AJAX method.

I want to use JavaScript for my entire project so I can cut my teeth on it - I know a lot of solutions are provided in jQuery for AJAX but hopefully you can help me via vanilla JavaScript. :)

I pass the data in the 'prepare' variable in the URL as follows:

```<code>ajax("doit.php?preparedOutput=" + prepare);
</code>```

The AJAX function:

```<code>function ajax(queryURL) {
alert(queryURL); // check the right data is being sent
var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        alert(xhttp.responseText);
        output2.value = xhttp.responseText;
        result.innerHTML = "<h3>your HTML</h3>" + xhttp.responseText;
    }
}
//var encodedQueryURL = encodeURIComponent(queryURL);
xhttp.open("POST", "doit.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//alert(encodedQueryURL); // check the right encoded data is being sent
xhttp.send(queryURL);
}
</code>```

The alerts show me what data is supposedly being sent, whether encoded or not. All seems fine. But the response I get back from the PHP is... nothing.

```<code><?php
$preparedOutput = $_POST['preparedOutput'];

echo $preparedOutput;
?>
</code>```

Even if I use isset($preparedOutput) in an if/else block, else is triggered. Nothing's getting through. Not even if I try to pass simple numbers or letters without spaces, aside from HTML. Nothing's getting to the PHP file apparently.

I've been toying with the setRequestHeader, trying all sorts, namely "text/html" etc. Nothing changes the outcome. I feel I'm missing a key piece of the puzzle here!

If it helps, my environment is PHP enabled in IIS7 using FastCGI - if this makes any difference. PHP works, I previously had the PHP script embedded within the same page and it returned the entire page's HTML rather than the HTML in the preparedOutput variable, which is why I shifted it to its own file.

Thanks

答:
That's because you doubled the url string. Take a look:

You called it by

```<code>ajax("doit.php?preparedOutput=" + prepare);
</code>```

and the url you use in open is "doit.php"

so you basically call something like http://whatever/doit/?doit.php?preparedOutput=" + prepare.

Change to:

```<code>ajax("preparedOutput=" + prepare);
</code>```

Body:
I was wondering if you'd be able to help me with this issue please?

I'm looking to pass variable length HTML (or any data in fact) to a PHP file via POST in a JavaScript AJAX method.

I want to use JavaScript for my entire project so I can cut my teeth on it - I know a lot of solutions are provided in jQuery for AJAX but hopefully you can help me via vanilla JavaScript. :)

I pass the data in the 'prepare' variable in the URL as follows:

ajax("doit.php?preparedOutput=" + prepare);

The AJAX function:

function ajax(queryURL) {
alert(queryURL); // check the right data is being sent
var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        alert(xhttp.responseText);
        output2.value = xhttp.responseText;
        result.innerHTML = "
your HTML
" + xhttp.responseText;
    }
}
//var encodedQueryURL = encodeURIComponent(queryURL);
xhttp.open("POST", "doit.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//alert(encodedQueryURL); // check the right encoded data is being sent
xhttp.send(queryURL);
}

The alerts show me what data is supposedly being sent, whether encoded or not. All seems fine. But the response I get back from the PHP is... nothing.

<?php
$preparedOutput = $_POST['preparedOutput'];

echo $preparedOutput;
?>

Even if I use isset($preparedOutput) in an if/else block, else is triggered. Nothing's getting through. Not even if I try to pass simple numbers or letters without spaces, aside from HTML. Nothing's getting to the PHP file apparently.

I've been toying with the setRequestHeader, trying all sorts, namely "text/html" etc. Nothing changes the outcome. I feel I'm missing a key piece of the puzzle here!

If it helps, my environment is PHP enabled in IIS7 using FastCGI - if this makes any difference. PHP works, I previously had the PHP script embedded within the same page and it returned the entire page's HTML rather than the HTML in the preparedOutput variable, which is why I shifted it to its own file.

Thanks

Body:
That's because you doubled the url string. Take a look:

You called it by

ajax("doit.php?preparedOutput=" + prepare);

and the url you use in open is "doit.php"

so you basically call something like http://whatever/doit/?doit.php?preparedOutput=" + prepare.

Change to:

ajax("preparedOutput=" + prepare);


问:
Angular 2 Firebase Return Object Count
I am working in Angular 2 and have a booking component.

When a booking is made, the information is sent to firebase database in a bookings node.

I am trying to show on the home screen dashboard of the app if the admin has any bookings today. in my component I have subscribed to the bookings node in firebase using Angularfire as follows:

```<code>this.bookingItemsData = af.database.list('/bookings');
this.bookingItemsData.subscribe((res) => {
  this.bookingItems = res;
  console.log(res);
</code>```

I want to get the current date and compare it to the date give in firebase bookings node, so to get current date I have added this:

```<code>//get current date
    var getToday = new Date();
    var year = getToday.getFullYear();
    var month = getToday.getMonth() + 1;
    var day = getToday.getDate();
    // var time =  getToday.getTime();
    var currentDate = day + "/" + month + "/" + year;
</code>```

Which successfully gets me the currentDate I require.

I now run this to get the dates from the bookings:

```<code>// Get count of bookings
    af.database.list('/bookings').subscribe((res) => {
        this.numbeOfBookings = res.length;
        res.forEach(item => {
        //get the date propery from the bookings node
        var specialDate = (item.start);
        //transform the date property to matching format
        specialDate = this.datePipeEn.transform(new Date(item.start), 'dd/M/yyyy');

        // console.log(specialDate);
        // console.log(currentDate);

          if(specialDate === currentDate) {
          console.log(specialDate);
          }

        });
    });
</code>```

I first get the number of bookings in the booking list,

I then iterate through the bookings and assign the booking date to a variable 'specialDate' using a ForEach Statement

I then run the variable through the datePipe to match the booking date output to the required format,

I then run an if statement to see if any of my returned dates match the current date.

When I console.log my specialDate I am getting the one date returned out of the 2 that match todays date which is great.

console log

but when I do console.log(specialDate.length)

it counts the characters in the date instead of returning '1' (the amount of matching booking dates to the current date.

So I guess what I am returning is a string and its counting that instead of returning an object. how would I get the count of the objects with matching dates to the currentDate?

UPDATE:

I managed to return the only bookings that match the current date as an object using the following code:

```<code>// Get count of bookings
af.database.list('/bookings').subscribe((res) => {
    this.numbeOfBookings = res.length;
    res.forEach(item => {
    //get the date propery from the bookings node
    var specialDate = (item.start);
    //transform the date property to matching format
    specialDate = this.datePipeEn.transform(new Date(item.start), 'dd/M/yyyy');

      if(specialDate === currentDate) {
        console.log(item);
      }

    });
});
</code>```

On the console log I see the only object which is a booking that matches todays date.

console log

However, if I do this: console.log(item.length); it counts the keys in the object and not return the number '1' I was hoping for. (the amount of bookings that match todays date)

How would I return the number 1, for the 1 object that was returned?

UPDATE

I managed to get the count of objects returned which is 1 :)

here is what I did, I had to make each item an object, then put the returned objects into an array then I could successfully console.log the returned value i was after! :)

```<code> // Get count of bookings
this.test = af.database.list('/bookings').subscribe((res) => {
    this.numbeOfBookings = res.length;

    res.forEach(item => {
      var bookingDate = (item.start); //get the date propery from the bookings node
      bookingDate = this.datePipeEn.transform(new Date(item.start), 'dd/M/yyyy'); //transform the date property to matching format
      var myObj = {item}; // Put each returned item into an object
      var array = $.map(myObj, function (value, index) { // Create an array with the returned objects
        return [value];
      });

      if(bookingDate === currentDate) {

        var bookingsToday = array
        var bookingsCount = array.length
        // console.log(bookingsToday);
        return(bookingsCount);

      }

    });
});
</code>```

I do have one final question however.

How would I use {{interpolation}} to reference this returned 'bookingsCount' value in my html template? (Angular 2) Many thanks in advance.

Continuation of comments on first answer <<

new screenshot of console

Here is the screenshot of the console when I added console.log(specialDate,currentDate);

here is the code:

```<code>af.database.list('/bookings').subscribe((res) => {
    var i = 0
    this.numbeOfBookings = res.length;
    res.forEach(item => {
        var specialDate = (item.start);
        specialDate = this.datePipeEn.transform(new Date(item.start),'dd/M/yyyy');
        console.log(specialDate,currentDate);
          if(specialDate === currentDate) {
            i++
            console.log(item)
          }

        });
    //use you variable here
    console.log(i)
    });
</code>```

答:
you have to increment a variable in you if statement, and after forEach you can use your variable :

```<code>af.database.list('/bookings').subscribe((res) => {
var i = 0 <----------- init a variable
this.numbeOfBookings = res.length;
res.forEach(item => {
    var specialDate = (item.start);
    specialDate = this.datePipeEn.transform(new Date(item.start),'dd/M/yyyy');
      console.log(specialDate,currentDate); <-----------
      if(specialDate === currentDate) {
        i++ <-------------- increment it each time the date is the same
        console.log(item);
      }

    });
//use you variable here
console.log(i)
});
</code>```

i advice you :

to use, angularfire (official angular 2 firebase) you can find it in github,

if you work with angularfire, so try the queries, and get the list of your matching dates from the server

the ultimate advice is to quit firebase if you don't need realtime feature, even so, try AWS dynamo with lambda, or get you hand dirty using socket.io and Mlab(Free mongodb as service)

Title: Angular 2 Firebase Return Object Count

Body:
I am working in Angular 2 and have a booking component.

When a booking is made, the information is sent to firebase database in a bookings node.

I am trying to show on the home screen dashboard of the app if the admin has any bookings today. in my component I have subscribed to the bookings node in firebase using Angularfire as follows:

this.bookingItemsData = af.database.list('/bookings');
this.bookingItemsData.subscribe((res) => {
  this.bookingItems = res;
  console.log(res);

I want to get the current date and compare it to the date give in firebase bookings node, so to get current date I have added this:

//get current date
    var getToday = new Date();
    var year = getToday.getFullYear();
    var month = getToday.getMonth() + 1;
    var day = getToday.getDate();
    // var time =  getToday.getTime();
    var currentDate = day + "/" + month + "/" + year;

Which successfully gets me the currentDate I require.

I now run this to get the dates from the bookings:

// Get count of bookings
    af.database.list('/bookings').subscribe((res) => {
        this.numbeOfBookings = res.length;
        res.forEach(item => {
        //get the date propery from the bookings node
        var specialDate = (item.start);
        //transform the date property to matching format
        specialDate = this.datePipeEn.transform(new Date(item.start), 'dd/M/yyyy');

        // console.log(specialDate);
        // console.log(currentDate);

          if(specialDate === currentDate) {
          console.log(specialDate);
          }

        });
    });

I first get the number of bookings in the booking list,

I then iterate through the bookings and assign the booking date to a variable 'specialDate' using a ForEach Statement

I then run the variable through the datePipe to match the booking date output to the required format,

I then run an if statement to see if any of my returned dates match the current date.

When I console.log my specialDate I am getting the one date returned out of the 2 that match todays date which is great.

console log

but when I do console.log(specialDate.length)

it counts the characters in the date instead of returning '1' (the amount of matching booking dates to the current date.

So I guess what I am returning is a string and its counting that instead of returning an object. how would I get the count of the objects with matching dates to the currentDate?

UPDATE:

I managed to return the only bookings that match the current date as an object using the following code:

// Get count of bookings
af.database.list('/bookings').subscribe((res) => {
    this.numbeOfBookings = res.length;
    res.forEach(item => {
    //get the date propery from the bookings node
    var specialDate = (item.start);
    //transform the date property to matching format
    specialDate = this.datePipeEn.transform(new Date(item.start), 'dd/M/yyyy');

      if(specialDate === currentDate) {
        console.log(item);
      }

    });
});

On the console log I see the only object which is a booking that matches todays date.

console log

However, if I do this: console.log(item.length); it counts the keys in the object and not return the number '1' I was hoping for. (the amount of bookings that match todays date)

How would I return the number 1, for the 1 object that was returned?

UPDATE

I managed to get the count of objects returned which is 1 :)

here is what I did, I had to make each item an object, then put the returned objects into an array then I could successfully console.log the returned value i was after! :)

 // Get count of bookings
this.test = af.database.list('/bookings').subscribe((res) => {
    this.numbeOfBookings = res.length;

    res.forEach(item => {
      var bookingDate = (item.start); //get the date propery from the bookings node
      bookingDate = this.datePipeEn.transform(new Date(item.start), 'dd/M/yyyy'); //transform the date property to matching format
      var myObj = {item}; // Put each returned item into an object
      var array = $.map(myObj, function (value, index) { // Create an array with the returned objects
        return [value];
      });

      if(bookingDate === currentDate) {

        var bookingsToday = array
        var bookingsCount = array.length
        // console.log(bookingsToday);
        return(bookingsCount);

      }

    });
});

I do have one final question however.

How would I use {{interpolation}} to reference this returned 'bookingsCount' value in my html template? (Angular 2) Many thanks in advance.

Continuation of comments on first answer <<

new screenshot of console

Here is the screenshot of the console when I added console.log(specialDate,currentDate);

here is the code:

af.database.list('/bookings').subscribe((res) => {
    var i = 0
    this.numbeOfBookings = res.length;
    res.forEach(item => {
        var specialDate = (item.start);
        specialDate = this.datePipeEn.transform(new Date(item.start),'dd/M/yyyy');
        console.log(specialDate,currentDate);
          if(specialDate === currentDate) {
            i++
            console.log(item)
          }

        });
    //use you variable here
    console.log(i)
    });

Body:
you have to increment a variable in you if statement, and after forEach you can use your variable :

af.database.list('/bookings').subscribe((res) => {
var i = 0 <----------- init a variable
this.numbeOfBookings = res.length;
res.forEach(item => {
    var specialDate = (item.start);
    specialDate = this.datePipeEn.transform(new Date(item.start),'dd/M/yyyy');
      console.log(specialDate,currentDate); <-----------
      if(specialDate === currentDate) {
        i++ <-------------- increment it each time the date is the same
        console.log(item);
      }

    });
//use you variable here
console.log(i)
});

i advice you :

to use, angularfire (official angular 2 firebase) you can find it in github,

if you work with angularfire, so try the queries, and get the list of your matching dates from the server

the ultimate advice is to quit firebase if you don't need realtime feature, even so, try AWS dynamo with lambda, or get you hand dirty using socket.io and Mlab(Free mongodb as service)


问:
Why is a refresh_token not provided by OAuth2 servers responding to a "client_credentials" grant?
I'm reading the OAuth2 spec:

https://www.rfc-editor.org/rfc/rfc6749#section-4.4.2

Specially the section on client_credentials grant type.

If the access token request is valid and authorized, the

authorization server issues an access token as described in    Section
5.1.

A refresh token SHOULD NOT be included.  If the request    failed client authentication or is invalid, the authorization server
returns an error response as described in Section 5.2.

An example successful response:

```<code> HTTP/1.1 200 OK
 Content-Type: application/json;charset=UTF-8
 Cache-Control: no-store
 Pragma: no-cache

 {
   "access_token":"2YotnFZFEjr1zCsicMWpAA",
   "token_type":"example",
   "expires_in":3600,
   "example_parameter":"example_value"
 }
</code>```

`

I'm somewhat confused why an authorization server can return refresh_tokens for password grant types but not for client_credentials.

I'm guessing that it has something to do with the fact that the refresh_token can be exchanged for an access_token and because the client_credentials grant type does not require a username and password, in the event that your application keys and refresh_token is compromised revocation becomes much more difficult?

答:
The key part to understand this, is that the refresh concept is NOT designed for you to refresh a whatever access token you already have.

The "refresh token" is simply a way to skip end user intervention and still regain a new access token, IF your app is using end user username/password authentication, i.e. acting on behalf of a specific end user. (If I were the designer, I might name "refresh token" as "bypass-user-intervention token", so the current question wouldn't need to be asked.)

But if your app is using client credential to authenticate, it is acting on its own behalf, and you don't need user intervention at all, and the server doesn't need to (and won't) give you a refresh token either.

Body:
I'm reading the OAuth2 spec:

https://www.rfc-editor.org/rfc/rfc6749#section-4.4.2

Specially the section on client_credentials grant type.

If the access token request is valid and authorized, the

authorization server issues an access token as described in    Section
5.1.

A refresh token SHOULD NOT be included.  If the request    failed client authentication or is invalid, the authorization server
returns an error response as described in Section 5.2.

An example successful response:

 HTTP/1.1 200 OK
 Content-Type: application/json;charset=UTF-8
 Cache-Control: no-store
 Pragma: no-cache

 {
   "access_token":"2YotnFZFEjr1zCsicMWpAA",
   "token_type":"example",
   "expires_in":3600,
   "example_parameter":"example_value"
 }

`

I'm somewhat confused why an authorization server can return refresh_tokens for password grant types but not for client_credentials.

I'm guessing that it has something to do with the fact that the refresh_token can be exchanged for an access_token and because the client_credentials grant type does not require a username and password, in the event that your application keys and refresh_token is compromised revocation becomes much more difficult?


问:
Does Earlgrey for iOS support UI elements outside of the test app?
I am totally new to iOS, Xcode and automated test frameworks.

I would like to confirm 3 things about iOS testing using EarlGrey:

It cannot access elements outside of the test app. For example, the test app cannot press the 'HOME' key

It does not support the 'swipe up' gesture to bring up the control centre

It cannot not put a test app in background and then bring it to the foreground

If I understand correctly, EarlGrey only allows control of the UI elements defined inside the test app.

Is this correct?

Thanks

答: Yup, you are right but Out-of-app interaction is being worked on please follow along here.</p>


问:
Create empty disk for Google Deployment Manager
I am try to creat a compute instance using Googles deployment manager. It has shall get two disk, one based on a boot image and a second that shall be blank. The blank disk will later on be formated and mounted correctly by salt stack. Deployment manager complains with "Source image must be specified."  How do I create a second blank disk for a compute instance using deployment manager?

My compute-instance.jinja:

```<code>resources:
- type: compute.v1.instance
  name: {{ env["deployment"] }}-{{ env["name"] }}
  properties:
    zone: europe-west1-c
    machineType: zones/europe-west1-c/machineTypes/n1-standard-1
    disks:
    - deviceName: {{ env["deployment"] }}-{{ env["name"] }}
      type: PERSISTENT
      boot: true
      autoDelete: true
      initializeParams:
        sourceImage: global/images/XXXXXXX
    - deviceName: {{ env["deployment"] }}-{{ env["name"] }}-data
      type: PERSISTENT
      boot: false
      autoDelete: true
      initializeParams:
        diskSizeGb: {{ properties["size"] }}
    networkInterfaces:
    - network: global/networks/default
      accessConfigs:
      - name: External NAT
        type: ONE_TO_ONE_NAT
</code>```

答:
If you must supply the source image, you can create an image of an empty disk.

The downside of this, is that you will start paying (not much tough) for 10gb of image storage when your actually storing nothing.

```<code>gcloud compute disks create emptydisk --size 10GB
gcloud compute images create empty-disk-image --source-disk emptydisk
</code>```

And then use it as the source image

```<code>- deviceName: {{ env["deployment"] }}-{{ env["name"] }}-data
  type: PERSISTENT
  boot: false
  autoDelete: true
  initializeParams:
    sourceImage: projects/your-project-id/global/images/empty-disk-image
    diskSizeGb: {{ properties["size"] }}
</code>```

Body:
I am try to creat a compute instance using Googles deployment manager. It has shall get two disk, one based on a boot image and a second that shall be blank. The blank disk will later on be formated and mounted correctly by salt stack. Deployment manager complains with "Source image must be specified."  How do I create a second blank disk for a compute instance using deployment manager?

My compute-instance.jinja:

resources:
- type: compute.v1.instance
  name: {{ env["deployment"] }}-{{ env["name"] }}
  properties:
    zone: europe-west1-c
    machineType: zones/europe-west1-c/machineTypes/n1-standard-1
    disks:
    - deviceName: {{ env["deployment"] }}-{{ env["name"] }}
      type: PERSISTENT
      boot: true
      autoDelete: true
      initializeParams:
        sourceImage: global/images/XXXXXXX
    - deviceName: {{ env["deployment"] }}-{{ env["name"] }}-data
      type: PERSISTENT
      boot: false
      autoDelete: true
      initializeParams:
        diskSizeGb: {{ properties["size"] }}
    networkInterfaces:
    - network: global/networks/default
      accessConfigs:
      - name: External NAT
        type: ONE_TO_ONE_NAT

Body:
If you must supply the source image, you can create an image of an empty disk.

The downside of this, is that you will start paying (not much tough) for 10gb of image storage when your actually storing nothing.

gcloud compute disks create emptydisk --size 10GB
gcloud compute images create empty-disk-image --source-disk emptydisk

And then use it as the source image

- deviceName: {{ env["deployment"] }}-{{ env["name"] }}-data
  type: PERSISTENT
  boot: false
  autoDelete: true
  initializeParams:
    sourceImage: projects/your-project-id/global/images/empty-disk-image
    diskSizeGb: {{ properties["size"] }}


问:
How field_with_errors div Gets Added in a Form When Validations Fail Within fields_for
It is clear to me that when a validation fails in a form: what happens is the errors hash associated to your object gains a new key which is magically mapped to that object's invalid attribute.  That key's value is the relevant error message for that invalidation.

The above is all explained nicely in the Working with Validation Errors Rails Guide

This next part is what does not make sense to me.  Magically: rails appears to somehow look at the keys in your errors hash, map those to the appropriate form labels and inputs, and then wraps those invalid form labels and inputs with a
 ...
.

I am trying to figure out how that magic works.

To be more specific: I am wondering how rails is able to map the field_with_errors appropriately when there are fields_for present in a form for a has_many association.

Example: Say I have the following associations:

```<code># models/user.rb
class User < ApplicationRecord
  has_many :user_emails
end

# models/user_email.rb
class UserEmail < ApplicationRecord
  belongs_to :user
  validates_presence_of :email_text
end
</code>```

I then have a userform that has fields_for for 5 different nested user_email records.  Let us say two of those user_emails are invalid:

The form will re-render, and magically the fields_with_errors div only gets applied to those two invalid user_email records as opposed to ALL of the user_email records in the form.

How does rails do this?  I cannot find the documentation on this, or find any resources online in regards to the magic that is going on behind the scenes.

答:
The objects are passed through the field_error_proc one by one, so each is UserEmail is evaluated separately. The default proc specification is defined here:  https://github.com/rails/rails/blob/7da8d76206271bdf200ea201f7e5a49afb9bc9e7/actionview/lib/action_view/base.rb#L144 as:

```<code>@@field_error_proc = Proc.new { |html_tag, instance| "<div class=\"field_with_errors\">#{html_tag}</div>".html_safe }
</code>```

This is called by ActiveModelInstanceTag: https://github.com/rails/rails/blob/92703a9ea5d8b96f30e0b706b801c9185ef14f0e/actionview/lib/action_view/helpers/active_model_helper.rb#L28 with:

```<code>Base.field_error_proc.call(html_tag, self)
</code>```

Note that self here refers to an individual UserEmail object being evaluated. More information on this proc is available at https://github.com/rails/rails/blob/09436fb6d6d188739b40ef120b4344106d81caf9/guides/source/configuring.md#configuring-action-view and at https://github.com/rails/rails/blob/7c3a99eeca07f602bb1e5659656e8eab0a4eacfe/guides/source/active_support_core_extensions.md#cattr_reader-cattr_writer-and-cattr_accessor.

There's no magic at work; it evaluates all the models.

Body:
It is clear to me that when a validation fails in a form: what happens is the errors hash associated to your object gains a new key which is magically mapped to that object's invalid attribute.  That key's value is the relevant error message for that invalidation.

The above is all explained nicely in the Working with Validation Errors Rails Guide

This next part is what does not make sense to me.  Magically: rails appears to somehow look at the keys in your errors hash, map those to the appropriate form labels and inputs, and then wraps those invalid form labels and inputs with a
 ...
.

I am trying to figure out how that magic works.

To be more specific: I am wondering how rails is able to map the field_with_errors appropriately when there are fields_for present in a form for a has_many association.

Example: Say I have the following associations:

# models/user.rb
class User < ApplicationRecord
  has_many :user_emails
end

# models/user_email.rb
class UserEmail < ApplicationRecord
  belongs_to :user
  validates_presence_of :email_text
end

I then have a userform that has fields_for for 5 different nested user_email records.  Let us say two of those user_emails are invalid:

The form will re-render, and magically the fields_with_errors div only gets applied to those two invalid user_email records as opposed to ALL of the user_email records in the form.

How does rails do this?  I cannot find the documentation on this, or find any resources online in regards to the magic that is going on behind the scenes.

Body:
The objects are passed through the field_error_proc one by one, so each is UserEmail is evaluated separately. The default proc specification is defined here:  https://github.com/rails/rails/blob/7da8d76206271bdf200ea201f7e5a49afb9bc9e7/actionview/lib/action_view/base.rb#L144 as:

@@field_error_proc = Proc.new { |html_tag, instance| "<div class=\"field_with_errors\">#{html_tag}</div>".html_safe }

This is called by ActiveModelInstanceTag: https://github.com/rails/rails/blob/92703a9ea5d8b96f30e0b706b801c9185ef14f0e/actionview/lib/action_view/helpers/active_model_helper.rb#L28 with:

Base.field_error_proc.call(html_tag, self)

Note that self here refers to an individual UserEmail object being evaluated. More information on this proc is available at https://github.com/rails/rails/blob/09436fb6d6d188739b40ef120b4344106d81caf9/guides/source/configuring.md#configuring-action-view and at https://github.com/rails/rails/blob/7c3a99eeca07f602bb1e5659656e8eab0a4eacfe/guides/source/active_support_core_extensions.md#cattr_reader-cattr_writer-and-cattr_accessor.

There's no magic at work; it evaluates all the models.


问:
How to get name of dataframe column in PySpark?
In pandas, this can be done by column.name.

But how to do the same when it's a column of Spark dataframe?

E.g. the calling program has a Spark dataframe: spark_df

```<code>>>> spark_df.columns
['admit', 'gre', 'gpa', 'rank']
</code>```

This program calls my function: my_function(spark_df['rank'])

In my_function, I need the name of the column, i.e. 'rank'.

If it was pandas dataframe, we could use this:

```<code>>>> pandas_df['rank'].name
'rank'
</code>```

答:
The only way is to go an underlying level to the JVM.

```<code>df.col._jc.toString().encode('utf8')
</code>```

This is also how it is converted to a str in the pyspark code itself.

From pyspark/sql/column.py:

```<code>def __repr__(self):
    return 'Column<%s>' % self._jc.toString().encode('utf8')
</code>```

Body:
In pandas, this can be done by column.name.

But how to do the same when it's a column of Spark dataframe?

E.g. the calling program has a Spark dataframe: spark_df

>>> spark_df.columns
['admit', 'gre', 'gpa', 'rank']

This program calls my function: my_function(spark_df['rank'])

In my_function, I need the name of the column, i.e. 'rank'.

If it was pandas dataframe, we could use this:

>>> pandas_df['rank'].name
'rank'

Body:
The only way is to go an underlying level to the JVM.

df.col._jc.toString().encode('utf8')

This is also how it is converted to a str in the pyspark code itself.

From pyspark/sql/column.py:

def __repr__(self):
    return 'Column<%s>' % self._jc.toString().encode('utf8')


问:
Timestamp comparision not working properly for presto cassandra
I have the below presto query to retrieve data from cassandra

select * from table where created_time >= '2017-03-23 00:00:00.0' and created_time <= '2017-03-25 00:00:00.0';

The table has 70 rows with created_time as 2017-03-25 but the above query is not returning me all the rows.

created_time is defined as timeuuid in cassandra. Can someone help me why the query does not work

答:
If created_time is defined as timeuuid, I would think that a query predicate  would compare that to a timeuuid value, not a string or a date string.

We can use the minTimeuuid and maxTimeuuid functions to generate values we can compare to a timeuuid column.

If we want rows with created_time sometime on March 25, we probably want the comparison to be "less than" the 26th '2017-03-26'

For example:

```<code>   where created_time >= minTimeuuid('2017-03-25 00:00+0000')
     and created_time <  minTimeuuid('2017-03-26 00:00+0000')
</code>```

Body:
If created_time is defined as timeuuid, I would think that a query predicate  would compare that to a timeuuid value, not a string or a date string.

We can use the minTimeuuid and maxTimeuuid functions to generate values we can compare to a timeuuid column.

If we want rows with created_time sometime on March 25, we probably want the comparison to be "less than" the 26th '2017-03-26'

For example:

   where created_time >= minTimeuuid('2017-03-25 00:00+0000')
     and created_time <  minTimeuuid('2017-03-26 00:00+0000')


问:
How to get local time zone for an email sent from another country in Microsoft Graph API
When you make a call on Microsoft Graph API for a specific email message, all DateTimeOffset are in UTC time : createdDateTime, sentDateTime...

I would like to know the local time zone of an email when it was sent from some place. Example : I am french, travelling to US, and sending an email during my stay : the time zone of the 'sentDateTime' should be different, but it remains in UTC, losing this information. Is it possible to find this information using Microsoft Graph API somewhere else ?

Thanks for your help !

答:
At the moment this isn't possible. All of the times are returned by Graph (and the Outlook REST API) as zulu.

There is however a UserVoice request to "Allow Microsoft Graph API to return mail headers" that would also help with this scenario. These are actively reviewed so each vote counts (hint hint).


答: You have npm already installed, seems that the problem is you don't have a package.json in that location. It says ENOENT: No such file or directory

Title: I can't install npm not matter what I do

Body:
So I'm trying to get myself a good Discord Selfbot and one of them requires nodejs, then it said to do npm install. But it gave me an error. I tried again again again and again but nothing worked. The latest thing I did was installing nodejs via scoop but I get this error trying to install npm. Is there a way to do this manually or something? I've tried installing different versions but nothing. I believe scoop installed the latest version.
Here's the image. (the red squares cover up just names)


问:
How to safely use current identity as value in insert query
I have a table where one of the columns is a path to an image and I need to create a directory for the record being inserted.

Example:

```<code>Id | PicPath |<br>
 1 | /Pics/1/0.jpg|<br>
 2 | /Pics/2/0.jpg|
</code>```

This way I can be sure that the folder name is always valid and it is unique (no clash between two records).

Question is: how can I safely refer to the current id of the record being insert? Keep in mind that this is a highly concurrent environment, and I would like to avoid multiple trips to the DB if possible.

I have tried the following:

```<code>insert into Dummy values(CONCAT('a', (select IDENT_CURRENT('Dummy'))))
</code>```

and

```<code>insert into Dummy values(CONCAT('a', (select SCOPE_IDENTITY() + 1)))
</code>```

The first query is not safe, for when running 1000 concurrent inserts I got 58 'duplicate key' exceptions.

The second query didn't work because SCOPE_IDENTITY() returned the same value for all queries as I suspected.

What are my alternatives here?

答:
Try a temporary table to track your inserted ids using OUTPUT clause

```<code>INSERT #temp_ids(someval) OUTPUT inserted.identity_column
</code>```

This will get all the inserted ids from your queries. 'inserted' is context safe.

Body:
I have a table where one of the columns is a path to an image and I need to create a directory for the record being inserted.

Example:

Id | PicPath |

 1 | /Pics/1/0.jpg|

 2 | /Pics/2/0.jpg|

This way I can be sure that the folder name is always valid and it is unique (no clash between two records).

Question is: how can I safely refer to the current id of the record being insert? Keep in mind that this is a highly concurrent environment, and I would like to avoid multiple trips to the DB if possible.

I have tried the following:

insert into Dummy values(CONCAT('a', (select IDENT_CURRENT('Dummy'))))

and

insert into Dummy values(CONCAT('a', (select SCOPE_IDENTITY() + 1)))

The first query is not safe, for when running 1000 concurrent inserts I got 58 'duplicate key' exceptions.

The second query didn't work because SCOPE_IDENTITY() returned the same value for all queries as I suspected.

What are my alternatives here?

Body:
Try a temporary table to track your inserted ids using OUTPUT clause

INSERT #temp_ids(someval) OUTPUT inserted.identity_column

This will get all the inserted ids from your queries. 'inserted' is context safe.


问:
C# serialize private class member
```<code>class Person
{
    public string m_name;
    private int m_age; // << how do I serialize the darn little rat?
}
</code>```

Simple question yet it seems like a big mess when trying to answer it.

Everyone suggest to use public getter/setter but my app is too big and making a getter/setter for each member would just cause maintainability issues.

Am I forced to create a custom serialization here or is there a magic attribute for such members?

How do I serialize private class members?

Edit #1:

Ok everyone, sorry for the unclarity, I was a bit upset when I wrote this question, it was several hours after trying to find the solution.

Anyway, here are more facts:

 1. I'm trying to XML serialize this class. Currently I'm using System.Xml.Serialization.XmlSerializer.

 2. I'm serializing into XML to have version compatibility, which as far as I understand binary doesn't offer me that.

 3.I was hoping that there's a certain attribute like:

```<code>class Person
{
    public string m_name;
    [SerializeThat(ElementName="Age")]
    private int m_age; // << how do I serialize the darn little rat?
}
</code>```

OR (continue of fact #3) an attribute that goes on the class which would look like:

```<code>[Serializable(DoPrivate = true, DoProtected = true)]
class Person
{
    public string m_name;
    private int m_age; // << how do I serialize the darn little rat?
}
</code>```

Now, what can I do to achieve it?

答:
Don't know if you can use DataContract. But with this you could write:

```<code>[DataContract]
class Person
{
    [DataMember]
    public string m_name;

    [DataMember]
    private int m_age;
}
</code>```

The advantage of DataContract that you can serialize private fields and your class doesn't need a default constructor.

ContentLicense: CC BY-SA 2.5

Title: C# serialize private class member

Body:
class Person
{
    public string m_name;
    private int m_age; // << how do I serialize the darn little rat?
}

Simple question yet it seems like a big mess when trying to answer it.

Everyone suggest to use public getter/setter but my app is too big and making a getter/setter for each member would just cause maintainability issues.

Am I forced to create a custom serialization here or is there a magic attribute for such members?

How do I serialize private class members?

Edit #1:

Ok everyone, sorry for the unclarity, I was a bit upset when I wrote this question, it was several hours after trying to find the solution.

Anyway, here are more facts:

 1. I'm trying to XML serialize this class. Currently I'm using System.Xml.Serialization.XmlSerializer.

 2. I'm serializing into XML to have version compatibility, which as far as I understand binary doesn't offer me that.

 3.I was hoping that there's a certain attribute like:

class Person
{
    public string m_name;
    [SerializeThat(ElementName="Age")]
    private int m_age; // << how do I serialize the darn little rat?
}

OR (continue of fact #3) an attribute that goes on the class which would look like:

[Serializable(DoPrivate = true, DoProtected = true)]
class Person
{
    public string m_name;
    private int m_age; // << how do I serialize the darn little rat?
}

Now, what can I do to achieve it?

Body:
Don't know if you can use DataContract. But with this you could write:

[DataContract]
class Person
{
    [DataMember]
    public string m_name;

    [DataMember]
    private int m_age;
}

The advantage of DataContract that you can serialize private fields and your class doesn't need a default constructor.


问:
Redirection not happening in Php
I am using a special wrapper class around session_start() function to add protections on my sessions.

To log the user out, I have a button like this:

```<code> <a href="logout.php">
  <button data-toggle="modal" data-backdrop="false" href="" name="out" class="btn btn-primary navbar-btn" style="margin-right: 3px"><span class="glyphicon glyphicon-user"></span>Log Out</button></a>
</code>```

Here is the logout.php:

```<code><?php

error_reporting(0);
include('SessionManager.php');
$mySess = new SessionManager();
$session = $mySess -> sessionStart('InstallationName'); // create/start a new session or start the existent session

$mySess -> destroy(); //destroy the session

header('Location: page1bis.php');
exit();
?>
</code>```

Here is the destroy() function in my SessionManager Class:

```<code><?php
class SessionManager
{
          .
          .
          .
static protected function destroy()
{
    echo $_SESSION['cook'];echo "<br>";
    echo "hello !";
    session_destroy();
    echo $_SESSION['cook'];
}
}
?>
</code>```

But when one click on the logout button, it goes to the lougout.php page, but no redirection is made, also here is the output of the lougout.php page:

```<code>tfe0eccar02k3pgi5b7i8i2ek5
hello !
</code>```

p.s: The echos in the logout.php are just here to show that the session is effectively destroy (or there should to 2 tokens), also even if I remove them there is still the same problem

答:
You can't output prior to redirection.

Either move the location redirect logic prior to output or you can add ob_start(); as the first line in your script and then that output will get discarded upon redirect.

Title: Redirection not happening in Php

Body:
I am using a special wrapper class around session_start() function to add protections on my sessions.

To log the user out, I have a button like this:

  <button data-toggle="modal" data-backdrop="false" href="" name="out" class="btn btn-primary navbar-btn" style="margin-right: 3px">Log Out</button>

Here is the logout.php:

<?php

error_reporting(0);
include('SessionManager.php');
$mySess = new SessionManager();
$session = $mySess -> sessionStart('InstallationName'); // create/start a new session or start the existent session

$mySess -> destroy(); //destroy the session

header('Location: page1bis.php');
exit();
?>

Here is the destroy() function in my SessionManager Class:

<?php
class SessionManager
{
          .
          .
          .
static protected function destroy()
{
    echo $_SESSION['cook'];echo "
";
    echo "hello !";
    session_destroy();
    echo $_SESSION['cook'];
}
}
?>

But when one click on the logout button, it goes to the lougout.php page, but no redirection is made, also here is the output of the lougout.php page:

tfe0eccar02k3pgi5b7i8i2ek5
hello !

p.s: The echos in the logout.php are just here to show that the session is effectively destroy (or there should to 2 tokens), also even if I remove them there is still the same problem


问:
DB Schema Design - Designing multiple many to many tables
I am trying to design a DB that has multiple many to many junction tables but each many to many is a cascading option based on previous tables.

For Example: Let's begin with four tables with their primary keys.

Style table --> Style ID (PK)

     Fabric table --> FabricID (PK)

     Body table --> BodyID (PK)

     Color table --> ColorID (PK)

A User chooses a Style and then a Fabric, so this is easy to define the many to many.

StyleFabric table --> StyleID, FabricID (Composite PK)

Now this is where I get confused. The User after choosing Style and Fabric can now choose Body. So I created a table called:

StyleFabricBody table --> StyleID, FabricID, BodyID  (Composite PK)

Now Based on Style,Fabric and Body, the user can select a color

StyleFabricBodyColor table --> StyleID, FabricID, BodyID, ColorID (Composite PK)

Hopefully you can see the pattern by now and I have 5 more tables to add.

Is this a correct approach to connect the main tables ?

答:
So I suggest you have the structure like:</p>

```<code>CREATE TABLE Choosable
(
    ChoosableId int,            -- This is PK
    Name        varchar(10),    -- This can have values 'Style', 'Fabric', 'Body', 'Color'
)

Data in this table

Style1
Style2
Fab1
Fab2
Fab3
Body1
Body2
Blue
Red
Gray

CREATE TABLE Choices
(
    ChoiceId       int,     -- This is PK
    ChoosableId    int,     -- This is FK to Choosable.ChoosableId
    ParentId       int      -- This is FK to ChoiceId
)

Structure for this table can support below data

Style1
    Fab1
        Body1
            Red
            Blue
        Body2
            Red
    Fab2
        Body1
            Blue
            Gray
            Red
</code>```

Body:
So I suggest you have the structure like:

CREATE TABLE Choosable
(
    ChoosableId int,            -- This is PK
    Name        varchar(10),    -- This can have values 'Style', 'Fabric', 'Body', 'Color'
)

Data in this table

Style1
Style2
Fab1
Fab2
Fab3
Body1
Body2
Blue
Red
Gray

CREATE TABLE Choices
(
    ChoiceId       int,     -- This is PK
    ChoosableId    int,     -- This is FK to Choosable.ChoosableId
    ParentId       int      -- This is FK to ChoiceId
)

Structure for this table can support below data

Style1
    Fab1
        Body1
            Red
            Blue
        Body2
            Red
    Fab2
        Body1
            Blue
            Gray
            Red


问:
Autoit Why is (0 <> "Test") False
I am fetching a numeric value from an HTML table. If it fails to fetch the value I fill the value "NA" instead. Here is the odd part 0 <> "NA" is false, 0 = "NA" is true, 0 == "NA" is False. I get that = is not case sensitive, and == is, but I thought <> was case sensitive... So why does it work like this?

```<code>Local $x = 0
If $x <> "Test" Then
    MsgBox(0,"","x <> Test")
Else
    MsgBox(0,"","x = Test")
EndIf
</code>```

With this exaplle I get a message box "x = Test"

答:
but I thought <> was case sensitive

According to the docs, it is not a string-specific comparison operator like ==. Rather, it’s just the negation of =, so your string will still be interpreted as an integer – both "NA" and "Test" becoming 0 – and fail to satisfy 0 <> 0.

Tests if two values are not equal. Case insensitive when used with strings. To do a case sensitive not equal comparison use Not ("string1" == "string2")

Title: Autoit Why is (0 <> "Test") False

Body:
I am fetching a numeric value from an HTML table. If it fails to fetch the value I fill the value "NA" instead. Here is the odd part 0 <> "NA" is false, 0 = "NA" is true, 0 == "NA" is False. I get that = is not case sensitive, and == is, but I thought <> was case sensitive... So why does it work like this?

Local $x = 0
If $x <> "Test" Then
    MsgBox(0,"","x <> Test")
Else
    MsgBox(0,"","x = Test")
EndIf

With this exaplle I get a message box "x = Test"


问:
CSV indentation and Proper language in Python
I want to return the list that comes out with the print function into a CSV list.

```<code>import re

import requests
from bs4 import BeautifulSoup

for i in range(146):
    r = requests.get(("http://www.yellowpages.com/atlanta-ga/trends/{}").format(i))
    soup = BeautifulSoup(r.content , "html.parser")
    for link in soup.find_all("a",href=re.compile('/atlanta-ga/')):
        if 'trends' not in link.get('href'):
            link = (link.get('href'))
            results = (("http://www.yellowpages.com{}?page=").format(link))
            import csv

            with open('Catagories', 'w') as myfile:
                wr = csv.writer(myfile)
                wr.writerow([results])

            print(results)
</code>```

The purpose of this should be very apparent

答:
@tdelaney is right: every time you open the file with "w", you're overwritting the previous text.

The fix is to use "a" instead:

```<code>with open('Catagories', 'a') as myfile:
    ...
</code>```

Check out the docs: https://docs.python.org/3/library/functions.html#open

Body:
I want to return the list that comes out with the print function into a CSV list.

import re

import requests
from bs4 import BeautifulSoup

for i in range(146):
    r = requests.get(("http://www.yellowpages.com/atlanta-ga/trends/{}").format(i))
    soup = BeautifulSoup(r.content , "html.parser")
    for link in soup.find_all("a",href=re.compile('/atlanta-ga/')):
        if 'trends' not in link.get('href'):
            link = (link.get('href'))
            results = (("http://www.yellowpages.com{}?page=").format(link))
            import csv

            with open('Catagories', 'w') as myfile:
                wr = csv.writer(myfile)
                wr.writerow([results])

            print(results)

The purpose of this should be very apparent

Body:
@tdelaney is right: every time you open the file with "w", you're overwritting the previous text.

The fix is to use "a" instead:

with open('Catagories', 'a') as myfile:
    ...

Check out the docs: https://docs.python.org/3/library/functions.html#open


问:
My c++ programm keeps crashing ist my code bad?
Can somebody pls check if my code is bad? My command prompt crashes when I execute it.

I narrowed the problem down to this section:

```<code>    string result = "";
    result = pwpasst (username, password, "admin", "123");
    result = pwpasst (username, password, "root", "456");
    result = pwpasst (username, password, "peter", "789");
</code>```

If I comment out 2 out of the 3 functions it seems to work. +
I don't know if my code is bad or of there is a problem with my command prompt.

The rest of the code:

```<code>#include <iostream>

using namespace std;

    string pwpasst (string username, string password, string un, string pw){
        if (username == un && password == pw)
        {
            return "You are logged in!";
        }
    };

int main()
{
    string username;
    string password;

    cout << "Enter your username: ";
    cin >> username;

    cout << "Enter your password: ";
    cin >> password;

    string result = "";
    result = pwpasst (username, password, "admin", "123");
    result = pwpasst (username, password, "root", "456");
    result = pwpasst (username, password, "peter", "789");

    if (result != "You are logged in!"){
        cout << "Wrong password or username!";
    }   else { cout << result;}
}
</code>```

答:
pwpasst() might return the string "You are ..."

But the else clause is missing and nothing is returned, a logic error.
Your function should always return the string it promised.

```<code>string pwpasst (string username, string password, string un, string pw)
{
   if (username == un && password == pw)
   {
      return "You are logged in!";
   }
   else
   {
      // perhaps - but not a good choice.
      std::cerr << "unknown user name or password" << std::endl;
      return ""; // return null string
   }
};
</code>```

Not a good choice because the previous would output 1, or 2 error messages each time.

In this code snippet, the three assignments will always be executed.

```<code>string result = "";
result = pwpasst (username, password, "admin", "123");
result = pwpasst (username, password, "root", "456");
result = pwpasst (username, password, "peter", "789");
</code>```

You want to break out when you get a result, something like the following, (but this is not a good choice either):

```<code>string result = "";
do {
   result = pwpasst (username, password, "admin", "123");
            if(result.size()) break;
   result = pwpasst (username, password, "root", "456");
            if(result.size()) break;
   result = pwpasst (username, password, "peter", "789");
            if(result.size()) break;
}while(0);
</code>```

Probably need to place the error message in this snippet, not in the function.

Some logic changes are required. Perhaps the function should return a bool (indicating valid name/pw or not), and the string 'result' might passed by reference for the function to fill in.

Body:
Can somebody pls check if my code is bad? My command prompt crashes when I execute it.

I narrowed the problem down to this section:

    string result = "";
    result = pwpasst (username, password, "admin", "123");
    result = pwpasst (username, password, "root", "456");
    result = pwpasst (username, password, "peter", "789");

If I comment out 2 out of the 3 functions it seems to work. +
I don't know if my code is bad or of there is a problem with my command prompt.

The rest of the code:

#include <iostream>

using namespace std;

    string pwpasst (string username, string password, string un, string pw){
        if (username == un && password == pw)
        {
            return "You are logged in!";
        }
    };

int main()
{
    string username;
    string password;

    cout << "Enter your username: ";
    cin >> username;

    cout << "Enter your password: ";
    cin >> password;

    string result = "";
    result = pwpasst (username, password, "admin", "123");
    result = pwpasst (username, password, "root", "456");
    result = pwpasst (username, password, "peter", "789");

    if (result != "You are logged in!"){
        cout << "Wrong password or username!";
    }   else { cout << result;}
}

Body:
pwpasst() might return the string "You are ..."

But the else clause is missing and nothing is returned, a logic error.
Your function should always return the string it promised.

string pwpasst (string username, string password, string un, string pw)
{
   if (username == un && password == pw)
   {
      return "You are logged in!";
   }
   else
   {
      // perhaps - but not a good choice.
      std::cerr << "unknown user name or password" << std::endl;
      return ""; // return null string
   }
};

Not a good choice because the previous would output 1, or 2 error messages each time.

In this code snippet, the three assignments will always be executed.

string result = "";
result = pwpasst (username, password, "admin", "123");
result = pwpasst (username, password, "root", "456");
result = pwpasst (username, password, "peter", "789");

You want to break out when you get a result, something like the following, (but this is not a good choice either):

string result = "";
do {
   result = pwpasst (username, password, "admin", "123");
            if(result.size()) break;
   result = pwpasst (username, password, "root", "456");
            if(result.size()) break;
   result = pwpasst (username, password, "peter", "789");
            if(result.size()) break;
}while(0);

Probably need to place the error message in this snippet, not in the function.

Some logic changes are required. Perhaps the function should return a bool (indicating valid name/pw or not), and the string 'result' might passed by reference for the function to fill in.


问:
git svn fetch gives "Invalid revision range" "error: 128" after bfg cleanup
I have a Git repo in migration from SVN with git-svn.
I used git svn fetch to get the latest commits from SVN. I wanted to push the repo to GitHub, but there were some files in the history larger than 100 MB that I had to remove, so I used bfg repo cleaner to get rid of them.

```<code>$ java -jar bfg-1.12.14.jar --strip-blobs-bigger-than 100M
...
In total, 10235 object ids were changed. Full details are logged here:
...
BFG run is complete! When ready, run: git reflog expire --expire=now --all && git gc --prune=now --aggressive
...
$ git reflog expire --expire=now --all && git gc --prune=now --aggressive
Counting objects: 204963, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (171827/171827), done.
Writing objects: 100% (204963/204963), done.
Total 204963 (delta 91547), reused 106805 (delta 0)

$ git svn fetch -A authors-transform.txt
fatal: Invalid revision range b156a7b66be002c3bf38987ea503f5c852146343
rev-list --pretty=raw --reverse b156a7b66be002c3bf38987ea503f5c852146343..refs/remotes/git-svn --: command returned error: 128
</code>```

How can I make it work without reinitialising the whole repository, as I don't want those files again in the history (they exceed GitHub's limit)? Any way to recalculate the hash or to make it ignore the mismatch?

答:
After doing something similar to you (cloning an svn repo with git svn clone --prefix=svn/ ...) and then running

```<code>> bfg --strip-blobs-bigger-than 20M
> git reflog expire --expire=now --all && git gc --prune=now --aggressive
</code>```

to remove large files from my repo, I found I also could not update from the svn repo with either a git svn fetch or a git svn rebase.  At first I had errors related to revision range, then I had errors related to missing or invalid objects.  To fix this, I had to remove the .revmap.* file, as well as the index on both the local and remote branches, then regenerate them.  The complete set of commands that fixed the problem for me were:

```<code>> git fsck --full
> git prune
> rm .git/svn/refs/remotes/svn/trunk/.rev_map.*
> rm .git/index
> rm .git/svn/refs/remotes/svn/trunk/index
> git svn rebase
</code>```

I have no idea what kind of dragons I unleashed for the future, but my repo seems to work now.  I can successfully pull new svn updates to my git repo, and merge them into other branches locally.

Note that I do not push back up to svn through git, so I don't know if that will cause issues.  Instead, I keep an "svn" branch that contains a pure copy pulled from the svn repo, and I work locally in git on branch "master".  I then push changes back up using command-line svn from "master", pull them back to my "svn" branch, then merge them back into "master".

Body:
I have a Git repo in migration from SVN with git-svn.
I used git svn fetch to get the latest commits from SVN. I wanted to push the repo to GitHub, but there were some files in the history larger than 100 MB that I had to remove, so I used bfg repo cleaner to get rid of them.

$ java -jar bfg-1.12.14.jar --strip-blobs-bigger-than 100M
...
In total, 10235 object ids were changed. Full details are logged here:
...
BFG run is complete! When ready, run: git reflog expire --expire=now --all && git gc --prune=now --aggressive
...
$ git reflog expire --expire=now --all && git gc --prune=now --aggressive
Counting objects: 204963, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (171827/171827), done.
Writing objects: 100% (204963/204963), done.
Total 204963 (delta 91547), reused 106805 (delta 0)

$ git svn fetch -A authors-transform.txt
fatal: Invalid revision range b156a7b66be002c3bf38987ea503f5c852146343
rev-list --pretty=raw --reverse b156a7b66be002c3bf38987ea503f5c852146343..refs/remotes/git-svn --: command returned error: 128

How can I make it work without reinitialising the whole repository, as I don't want those files again in the history (they exceed GitHub's limit)? Any way to recalculate the hash or to make it ignore the mismatch?

Body:
After doing something similar to you (cloning an svn repo with git svn clone --prefix=svn/ ...) and then running

> bfg --strip-blobs-bigger-than 20M
> git reflog expire --expire=now --all && git gc --prune=now --aggressive

to remove large files from my repo, I found I also could not update from the svn repo with either a git svn fetch or a git svn rebase.  At first I had errors related to revision range, then I had errors related to missing or invalid objects.  To fix this, I had to remove the .revmap.* file, as well as the index on both the local and remote branches, then regenerate them.  The complete set of commands that fixed the problem for me were:

> git fsck --full
> git prune
> rm .git/svn/refs/remotes/svn/trunk/.rev_map.*
> rm .git/index
> rm .git/svn/refs/remotes/svn/trunk/index
> git svn rebase

I have no idea what kind of dragons I unleashed for the future, but my repo seems to work now.  I can successfully pull new svn updates to my git repo, and merge them into other branches locally.

Note that I do not push back up to svn through git, so I don't know if that will cause issues.  Instead, I keep an "svn" branch that contains a pure copy pulled from the svn repo, and I work locally in git on branch "master".  I then push changes back up using command-line svn from "master", pull them back to my "svn" branch, then merge them back into "master".