问:
make a program see a PCIe card that has been programmed to detect PCI
I have a 3rd party propriety software that was on some old hardware, this box also had a PCI SCSI card that plugged into a special machine, this software is programmed to look at a PCI port that the card is plugged into. i recently upgraded the box to an HP elitedesk 800 G3 tower. i purchased a custom SCSI to PCIe card to put into it as it no longer has PCI ports. the problem im running into is that the program is looking for PCI and wont detect anything because there is no PCI port. i know this may take some ingeniuity but i would like to get some work around as we already spent alot of money upgrading these systems. i seen PCI to PCIe adapters but that wont solve anything. is there software out that that will give me some sort of virtual PCI port that we can "trick" the software to think is installed and point the PCIe to it? i dont know if this is even possible or not. the config file for this software is below and i have no idea what all that greek is. maybe someone with more knowledge will have an idea?</p>

```<code>; ICS.INF
; Copyright (c) 1999

[Version]
Signature="$CHICAGO$"
Class="Data Acquisition"
Provider=%IO%

[DestinationDirs]
DefaultDestDir=11
ComPort.Copy=17

[Manufacturer]
%ACCES%=IOMAN

[IOMAN]
%PCICOM1S%=ComPort,PCI\VEN_494F&DEV_10C8
%PCICOM1Sa%=ComPort,PCI\VEN_494F&DEV_10C9
%PCICOM2321S%=ComPort,PCI\VEN_494F&DEV_1088
%PCICOM2S%=ComPort2,PCI\VEN_494F&DEV_10D0
%PCICOM2322S%=ComPort2,PCI\VEN_494F&DEV_1090
%PCIICM1S%=ComPort,PCI\VEN_494F&DEV_1148
%PCIICM4222%=ComPort2,PCI\VEN_494F&DEV_1150
%PCIICM4852%=ComPort2,PCI\VEN_494F&DEV_1151
%PCIICM4224%=ComPort4,PCI\VEN_494F&DEV_1158
%PCIICM4854%=ComPort4,PCI\VEN_494F&DEV_1159
%PCICOM4224%=ComPort4,PCI\VEN_494F&DEV_1058
%PCICOM4854%=ComPort4,PCI\VEN_494F&DEV_1059
%PCIDA1216%=InstallSect,PCI\VEN_494F&DEV_6CB0
%PCIDA128%=InstallSect,PCI\VEN_494F&DEV_6CA8
%PCIDA1216V%=InstallSect,PCI\VEN_494F&DEV_6CB1
%PCIDA128V%=InstallSect,PCI\VEN_494F&DEV_6CA9
%PCIDIO24H%=InstallSect,PCI\VEN_494F&DEV_0C50
%PCIDIO24D%=InstallSect,PCI\VEN_494F&DEV_0C51
%PCIDIO24HC%=InstallSect,PCI\VEN_494F&DEV_0E51
%PCIDIO24DC%=InstallSect,PCI\VEN_494F&DEV_0E52
%PCIDIO24S%=InstallSect,PCI\VEN_494F&DEV_0E50
%PCIDIO48%=InstallSect,PCI\VEN_494F&DEV_0C60
%PCIDIO48S%=InstallSect,PCI\VEN_494F&DEV_0E60
%PCIDIO72%=InstallSect,PCI\VEN_494F&DEV_0C68
%PCIDIO96%=InstallSect,PCI\VEN_494F&DEV_0C70
%PCIDIO120%=InstallSect,PCI\VEN_494F&DEV_0C78
%PCIWDGCSM%=InstallSect,PCI\VEN_494F&DEV_22C0
%PCIAI1216%=InstallSect,PCI\VEN_494F&DEV_ACA8
%PCIAI1216A%=InstallSect,PCI\VEN_494F&DEV_ACA9
%PCIIIRO8%=InstallSect,PCI\VEN_494F&DEV_0F00
%PCM485%=ComPort,PCMCIA\Industrial_Computer_Source-PCM485-A505
%PCM485%=ComPort,PCMCIA\Industrial_Computer_Source-PCM485-D2B0
%PCM485%=ComPort,PCMCIA\Industrial_Computer_Source-PCM485-B233
%PCM485%=ComPort,PCMCIA\Industrial_Computer_Source-PCM485-D2ED
%PCM485%=ComPort,PCMCIA\Industrial_Computer_Source-PCM485-7609
%PAD128%=InstallSect,PCMCIA\Industrial_Computer_Source-PAD128-4498
%PAD128%=InstallSect,PCMCIA\Industrial_Computer_Source-PAD128-74EE
%PIOD24%=InstallSect,PCMCIA\Industrial_Computer_Source-PIOD24-2705
%PIOD24%=InstallSect,PCMCIA\Industrial_Computer_Source-PIOD24-368B
%PIOD24%=InstallSect,PCMCIA\Industrial_Computer_Source-PIOD24-32B6
%PIOD24%=InstallSect,PCMCIA\Industrial_Computer_Source-PIOD24-8BDC
%MF\485PORTA%=ComPort,MF\485PORTA
%MF\485PORTB%=ComPort,MF\485PORTB
%MF\485PORTC%=ComPort,MF\485PORTC
%MF\485PORTD%=ComPort,MF\485PORTD

[InstallSect]

[ComPort2]
AddReg=StandardMF.Reg

[ComPort4]
AddReg=StandardMF.Reg

[StandardMF.Reg]
HKR,,DevLoader,,*CONFIGMG
HKR,,Enumerator,,*CONFIGMG
HKR,,CMDrivFlags,01,03,00,00,00

[ComPort2.HW]
AddReg=ComPort2.RegHW

[ComPort4.HW]
AddReg=ComPort4.RegHW

[ComPort2.RegHW]
HKR,Child0000,HardwareID,,MF\485PORTA
HKR,Child0000,ResourceMap,1,00,03
HKR,Child0001,HardwareID,,MF\485PORTB
HKR,Child0001,ResourceMap,1,00,04

[ComPort4.RegHW]
HKR,Child0000,HardwareID,,MF\485PORTA
HKR,Child0000,ResourceMap,1,00,03
HKR,Child0001,HardwareID,,MF\485PORTB
HKR,Child0001,ResourceMap,1,00,04
HKR,Child0002,HardwareID,,MF\485PORTC
HKR,Child0002,ResourceMap,1,00,05
HKR,Child0003,HardwareID,,MF\485PORTD
HKR,Child0003,ResourceMap,1,00,06

[Ports.AddReg]
HKR,,NoSetupUI,,1

[ComPort]
CopyFiles=ComPort.Copy,VXD.Copy
AddReg=ComPort.AddReg
LogConfig=c14,c1a,c23,c2a,c34,c3a,c43,c4a,caa

[ComPort.Copy]
ics.inf

[VXD.Copy]

[ComPort.AddReg]
HKR,,DevLoader,,*vcomm
HKR,,Enumerator,,serenum.vxd
HKR,,PortDriver,,serial.vxd
HKR,,Contention,,*vcd
HKR,,ConfigDialog,,serialui.dll
HKR,,DCB,3,1C,00,00,00, 80,25,00,00, 11,33,00,00, 00,00, 0a,00, 0a,00, 08,    00, 00, 11, 13, 00, 00, 00
HKR,,PortSubClass,1,01
HKR,,EnumPropPages,,"serialui.dll,EnumPropPages"

[*pnp0500.det]
AddReg=Ports.AddReg,DevMap.AddReg

; The following sections are COM port resource configs.
; Section name format means:
; Char 1 = c (COM port)
; Char 2 = I/O config: 1 (3f8), 2 (2f8), 3 (3e8), 4 (2e8), a (any)
; Char 3 = IRQ config: #, a (any)

[c14]                   ; COM1,IRQ4
ConfigPriority=HARDRECONFIG
IOConfig=3f8-3ff(3ff::)
IRQConfig=S:4

[c1a]                   ; COM1, any IRQ
ConfigPriority=HARDRECONFIG
IOConfig=3f8-3ff(3ff::)
IRQConfig=S:3,4,5,7,9,10,11,12,14,15

[c23]                   ; COM2, IRQ3
ConfigPriority=HARDRECONFIG
IOConfig=2f8-2ff(3ff::)
IRQConfig=S:3

[c2a]                   ; COM2, any IRQ
ConfigPriority=HARDRECONFIG
IOConfig=2f8-2ff(3ff::)
IRQConfig=S:3,4,5,7,9,10,11,12,14,15

[c34]                   ; COM3, IRQ4
ConfigPriority=HARDRECONFIG
IOConfig=3e8-3ef(3ff::)
IRQConfig=S:4

[c3a]                   ; COM3, any IRQ
ConfigPriority=HARDRECONFIG
IOConfig=3e8-3ef(3ff::)
IRQConfig=S:3,4,5,7,9,10,11,12,14,15

[c43]                   ; COM4, IRQ3
ConfigPriority=HARDRECONFIG
IOConfig=2e8-2ef(3ff::)
IRQConfig=S:3,5

[c4a]                   ; COM4, any IRQ
ConfigPriority=HARDRECONFIG
IOConfig=2e8-2ef(3ff::)
IRQConfig=S:3,4,5,7,9,10,11,12,14,15

[caa]                   ; Any base, any IRQ
ConfigPriority=HARDRECONFIG
IOConfig=8@100-ffff%fff8(3ff::)
IRQConfig=S:3,4,5,7,9,10,11,12,14,15

; End COM port LogConfig sections

[ComPort.PosDup]
*PNP0500,*PNP0501

[ControlFlags]

[Strings]
IO="Industrial Computer Source"
PCICOM1S="Industrial Computer Source PCI-COM1S"
PCICOM1Sa="Industrial Computer Source PCI-COM-1S"
PCICOM2321S="Industrial Computer Source PCI-COM-232/1"
PCICOM2S="Industrial Computer Source PCI-COM-2S"
PCICOM2322S="Industrial Computer Source PCI-COM-232/2"
PCIICM1S="Industrial Computer Source PCI-ICM-1S"
PCIICM4222="Industrial Computer Source PCI-ICM422/2"
PCIICM4852="Industrial Computer Source PCI-ICM485/2"
PCIICM4224="Industrial Computer Source PCI-ICM422/4"
PCIICM4854="Industrial Computer Source PCI-ICM485/4"
PCICOM4224="Industrial Computer Source PCI-COM422/4"
PCICOM4854="Industrial Computer Source PCI-COM485/4"
PCIDA1216="Industrial Computer Source PCI-DA12-16"
PCIDA128="Industrial Computer Source PCI-DA12-8"
PCIDA1216V="Industrial Computer Source PCI-DA12-16V"
PCIDA128V="Industrial Computer Source PCI-DA12-8V"
PCIDIO24H="Industrial Computer Source PCI-DIO-24H"
PCIDIO24D="Industrial Computer Source PCI-DIO-24D"
PCIDIO24HC="Industrial Computer Source PCI-DIO-24H With Counter(s)"
PCIDIO24DC="Industrial Computer Source PCI-DIO-24D With Counter(s)"
PCIDIO24S="Industrial Computer Source PCI-DIO-24S"
PCIDIO48="Industrial Computer Source PCI-DIO-48"
PCIDIO48S="Industrial Computer Source PCI-DIO-48S"
PCIDIO72="Industrial Computer Source PCI-DIO-72"
PCIDIO96="Industrial Computer Source PCI-DIO-96"
PCIDIO120="Industrial Computer Source PCI-DIO-120"
PCIWDGCSM="Industrial Computer Source PCI-WDG-CSM"
PCIAI1216="Industrial Computer Source PCI-AI12-16"
PCIAI1216A="Industrial Computer Source PCI-AI12-16A"
PCIIIRO8="Industrial Computer Source PCI-IIRO-8"
PCM485="Industrial Computer Source PC CARD (PCMCIA) PCM485"
PAD128="Industrial Computer Source PC CARD (PCMCIA) PAD128"
PIOD24="Industrial Computer Source PC CARD (PCMCIA) PIOD24"
MF\485PORTA="COM Port A"
MF\485PORTB="COM Port B"
MF\485PORTC="COM Port C"
MF\485PORTD="COM Port D"
</code>```

答:
The problem isn't with PCI vs. PCIe. PCI and PCIe look pretty much the same to software. The problem is that the software is looking for one of a specific list of Vendor ID/Device IDs and your new SCSI card has a different ID.

I'm not sure why you say a PCIe to PCI bridge won't solve anything; it would allow you to plug in the old PCI card, and it seems to me that it would probably work. (Can't be sure without trying it, of course.)

If you want to use the new card, the best thing to do would be to get a driver for the new card that provides the software interfaces required by the old software. Depending on the design of the old software, this may or may not be possible. If the software is searching for the hardware directly, without going through a driver, this would require modification of the software to use the new hardware.

Finally, the solution you're asking for would be to run your old software in a virtual machine (VM) using a virtual machine manager (VMM) that provides a virtual device matching the PCI device that your software is looking for. In the unlikely event that the PCI device is a standard one supported by an existing VMM, this could be the easiest solution, Unfortunately, it's more likely that it would require a virtualization expert to write custom software and it would be more work than the previous suggestions.

Body:
I have a 3rd party propriety software that was on some old hardware, this box also had a PCI SCSI card that plugged into a special machine, this software is programmed to look at a PCI port that the card is plugged into. i recently upgraded the box to an HP elitedesk 800 G3 tower. i purchased a custom SCSI to PCIe card to put into it as it no longer has PCI ports. the problem im running into is that the program is looking for PCI and wont detect anything because there is no PCI port. i know this may take some ingeniuity but i would like to get some work around as we already spent alot of money upgrading these systems. i seen PCI to PCIe adapters but that wont solve anything. is there software out that that will give me some sort of virtual PCI port that we can "trick" the software to think is installed and point the PCIe to it? i dont know if this is even possible or not. the config file for this software is below and i have no idea what all that greek is. maybe someone with more knowledge will have an idea?

; ICS.INF
; Copyright (c) 1999

[Version]
Signature="$CHICAGO$"
Class="Data Acquisition"
Provider=%IO%

[DestinationDirs]
DefaultDestDir=11
ComPort.Copy=17

[Manufacturer]
%ACCES%=IOMAN

[IOMAN]
%PCICOM1S%=ComPort,PCI\VEN_494F&DEV_10C8
%PCICOM1Sa%=ComPort,PCI\VEN_494F&DEV_10C9
%PCICOM2321S%=ComPort,PCI\VEN_494F&DEV_1088
%PCICOM2S%=ComPort2,PCI\VEN_494F&DEV_10D0
%PCICOM2322S%=ComPort2,PCI\VEN_494F&DEV_1090
%PCIICM1S%=ComPort,PCI\VEN_494F&DEV_1148
%PCIICM4222%=ComPort2,PCI\VEN_494F&DEV_1150
%PCIICM4852%=ComPort2,PCI\VEN_494F&DEV_1151
%PCIICM4224%=ComPort4,PCI\VEN_494F&DEV_1158
%PCIICM4854%=ComPort4,PCI\VEN_494F&DEV_1159
%PCICOM4224%=ComPort4,PCI\VEN_494F&DEV_1058
%PCICOM4854%=ComPort4,PCI\VEN_494F&DEV_1059
%PCIDA1216%=InstallSect,PCI\VEN_494F&DEV_6CB0
%PCIDA128%=InstallSect,PCI\VEN_494F&DEV_6CA8
%PCIDA1216V%=InstallSect,PCI\VEN_494F&DEV_6CB1
%PCIDA128V%=InstallSect,PCI\VEN_494F&DEV_6CA9
%PCIDIO24H%=InstallSect,PCI\VEN_494F&DEV_0C50
%PCIDIO24D%=InstallSect,PCI\VEN_494F&DEV_0C51
%PCIDIO24HC%=InstallSect,PCI\VEN_494F&DEV_0E51
%PCIDIO24DC%=InstallSect,PCI\VEN_494F&DEV_0E52
%PCIDIO24S%=InstallSect,PCI\VEN_494F&DEV_0E50
%PCIDIO48%=InstallSect,PCI\VEN_494F&DEV_0C60
%PCIDIO48S%=InstallSect,PCI\VEN_494F&DEV_0E60
%PCIDIO72%=InstallSect,PCI\VEN_494F&DEV_0C68
%PCIDIO96%=InstallSect,PCI\VEN_494F&DEV_0C70
%PCIDIO120%=InstallSect,PCI\VEN_494F&DEV_0C78
%PCIWDGCSM%=InstallSect,PCI\VEN_494F&DEV_22C0
%PCIAI1216%=InstallSect,PCI\VEN_494F&DEV_ACA8
%PCIAI1216A%=InstallSect,PCI\VEN_494F&DEV_ACA9
%PCIIIRO8%=InstallSect,PCI\VEN_494F&DEV_0F00
%PCM485%=ComPort,PCMCIA\Industrial_Computer_Source-PCM485-A505
%PCM485%=ComPort,PCMCIA\Industrial_Computer_Source-PCM485-D2B0
%PCM485%=ComPort,PCMCIA\Industrial_Computer_Source-PCM485-B233
%PCM485%=ComPort,PCMCIA\Industrial_Computer_Source-PCM485-D2ED
%PCM485%=ComPort,PCMCIA\Industrial_Computer_Source-PCM485-7609
%PAD128%=InstallSect,PCMCIA\Industrial_Computer_Source-PAD128-4498
%PAD128%=InstallSect,PCMCIA\Industrial_Computer_Source-PAD128-74EE
%PIOD24%=InstallSect,PCMCIA\Industrial_Computer_Source-PIOD24-2705
%PIOD24%=InstallSect,PCMCIA\Industrial_Computer_Source-PIOD24-368B
%PIOD24%=InstallSect,PCMCIA\Industrial_Computer_Source-PIOD24-32B6
%PIOD24%=InstallSect,PCMCIA\Industrial_Computer_Source-PIOD24-8BDC
%MF\485PORTA%=ComPort,MF\485PORTA
%MF\485PORTB%=ComPort,MF\485PORTB
%MF\485PORTC%=ComPort,MF\485PORTC
%MF\485PORTD%=ComPort,MF\485PORTD

[InstallSect]

[ComPort2]
AddReg=StandardMF.Reg

[ComPort4]
AddReg=StandardMF.Reg

[StandardMF.Reg]
HKR,,DevLoader,,*CONFIGMG
HKR,,Enumerator,,*CONFIGMG
HKR,,CMDrivFlags,01,03,00,00,00

[ComPort2.HW]
AddReg=ComPort2.RegHW

[ComPort4.HW]
AddReg=ComPort4.RegHW

[ComPort2.RegHW]
HKR,Child0000,HardwareID,,MF\485PORTA
HKR,Child0000,ResourceMap,1,00,03
HKR,Child0001,HardwareID,,MF\485PORTB
HKR,Child0001,ResourceMap,1,00,04

[ComPort4.RegHW]
HKR,Child0000,HardwareID,,MF\485PORTA
HKR,Child0000,ResourceMap,1,00,03
HKR,Child0001,HardwareID,,MF\485PORTB
HKR,Child0001,ResourceMap,1,00,04
HKR,Child0002,HardwareID,,MF\485PORTC
HKR,Child0002,ResourceMap,1,00,05
HKR,Child0003,HardwareID,,MF\485PORTD
HKR,Child0003,ResourceMap,1,00,06

[Ports.AddReg]
HKR,,NoSetupUI,,1

[ComPort]
CopyFiles=ComPort.Copy,VXD.Copy
AddReg=ComPort.AddReg
LogConfig=c14,c1a,c23,c2a,c34,c3a,c43,c4a,caa

[ComPort.Copy]
ics.inf

[VXD.Copy]

[ComPort.AddReg]
HKR,,DevLoader,,*vcomm
HKR,,Enumerator,,serenum.vxd
HKR,,PortDriver,,serial.vxd
HKR,,Contention,,*vcd
HKR,,ConfigDialog,,serialui.dll
HKR,,DCB,3,1C,00,00,00, 80,25,00,00, 11,33,00,00, 00,00, 0a,00, 0a,00, 08,    00, 00, 11, 13, 00, 00, 00
HKR,,PortSubClass,1,01
HKR,,EnumPropPages,,"serialui.dll,EnumPropPages"

[*pnp0500.det]
AddReg=Ports.AddReg,DevMap.AddReg

; The following sections are COM port resource configs.
; Section name format means:
; Char 1 = c (COM port)
; Char 2 = I/O config: 1 (3f8), 2 (2f8), 3 (3e8), 4 (2e8), a (any)
; Char 3 = IRQ config: #, a (any)

[c14]                   ; COM1,IRQ4
ConfigPriority=HARDRECONFIG
IOConfig=3f8-3ff(3ff::)
IRQConfig=S:4

[c1a]                   ; COM1, any IRQ
ConfigPriority=HARDRECONFIG
IOConfig=3f8-3ff(3ff::)
IRQConfig=S:3,4,5,7,9,10,11,12,14,15

[c23]                   ; COM2, IRQ3
ConfigPriority=HARDRECONFIG
IOConfig=2f8-2ff(3ff::)
IRQConfig=S:3

[c2a]                   ; COM2, any IRQ
ConfigPriority=HARDRECONFIG
IOConfig=2f8-2ff(3ff::)
IRQConfig=S:3,4,5,7,9,10,11,12,14,15

[c34]                   ; COM3, IRQ4
ConfigPriority=HARDRECONFIG
IOConfig=3e8-3ef(3ff::)
IRQConfig=S:4

[c3a]                   ; COM3, any IRQ
ConfigPriority=HARDRECONFIG
IOConfig=3e8-3ef(3ff::)
IRQConfig=S:3,4,5,7,9,10,11,12,14,15

[c43]                   ; COM4, IRQ3
ConfigPriority=HARDRECONFIG
IOConfig=2e8-2ef(3ff::)
IRQConfig=S:3,5

[c4a]                   ; COM4, any IRQ
ConfigPriority=HARDRECONFIG
IOConfig=2e8-2ef(3ff::)
IRQConfig=S:3,4,5,7,9,10,11,12,14,15

[caa]                   ; Any base, any IRQ
ConfigPriority=HARDRECONFIG
IOConfig=8@100-ffff%fff8(3ff::)
IRQConfig=S:3,4,5,7,9,10,11,12,14,15

; End COM port LogConfig sections

[ComPort.PosDup]
*PNP0500,*PNP0501

[ControlFlags]

[Strings]
IO="Industrial Computer Source"
PCICOM1S="Industrial Computer Source PCI-COM1S"
PCICOM1Sa="Industrial Computer Source PCI-COM-1S"
PCICOM2321S="Industrial Computer Source PCI-COM-232/1"
PCICOM2S="Industrial Computer Source PCI-COM-2S"
PCICOM2322S="Industrial Computer Source PCI-COM-232/2"
PCIICM1S="Industrial Computer Source PCI-ICM-1S"
PCIICM4222="Industrial Computer Source PCI-ICM422/2"
PCIICM4852="Industrial Computer Source PCI-ICM485/2"
PCIICM4224="Industrial Computer Source PCI-ICM422/4"
PCIICM4854="Industrial Computer Source PCI-ICM485/4"
PCICOM4224="Industrial Computer Source PCI-COM422/4"
PCICOM4854="Industrial Computer Source PCI-COM485/4"
PCIDA1216="Industrial Computer Source PCI-DA12-16"
PCIDA128="Industrial Computer Source PCI-DA12-8"
PCIDA1216V="Industrial Computer Source PCI-DA12-16V"
PCIDA128V="Industrial Computer Source PCI-DA12-8V"
PCIDIO24H="Industrial Computer Source PCI-DIO-24H"
PCIDIO24D="Industrial Computer Source PCI-DIO-24D"
PCIDIO24HC="Industrial Computer Source PCI-DIO-24H With Counter(s)"
PCIDIO24DC="Industrial Computer Source PCI-DIO-24D With Counter(s)"
PCIDIO24S="Industrial Computer Source PCI-DIO-24S"
PCIDIO48="Industrial Computer Source PCI-DIO-48"
PCIDIO48S="Industrial Computer Source PCI-DIO-48S"
PCIDIO72="Industrial Computer Source PCI-DIO-72"
PCIDIO96="Industrial Computer Source PCI-DIO-96"
PCIDIO120="Industrial Computer Source PCI-DIO-120"
PCIWDGCSM="Industrial Computer Source PCI-WDG-CSM"
PCIAI1216="Industrial Computer Source PCI-AI12-16"
PCIAI1216A="Industrial Computer Source PCI-AI12-16A"
PCIIIRO8="Industrial Computer Source PCI-IIRO-8"
PCM485="Industrial Computer Source PC CARD (PCMCIA) PCM485"
PAD128="Industrial Computer Source PC CARD (PCMCIA) PAD128"
PIOD24="Industrial Computer Source PC CARD (PCMCIA) PIOD24"
MF\485PORTA="COM Port A"
MF\485PORTB="COM Port B"
MF\485PORTC="COM Port C"
MF\485PORTD="COM Port D"


来源: stackexchange

问:
Javascript play button for animation
I have a Javascript animation using Raphael which is in an external file linked to HTML. I would like to have the user click on the animation to start it rather than the animation starting as soon as the page is loaded.</p>

```<code>window.addEventListener("load",function(){
    var paper = new Raphael(document.getElementById("animation"), 800, 600);
    var img = paper.image("backimg.jpg",0,0,950,600);
    img.attr({"clip-rect":"0,0,800,600"});
    img.addEventListener("click",function() {
      var squ = paper.rect(-100,50,100,100);
      squ.attr("fill", "#ffffff");

      squ.animate({transform: "T450,0"}, 2000, "ease-out", explode);
      var cir2 = paper.rect(400,100,1,1);

      function explode(){
        cir2.attr("fill","#f00");
        cir2.animate({ transform:'s100' }, 2000);
      }
    });
});
</code>```

答:
if you want doing it using a button it should look like this:

```<code><button onclick="myAnimation()">Play Animation</button>
</code>```

where myAnimation is the name of the function that runs the animation.

ContentLicense: CC BY-SA 3.0

Title: Javascript play button for animation

Body:
I have a Javascript animation using Raphael which is in an external file linked to HTML. I would like to have the user click on the animation to start it rather than the animation starting as soon as the page is loaded.

window.addEventListener("load",function(){
    var paper = new Raphael(document.getElementById("animation"), 800, 600);
    var img = paper.image("backimg.jpg",0,0,950,600);
    img.attr({"clip-rect":"0,0,800,600"});
    img.addEventListener("click",function() {
      var squ = paper.rect(-100,50,100,100);
      squ.attr("fill", "#ffffff");

      squ.animate({transform: "T450,0"}, 2000, "ease-out", explode);
      var cir2 = paper.rect(400,100,1,1);

      function explode(){
        cir2.attr("fill","#f00");
        cir2.animate({ transform:'s100' }, 2000);
      }
    });
});

Body:
if you want doing it using a button it should look like this:

<button onclick="myAnimation()">Play Animation</button>

where myAnimation is the name of the function that runs the animation.


问:
In Elastic Beanstalk, how to set existing security group to load balancer with .ebextensions?
I'm trying to set existing Security Group for the ELB in my Elastic Beanstalk application with .ebextensions.

For some reason, .configs like

```<code>option_settings:
  aws:elb:loadbalancer:
    SecurityGroups: sg-abcd1234
</code>```

Don't seem to do anything. Also, since that existing SG is strictly defined, I don't want to use ManagedSecurityGroup since that would modify the existing SG.

Any ideas how to achieve this? Help would be highly appreciated.

答:
The question is the namespace of Application Load Balancer aws:elbv2 (different from Elastic Load Balancer classic aws:elb)

http://docs.aws.amazon.com/pt_br/elasticbeanstalk/latest/dg/environments-cfg-applicationloadbalancer.html

this works in ALB

```<code>option_settings:
  - namespace:  aws:elbv2:loadbalancer
    option_name:  ManagedSecurityGroup
    value:  sg-XXXXXXXX
  - namespace:  aws:elbv2:loadbalancer
    option_name:  SecurityGroups
    value:  sg-XXXXXXXX
</code>```

Body:
I'm trying to set existing Security Group for the ELB in my Elastic Beanstalk application with .ebextensions.

For some reason, .configs like

option_settings:
  aws:elb:loadbalancer:
    SecurityGroups: sg-abcd1234

Don't seem to do anything. Also, since that existing SG is strictly defined, I don't want to use ManagedSecurityGroup since that would modify the existing SG.

Any ideas how to achieve this? Help would be highly appreciated.

Body:
The question is the namespace of Application Load Balancer aws:elbv2 (different from Elastic Load Balancer classic aws:elb)

http://docs.aws.amazon.com/pt_br/elasticbeanstalk/latest/dg/environments-cfg-applicationloadbalancer.html

this works in ALB

option_settings:
  - namespace:  aws:elbv2:loadbalancer
    option_name:  ManagedSecurityGroup
    value:  sg-XXXXXXXX
  - namespace:  aws:elbv2:loadbalancer
    option_name:  SecurityGroups
    value:  sg-XXXXXXXX


问:
How add shared-library to my library project in QT
May i load external library in my library project? If yes. How i can do this.
With Qlibrary? or typically include in pro file LIBS += -L /lib -lmylib and add *.h file to project?

Sorry for my English))))

答:
Yes you can.
If you want to use shared library just add in you application *.pro file

```<code>LIBS+=-Llibrary_location_path -llibraryName
INCLUDEPATH += library_headers_location
</code>```

Check original documentation http://doc.qt.io/qt-5/third-party-libraries.html

P.S.  I suppose you understand that .h files contains declaration of methods that you are going to use in your appplication, while library contains implementation of this methods

Body:
Yes you can.
If you want to use shared library just add in you application *.pro file

LIBS+=-Llibrary_location_path -llibraryName
INCLUDEPATH += library_headers_location

Check original documentation http://doc.qt.io/qt-5/third-party-libraries.html

P.S.  I suppose you understand that .h files contains declaration of methods that you are going to use in your appplication, while library contains implementation of this methods


问:
Using procdump to dump subprocesses
I'm writing a wrapper around Sysinternal's ProcDump and I want it to dump spawned subprocesses of the initial process as well. Is there any easy way to do it or do I have to do some kind of API hooking on CreateProcess?</p>

答:
In this answer I explain why there is no easy way. Another answer of that question gives you code for the closest possible solution.

You'll need to hook CreateProcess, CreateProcessAsUser, CreateJob, ShellExecute, ShellExecuteEx and maybe others.

Title: Using procdump to dump subprocesses


问:
Why is using a loop to iterate from start of array to end faster than iterating both start to end and end to start?
Given an array having .length 100 containing elements having values 0 to 99 at the respective indexes, where the requirement is to find element of of array equal to n : 51.

Why is using a loop to iterate from start of array to end faster than iterating both start to end and end to start?

const arr = Array.from({length: 100}, (_, i) => i);
const n = 51;
const len = arr.length;

console.time("iterate from start");
for (let i = 0; i < len; i++) {
  if (arr[i] === n) break;
}
console.timeEnd("iterate from start");```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const arr = Array.from({length: 100}, (_, i) => i);
const n = 51;
const len = arr.length;

console.time("iterate from start and end");
for (let i = 0, k = len - 1; i < len && k >= 0; i++, k--) {
  if (arr[i] === n || arr[k] === n) break;
}
console.timeEnd("iterate from start and end");</code>```

jsperf https://jsperf.com/iterate-from-start-iterate-from-start-and-end/1

答:
@Bergi is correct.  More operations is more time.  Why?  More CPU clock cycles.
Time is really a reference to how many clock cycles it takes to execute the code.
In order to get to the nitty-gritty of that you need to look at the machine level code (like assembly level code) to find the true evidence.  Each CPU (core?) clock cycle can execute one instruction, so how many instructions are you executing?

I haven't counted the clock cycles in a long time since programming Motorola CPUs for embedded applications.  If your code is taking longer then it is in fact generating a larger instruction set of machine code, even if the loop is shorter or runs an equal amount of times.

Never forget that your code is actually getting compiled into a set of commands that the CPU is going to execute (memory pointers, instruction-code level pointers, interrupts, etc.).  That is how computers work and its easier to understand at the micro controller level like an ARM or Motorola processor but the same is true for the sophisticated machines that we are running on today.

Your code simply does not run the way you write it (sounds crazy right?).  It is run as it is compiled to run as machine level instructions (writing a compiler is no fun).  Mathematical expression and logic can be compiled in to quite a heap of assembly, machine level code and that is up to how the compiler chooses to interpret it (it is bit shifting, etc, remember binary mathematics anyone?)

Reference:
https://software.intel.com/en-us/articles/introduction-to-x64-assembly

Your question is hard to answer but as @Bergi stated the more operations the longer, but why?  The more clock cycles it takes to execute your code.  Dual core, quad core, threading, assembly (machine language) it is complex.  But no code gets executed as you have written it.  C++, C, Pascal, JavaScript, Java, unless you are writing in assembly (even that compiles down to machine code) but it is closer to actual execution code.

A masters in CS and you will get to counting clock cycles and sort times. You will likely make you own language framed on machine instruction sets.

Most people say who cares?  Memory is cheap today and CPUs are screaming fast and getting faster.

But there are some critical applications where 10 ms matters, where an immediate interrupt is needed, etc.

Commerce, NASA, a Nuclear power plant, Defense Contractors, some robotics, you get the idea . . .

I vote let it ride and keep moving.

Cheers,
Wookie

Body:
Given an array having .length 100 containing elements having values 0 to 99 at the respective indexes, where the requirement is to find element of of array equal to n : 51.

Why is using a loop to iterate from start of array to end faster than iterating both start to end and end to start?

const arr = Array.from({length: 100}, (_, i) => i);
const n = 51;
const len = arr.length;

console.time("iterate from start");
for (let i = 0; i < len; i++) {
  if (arr[i] === n) break;
}
console.timeEnd("iterate from start");

const arr = Array.from({length: 100}, (_, i) => i);
const n = 51;
const len = arr.length;

console.time("iterate from start and end");
for (let i = 0, k = len - 1; i < len && k >= 0; i++, k--) {
  if (arr[i] === n || arr[k] === n) break;
}
console.timeEnd("iterate from start and end");

jsperf https://jsperf.com/iterate-from-start-iterate-from-start-and-end/1


问:
Upload files to same random folder in django
I am uploading two files using django rest framework, i want to upload these two files into the same folder and create said folder with a random name.

So far I can upload both files to different random folders using the following:

```<code>from uuid import uuid4

def path_and_rename(path, dataset):
    def wrapper(instance, filename):
        main_folder = '{}/{}/'.format(path, uuid4().hex)
        name = '{}.csv'.format(dataset)

        return os.path.join(main_folder, name)
    return wrapper

class Dataset(Model):
    trainFile = FileField(null=False, blank=False,
                      validators=[FileExtensionValidator(['csv'])],
                      upload_to=path_and_rename('files/', 'train'))
    testFile = FileField(null=False, blank=False,
                     validators=[FileExtensionValidator(['csv'])],
                     upload_to=path_and_rename('files/', 'test'))

class DatasetSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Dataset
        fields = (
            'id',
            'trainFile',
            'testFile',
        )
        read_only_fields = ('created',)
</code>```

How could I get both files to be uploaded to the same random folder?

答:
You are calling path_to_rename(), and in turn uuid4() on two separate occasions so you're going to get two random UUIDs. As a sidenote, for better code readability, your "wrapper" should be the outer function.

Try:

```<code>def upload_to_wrapper(upload_dir, dataset):
    def path_and_rename(instance, filename):
        return os.path.join(upload_dir, '{}.csv'.format(dataset))
    return path_and_rename

class Dataset(Model):
    upload_dir = 'files/{}'.format(uuid4().hex)
    trainFile = FileField(null=False, blank=False,
                          validators=[FileExtensionValidator(['csv'])],
                          upload_to=upload_to_wrapper(upload_dir, 'train'))
    testFile = FileField(null=False, blank=False,
                         validators=[FileExtensionValidator(['csv'])],
                         upload_to=upload_to_wrapper(upload_dir, 'test'))
</code>```

Body:
I am uploading two files using django rest framework, i want to upload these two files into the same folder and create said folder with a random name.

So far I can upload both files to different random folders using the following:

from uuid import uuid4

def path_and_rename(path, dataset):
    def wrapper(instance, filename):
        main_folder = '{}/{}/'.format(path, uuid4().hex)
        name = '{}.csv'.format(dataset)

        return os.path.join(main_folder, name)
    return wrapper

class Dataset(Model):
    trainFile = FileField(null=False, blank=False,
                      validators=[FileExtensionValidator(['csv'])],
                      upload_to=path_and_rename('files/', 'train'))
    testFile = FileField(null=False, blank=False,
                     validators=[FileExtensionValidator(['csv'])],
                     upload_to=path_and_rename('files/', 'test'))

class DatasetSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Dataset
        fields = (
            'id',
            'trainFile',
            'testFile',
        )
        read_only_fields = ('created',)

How could I get both files to be uploaded to the same random folder?

Body:
You are calling path_to_rename(), and in turn uuid4() on two separate occasions so you're going to get two random UUIDs. As a sidenote, for better code readability, your "wrapper" should be the outer function.

Try:

def upload_to_wrapper(upload_dir, dataset):
    def path_and_rename(instance, filename):
        return os.path.join(upload_dir, '{}.csv'.format(dataset))
    return path_and_rename

class Dataset(Model):
    upload_dir = 'files/{}'.format(uuid4().hex)
    trainFile = FileField(null=False, blank=False,
                          validators=[FileExtensionValidator(['csv'])],
                          upload_to=upload_to_wrapper(upload_dir, 'train'))
    testFile = FileField(null=False, blank=False,
                         validators=[FileExtensionValidator(['csv'])],
                         upload_to=upload_to_wrapper(upload_dir, 'test'))


问:
compare arrays with repetitive elements and add the elements not present to the respective arrays including the repetitive elements
I am working on a program where we compare two strings and add the characters that are not present in one string to the other string and vice versa.
For example: String 1- aabccd
             String 2- acccdd
The output should be- Characters to be added to String 1- cd
                      Characters to be added to String 2- ab
I am able to achieve it when the characters are not repeating,
For example: String 1- mango
             String 2- anglo
The output is- Characters to be added to String 1- l
               Characters to be added to String 2- m
but could not get it when the characters are repeating.

Here is the code that I have written-

```<code>import java.util.Scanner;

public class Test {

public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);

        String S1, S2;

        System.out.println("Enter String 1: ");
        S1 = user_input.next();

        System.out.println("Enter String 2: ");
        S2 = user_input.next();

        user_input.close();

        char[] S1Array = S1.toLowerCase().toCharArray();
        char[] S2Array = S2.toLowerCase().toCharArray();
        charAddition(S1Array, S2Array);
        charAdditionReverse(S2Array,S1Array);
}
private static void charAddition(char[] n, char[] S1Array) {
for (char n1 : n) {
            if (!isPresent(n1, S1Array)) {
                System.out.println("character to be added to S2Array
is: " + n1);
            }
        }
}
private static void charAdditionReverse(char[] n, char[] S1Array) {
for (char n1 : n) {
            if (!isPresent(n1, S1Array)) {
                System.out.println("character to be added to S1Array
is: " + n1);

            }
        }
}

    private static boolean isPresent(char n, char[] S1Array) {
        for (char i : S1Array) {
            if (n == i) {
                return true;
            }
        }
        return false;
    }
}
</code>```

答:
A whole different approach:</p>

```<code>void disjoint(String s1, String s2) {
    // Convert two strings to character lists
    List<Character> chars1 = s1.chars()
        .mapToObj(t -> (char) t)
        .collect(Collectors.toList());
    List<Character> chars2 = s2.chars()
        .mapToObj(t -> (char) t)
        .collect(Collectors.toList());

    // Make a list of elements we are going to remove from chars1
    List<Character> removedElements = new ArrayList<>();
    chars1.forEach(t -> {
        // Try to remove the current character from chars2, and if it has
        // successfully been removed, add it to our removedElements list
        if (chars2.remove(t)) {
            removedElements.add(t);
        }
    });
    // At last remove each removed element from chars2 also from chars1
    removedElements.forEach(chars1::remove);

    System.out.println(chars1);
    System.out.println(chars2);

}
</code>```

Body:
I am working on a program where we compare two strings and add the characters that are not present in one string to the other string and vice versa.
For example: String 1- aabccd
             String 2- acccdd
The output should be- Characters to be added to String 1- cd
                      Characters to be added to String 2- ab
I am able to achieve it when the characters are not repeating,
For example: String 1- mango
             String 2- anglo
The output is- Characters to be added to String 1- l
               Characters to be added to String 2- m
but could not get it when the characters are repeating.

Here is the code that I have written-

import java.util.Scanner;

public class Test {

public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);

        String S1, S2;

        System.out.println("Enter String 1: ");
        S1 = user_input.next();

        System.out.println("Enter String 2: ");
        S2 = user_input.next();

        user_input.close();

        char[] S1Array = S1.toLowerCase().toCharArray();
        char[] S2Array = S2.toLowerCase().toCharArray();
        charAddition(S1Array, S2Array);
        charAdditionReverse(S2Array,S1Array);
}
private static void charAddition(char[] n, char[] S1Array) {
for (char n1 : n) {
            if (!isPresent(n1, S1Array)) {
                System.out.println("character to be added to S2Array
is: " + n1);
            }
        }
}
private static void charAdditionReverse(char[] n, char[] S1Array) {
for (char n1 : n) {
            if (!isPresent(n1, S1Array)) {
                System.out.println("character to be added to S1Array
is: " + n1);

            }
        }
}

    private static boolean isPresent(char n, char[] S1Array) {
        for (char i : S1Array) {
            if (n == i) {
                return true;
            }
        }
        return false;
    }
}

Body:
A whole different approach:

void disjoint(String s1, String s2) {
    // Convert two strings to character lists
    List<Character> chars1 = s1.chars()
        .mapToObj(t -> (char) t)
        .collect(Collectors.toList());
    List<Character> chars2 = s2.chars()
        .mapToObj(t -> (char) t)
        .collect(Collectors.toList());

    // Make a list of elements we are going to remove from chars1
    List<Character> removedElements = new ArrayList<>();
    chars1.forEach(t -> {
        // Try to remove the current character from chars2, and if it has
        // successfully been removed, add it to our removedElements list
        if (chars2.remove(t)) {
            removedElements.add(t);
        }
    });
    // At last remove each removed element from chars2 also from chars1
    removedElements.forEach(chars1::remove);

    System.out.println(chars1);
    System.out.println(chars2);

}


问:
How can I generate database tables from C# classes?
Does anyone know a way to auto-generate database tables for a given class?  I'm not looking for an entire persistence layer - I already have a data access solution I'm using, but I suddenly have to store a lot of information from a large number of classes and I really don't want to have to create all these tables by hand.  For example, given the following class:

```<code>class Foo
{
    private string property1;
    public string Property1
    {
        get { return property1; }
        set { property1 = value; }
    }

    private int property2;
    public int Property2
    {
        get { return property2; }
        set { property2 = value; }
    }
}
</code>```

I'd expect the following SQL:

```<code>CREATE TABLE Foo
(
    Property1 VARCHAR(500),
    Property2 INT
)
</code>```

I'm also wondering how you could handle complex types.  For example, in the previously cited class, if we changed that to be :

```<code>class Foo
{
    private string property1;
    public string Property1
    {
        get { return property1; }
        set { property1 = value; }
    }

    private System.Management.ManagementObject property2;
    public System.Management.ManagementObject Property2
    {
        get { return property2; }
        set { property2 = value; }
    }
}
</code>```

How could I handle this?

I've looked at trying to auto-generate the database scripts by myself using reflection to enumerate through each class' properties, but it's clunky and the complex data types have me stumped.

答: Also... maybe you can use some tool such as Visio (not sure if Visio does this, but I think it does) to reverse engineer your classes into UML and then use the UML to generate the DB Schema... or maybe use a tool such as this http://www.tangiblearchitect.net/visual-studio/</p>

OwnerDisplayName: VanOrman

Body:
Does anyone know a way to auto-generate database tables for a given class?  I'm not looking for an entire persistence layer - I already have a data access solution I'm using, but I suddenly have to store a lot of information from a large number of classes and I really don't want to have to create all these tables by hand.  For example, given the following class:

class Foo
{
    private string property1;
    public string Property1
    {
        get { return property1; }
        set { property1 = value; }
    }

    private int property2;
    public int Property2
    {
        get { return property2; }
        set { property2 = value; }
    }
}

I'd expect the following SQL:

CREATE TABLE Foo
(
    Property1 VARCHAR(500),
    Property2 INT
)

I'm also wondering how you could handle complex types.  For example, in the previously cited class, if we changed that to be :

class Foo
{
    private string property1;
    public string Property1
    {
        get { return property1; }
        set { property1 = value; }
    }

    private System.Management.ManagementObject property2;
    public System.Management.ManagementObject Property2
    {
        get { return property2; }
        set { property2 = value; }
    }
}

How could I handle this?

I've looked at trying to auto-generate the database scripts by myself using reflection to enumerate through each class' properties, but it's clunky and the complex data types have me stumped.

OwnerDisplayName: Vaibhav

ContentLicense: CC BY-SA 2.5


问:
How to pass an array size as a template with template type?
My compiler behaves oddly when I try to pass a fixed-size array to a template function. The code looks as follows:

```<code>#include <algorithm>
#include <iostream>
#include <iterator>

template <typename TSize, TSize N>
void f(TSize (& array)[N]) {
    std::copy(array, array + N, std::ostream_iterator<TSize>(std::cout, " "));
    std::cout << std::endl;
}

int main() {
    int x[] = { 1, 2, 3, 4, 5 };
    unsigned int y[] = { 1, 2, 3, 4, 5 };
    f(x);
    f(y); //line 15 (see the error message)
}
</code>```

It produces the following compile error in GCC 4.1.2:

```<code>test.cpp|15| error: size of array has non-integral type ‘TSize’
test.cpp|15| error: invalid initialization of reference of type
  ‘unsigned int (&)[1]’ from expression of type ‘unsigned int [5]’
test.cpp|6| error: in passing argument 1 of ‘void f(TSize (&)[N])
  [with TSize = unsigned int, TSize N = ((TSize)5)]’
</code>```

Note that the first call compiles and succeeds. This seems to imply that while int is integral, unsigned int isn't.

However, if I change the declaration of my above function template to

```<code>template <typename TSize, unsigned int N>
void f(TSize (& array)[N])
</code>```

the problem just goes away! Notice that the only change here is from TSize N to unsigned int N.

Section [dcl.type.simple] in the final draft ISO/IEC FDIS 14882:1998 seems to imply that an "integral type" is either signed or unsigned:

The signed specifier forces char objects and bit-fields to be signed; it is redundant with other integral types.

Regarding fixed-size array declarations, the draft says [dcl.array]:

If the constant-expression (expr.const) is present, it shall be an integral constant expression and its value shall be greater than zero.

So why does my code work with an explicit unsigned size type, with an inferred signed size type but not with an inferred unsigned size type?

EDIT Serge wants to know where I'd need the first version. First, this code example is obviously simplified. My real code is a bit more elaborate. The array is actually an array of indices/offsets in another array. So, logically, the type of the array should be the same as its size type for maximum correctness. Otherwise, I might get a type mismatch (e.g. between unsigned int and std::size_t). Admittedly, this shouldn't be a problem in practice since the compiler implicitly converts to the larger of the two types.

EDIT 2 I stand corrected (thanks, litb): size and offset are of course logically different types, and offsets into C arrays in particular are of type std::ptrdiff_t.

答:
Hmm, the Standard says in 14.8.2.4 / 15:

If, in the declaration of a function template with a non-type template-parameter, the non-type template-parameter is used in an expression in the function parameter-list and, if the corresponding template-argument is deduced, the template-argument type shall match the type of the template-parameter exactly, except that a template-argument deduced from an array bound may be of any integral type.

Providing this example:

```<code>template<int i> class A { /* ... */ };
template<short s> void f(A<s>);
void k1() {
    A<1> a;
    f(a);    // error: deduction fails for conversion from int to short
    f<1>(a); // OK
}
</code>```

That suggests that the compilers that fail to compile your code (apparently GCC and Digital Mars) do it wrong. I tested the code with Comeau, and it compiles your code fine. I don't think there is a different to whether the type of the non-type template parameter depends on the type of the type-parameter or not. 14.8.2.4/2 says the template arguments should be deduced independent from each other, and then combined into the type of the function-parameter. Combined with /15, which allows the type of the dimension to be of different integral type, i think your code is all fine. As always, i take the c++-is-complicated-so-i-may-be-wrong card :)

Update: I've looked into the passage in GCC where it spits out that error message:

```<code>  ...
  type = TREE_TYPE (size);
  /* The array bound must be an integer type.  */
  if (!dependent_type_p (type) && !INTEGRAL_TYPE_P (type))
    {
      if (name)
    error ("size of array %qD has non-integral type %qT", name, type);
      else
    error ("size of array has non-integral type %qT", type);
      size = integer_one_node;
      type = TREE_TYPE (size);
    }
  ...
</code>```

It seems to have missed to mark the type of the size as dependent in an earlier code block. As that type is a template parameter, it is a dependent type (see 14.6.2.1).

Update: GCC developers fixed it: Bug #38950

OwnerDisplayName: Konrad Rudolph

Body:
My compiler behaves oddly when I try to pass a fixed-size array to a template function. The code looks as follows:

#include <algorithm>
#include <iostream>
#include <iterator>

template <typename TSize, TSize N>
void f(TSize (& array)[N]) {
    std::copy(array, array + N, std::ostream_iterator<TSize>(std::cout, " "));
    std::cout << std::endl;
}

int main() {
    int x[] = { 1, 2, 3, 4, 5 };
    unsigned int y[] = { 1, 2, 3, 4, 5 };
    f(x);
    f(y); //line 15 (see the error message)
}

It produces the following compile error in GCC 4.1.2:

test.cpp|15| error: size of array has non-integral type ‘TSize’
test.cpp|15| error: invalid initialization of reference of type
  ‘unsigned int (&)[1]’ from expression of type ‘unsigned int [5]’
test.cpp|6| error: in passing argument 1 of ‘void f(TSize (&)[N])
  [with TSize = unsigned int, TSize N = ((TSize)5)]’

Note that the first call compiles and succeeds. This seems to imply that while int is integral, unsigned int isn't.

However, if I change the declaration of my above function template to

template <typename TSize, unsigned int N>
void f(TSize (& array)[N])

the problem just goes away! Notice that the only change here is from TSize N to unsigned int N.

Section [dcl.type.simple] in the final draft ISO/IEC FDIS 14882:1998 seems to imply that an "integral type" is either signed or unsigned:

The signed specifier forces char objects and bit-fields to be signed; it is redundant with other integral types.

Regarding fixed-size array declarations, the draft says [dcl.array]:

If the constant-expression (expr.const) is present, it shall be an integral constant expression and its value shall be greater than zero.

So why does my code work with an explicit unsigned size type, with an inferred signed size type but not with an inferred unsigned size type?

EDIT Serge wants to know where I'd need the first version. First, this code example is obviously simplified. My real code is a bit more elaborate. The array is actually an array of indices/offsets in another array. So, logically, the type of the array should be the same as its size type for maximum correctness. Otherwise, I might get a type mismatch (e.g. between unsigned int and std::size_t). Admittedly, this shouldn't be a problem in practice since the compiler implicitly converts to the larger of the two types.

EDIT 2 I stand corrected (thanks, litb): size and offset are of course logically different types, and offsets into C arrays in particular are of type std::ptrdiff_t.

LastEditorDisplayName: Konrad Rudolph

Body:
Hmm, the Standard says in 14.8.2.4 / 15:

If, in the declaration of a function template with a non-type template-parameter, the non-type template-parameter is used in an expression in the function parameter-list and, if the corresponding template-argument is deduced, the template-argument type shall match the type of the template-parameter exactly, except that a template-argument deduced from an array bound may be of any integral type.

Providing this example:

template<int i> class A { /* ... */ };
template<short s> void f(A<s>);
void k1() {
    A<1> a;
    f(a);    // error: deduction fails for conversion from int to short
    f<1>(a); // OK
}

That suggests that the compilers that fail to compile your code (apparently GCC and Digital Mars) do it wrong. I tested the code with Comeau, and it compiles your code fine. I don't think there is a different to whether the type of the non-type template parameter depends on the type of the type-parameter or not. 14.8.2.4/2 says the template arguments should be deduced independent from each other, and then combined into the type of the function-parameter. Combined with /15, which allows the type of the dimension to be of different integral type, i think your code is all fine. As always, i take the c++-is-complicated-so-i-may-be-wrong card :)

Update: I've looked into the passage in GCC where it spits out that error message:

  ...
  type = TREE_TYPE (size);
  /* The array bound must be an integer type.  */
  if (!dependent_type_p (type) && !INTEGRAL_TYPE_P (type))
    {
      if (name)
    error ("size of array %qD has non-integral type %qT", name, type);
      else
    error ("size of array has non-integral type %qT", type);
      size = integer_one_node;
      type = TREE_TYPE (size);
    }
  ...

It seems to have missed to mark the type of the size as dependent in an earlier code block. As that type is a template parameter, it is a dependent type (see 14.6.2.1).

Update: GCC developers fixed it: Bug #38950

OwnerDisplayName: litb

LastEditorDisplayName: litb


问:
Lua script to C++ code
I am writing C functions for Lua.
I have many calls like lua_gettable, lua_touserdata, etc

My C function may receive complex structures like table with tables as fields.

It is hard for me to program stacked machine.

Is there way to write Lua script that would be converted to C code.

Or some other tools that may help me to code such C functions for lua scripts.

Thanks.

PS

Here is example:-

```<code>local data = {}
data.x = {}
data.x.y = 1
myCfunc(data)
</code>```

```<code>int myCfunc(lua_State * L){
 lua_pushstring(L, "x");
 lua_gettable(L, 2);
 lua_pushstring(L, "y");
 lua_gettable(L, -2);
 double y = lua_tonumber(L, -1);
 lua_pop(L, 2);
}
</code>```

instead of

```<code>function myCfunc(data)
 y = data.x.y
end
</code>```

My real code is much more complex and I am looking for some
automated code generation that will help me.

答: From C#, something I've done is written code to convert LUA datastructures in JSON format.  Then I can load the data via any JSON library, with all their bells and whistles.  Its kind of a round-about solution but you only have to write the JSON Encoding code once.</p>

Title: Lua script to C++ code

Body:
I am writing C functions for Lua.
I have many calls like lua_gettable, lua_touserdata, etc

My C function may receive complex structures like table with tables as fields.

It is hard for me to program stacked machine.

Is there way to write Lua script that would be converted to C code.

Or some other tools that may help me to code such C functions for lua scripts.

Thanks.

PS

Here is example:-

local data = {}
data.x = {}
data.x.y = 1
myCfunc(data)

int myCfunc(lua_State * L){
 lua_pushstring(L, "x");
 lua_gettable(L, 2);
 lua_pushstring(L, "y");
 lua_gettable(L, -2);
 double y = lua_tonumber(L, -1);
 lua_pop(L, 2);
}

instead of

function myCfunc(data)
 y = data.x.y
end

My real code is much more complex and I am looking for some
automated code generation that will help me.


问:
XCode - C++ Static & Dynamic library linking
I compiled a program by statically linking external libraries on XCode. However, I am having errors on how to dynamically link those libraries.

For Static Linking, I did
1. Went to Build Phases, Link Binary with Libraries, Chose the static .a libraries
2. Went to Build settings and modified the Header Search path to the header files directory
3. Modified the Library search path to the static library directory.

I compiled the program and it works.

Then I am trying to dynamic linking
1. Went to Build Phases, Link Binary with Libraries, removed the static .a libraries and added the .dylib libraries (they are in the same directory)
2. Tried compiling - But I am getting 'Library not loaded:@loader_path/(lib name).dylib.. Reason: image not found'.

Am I missing one of the paths? What am I doing wrong?

答:
Solved it by adding DYLD_LIBRARY_PATH environment variable.

Make sure that dynamic libraries are not in the same directory as the static libraries. This creates a conflict. I created a separate directory and copied all the dynamic libraries I needed to that directory

Went to Build Phases, Link Binary with Libraries, Chose the dynamic libraries I needed

Went to Build settings and modified the Header Search path to the header files directory

Modified the Library search path to the dynamic library directory.

Created an environment variable by (menu) Product -> Scheme -> Edit Scheme. Under 'Environment Variables', created a 'DYLD_LIBRARY_PATH' variable and pointed it to my dynamic library directory.

It works :)


问:
How to work with multiple URL's for same site in multi-site Wagtail environment
I'm setting up a multi-site environment with Wagtail (perhaps a bit ambitious as I'm new to Wagtail, Django and Python, but I would like to migrate some simple sites to Wagtail and wanted to have the correct setup from the beginning).
I have created a list of sites in the Wagtail admin and the home pages for each of the sites.
I would like some of the site to be reachable through multiple URL's (name.com + name.othername.com).
Should I create a new site setting (through "Add Site" in the admin) for each URL, or is there a better/different way to handle this?</p>

答:
I would recommend to use an external web server (eg. Apache) to work with multiple domains. Define a virtual host proxy to point to your wagtail app.

Here is an example:

```<code><VirtualHost *:80>
    ServerName example1.com
    ServerAlias www.example1.com
    ServerAlias example2.com

    # Here we define the proxy to your wagtail app
    ProxyPass / http://localhost:8000/
    # Reverse Proxy for load balancing
    ProxyPassReverse / http://localhost:8000/
    # Preserves the host if you use docker
    ProxyPreserveHost On
</VirtualHost>
</code>```

You will need an external web server anyway to serve static content in non-debug mode.

Body:
I would recommend to use an external web server (eg. Apache) to work with multiple domains. Define a virtual host proxy to point to your wagtail app.

Here is an example:

<VirtualHost *:80>
    ServerName example1.com
    ServerAlias www.example1.com
    ServerAlias example2.com

    # Here we define the proxy to your wagtail app
    ProxyPass / http://localhost:8000/
    # Reverse Proxy for load balancing
    ProxyPassReverse / http://localhost:8000/
    # Preserves the host if you use docker
    ProxyPreserveHost On
</VirtualHost>

You will need an external web server anyway to serve static content in non-debug mode.


问:
What is the nicest way to dynamically implement an interface in C#?
I often find it quite a distraction to have to implement an interface just because I need it once for some method call. I have to create a class somewhere else, implement the interface etc. etc.

Java has a feature called Anonymous Classes that allows one to implement the interface "inline". My question is thus: what is the nicest way you can think of of accomplishing something similar in C# using existing syntax (and I realise that "nicest" is subjective). I'm looking for nice syntax, not necessarily performance.

I implemented the following as POC in C#:

Given

```<code>interface IFoobar
{
   Boolean Foobar(String s);
}

IFoobar foo = Implement.Interface<IFoobar>(new {
   Foobar = new Func<String, Boolean>(s => s == "foobar")
});
</code>```

This uses an anonymous object and some reflection/emit to implement the IFoobar interface (overlooking properties, generic methods and overloading). But, I'm not a fan of the new Func<...> stuff but can't do without.

Looking around I noticed a library called Impromptu Interface, but wasn't impressed by its syntax to support methods.

Is there a "nicer" way?

Edit: I'm not looking for Java vs C# flame wars.

答:
If your biggest complaint is implementing the interface somewhere else, why not create a nested class directly before/after your method? (Compare to a Java static nested class.)

That's more idiomatic C# than creating/using some dynamic framework.

Body:
I often find it quite a distraction to have to implement an interface just because I need it once for some method call. I have to create a class somewhere else, implement the interface etc. etc.

Java has a feature called Anonymous Classes that allows one to implement the interface "inline". My question is thus: what is the nicest way you can think of of accomplishing something similar in C# using existing syntax (and I realise that "nicest" is subjective). I'm looking for nice syntax, not necessarily performance.

I implemented the following as POC in C#:

Given

interface IFoobar
{
   Boolean Foobar(String s);
}

IFoobar foo = Implement.Interface<IFoobar>(new {
   Foobar = new Func<String, Boolean>(s => s == "foobar")
});

This uses an anonymous object and some reflection/emit to implement the IFoobar interface (overlooking properties, generic methods and overloading). But, I'm not a fan of the new Func<...> stuff but can't do without.

Looking around I noticed a library called Impromptu Interface, but wasn't impressed by its syntax to support methods.

Is there a "nicer" way?

Edit: I'm not looking for Java vs C# flame wars.

ContentLicense: CC BY-SA 4.0


问:
LaTeX: Avoid the increase of text row height due to inline math
In the following example code the height of the second row of text increases due to the presence of the inline math formula:

```<code>\documentclass{article}
\linespread{0.9}
\begin{document}
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Ut purus elit, vestibulum ut, placerat ac, adipiscing vitae,
felis. $A_n^{\{x\}}$ Curabitur dictum gravida mauris. Nam arcu
libero, nonummy eget, consectetuer id, vulputate a, magna.
\end{document}
</code>```

How can this be avoided without changing the general linespread, so that the height of the second row is identical to that of the other rows?

答:
You can \smash the inline math formula:

```<code>\documentclass{article}

\begin{document}

% Default layout/spacing
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Ut purus elit, vestibulum ut, placerat ac, adipiscing vitae,
felis. $A_n^{\{x\}}$ Curabitur dictum gravida mauris. Nam arcu
libero, nonummy eget, consectetuer id, vulputate a, magna.

% Smashed inline math
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Ut purus elit, vestibulum ut, placerat ac, adipiscing vitae,
felis. \smash{$A_n^{\{x\}}$} Curabitur dictum gravida mauris. Nam arcu
libero, nonummy eget, consectetuer id, vulputate a, magna.

\end{document}
</code>```

However, it's obvious that tall [deep] inline expressions may butt into descenders [ascenders] of the line above [below].

Body:
In the following example code the height of the second row of text increases due to the presence of the inline math formula:

\documentclass{article}
\linespread{0.9}
\begin{document}
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Ut purus elit, vestibulum ut, placerat ac, adipiscing vitae,
felis. $A_n^{\{x\}}$ Curabitur dictum gravida mauris. Nam arcu
libero, nonummy eget, consectetuer id, vulputate a, magna.
\end{document}

How can this be avoided without changing the general linespread, so that the height of the second row is identical to that of the other rows?

Body:
You can \smash the inline math formula:

\documentclass{article}

\begin{document}

% Default layout/spacing
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Ut purus elit, vestibulum ut, placerat ac, adipiscing vitae,
felis. $A_n^{\{x\}}$ Curabitur dictum gravida mauris. Nam arcu
libero, nonummy eget, consectetuer id, vulputate a, magna.

% Smashed inline math
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Ut purus elit, vestibulum ut, placerat ac, adipiscing vitae,
felis. \smash{$A_n^{\{x\}}$} Curabitur dictum gravida mauris. Nam arcu
libero, nonummy eget, consectetuer id, vulputate a, magna.

\end{document}

However, it's obvious that tall [deep] inline expressions may butt into descenders [ascenders] of the line above [below].


问:
Dereferencing pointer C++
I just managed to write a global CBT hook in c++, usable with c#.
It may sound stupid but my knowledge of pointers and dereferencing of those is very bad due to my work with c#.

I'm not able to dereference a pointer inside a struct pointed to by the lParam.

It looks like this: the lParam is a long Pointer to a CBT_CREATEWND struct, which in turn holds a member "lpcs", and a pointer to a CREATESTRUCT. This struct contains a member "x", which I want to read. I tried the following, but I get invalid values for x:

```<code>CREATESTRUCT str = *(LPCREATESTRUCT)(((LPCBT_CREATEWND)lParam)->lpcs);
int normal = str.x;
PostMessage(FindWindow(NULL, L"Process Watcher Window"), RegisterWindowMessage(L"ALEXX_SEINE_WNDMESSAGE_C"), wParam, normal);
</code>```

could someone please help me?

答:
Your syntax seems to check out, even though it is perhaps a bit unreadable, and the LPCREATESTRUCT cast is obviously unnecessary.

You mentioned that you get invalid values for x, perhaps lParam is not really a pointer to a CBT_CREATEWND structure? Are you checking that nCode of the callback function is equal to HCBT_CREATEWND before casting lParam?

Title: Dereferencing pointer C++

Body:
I just managed to write a global CBT hook in c++, usable with c#.
It may sound stupid but my knowledge of pointers and dereferencing of those is very bad due to my work with c#.

I'm not able to dereference a pointer inside a struct pointed to by the lParam.

It looks like this: the lParam is a long Pointer to a CBT_CREATEWND struct, which in turn holds a member "lpcs", and a pointer to a CREATESTRUCT. This struct contains a member "x", which I want to read. I tried the following, but I get invalid values for x:

CREATESTRUCT str = *(LPCREATESTRUCT)(((LPCBT_CREATEWND)lParam)->lpcs);
int normal = str.x;
PostMessage(FindWindow(NULL, L"Process Watcher Window"), RegisterWindowMessage(L"ALEXX_SEINE_WNDMESSAGE_C"), wParam, normal);

could someone please help me?


问:
How to `dot` weights to batch data in PyTorch?
I have batch data and want to dot() to the data. W is trainable parameters.
How to dot between batch data and weights?

```<code>hid_dim = 32
data = torch.randn(10, 2, 3, hid_dim)
data = data.view(10, 2*3, hid_dim)
W = torch.randn(hid_dim) # assume trainable parameters via nn.Parameter
result = torch.bmm(data, W).squeeze() # error, want (N, 6)
result = result.view(10, 2, 3)
</code>```

Update

How about this one?

```<code>hid_dim = 32
data = torch.randn(10, 2, 3, hid_dim)
data = tdata.view(10, 2*3, hid_dim)
W = torch.randn(hid_dim, 1) # assume trainable parameters via nn.Parameter
W = W.unsqueeze(0).expand(10, hid_dim, 1)
result = torch.bmm(data, W).squeeze() # error, want (N, 6)
result = result.view(10, 2, 3)
</code>```

答:
Expand W tensor to match the shape of data tensor. The following should work.

```<code>hid_dim = 32
data = torch.randn(10, 2, 3, hid_dim)
data = data.view(10, 2*3, hid_dim)
W = torch.randn(hid_dim)
W = W.unsqueeze(0).unsqueeze(0).expand(*data.size())
result = torch.sum(data * W, 2)
result = result.view(10, 2, 3)
</code>```

Edit: Your updated code is correct. Since you are converting W to a Bxhid_dimx1 and your data is of shape Bxdxhid_dim, so doing batch matrix multiplication will result in Bxdx1 which is essentially the dot product between W parameter and all the row vectors in data (dxhid_dim).

Body:
I have batch data and want to dot() to the data. W is trainable parameters.
How to dot between batch data and weights?

hid_dim = 32
data = torch.randn(10, 2, 3, hid_dim)
data = data.view(10, 2*3, hid_dim)
W = torch.randn(hid_dim) # assume trainable parameters via nn.Parameter
result = torch.bmm(data, W).squeeze() # error, want (N, 6)
result = result.view(10, 2, 3)

Update

How about this one?

hid_dim = 32
data = torch.randn(10, 2, 3, hid_dim)
data = tdata.view(10, 2*3, hid_dim)
W = torch.randn(hid_dim, 1) # assume trainable parameters via nn.Parameter
W = W.unsqueeze(0).expand(10, hid_dim, 1)
result = torch.bmm(data, W).squeeze() # error, want (N, 6)
result = result.view(10, 2, 3)

Body:
Expand W tensor to match the shape of data tensor. The following should work.

hid_dim = 32
data = torch.randn(10, 2, 3, hid_dim)
data = data.view(10, 2*3, hid_dim)
W = torch.randn(hid_dim)
W = W.unsqueeze(0).unsqueeze(0).expand(*data.size())
result = torch.sum(data * W, 2)
result = result.view(10, 2, 3)

Edit: Your updated code is correct. Since you are converting W to a Bxhid_dimx1 and your data is of shape Bxdxhid_dim, so doing batch matrix multiplication will result in Bxdx1 which is essentially the dot product between W parameter and all the row vectors in data (dxhid_dim).


问:
Dependency Injection with PowerShell
Is it possible to use Dependency Injection (DI) with Windows PowerShell?

My intitial experiments suggest that it isn't. If I attempt to use Constructor Injection in a CmdLet it doesn't even register itself. In other words, this is not possible:

```<code>[Cmdlet(VerbsDiagnostic.Test, "Ploeh")]
public class PloehCmdlet : Cmdlet
{
    public PloehCmdlet(IFoo foo)
    {
        if (foo == null)
        {
            throw new ArgumentNullException("foo");
        }

        // save foo for later use
    }

    protected override void ProcessRecord()
    {
        this.WriteObject("Ploeh");
    }
}
</code>```

If I add a default constructor, the CmdLet can be registered and used, but without the default constructor, it's simply not available.

I know I could use a Service Locator to retrieve my dependencies, but I consider that an anti-pattern so don't want to go that way.

I would have hoped that the PowerShell API had some kind of 'Factory' hook similar to WCF's ServiceHostFactory, but if there is, I can't find it.

答:
Though you can't use constructor injection for this, you could use the cmdlet itself.  Have a first call to it on one parameter set to initialise, store the relevant information in the current session state, and have subsequent calls pull the stored value back from the session state.

Here I've used a single string, message to represent the stored value; but obviously you can have as many parameters / of whatever types you like.

NB: The below C# is wrapped in PowerShell, so you can test the whole thing directly in PS.

$cs = @'
```

<pre class="lang-cs prettyprint-override"><code>using System.Management.Automation;

[Cmdlet(VerbsDiagnostic.Test, "Ploeh", DefaultParameterSetName = "None")]
public class PloehCmdlet : PSCmdlet
{
    const string InitialiseParameterSetName = "Initialise";
    const string MessageVariable = "Test_Ploeh_Message_39fbe50c_25fc_48b1_8348_d155cad99e93"; //since this is held as a variable in the session state, make sure the name will not clash with any existing variables

    [Parameter(Mandatory=true, ParameterSetName = InitialiseParameterSetName)]
    public string InitialiseMessage
    {
        set { SaveMessageToSessionState(value); }
    }

    protected override void ProcessRecord()
    {
        if (this.ParameterSetName != InitialiseParameterSetName) //do not run the cmdlet if we're just initialising it
        {
            this.WriteObject(GetMessageFromSessionState());
            base.ProcessRecord();
        }
    }

    void SaveMessageToSessionState(string message)
    {
        this.SessionState.PSVariable.Set(MessageVariable, message);
    }
    string GetMessageFromSessionState()
    {
        return (string)this.SessionState.PSVariable.GetValue(MessageVariable);
    }

}
</code>```

'@
```

<pre class="lang-powershell prettyprint-override"><code>#Trick courtesy of: http://community.idera.com/powershell/powertips/b/tips/posts/compiling-binary-cmdlets
$DLLPath = Join-Path $env:temp ('CSharpPSCmdLet{0:yyyyMMddHHmmssffff}.dll' -f (Get-Date))
Add-Type -OutputAssembly $DLLPath  -Language 'CSharp' -ReferencedAssemblies 'System.Management.Automation.dll' -TypeDefinition $cs
Import-Module -Name $DLLPath -Force -Verbose

#demo commands

Test-Ploeh -InitialiseMessage 'this is a test'
Test-Ploeh
Test-Ploeh

Test-Ploeh -InitialiseMessage 'change value'
Test-Ploeh
Test-Ploeh

"NB: Beware, your value can be accessed / amended outside of your cmdlet: $Test_Ploeh_Message_39fbe50c_25fc_48b1_8348_d155cad99e93"
$Test_Ploeh_Message_39fbe50c_25fc_48b1_8348_d155cad99e93 = "I've changed my mind"
Test-Ploeh
</code>```

Example Output

VERBOSE: Loading module from path 'C:\Users\UserNa~1\AppData\Local\Temp\CSharpPSCmdLet201711132257130536.dll'.
VERBOSE: Importing cmdlet 'Test-Ploeh'.
this is a test
this is a test
change value
change value
NB: Beware, your value can be accessed / amended outside of your cmdlet: change value
I've changed my mind
```

Title: Dependency Injection with PowerShell

Body:
Is it possible to use Dependency Injection (DI) with Windows PowerShell?

My intitial experiments suggest that it isn't. If I attempt to use Constructor Injection in a CmdLet it doesn't even register itself. In other words, this is not possible:

[Cmdlet(VerbsDiagnostic.Test, "Ploeh")]
public class PloehCmdlet : Cmdlet
{
    public PloehCmdlet(IFoo foo)
    {
        if (foo == null)
        {
            throw new ArgumentNullException("foo");
        }

        // save foo for later use
    }

    protected override void ProcessRecord()
    {
        this.WriteObject("Ploeh");
    }
}

If I add a default constructor, the CmdLet can be registered and used, but without the default constructor, it's simply not available.

I know I could use a Service Locator to retrieve my dependencies, but I consider that an anti-pattern so don't want to go that way.

I would have hoped that the PowerShell API had some kind of 'Factory' hook similar to WCF's ServiceHostFactory, but if there is, I can't find it.

Body:
Though you can't use constructor injection for this, you could use the cmdlet itself.  Have a first call to it on one parameter set to initialise, store the relevant information in the current session state, and have subsequent calls pull the stored value back from the session state.

Here I've used a single string, message to represent the stored value; but obviously you can have as many parameters / of whatever types you like.

NB: The below C# is wrapped in PowerShell, so you can test the whole thing directly in PS.

$cs = @'

using System.Management.Automation;

[Cmdlet(VerbsDiagnostic.Test, "Ploeh", DefaultParameterSetName = "None")]
public class PloehCmdlet : PSCmdlet
{
    const string InitialiseParameterSetName = "Initialise";
    const string MessageVariable = "Test_Ploeh_Message_39fbe50c_25fc_48b1_8348_d155cad99e93"; //since this is held as a variable in the session state, make sure the name will not clash with any existing variables

    [Parameter(Mandatory=true, ParameterSetName = InitialiseParameterSetName)]
    public string InitialiseMessage
    {
        set { SaveMessageToSessionState(value); }
    }

    protected override void ProcessRecord()
    {
        if (this.ParameterSetName != InitialiseParameterSetName) //do not run the cmdlet if we're just initialising it
        {
            this.WriteObject(GetMessageFromSessionState());
            base.ProcessRecord();
        }
    }

    void SaveMessageToSessionState(string message)
    {
        this.SessionState.PSVariable.Set(MessageVariable, message);
    }
    string GetMessageFromSessionState()
    {
        return (string)this.SessionState.PSVariable.GetValue(MessageVariable);
    }

}

'@

#Trick courtesy of: http://community.idera.com/powershell/powertips/b/tips/posts/compiling-binary-cmdlets
$DLLPath = Join-Path $env:temp ('CSharpPSCmdLet{0:yyyyMMddHHmmssffff}.dll' -f (Get-Date))
Add-Type -OutputAssembly $DLLPath  -Language 'CSharp' -ReferencedAssemblies 'System.Management.Automation.dll' -TypeDefinition $cs
Import-Module -Name $DLLPath -Force -Verbose

#demo commands

Test-Ploeh -InitialiseMessage 'this is a test'
Test-Ploeh
Test-Ploeh

Test-Ploeh -InitialiseMessage 'change value'
Test-Ploeh
Test-Ploeh

"NB: Beware, your value can be accessed / amended outside of your cmdlet: $Test_Ploeh_Message_39fbe50c_25fc_48b1_8348_d155cad99e93"
$Test_Ploeh_Message_39fbe50c_25fc_48b1_8348_d155cad99e93 = "I've changed my mind"
Test-Ploeh

Example Output

VERBOSE: Loading module from path 'C:\Users\UserNa~1\AppData\Local\Temp\CSharpPSCmdLet201711132257130536.dll'.
VERBOSE: Importing cmdlet 'Test-Ploeh'.
this is a test
this is a test
change value
change value
NB: Beware, your value can be accessed / amended outside of your cmdlet: change value
I've changed my mind


问:
Create a JsonProcessingException
I'm trying to create a JsonProcessingException to be thrown by a mock object.

```<code>when(mapper.writeValueAsString(any(Object.class))).thenThrow(new JsonProcessingException("Error"));
</code>```

However I'm unable to create a JsonProcessingException object as all the constructors are protected. How do I get around this?

答:
how about you create an anonymous exception of type JsonProcessingException

```<code>when(mapper.writeValueAsString(any(Object.class))).thenThrow(new JsonProcessingException("Error"){});
</code>```

The {} braces does the trick. This is much better since it is not confusing to the reader of the test code.

Title: Create a JsonProcessingException

Body:
I'm trying to create a JsonProcessingException to be thrown by a mock object.

when(mapper.writeValueAsString(any(Object.class))).thenThrow(new JsonProcessingException("Error"));

However I'm unable to create a JsonProcessingException object as all the constructors are protected. How do I get around this?

Body:
how about you create an anonymous exception of type JsonProcessingException

when(mapper.writeValueAsString(any(Object.class))).thenThrow(new JsonProcessingException("Error"){});

The {} braces does the trick. This is much better since it is not confusing to the reader of the test code.


问:
Is there a way to convert a conditional assignment to branch free code?
Is there a way to convert the following C code to something without any conditional statements? I have profiled some of my code and noticed that it is getting many branch misses on an if statement that is very similar to this one.</p>

```<code>int cond = /*...*/;
int a = /*...*/;
int b = /*...*/;

int x;
if (cond) {
   x = a;
} else {
   x = b;
}
</code>```

答:
A more complete example would be more helpful as the way the variables x, a, b and cond are accessed can play a role. If they are global variables declared outside the function that performs the conditional assignment then they will be accessed using loads and stores, which the compiler may deem to be too expensive to execute conditionally.
Look at the examples at https://godbolt.org/g/GEZbuf where the same conditional assignment is performed on globals and in foo and on local arguments in foo2

Body:
Is there a way to convert the following C code to something without any conditional statements? I have profiled some of my code and noticed that it is getting many branch misses on an if statement that is very similar to this one.

int cond = /*...*/;
int a = /*...*/;
int b = /*...*/;

int x;
if (cond) {
   x = a;
} else {
   x = b;
}


答:
You can find the latest record for every ID using row_number. You will need to issue 2 UPDATE statements though, one for updating the latest record to 1 and another one to re-set the others to 0. </p>

<p>Hope the query below answers your query. If you are using true boolean columns, change the values to True and False. </p>

```<code>DROP TABLE some_tab;

CREATE TABLE some_tab (some_id NUMBER, some_date DATE, some_bool NUMBER, some_data VARCHAR2(50));

INSERT INTO some_tab VALUES (001, TO_DATE('11.13.2017', 'MM.DD.YYYY'), 0,  'value 1');
INSERT INTO some_tab VALUES (001, TO_DATE('09.13.2017', 'MM.DD.YYYY'), 1,  'value 2');
INSERT INTO some_tab VALUES (001, TO_DATE('01.01.2017', 'MM.DD.YYYY'), 0,  'value 0');
INSERT INTO some_tab VALUES (002, TO_DATE('06.15.2017', 'MM.DD.YYYY'), 1,  'value 3');
INSERT INTO some_tab VALUES (003, TO_DATE('04.23.2017', 'MM.DD.YYYY'), 1,  'value 4');
INSERT INTO some_tab VALUES (003, TO_DATE('12.13.2017', 'MM.DD.YYYY'), 0,  'value 5');

SELECT * FROM some_tab;

UPDATE some_tab
   SET some_bool = 1
 WHERE rowid IN (SELECT v.r_id
                   FROM (SELECT rowid AS r_id, ROW_NUMBER() OVER(PARTITION BY some_id ORDER BY some_date DESC) AS r_num
                           FROM some_tab) v
                  WHERE v.r_num = 1);

UPDATE some_tab
   SET some_bool = 0
 WHERE rowid IN (SELECT v.r_id
                   FROM (SELECT rowid AS r_id, ROW_NUMBER() OVER(PARTITION BY some_id ORDER BY some_date DESC) AS r_num
                           FROM some_tab) v
                  WHERE v.r_num <> 1);

SELECT * FROM some_tab;
</code>```

Title: Update 1 record according to 2 sorts criteria

Body:
Do you know how can I update 1 record according to 2 sorts criteria?

I have in my table A :

id    |     date    | boolean  | data
-------------------------------------------
001    | 11.13.2017  |    0     | value 1
001    | 09.13.2017  |    1     | value 2
001    | 01.01.2017  |    0     | value 0
002    | 06.15.2017  |    1     | value 3
003    | 04.23.2017  |    1     | value 4
003    | 12.13.2017  |    0     | value 5

I would like by id, change the boolean value according with the most recent date.

for example:

id     |     date    | boolean  | data
-------------------------------------------
001    | 11.13.2017  |    1     | value 1
001    | 09.13.2017  |    0     | value 2
001    | 01.01.2017  |    0     | value 0

Thank you

Body:
You can find the latest record for every ID using row_number. You will need to issue 2 UPDATE statements though, one for updating the latest record to 1 and another one to re-set the others to 0.

Hope the query below answers your query. If you are using true boolean columns, change the values to True and False.

DROP TABLE some_tab;

CREATE TABLE some_tab (some_id NUMBER, some_date DATE, some_bool NUMBER, some_data VARCHAR2(50));

INSERT INTO some_tab VALUES (001, TO_DATE('11.13.2017', 'MM.DD.YYYY'), 0,  'value 1');
INSERT INTO some_tab VALUES (001, TO_DATE('09.13.2017', 'MM.DD.YYYY'), 1,  'value 2');
INSERT INTO some_tab VALUES (001, TO_DATE('01.01.2017', 'MM.DD.YYYY'), 0,  'value 0');
INSERT INTO some_tab VALUES (002, TO_DATE('06.15.2017', 'MM.DD.YYYY'), 1,  'value 3');
INSERT INTO some_tab VALUES (003, TO_DATE('04.23.2017', 'MM.DD.YYYY'), 1,  'value 4');
INSERT INTO some_tab VALUES (003, TO_DATE('12.13.2017', 'MM.DD.YYYY'), 0,  'value 5');

SELECT * FROM some_tab;

UPDATE some_tab
   SET some_bool = 1
 WHERE rowid IN (SELECT v.r_id
                   FROM (SELECT rowid AS r_id, ROW_NUMBER() OVER(PARTITION BY some_id ORDER BY some_date DESC) AS r_num
                           FROM some_tab) v
                  WHERE v.r_num = 1);

UPDATE some_tab
   SET some_bool = 0
 WHERE rowid IN (SELECT v.r_id
                   FROM (SELECT rowid AS r_id, ROW_NUMBER() OVER(PARTITION BY some_id ORDER BY some_date DESC) AS r_num
                           FROM some_tab) v
                  WHERE v.r_num <> 1);

SELECT * FROM some_tab;


问:
Transforming target data (angles/degrees) such that 1 degree and 359 degrees are treated similarly
I'm working on a model that predicts angles. What's a good way to transform the targets (currently they take on values 0 to 360 degrees) such that close angles are treated similarly? I suspect leaving them as they are now isn't optimal as values close to 360 and 0 are similar, yet have totally different magnitudes. </p>

答:
You can just use sine and cosine transformation for them! Of course, your model will not predict them perfectly, so you need to re-normalize your results after prediction. See the sample code:</p>

```<code># predicting the angle (in radians)
import numpy as np
from sklearn.neural_network import MLPRegressor
from sklearn.model_selection import cross_val_predict
from sklearn.metrics import r2_score
# generate toy data
np.random.seed(1)
X = np.random.normal(size=(100, 2))
y = np.arctan2(np.dot(X, [1,2]), np.dot(X, [3,0.4]))
# simple prediction
model = MLPRegressor(random_state=42, activation='tanh', max_iter=10000)
y_simple_pred = cross_val_predict(model, X, y)
# transformed prediction
joint = cross_val_predict(model, X, np.column_stack([np.sin(y), np.cos(y)]))
y_trig_pred = np.arctan2(joint[:,0], joint[:,1])
# compare
print(r2_score(y, y_simple_pred)) # R^2 about 0.53
print(r2_score(y, y_trig_pred))   # R^2 about 0.85
</code>```

Body:
You can just use sine and cosine transformation for them! Of course, your model will not predict them perfectly, so you need to re-normalize your results after prediction. See the sample code:

# predicting the angle (in radians)
import numpy as np
from sklearn.neural_network import MLPRegressor
from sklearn.model_selection import cross_val_predict
from sklearn.metrics import r2_score
# generate toy data
np.random.seed(1)
X = np.random.normal(size=(100, 2))
y = np.arctan2(np.dot(X, [1,2]), np.dot(X, [3,0.4]))
# simple prediction
model = MLPRegressor(random_state=42, activation='tanh', max_iter=10000)
y_simple_pred = cross_val_predict(model, X, y)
# transformed prediction
joint = cross_val_predict(model, X, np.column_stack([np.sin(y), np.cos(y)]))
y_trig_pred = np.arctan2(joint[:,0], joint[:,1])
# compare
print(r2_score(y, y_simple_pred)) # R^2 about 0.53
print(r2_score(y, y_trig_pred))   # R^2 about 0.85


问:
Error in socket.emit with special characters
First of all, Sorry if my English is not very good.

I'm trying to make a chat in nodeJS with socket.io:

The users send messages to the node server, and they are sent correctly to all clients connected.

The messages are saved in a "historical" variable, so the new connections can see what has been spoken.

The problem is when a special character is stored in the history var, such as "¿".

Source code (Server):

```<code>var io = require('socket.io')(3333);

var historico_mensajes = [];

console.log('Iniciando aplicacion');

io.on('connection',function(socket) {
    console.log('Nueva conexion');
    console.log(historico_mensajes);

    socket.emit("chat_hist",{ historico_mensajes });

    socket.on('chat_msg',function(data){
        console.log("Msg no escapado: "+data.msg);
        if(data.msg.length>150) {
            socket.emit('sv_chat_msg', {
                type: 'error',
                msg: 'too long'
            });
        } else {
            io.sockets.emit('sv_chat_msg', {
                type: 'chat',
                msg: data.msg,
                name: 'Test name',
                icon: 'Test icon',
                user: 'Test user',
                rank: 'Test rank'
            });
            historico_mensajes.push({
                    type: 'chat',
                    msg: data.msg,
                    name: 'Test name',
                    icon: 'Test icon',
                    user: 'Test user',
                    rank: 'Test rank'
            });
            if(historico_mensajes.length > 15) { historico_mensajes.splice(0,1); }

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

Source code (client):

```<code>var HOST = "http://127.0.0.1:3333";
var SOCKET = null;

$(document).ready(function() {
    connect();
});

function connect() {
    if (!SOCKET) {
        console.log("Connecting to server...");
        SOCKET = io(HOST);
        SOCKET.on('connect', function() {
            console.log("Established connection!");
        });
        SOCKET.on('chat_hist', function(m=null) {
            console.log("chat hist recibido");
            console.log(m);
            /*
            if(m) {
                for (var ms = 0; ms < m.historico_mjs.length; ms++) {
                    chat("user", m.historico_mjs[ms].name, m.historico_mjs[ms].msg, m.historico_mjs[ms].icon, m.historico_mjs[ms].rank);
                }
            } else {
                console.log("no historico");
            }
            */
        });
        SOCKET.on('sv_chat_msg', function(data) {
            console.log("mensaje del server recibido para el usuario");
            switch(data.type) {
                case "error":
                    chat('bot_errors','Test Bot',data.msg);
                    break;
                case "chat":
                    chat('user',data.name,data.msg,data.icon,data.rank);
                    break;
                default:
                    chat('bot','Test Bot','Unknow msg');
                    break;
            }
        });
    }
}

if (!String.prototype.format) {
    String.prototype.format = function() {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function(match, number) {
            return typeof args[number] != 'undefined' ? args[number] : match;
        });
    };
}

function chat(tipo,name,msg,avatar,rank){
    var toChat = "";
    if(msg && name) {
        msg = msg.replace(/(<|>)/g, '');
        name = name.replace(/(<|>)/g, '');
        switch(tipo) {
            case "bot":
                toChat='<li><div class="comment-box"><header class="header"><span class="cmt-user-level">100</span><a href="#" data-show-profile="001"><img width="18px" src="images/crown.png" alt="user snap" /><em style="color:#ff8b00;">'+name+'</em></a></header><div class="text" style="color:#ff9800;">'+msg+'</div><span class="remove-comment"><i class="flaticon-remove-user"></i></span></div></li>';
                break;
            case "bot_errors":
                toChat='<li><div class="comment-box"><header class="header"><span class="cmt-user-level">100</span><a href="#" data-show-profile="001"><img width="18px" src="images/crown.png" alt="user snap" /><em style="color:#ff8b00;">'+name+'</em></a></header><div class="text" style="color:#a94442;">'+msg+'</div><span class="remove-comment"><i class="flaticon-remove-user"></i></span></div></li>';
                break;
            case "user":
                toChat='<li><div class="comment-box"><header class="header"><span class="cmt-user-level">'+rank+'</span><a href="#" data-show-profile="001"><img width="18px" src="'+avatar+'" alt="user snap" /><em>'+name+'</em></a></header><div class="text">'+msg+'</div><span class="remove-comment"><i class="flaticon-remove-user"></i></span></div></li>';
                break;
        }

        $("#chatArea").append(toChat);
    }
}
</code>```

Examples:

When I send normal characters everything works fine:

If press F5 and get array with chat:

But... if I send a message with "¿" charset:

If now i press F5... this happens:

what can i do??

答:
on pressing F5 following code runs:

```<code>SOCKET.on('chat_hist', function(m=null) {
            console.log("chat hist recibido");
            console.log(m);//you fave commented code here
            m && m.historico_mjs.forEach(data=>chat('user',data.name,data.msg,data.icon,data.rank););
      });
</code>```

complete above code and which will put history on screen.Please use code similar to above to get results.

Body:
First of all, Sorry if my English is not very good.

I'm trying to make a chat in nodeJS with socket.io:

The users send messages to the node server, and they are sent correctly to all clients connected.

The messages are saved in a "historical" variable, so the new connections can see what has been spoken.

The problem is when a special character is stored in the history var, such as "¿".

Source code (Server):

var io = require('socket.io')(3333);

var historico_mensajes = [];

console.log('Iniciando aplicacion');

io.on('connection',function(socket) {
    console.log('Nueva conexion');
    console.log(historico_mensajes);

    socket.emit("chat_hist",{ historico_mensajes });

    socket.on('chat_msg',function(data){
        console.log("Msg no escapado: "+data.msg);
        if(data.msg.length>150) {
            socket.emit('sv_chat_msg', {
                type: 'error',
                msg: 'too long'
            });
        } else {
            io.sockets.emit('sv_chat_msg', {
                type: 'chat',
                msg: data.msg,
                name: 'Test name',
                icon: 'Test icon',
                user: 'Test user',
                rank: 'Test rank'
            });
            historico_mensajes.push({
                    type: 'chat',
                    msg: data.msg,
                    name: 'Test name',
                    icon: 'Test icon',
                    user: 'Test user',
                    rank: 'Test rank'
            });
            if(historico_mensajes.length > 15) { historico_mensajes.splice(0,1); }

        }
    });
});

Source code (client):

var HOST = "http://127.0.0.1:3333";
var SOCKET = null;

$(document).ready(function() {
    connect();
});

function connect() {
    if (!SOCKET) {
        console.log("Connecting to server...");
        SOCKET = io(HOST);
        SOCKET.on('connect', function() {
            console.log("Established connection!");
        });
        SOCKET.on('chat_hist', function(m=null) {
            console.log("chat hist recibido");
            console.log(m);
            /*
            if(m) {
                for (var ms = 0; ms < m.historico_mjs.length; ms++) {
                    chat("user", m.historico_mjs[ms].name, m.historico_mjs[ms].msg, m.historico_mjs[ms].icon, m.historico_mjs[ms].rank);
                }
            } else {
                console.log("no historico");
            }
            */
        });
        SOCKET.on('sv_chat_msg', function(data) {
            console.log("mensaje del server recibido para el usuario");
            switch(data.type) {
                case "error":
                    chat('bot_errors','Test Bot',data.msg);
                    break;
                case "chat":
                    chat('user',data.name,data.msg,data.icon,data.rank);
                    break;
                default:
                    chat('bot','Test Bot','Unknow msg');
                    break;
            }
        });
    }
}

if (!String.prototype.format) {
    String.prototype.format = function() {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function(match, number) {
            return typeof args[number] != 'undefined' ? args[number] : match;
        });
    };
}

function chat(tipo,name,msg,avatar,rank){
    var toChat = "";
    if(msg && name) {
        msg = msg.replace(/(<|>)/g, '');
        name = name.replace(/(<|>)/g, '');
        switch(tipo) {
            case "bot":
                toChat='

100'+name+'
'+msg+'

';
                break;
            case "bot_errors":
                toChat='

100'+name+'
'+msg+'

';
                break;
            case "user":
                toChat='

'+rank+''+name+'
'+msg+'

';
                break;
        }

        $("#chatArea").append(toChat);
    }
}

Examples:

When I send normal characters everything works fine:

If press F5 and get array with chat:

But... if I send a message with "¿" charset:

If now i press F5... this happens:

what can i do??

Body:
on pressing F5 following code runs:

SOCKET.on('chat_hist', function(m=null) {
            console.log("chat hist recibido");
            console.log(m);//you fave commented code here
            m && m.historico_mjs.forEach(data=>chat('user',data.name,data.msg,data.icon,data.rank););
      });

complete above code and which will put history on screen.Please use code similar to above to get results.


问:
Transaction management in Play Framework (scala)
I'm new in Play Framework and used to manage transactions in java/spring style with controller, transactional service and dao layers. It's pretty usual case for me to have multiply operations with dao in service method and make him @Transactional to rollback all changes if something goes wrong. Service isolated from dao and know nothing about database.

But I didn't find something like this in Anorm framework and Play. All logic placed in controllers and you can make transaction only this ugly way - Database transactions in Play framework scala applications (anorm)

We have several problems here:

Service turns into dao

If we need to call same dao method from another service we have change it same way

Is there nice way to manage transactions in Play? Other frameworks like Slick? How to use Play in production with such restricments

答:
Anorm's DB.withTransaction creates and commits a transaction when it exits, so there is no out-of-the-box support for your use case. Though it is quite straightforward to create your own transaction engine based on what Anorm offers that spans multiple services: it creates a transaction if none is present in ThreadLocal and stores it there or uses the one obtained from it in subsequent 'transactional' usages. Then you could have one, big transaction that rollbacks on an error deep down the dao layer. We have a solution like this in production and works just fine.

However, there is a conceptual problem, that you should be aware of. As soon as you need to call a service that returns a Future you no longer have the transaction (you are possibly on another thread) or you should block (which is not a good thing in production).


问:
generic call of class in c#
```<code>SlovenianSearchQueryManager.ApplySloveniaQueries(rawQuery, page, pageSize, orderBy, out count);
</code>```

is it possible to get SlovenianSearchQueryManager class by concatinating HttpContext.Current.Session["lang_name"] and "SearchQueryManager";

HttpContext.Current.Session["lang_name"] is Slovenian so together is SlovenianSearchQueryManager

next time

HttpContext.Current.Session["lang_name"] is German so together is
GermanSearchQueryManager

i try to make this generic instead of making

```<code>if (HttpContext.Current.Session["lang_name"] == "Slovenian)
{
SlovenianSearchQueryManager.ApplySloveniaQueries(rawQuery, page, pageSize, orderBy, out count);
}
else ...
</code>```

i want to make something like

```<code>(HttpContext.Current.Session["lang_name"] + "SearchQueryManager").ApplySloveniaQueries(...
</code>```

is this even possible to make something like this and the type SlovenianSearchQueryManager for example exists, it's in a different class library.

答:
Use Type.GetType and Activator.CreateInstance:

```<code>var queryManagerType = Type.GetType(HttpContext.Current.Session["lang_name"] + "SearchQueryManager");
var queryManager = Activator.CreateInstance(queryManagerType);
</code>```

Activator.CreateInstance returns an object. You might want to define an interface that you query managers will need to implement.

```<code>public interface ISearchQueryManager {
    void ApplyQueries(/* add parameters here */);
}
</code>```

Then you can cast the object returned by CreateInstance to the interface:

```<code>var queryManagerType = Type.GetType(HttpContext.Current.Session["lang_name"] + "SearchQueryManager");
var queryManager = (ISearchQueryManager)Activator.CreateInstance(queryManagerType);
queryManager.ApplyQueries(rawQuery, page, pageSize, orderBy, out count);
</code>```

Title: generic call of class in c#

Body:
SlovenianSearchQueryManager.ApplySloveniaQueries(rawQuery, page, pageSize, orderBy, out count);

is it possible to get SlovenianSearchQueryManager class by concatinating HttpContext.Current.Session["lang_name"] and "SearchQueryManager";

HttpContext.Current.Session["lang_name"] is Slovenian so together is SlovenianSearchQueryManager

next time

HttpContext.Current.Session["lang_name"] is German so together is
GermanSearchQueryManager

i try to make this generic instead of making

if (HttpContext.Current.Session["lang_name"] == "Slovenian)
{
SlovenianSearchQueryManager.ApplySloveniaQueries(rawQuery, page, pageSize, orderBy, out count);
}
else ...

i want to make something like

(HttpContext.Current.Session["lang_name"] + "SearchQueryManager").ApplySloveniaQueries(...

is this even possible to make something like this and the type SlovenianSearchQueryManager for example exists, it's in a different class library.

Body:
Use Type.GetType and Activator.CreateInstance:

var queryManagerType = Type.GetType(HttpContext.Current.Session["lang_name"] + "SearchQueryManager");
var queryManager = Activator.CreateInstance(queryManagerType);

Activator.CreateInstance returns an object. You might want to define an interface that you query managers will need to implement.

public interface ISearchQueryManager {
    void ApplyQueries(/* add parameters here */);
}

Then you can cast the object returned by CreateInstance to the interface:

var queryManagerType = Type.GetType(HttpContext.Current.Session["lang_name"] + "SearchQueryManager");
var queryManager = (ISearchQueryManager)Activator.CreateInstance(queryManagerType);
queryManager.ApplyQueries(rawQuery, page, pageSize, orderBy, out count);


问:
How to call random function from list of functions?
```<code>t = 1
while t < total:
    random.choice([xs_tables(t), medium_tables(t), large_tables(t), xl_tables(t)])
    t = t + total
</code>```

Above I"m trying to call a random function from a list of 4 functions that will take t as a input.  Right now the code is calling each function in the list instead of just one random function.  I think it might have something to do with the (t) but I'm not sure how else to pass the functions t.

答:
Do this instead:

```<code>random.choice([xs_tables, medium_tables, large_tables, xl_tables])(t)
</code>```

This way, you first select the function and then call it with the argument t.

Body:
t = 1
while t < total:
    random.choice([xs_tables(t), medium_tables(t), large_tables(t), xl_tables(t)])
    t = t + total

Above I"m trying to call a random function from a list of 4 functions that will take t as a input.  Right now the code is calling each function in the list instead of just one random function.  I think it might have something to do with the (t) but I'm not sure how else to pass the functions t.

Body:
Do this instead:

random.choice([xs_tables, medium_tables, large_tables, xl_tables])(t)

This way, you first select the function and then call it with the argument t.