text:
Q: My USB audio input channels max_out/clips at ~15% I got an M-track 8 audio device (8 I/Os). It works fine for playback. However, the microphone (48 volt XLR mics) barely make any sound. When recording, they cap out at 15% volume in any application.

*

*According to the mixer spectrum analyser, they are working totally fine.

*If I redirect the m-track input to the analog output and record it using the built-in mic, then it works correctly

*If I record in macOS or Windows, it works correctly.

So the problem is somewhere in ALSA or the driver. This is a normal USB audio class device, so the driver is very unlikely to be the problem (reproduced in Gentoo, Ubuntu 20.04 and Ubuntu 18.04 live-usb).

*

*alsamixer show all inputs are at 100%

*pavucontrol shows all inputs at 100%

*I tried adding some .asoundrc configs to force 96kHz and it did nothing

*The problem has nothing to do with mic boost. The signal is ultra weak

amixer -c2:
Simple mixer control 'Mic',0
  Capabilities: cvolume cswitch
  Capture channels: Front Left - Front Right - Rear Left - Rear Right - Front Center - Woofer - Side Left - Side Right
  Limits: Capture 0 - 127
  Front Left: Capture 127 [100%] [0.00dB] [on]
  Front Right: Capture 127 [100%] [0.00dB] [on]
  Rear Left: Capture 127 [100%] [0.00dB] [on]
  Rear Right: Capture 127 [100%] [0.00dB] [on]
  Front Center: Capture 127 [100%] [0.00dB] [on]
  Woofer: Capture 127 [100%] [0.00dB] [on]
  Side Left: Capture 127 [100%] [0.00dB] [on]
  Side Right: Capture 127 [100%] [0.00dB] [on]
Simple mixer control 'Mic',1
  Capabilities: cvolume cvolume-joined cswitch cswitch-joined
  Capture channels: Mono
  Limits: Capture 0 - 127
  Mono: Capture 127 [100%] [0.00dB] [on]
Simple mixer control 'M-Audio M-Track Eight',0
  Capabilities: pvolume pswitch
  Playback channels: Front Left - Front Right - Rear Left - Rear Right - Front Center - Woofer - Side Left - Side Right
  Limits: Playback 0 - 127
  Mono:
  Front Left: Playback 121 [95%] [-6.00dB] [on]
  Front Right: Playback 121 [95%] [-6.00dB] [on]
  Rear Left: Playback 127 [100%] [0.00dB] [on]
  Rear Right: Playback 127 [100%] [0.00dB] [on]
  Front Center: Playback 127 [100%] [0.00dB] [on]
  Woofer: Playback 127 [100%] [0.00dB] [on]
  Side Left: Playback 127 [100%] [0.00dB] [on]
  Side Right: Playback 127 [100%] [0.00dB] [on]
Simple mixer control 'M-Audio M-Track Eight',1
  Capabilities: pvolume pvolume-joined pswitch pswitch-joined
  Playback channels: Mono
  Limits: Playback 0 - 127
  Mono: Playback 127 [100%] [0.00dB] [on]

lsusb -vv -d 0763:4003
Bus 001 Device 049: ID 0763:4003 M-Audio
Couldn't open device, some information will be missing
Device Descriptor:
  bLength                18
  bDescriptorType         1
  bcdUSB               2.00
  bDeviceClass          239 Miscellaneous Device
  bDeviceSubClass         2
  bDeviceProtocol         1 Interface Association
  bMaxPacketSize0        64
  idVendor           0x0763 M-Audio
  idProduct          0x4003
  bcdDevice            1.05
  iManufacturer           1
  iProduct                3
  iSerial                 0
  bNumConfigurations      2
  Configuration Descriptor:
    bLength                 9
    bDescriptorType         2
    wTotalLength       0x0148
    bNumInterfaces          4
    bConfigurationValue     1
    iConfiguration          0
    bmAttributes         0x80
      (Bus Powered)
    MaxPower              500mA
    Interface Association:
      bLength                 8
      bDescriptorType        11
      bFirstInterface         0
      bInterfaceCount         3
      bFunctionClass          1 Audio
      bFunctionSubClass       0
      bFunctionProtocol      32
      iFunction               0
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        0
      bAlternateSetting       0
      bNumEndpoints           0
      bInterfaceClass         1 Audio
      bInterfaceSubClass      1 Control Device
      bInterfaceProtocol     32
      iInterface              3
      AudioControl Interface Descriptor:
        bLength                 9
        bDescriptorType        36
        bDescriptorSubtype      1 (HEADER)
        bcdADC               2.00
        bCategory               8
        wTotalLength       0x00a7
        bmControls           0x00
      AudioControl Interface Descriptor:
        bLength                 8
        bDescriptorType        36
        bDescriptorSubtype     10 (CLOCK_SOURCE)
        bClockID               41
        bmAttributes            3 Internal programmable clock
        bmControls           0x07
          Clock Frequency Control (read/write)
          Clock Validity Control (read-only)
        bAssocTerminal          0
        iClockSource            9
      AudioControl Interface Descriptor:
        bLength                 8
        bDescriptorType        36
        bDescriptorSubtype     11 (CLOCK_SELECTOR)
        bClockID               40
        bNrInPins               1
        baCSourceID(0)         41
        bmControls           0x03
          Clock Selector Control (read/write)
        iClockSelector          8
      AudioControl Interface Descriptor:
        bLength                17
        bDescriptorType        36
        bDescriptorSubtype      2 (INPUT_TERMINAL)
        bTerminalID             2
        wTerminalType      0x0101 USB Streaming
        bAssocTerminal          0
        bCSourceID             40
        bNrChannels             8
        bmChannelConfig    0x00000000
        iChannelNames          19
        bmControls         0x0000
        iTerminal               6
      AudioControl Interface Descriptor:
        bLength                42
        bDescriptorType        36
        bDescriptorSubtype      6 (FEATURE_UNIT)
        bUnitID                10
        bSourceID               2
        bmaControls(0)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(1)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(2)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(3)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(4)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(5)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(6)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(7)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(8)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        iFeature                0
      AudioControl Interface Descriptor:
        bLength                12
        bDescriptorType        36
        bDescriptorSubtype      3 (OUTPUT_TERMINAL)
        bTerminalID            20
        wTerminalType      0x0301 Speaker
        bAssocTerminal          0
        bSourceID              10
        bCSourceID             40
        bmControls         0x0000
        iTerminal               0
      AudioControl Interface Descriptor:
        bLength                17
        bDescriptorType        36
        bDescriptorSubtype      2 (INPUT_TERMINAL)
        bTerminalID             1
        wTerminalType      0x0201 Microphone
        bAssocTerminal          0
        bCSourceID             40
        bNrChannels             8
        bmChannelConfig    0x00000000
        iChannelNames          19
        bmControls         0x0000
        iTerminal               0
      AudioControl Interface Descriptor:
        bLength                42
        bDescriptorType        36
        bDescriptorSubtype      6 (FEATURE_UNIT)
        bUnitID                11
        bSourceID               1
        bmaControls(0)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(1)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(2)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(3)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(4)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(5)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(6)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(7)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(8)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        iFeature                0
      AudioControl Interface Descriptor:
        bLength                12
        bDescriptorType        36
        bDescriptorSubtype      3 (OUTPUT_TERMINAL)
        bTerminalID            22
        wTerminalType      0x0101 USB Streaming
        bAssocTerminal          0
        bSourceID              11
        bCSourceID             40
        bmControls         0x0000
        iTerminal               7
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        1
      bAlternateSetting       0
      bNumEndpoints           0
      bInterfaceClass         1 Audio
      bInterfaceSubClass      2 Streaming
      bInterfaceProtocol     32
      iInterface              4
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        1
      bAlternateSetting       1
      bNumEndpoints           2
      bInterfaceClass         1 Audio
      bInterfaceSubClass      2 Streaming
      bInterfaceProtocol     32
      iInterface              4
      AudioStreaming Interface Descriptor:
        bLength                16
        bDescriptorType        36
        bDescriptorSubtype      1 (AS_GENERAL)
        bTerminalLink           2
        bmControls           0x00
        bFormatType             1
        bmFormats          0x00000001
          PCM
        bNrChannels             8
        bmChannelConfig    0x00000000
        iChannelNames          11
      AudioStreaming Interface Descriptor:
        bLength                 6
        bDescriptorType        36
        bDescriptorSubtype      2 (FORMAT_TYPE)
        bFormatType             1 (FORMAT_TYPE_I)
        bSubslotSize            4
        bBitResolution         24
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x01  EP 1 OUT
        bmAttributes            5
          Transfer Type            Isochronous
          Synch Type               Asynchronous
          Usage Type               Data
        wMaxPacketSize     0x0400  1x 1024 bytes
        bInterval               1
        AudioStreaming Endpoint Descriptor:
          bLength                 8
          bDescriptorType        37
          bDescriptorSubtype      1 (EP_GENERAL)
          bmAttributes         0x00
          bmControls           0x00
          bLockDelayUnits         2 Decoded PCM samples
          wLockDelay         0x0008
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x81  EP 1 IN
        bmAttributes           17
          Transfer Type            Isochronous
          Synch Type               None
          Usage Type               Feedback
        wMaxPacketSize     0x0004  1x 4 bytes
        bInterval               4
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        2
      bAlternateSetting       0
      bNumEndpoints           0
      bInterfaceClass         1 Audio
      bInterfaceSubClass      2 Streaming
      bInterfaceProtocol     32
      iInterface              5
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        2
      bAlternateSetting       1
      bNumEndpoints           1
      bInterfaceClass         1 Audio
      bInterfaceSubClass      2 Streaming
      bInterfaceProtocol     32
      iInterface              5
      AudioStreaming Interface Descriptor:
        bLength                16
        bDescriptorType        36
        bDescriptorSubtype      1 (AS_GENERAL)
        bTerminalLink          22
        bmControls           0x00
        bFormatType             1
        bmFormats          0x00000001
          PCM
        bNrChannels             8
        bmChannelConfig    0x00000000
        iChannelNames          19
      AudioStreaming Interface Descriptor:
        bLength                 6
        bDescriptorType        36
        bDescriptorSubtype      2 (FORMAT_TYPE)
        bFormatType             1 (FORMAT_TYPE_I)
        bSubslotSize            4
        bBitResolution         24
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x82  EP 2 IN
        bmAttributes            5
          Transfer Type            Isochronous
          Synch Type               Asynchronous
          Usage Type               Data
        wMaxPacketSize     0x0400  1x 1024 bytes
        bInterval               1
        AudioStreaming Endpoint Descriptor:
          bLength                 8
          bDescriptorType        37
          bDescriptorSubtype      1 (EP_GENERAL)
          bmAttributes         0x00
          bmControls           0x00
          bLockDelayUnits         2 Decoded PCM samples
          wLockDelay         0x0008
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        3
      bAlternateSetting       0
      bNumEndpoints           0
      bInterfaceClass       254 Application Specific Interface
      bInterfaceSubClass      1 Device Firmware Update
      bInterfaceProtocol      1
      iInterface             10
      Device Firmware Upgrade Interface Descriptor:
        bLength                             9
        bDescriptorType                    33
        bmAttributes                        7
          Will Not Detach
          Manifestation Tolerant
          Upload Supported
          Download Supported
        wDetachTimeout                    250 milliseconds
        wTransferSize                      64 bytes
        bcdDFUVersion                   1.10
  Configuration Descriptor:
    bLength                 9
    bDescriptorType         2
    wTotalLength       0x0148
    bNumInterfaces          4
    bConfigurationValue     1
    iConfiguration          0
    bmAttributes         0x80
      (Bus Powered)
    MaxPower              500mA
    Interface Association:
      bLength                 8
      bDescriptorType        11
      bFirstInterface         0
      bInterfaceCount         3
      bFunctionClass          1 Audio
      bFunctionSubClass       0
      bFunctionProtocol      32
      iFunction               0
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        0
      bAlternateSetting       0
      bNumEndpoints           0
      bInterfaceClass         1 Audio
      bInterfaceSubClass      1 Control Device
      bInterfaceProtocol     32
      iInterface              3
      AudioControl Interface Descriptor:
        bLength                 9
        bDescriptorType        36
        bDescriptorSubtype      1 (HEADER)
        bcdADC               2.00
        bCategory               8
        wTotalLength       0x00a7
        bmControls           0x00
      AudioControl Interface Descriptor:
        bLength                 8
        bDescriptorType        36
        bDescriptorSubtype     10 (CLOCK_SOURCE)
        bClockID               41
        bmAttributes            3 Internal programmable clock
        bmControls           0x07
          Clock Frequency Control (read/write)
          Clock Validity Control (read-only)
        bAssocTerminal          0
        iClockSource            9
      AudioControl Interface Descriptor:
        bLength                 8
        bDescriptorType        36
        bDescriptorSubtype     11 (CLOCK_SELECTOR)
        bClockID               40
        bNrInPins               1
        baCSourceID(0)         41
        bmControls           0x03
          Clock Selector Control (read/write)
        iClockSelector          8
      AudioControl Interface Descriptor:
        bLength                17
        bDescriptorType        36
        bDescriptorSubtype      2 (INPUT_TERMINAL)
        bTerminalID             2
        wTerminalType      0x0101 USB Streaming
        bAssocTerminal          0
        bCSourceID             40
        bNrChannels             8
        bmChannelConfig    0x00000000
        iChannelNames          19
        bmControls         0x0000
        iTerminal               6
      AudioControl Interface Descriptor:
        bLength                42
        bDescriptorType        36
        bDescriptorSubtype      6 (FEATURE_UNIT)
        bUnitID                10
        bSourceID               2
        bmaControls(0)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(1)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(2)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(3)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(4)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(5)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(6)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(7)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(8)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        iFeature                0
      AudioControl Interface Descriptor:
        bLength                12
        bDescriptorType        36
        bDescriptorSubtype      3 (OUTPUT_TERMINAL)
        bTerminalID            20
        wTerminalType      0x0301 Speaker
        bAssocTerminal          0
        bSourceID              10
        bCSourceID             40
        bmControls         0x0000
        iTerminal               0
      AudioControl Interface Descriptor:
        bLength                17
        bDescriptorType        36
        bDescriptorSubtype      2 (INPUT_TERMINAL)
        bTerminalID             1
        wTerminalType      0x0201 Microphone
        bAssocTerminal          0
        bCSourceID             40
        bNrChannels             8
        bmChannelConfig    0x00000000
        iChannelNames          19
        bmControls         0x0000
        iTerminal               0
      AudioControl Interface Descriptor:
        bLength                42
        bDescriptorType        36
        bDescriptorSubtype      6 (FEATURE_UNIT)
        bUnitID                11
        bSourceID               1
        bmaControls(0)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(1)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(2)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(3)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(4)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(5)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(6)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(7)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        bmaControls(8)     0x0000000f
          Mute Control (read/write)
          Volume Control (read/write)
        iFeature                0
      AudioControl Interface Descriptor:
        bLength                12
        bDescriptorType        36
        bDescriptorSubtype      3 (OUTPUT_TERMINAL)
        bTerminalID            22
        wTerminalType      0x0101 USB Streaming
        bAssocTerminal          0
        bSourceID              11
        bCSourceID             40
        bmControls         0x0000
        iTerminal               7
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        1
      bAlternateSetting       0
      bNumEndpoints           0
      bInterfaceClass         1 Audio
      bInterfaceSubClass      2 Streaming
      bInterfaceProtocol     32
      iInterface              4
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        1
      bAlternateSetting       1
      bNumEndpoints           2
      bInterfaceClass         1 Audio
      bInterfaceSubClass      2 Streaming
      bInterfaceProtocol     32
      iInterface              4
      AudioStreaming Interface Descriptor:
        bLength                16
        bDescriptorType        36
        bDescriptorSubtype      1 (AS_GENERAL)
        bTerminalLink           2
        bmControls           0x00
        bFormatType             1
        bmFormats          0x00000001
          PCM
        bNrChannels             8
        bmChannelConfig    0x00000000
        iChannelNames          11
      AudioStreaming Interface Descriptor:
        bLength                 6
        bDescriptorType        36
        bDescriptorSubtype      2 (FORMAT_TYPE)
        bFormatType             1 (FORMAT_TYPE_I)
        bSubslotSize            4
        bBitResolution         24
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x01  EP 1 OUT
        bmAttributes            5
          Transfer Type            Isochronous
          Synch Type               Asynchronous
          Usage Type               Data
        wMaxPacketSize     0x0400  1x 1024 bytes
        bInterval               1
        AudioStreaming Endpoint Descriptor:
          bLength                 8
          bDescriptorType        37
          bDescriptorSubtype      1 (EP_GENERAL)
          bmAttributes         0x00
          bmControls           0x00
          bLockDelayUnits         2 Decoded PCM samples
          wLockDelay         0x0008
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x81  EP 1 IN
        bmAttributes           17
          Transfer Type            Isochronous
          Synch Type               None
          Usage Type               Feedback
        wMaxPacketSize     0x0004  1x 4 bytes
        bInterval               4
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        2
      bAlternateSetting       0
      bNumEndpoints           0
      bInterfaceClass         1 Audio
      bInterfaceSubClass      2 Streaming
      bInterfaceProtocol     32
      iInterface              5
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        2
      bAlternateSetting       1
      bNumEndpoints           1
      bInterfaceClass         1 Audio
      bInterfaceSubClass      2 Streaming
      bInterfaceProtocol     32
      iInterface              5
      AudioStreaming Interface Descriptor:
        bLength                16
        bDescriptorType        36
        bDescriptorSubtype      1 (AS_GENERAL)
        bTerminalLink          22
        bmControls           0x00
        bFormatType             1
        bmFormats          0x00000001
          PCM
        bNrChannels             8
        bmChannelConfig    0x00000000
        iChannelNames          19
      AudioStreaming Interface Descriptor:
        bLength                 6
        bDescriptorType        36
        bDescriptorSubtype      2 (FORMAT_TYPE)
        bFormatType             1 (FORMAT_TYPE_I)
        bSubslotSize            4
        bBitResolution         24
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x82  EP 2 IN
        bmAttributes            5
          Transfer Type            Isochronous
          Synch Type               Asynchronous
          Usage Type               Data
        wMaxPacketSize     0x0400  1x 1024 bytes
        bInterval               1
        AudioStreaming Endpoint Descriptor:
          bLength                 8
          bDescriptorType        37
          bDescriptorSubtype      1 (EP_GENERAL)
          bmAttributes         0x00
          bmControls           0x00
          bLockDelayUnits         2 Decoded PCM samples
          wLockDelay         0x0008
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        3
      bAlternateSetting       0
      bNumEndpoints           0
      bInterfaceClass       254 Application Specific Interface
      bInterfaceSubClass      1 Device Firmware Update
      bInterfaceProtocol      1
      iInterface             10
      Device Firmware Upgrade Interface Descriptor:
        bLength                             9
        bDescriptorType                    33
        bmAttributes                        7
          Will Not Detach
          Manifestation Tolerant
          Upload Supported
          Download Supported
        wDetachTimeout                    250 milliseconds
        wTransferSize                      64 bytes
        bcdDFUVersion                   1.10

pacmd list-sources inputs:
   index: 16
        name: <alsa_output.usb-M-Audio_M-Track_Eight-00.analog-surround-71.monitor>
        driver: <module-alsa-card.c>
        flags: DECIBEL_VOLUME LATENCY DYNAMIC_LATENCY
        state: RUNNING
        suspend cause: (none)
        priority: 1040
        volume: front-left: 65536 / 100% / 0.00 dB,   front-right: 65536 / 100% / 0.00 dB,   rear-left: 65536 / 100% / 0.00 dB,   rear-right: 65536 / 100% / 0.00 dB,   front-center: 65536 / 100% / 0.00 dB,   lfe: 65536 / 100% / 0.00 dB,   side-left: 65536 / 100% / 0.00 dB,   side-right: 65536 / 100% / 0.00 dB
                balance 0.00
        base volume: 65536 / 100% / 0.00 dB
        volume steps: 65537
        muted: no
        current latency: 0.00 ms
        max rewind: 11 KiB
        sample spec: s32le 8ch 44100Hz
        channel map: front-left,front-right,rear-left,rear-right,front-center,lfe,side-left,side-right
                     Surround 7.1
        used by: 5
        linked by: 5
        configured latency: 40.00 ms; range is 8.00 .. 743.04 ms
        monitor_of: 7
        card: 5 <alsa_card.usb-M-Audio_M-Track_Eight-00>
        module: 27
        properties:
                device.description = "Monitor of M-Track Eight Analog Surround 7.1"
                device.class = "monitor"
                alsa.card = "2"
                alsa.card_name = "M-Track Eight"
                alsa.long_card_name = "M-Audio M-Track Eight at usb-0000:00:14.0-5.4, high speed"
                alsa.driver_name = "snd_usb_audio"
                device.bus_path = "pci-0000:00:14.0-usb-0:5.4:1.0"
                sysfs.path = "/devices/pci0000:00/0000:00:14.0/usb1/1-5/1-5.4/1-5.4:1.0/sound/card2"
                udev.id = "usb-M-Audio_M-Track_Eight-00"
                device.bus = "usb"
                device.vendor.id = "0763"
                device.vendor.name = "M-Audio"
                device.product.id = "4003"
                device.product.name = "M-Track Eight"
                device.serial = "M-Audio_M-Track_Eight"
                device.string = "2"
                module-udev-detect.discovered = "1"
                device.icon_name = "audio-card-usb"

Here is a recording:
parecord -r --format=s24le --file-format=wav ./foo.wav

file ./foo.wav

./foo.wav: RIFF (little-endian) data, WAVE audio, Microsoft PCM, 24 bit, stereo 44100 Hz

The sound is from the mic and is clipped on the device (vu-meter red bar is shown).

A: I don't see anything obvious, but two ideas:

*

*The USB device has two configurations, though from the information displayed about them, they seem to be identical. So I do not know what they are for. You could try to switch to the other one (with usb_modeswitch, unload kernel modules first) and see if that changes anything

*You are streaming 24 bits in 4 bytes, if I read the descriptors correctly. If the generic USB Audio driver picks out the wrong 3 bytes, you could end up with a most significant byte of zero, which would restrict the level to 12.5% (matching your observed 15%).
You can verify this by recording (e.g. parecord) to some file (WAV or raw) in 24-bit format, and examining it with a hex editor. If the MSB of all samples is zero, even when you produce a volume that clips on Mac or Windows, that would make this very likely.
In addition, you can use wireshark to capture the USB packets, so you can compare if they do have an additional third byte in the samples that doesn't make it into the recorded data.
In that case, it's a bug in the driver, so please file a bug report on the ALSA kernel list.

Quick excurse on use cases: Normally people buy something like the M-track 8 to record with multiple mics, e.g. a band where ever member has one or two mics (vocals + instrument). In that case, you'd just get all 8 channels from Pulseaudio (disabling downmixing), and your DAW would select which channels you'd actually record.
Often you'd even completely disable Pulseaudio for that, as it only adds latency, and go directly to ALSA, or use Jack instead of Pulseaudio.

"I want my laptop to play into my 7.1 surround speakers or my stereo headphone. Then if I make a conference call, I just want people to hear me.

Ok, so you have a single mic, and that's all you have in the use case. You also want to keep Pulseaudio, as you don't have latency issues, and you are using the 8 channels mainly for output.
So have a look at the module-remap-source and do something like
load-module module-remap-source master=alsa_input.usb-MTRACK.analog-stereo channels=1 master_channel_map=front-left channel_map=mono

where front-left is the channel you have your mic on, and MTRACK is replaced with the actual name of your M-Track source (use e.g. pactl list short). Then record from the new source.
If the only actual problem was that Pulseaudio was downmixing all 8 channels to stereo and reducing the level with that, the you should be good now.
If there's still another problem, please test recording all 8 channels without Pulseaudio and only with ALSA as described in the comments, so we can rule out Pulseaudio and see if the problem is in the ALSA drivers.


text:
Q: Downloading pdf files using mechanize and urllib I am new to Python, and my current task is to write a web crawler that looks for PDF files in certain webpages and downloads them. Here's my current approach (just for 1 sample url):
import mechanize
import urllib
import sys

mech = mechanize.Browser()
mech.set_handle_robots(False)

url = "http://www.xyz.com"

try:
    mech.open(url, timeout = 30.0)
except HTTPError, e:
    sys.exit("%d: %s" % (e.code, e.msg))

links = mech.links()

for l in links:
    #Some are relative links
    path = str(l.base_url[:-1])+str(l.url)
    if path.find(".pdf") > 0:
       urllib.urlretrieve(path)

The program runs without any errors, but I am not seeing the pdf being saved anywhere. I am able to access the pdf and save it through my browser. Any ideas what's going on? I am using pydev (eclipse based) as my development environment, if that makes any difference.
Another question is if I want give the pdf a specific name while saving it, how can I do that? Is this approach correct? Do I have to create a file with 'filename' before I can save the PDF?
urllib.urlretrieve(path, filename)

Thanks in advance.

A: The documentation for urllib says this about the urlretrieve function:

The second argument, if present, specifies the file location to copy
  to (if absent, the location will be a tempfile with a generated name).

The function's return value has the location of the file:

Return a tuple (filename, headers) where filename is the local file
  name under which the object can be found, and headers is whatever the
  info() method of the object returned by urlopen() returned (for a
  remote object, possibly cached).

So, change this line:
urllib.urlretrieve(path)

to this:
(filename, headers) = urllib.urlretrieve(path)

and the path in filename will have the location. Optionally, pass in the filename argument to urlretrieve to specify the location yourself.

A: I've never used mechanize, but from the documentation for urllib at http://docs.python.org/library/urllib.html:

urllib.urlretrieve(url[, filename[, reporthook[, data]]])
Copy a network object denoted by a URL to a local file, if
  necessary. If the URL points to a local file, or a valid cached copy
  of the object exists, the object is not copied. Return a tuple
  (filename, headers) where filename is the local file name under which
  the object can be found, and headers is whatever the info() method of
  the object returned by urlopen() returned (for a remote object,
  possibly cached). Exceptions are the same as for urlopen().

As you can see the urlretrieve function saves to a temporary file if you don't specify one.  So try specifying the filename as you suggested in your second piece of code.  Otherwise you could call urlretrieve like this:
    saved_filename,headers = urllib.urlretrieve(path)

and then use saved_filename later on.

redpajama_set_name: RedPajamaStackExchange


text:
Q: WhatsApp use only html to share url link by a descriptive text I want to enable my website users to share the current web page url (stored in ViewBag.OgUrl) via WhatsApp.
The WhatsApp message should contain the url title (stored in ViewBag.OgTitle) which, when clicked, will open the url (stored in ViewBag.OgUrl).
This needs to be done by html without js.
The standard way is:
 @{
    var urlWhatsapp = "whatsapp://send?text=" + @ViewBag.OgUrl;
  }

And then simply:
 WhatsApp Share

This works fine apart from the fact that the actual url is shared and not the title.
For example, a WhatsApp message contains the actual link http://example.org/ while I would like it to show in WhatsApp:
First example
Edit: If one wants to get the title and the link just replace the code with:
  @{var urlWhatsapp = "whatsapp://send?text=" + @ViewBag.OgTitle + " - " + @ViewBag.OgUrl;}

If one waits after the sharing, but before actually sending the message to the recipient, a clickable box appears above the original message (as would be for any whatsapp link with what is defined in the url - an image, text etc. according - see the example below)

A: It is not possible to share a link on WhatsApp the way you want to. You can only send a message with the full link like http://example.org/ and WhatsApp will detect this as a link for you.

A: the question asked about an html based procedure (no js)
The answer is that at this time, it is possible to send text + a link to be identified by WhatsApp.
it is not possible to send only a title which, when clicked, will be linked to the url itself.
The syntax in the html is:
    @{var urlWhatsapp = "whatsapp://send?text=" + @ViewBag.OgTitle + " - " + @ViewBag.OgUrl;}

where the @ViewBag.OgTitle is the title and the @ViewBag.OgUrl is the full url (including http:// or https://)

A: Try:

Where 0000000000 will be your 10 digit mobile no. and text= will be your predefined message.

A: You have two options to send messages to Whatsapp from a link on your site.
The first one...
 +55 (79) XXXXX-XXXX

The second, with predefined text...
 +55 (79) XXXXX-XXXX

*

*You don't need to put "+" (plus) in your number.

*To do spaces in the text, you need to use "%20" between words.


text:
Q: Upload A file to a ASP.NET WebService To send a File in AJAX request i used the way mentioned here . How do i write the WebMethod to accept the file?

A: The post & link provided gives a number of key points, please find them below:

*

*The action being done is a post

*The format of the object being sent is json

*As your tag's are .net & web-services, you are interested in a solution on Microsoft Stack.

*You use the term WebMethod, so you do not want to do this transaction via web api or WCF

See link for details for "Send and Receive JSON objects to Web Service Methods using jQuery AJAX in ASP.Net"


text:
Q: Scala-IDE or Scala unjustified syntax ambiguity I am learning Scala with Scala-IDE in Eclipse. While following the Chapter 9: Control Abstraction, part 1: Reducing Code Duplication in the Programming in Scala book, I have written the code from the book (fully represented below), it worked fine! When I started removing the unnecessary blank lines, a strange thing happened. Here is the entire code before the removal of the blank lines in the filterFiles() method:
object Code_c09s01_ControlAbstraction extends App{

  object FilesFilter {

    private def filterFiles(path: String, pattern: String, matcher: (String, String) => Boolean) = {

      val files = (new java.io.File(path)) listFiles

      for(file <- files if matcher(file.getName, pattern)) yield file
    }

    def filterExtension(path: String, pattern: String) = filterFiles(path, pattern, _.endsWith(_))
    def filterName(path: String, pattern: String) = filterFiles(path, pattern, _.contains(_))
    def filterRegex(path: String, pattern: String) = filterFiles(path, pattern, _.matches(_))
  }

  def printArray[A](message: String, arr: Array[A]) {
    println (message)
    println (arr mkString("\n"))
  }

  def test() {
    val path = "C:\\";

    printArray("--- filtering by ext: ---", FilesFilter.filterExtension(path, ".txt"))
    printArray("--- filtering by containment: ---", FilesFilter.filterName(path, "1"))
    printArray("--- filtering by regex: ---", FilesFilter.filterRegex(path, "."))
  }

  test

}

which works just fine! However, after removing the blank lines from the filterFiles() method, the method now looks like this:
private def filterFiles(path: String, pattern: String, matcher: (String, String) => Boolean) = {
  val files = (new java.io.File(path)) listFiles
  for(file <- files if matcher(file.getName, pattern)) yield file
}

And the IDE gives me errors on both lines of the body. The error of the first line says:
ambiguous reference to overloaded definition, both method listFiles in class File of type (x$1: java.io.FileFilter)Array[java.io.File] and method listFiles in class File of type
 (x$1: java.io.FilenameFilter)Array[java.io.File] match argument types (Null)

the error on the second line says:
illegal start of simple expression

and all the three calls to the printArray() in the test() method now also tell this:
type mismatch; found : Unit required: Array[?]

What does it all mean? Scala is not supposed to behave like Python when code alignment can ruin the code flow... so how come that removing the blank line between the first and the second line of the body of the filterFiles() method puts up such a serious error? Is it a bug somewhere or does it follow directly from the rules of Scala? Note: if I add ; between the line, it sorts everything out. Is it just semicolon inference bug?

A: When object's method can none or single argument you can call it like
val files = object method arg

or, in your snippet
val files = object method
  arg

In your code compiler wants to call listfiles with an for expression as an agument which returns Array[File]. And complains that listFiles hasn't implementation with this type of argument. Empty line prevents treating for expression as a parameter for listFiles function

A: Looks like semicolon inference problem as you suggest, I guess the compiler expects method arguments if you leave parenthesis out. Instead of semicolon, you can add parenthesis after listFiles:
val files = (new java.io.File(path)) listFiles ()


text:
Q: How To Create a Flexible Plug-In Architecture? A repeating theme in my development work has been the use of or creation of an in-house plug-in architecture.  I've seen it approached many ways - configuration files (XML, .conf, and so on), inheritance frameworks, database information, libraries, and others.  In my experience:

*

*A database isn't a great place to store your configuration information, especially co-mingled with data

*Attempting this with an inheritance hierarchy requires knowledge about the plug-ins to be coded in, meaning the plug-in architecture isn't all that dynamic

*Configuration files work well for providing simple information, but can't handle more complex behaviors

*Libraries seem to work well, but the one-way dependencies have to be carefully created.

As I seek to learn from the various architectures I've worked with, I'm also looking to the community for suggestions.  How have you implemented a SOLID plug-in architecture?  What was your worst failure (or the worst failure you've seen)?  What would you do if you were going to implement a new plug-in architecture?  What SDK or open source project that you've worked with has the best example of a good architecture?
A few examples I've been finding on my own:

*

*Perl's Module::Plugable and IOC for dependency injection in Perl

*The various Spring frameworks (Java, .NET, Python) for dependency injection.

*An SO question with a list for Java (including Service Provider Interfaces)

*An SO question for C++ pointing to a Dr. Dobbs article

*An SO question regarding a specific plugin idea for ASP.NET MVC

These examples seem to play to various language strengths.  Is a good plugin architecture necessarily tied to the language?  Is it best to use tools to create a plugin architecture, or to do it on one's own following models?

A: This is not an answer as much as a bunch of potentially useful remarks/examples.

*

*One effective way to make your application extensible is to expose its internals as a scripting language and write all the top level stuff in that language. This makes it quite modifiable and practically future proof (if your primitives are well chosen and implemented). A success story of this kind of thing is Emacs. I prefer this to the eclipse style plugin system because if I want to extend functionality, I don't have to learn the API and write/compile a separate plugin. I can write a 3 line snippet in the current buffer itself, evaluate it and use it. Very smooth learning curve and very pleasing results.

*One application which I've extended a little is Trac. It has a component architecture which in this situation means that tasks are delegated to modules that advertise extension points. You can then implement other components which would fit into these points and change the flow. It's a little like Kalkie's suggestion above.

*Another one that's good is py.test. It follows the "best API is no API" philosophy and relies purely on hooks being called at every level. You can override these hooks in files/functions named according to a convention and alter the behaviour. You can see the list of plugins on the site to see how quickly/easily they can be implemented.
A few general points.

*

*Try to keep your non-extensible/non-user-modifiable core as small as possible. Delegate everything you can to a higher layer so that the extensibility increases. Less stuff to correct in the core then in case of bad choices.

*Related to the above point is that you shouldn't make too many decisions about the direction of your project at the outset. Implement the smallest needed subset and then start writing plugins.

*If you are embedding a scripting language, make sure it's a full one in which you can write general programs and not a toy language just for your application.

*Reduce boilerplate as much as you can. Don't bother with subclassing, complex APIs, plugin registration and stuff like that. Try to keep it simple so that it's easy and not just possible to extend. This will let your plugin API be used more and will encourage end users to write plugins. Not just plugin developers. py.test does this well. Eclipse as far as I know, does not.

A: I once worked on a project that had to be so flexible in the way each customer could setup the system, which the only good design we found was to ship the customer a C# compiler!
If the spec is filled with words like:

*

*Flexible

*Plug-In

*Customisable

Ask lots of questions about how you will support the system (and how support will be charged for, as each customer will think their case is the normal case and should not need any plug-ins.), as in my experience

The support of customers (or
  fount-line support people) writing
  Plug-Ins is a lot harder than the
  Architecture

A: Usualy I use MEF. The Managed Extensibility Framework (or MEF for short) simplifies the creation of extensible applications. MEF offers discovery and composition capabilities that you can leverage to load application extensions.
If you are interested read more...

A: In my experience, the two best ways to create a flexible plugin architecture are scripting languages and libraries. These two concepts are in my mind orthogonal; the two can be mixed in any proportion, rather like functional and object-oriented programming, but find their greatest strengths when balanced. A library is typically responsible for fulfilling a specific interface with dynamic functionality, whereas scripts tend to emphasise functionality with a dynamic interface.
I have found that an architecture based on scripts managing libraries seems to work the best. The scripting language allows high-level manipulation of lower-level libraries, and the libraries are thus freed from any specific interface, leaving all of the application-level interaction in the more flexible hands of the scripting system.
For this to work, the scripting system must have a fairly robust API, with hooks to the application data, logic, and GUI, as well as the base functionality of importing and executing code from libraries. Further, scripts are usually required to be safe in the sense that the application can gracefully recover from a poorly-written script. Using a scripting system as a layer of indirection means that the application can more easily detach itself in case of Something Bad™.
The means of packaging plugins depends largely on personal preference, but you can never go wrong with a compressed archive with a simple interface, say PluginName.ext in the root directory.

A: I think you need to first answer the question: "What components are expected to be plugins?"
You want to keep this number to an absolute minimum or the number of combinations which you must test explodes.  Try to separate your core product (which should not have too much flexibility) from plugin functionality.
I've found that the IOC (Inversion of Control) principal (read springframework) works well for providing a flexible base, which you can add specialization to to make plugin development simpler.

*

*You can scan the container for the "interface as a plugin type advertisement" mechanism.

*You can use the container to inject common dependencies which plugins may require (i.e. ResourceLoaderAware or MessageSourceAware).

A: In my experience I've found there are really two types of plug-in Architectures.

*

*One follows the Eclipse model which is meant to allow for freedom and is open-ended.

*The other usually requires plugins to follow a narrow API because the plugin will fill a specific function.

To state this in a different way, one allows plugins to access your application while the other allows your application to access plugins.
The distinction is subtle, and sometimes there is no distiction... you want both for your application.
I do not have a ton of experience with Eclipse/Opening up your App to plugins model (the article in Kalkie's post is great). I've read a bit on the way eclipse does things, but nothing more than that.
Yegge's properties blog talks a bit about how the use of the properties pattern allows for plugins and extensibility.
Most of the work I've done has used a plugin architecture to allow my app to access plugins, things like time/display/map data, etc.
Years ago I would create factories, plugin managers and config files to manage all of it and let me determine which plugin to use at runtime.

*

*Now I usually just have a DI framework do most of that work.

I still have to write adapters to use third party libraries, but they usually aren't that bad.

A: One of the best plug-in architectures that I have seen is implemented in Eclipse. Instead of having an application with a plug-in model, everything is a plug-in. The base application itself is the plug-in framework.
http://www.eclipse.org/articles/Article-Plug-in-architecture/plugin_architecture.html

A: I'll describe a fairly simple technique that I have use in the past.  This approach uses C# reflection to help in the plugin loading process.  This technique can be modified so it is applicable to C++ but you lose the convenience of being able to use reflection.
An IPlugin interface is used to identify classes that implement plugins.  Methods are added to the interface to allow the application to communicate with the plugin.  For example the Init method that the application will use to instruct the plugin to initialize.
To find plugins the application scans a plugin folder for .Net assemblies.  Each assembly is loaded.  Reflection is used to scan for classes that implement IPlugin.  An instance  of each plugin class is created.
(Alternatively, an Xml file might list the assemblies and classes to load.  This might help performance but I never found an issue with performance).
The Init method is called for each plugin object.  It is passed a reference to an object that implements the application interface: IApplication (or something else named specific to your app, eg ITextEditorApplication).
IApplication contains methods that allows the plugin to communicate with the application.  For instance if you are writing a text editor this interface would have an OpenDocuments property that allows plugins to enumerate the collection of currently open documents.
This plugin system can be extended to scripting languages, eg Lua, by creating a derived plugin class, eg LuaPlugin that forwards IPlugin functions and the application interface to a Lua script.
This technique allows you to iteratively implement your IPlugin, IApplication and other application-specific interfaces during development.  When the application is complete and nicely refactored you can document your exposed interfaces and you should have a nice system for which users can write their own plugins.

A: The Plug-in Pattern is a software pattern for extending the behaviour of a class with a clean interface. Often behaviour of classes is extended by class inheritance, where the derived class overwrites some of the virtual methods of the class. A problem with this solution is that it conflicts with implementation hiding. It also leads to situations where derived class become a gathering places of unrelated behaviour extensions. Also, scripting is used to implement this pattern as mentioned above "Make internals as a scripting language and write all the top level stuff in that language. This makes it quite modifiable and practically future proof". Libraries use script managing libraries. The scripting language allows high-level manipulation of lower level libraries. (Also as mentioned above)


text:
Q: A number turn into a vector in R and the answer turn out to be the sum of components of the vector UrnA =rep(c(10,5,1),c(5,5,5))
UrnB =rep(c(20,5,1),c(9,3,3))
n=1e3
sum=0
for( i in 1:n ){
  dice=sample(1:6,1)
  sum=sum+(dice<=4)*sample(UrnA,2,replace = FALSE)+(dice>=5)*sample(UrnB,2,replace = FALSE)
}
E=sum/n

I want to use the sentences above to solve the problem below.
"Urn A contains 5 $10 bills, 5 $5 bills, and 5 $1 bills.
    Urn B contains 9 $20 bills, 3 $5 bills, and 3 $1 bills.
A dice is thrown.  If it lands on 1,2,3, or 4, two bills are drawn from Urn A (without replacement),
Otherwise two bills are drawn from Urn B.   Let X = the total value of the bills drawn.
(a) Use simulations to estimate E[X]."
And the problem is that,when I run the sentence the sum turn out to be a array with two components which really makes me confused.And I calculate it myself and the sum of each components of sum turn out to be the right answer . enter image description here

A: You can avoid the for loop if you consider that rolling a single die n times is the same as rolling n dice once.
UrnA <- rep(c(10,5,1), c(5,5,5))
UrnB <- rep(c(20,5,1), c(9,3,3))
n <- 1e3

set.seed(2018);
sum(as.integer(sapply(sample(1:6, n, replace = T), function(x)
    if (x <= 4) sample(UrnA, 2) else sample(UrnB, 2))))
#[1] 15818

I'm using a fixed seed here for reproducibility; remove if necessary.

We can confirm convergence by repeating the process 1000 times
val <- sapply(1:1000, function(x)
    sum(as.integer(sapply(sample(1:6, n, replace = T), function(x)
        if (x <= 4) sample(UrnA, 2) else sample(UrnB, 2)))))
ggplot(data.frame(idx = 1:1000, val = val), aes(idx, val)) +
    geom_point() +
    ylim(0, pretty(max(val))[2])

A: Both your sample function will return a set of two values. You need to sum their components.
# Instead of
sum=sum+(dice<=4)*sample(UrnA,2,replace = FALSE)+(dice>=5)*sample(UrnB,2,replace = FALSE)
#Use:
sum=sum+sum((dice<=4)*sample(UrnA,2,replace = FALSE)+(dice>=5)*sample(UrnB,2,replace = FALSE))


text:
Q: Usage of multimap with next_permutation c++ i am just trying to implement Knapsack Problem in a Naive way to stress test my original solution.
MY CODE
double StressTest(multimap<int, int> ValWt, int KnapscakWeight)
{
    vector<double> TotalValue;
    double Temp_KnapsackWeight = 0.0;
    double Value = 0.0;
    multimap<int, int>::iterator itr1;// = ValWt.begin();

    do
    {
        itr1 = ValWt.begin();
        Temp_KnapsackWeight = KnapscakWeight;
        while( (Temp_KnapsackWeight > 0) && (itr1 != ValWt.end()) )
        {
            if(itr1->second > Temp_KnapsackWeight)
            {
                Value += ( (Temp_KnapsackWeight/itr1->second) * itr1->first );
                Temp_KnapsackWeight = 0;
            }

            else
            {
                Temp_KnapsackWeight -= itr1->second;
                Value += itr1->first;
            }
            itr1++;
        }

        TotalValue.push_back(Value);
        Value = 0.0;

    }while( next_permutation(ValWt.begin(), ValWt.end()) );

    return *max_element(TotalValue.begin(), TotalValue.end());
}

ERROR
In file included from /usr/include/c++/7/bits/char_traits.h:39:0,
                 from /usr/include/c++/7/ios:40,
                 from /usr/include/c++/7/ostream:38,
                 from /usr/include/c++/7/iostream:39,
                 from 2_max_val_of_loot.cpp:1:
/usr/include/c++/7/bits/stl_algobase.h: In instantiation of 'void std::iter_swap(_ForwardIterator1, _ForwardIterator2) [with _ForwardIterator1 = std::_Rb_tree_iterator<std::pair<const int, int> >; _ForwardIterator2 = std::_Rb_tree_iterator<std::pair<const int, int> >]':
/usr/include/c++/7/bits/stl_algo.h:2926:22:   required from 'bool std::__next_permutation(_BidirectionalIterator, _BidirectionalIterator, _Compare) [with _BidirectionalIterator = std::_Rb_tree_iterator<std::pair<const int, int> >; _Compare = __gnu_cxx::__ops::_Iter_less_iter]'
/usr/include/c++/7/bits/stl_algo.h:2966:2:   required from 'bool std::next_permutation(_BIter, _BIter) [with _BIter = std::_Rb_tree_iterator<std::pair<const int, int> >]'
2_max_val_of_loot.cpp:39:53:   required from here
/usr/include/c++/7/bits/stl_algobase.h:148:11: error: use of deleted function 'typename std::enable_if<(! std::__and_<std::__is_swappable<_T1>, std::__is_swappable<_T2> >::value)>::type std::swap(std::pair<_T1, _T2>&, std::pair<_T1, _T2>&) [with _T1 = const int; _T2 = int; typename std::enable_if<(! std::__and_<std::__is_swappable<_T1>, std::__is_swappable<_T2> >::value)>::type = void]'
       swap(*__a, *__b);
       ~~~~^~~~~~~~~~~~
In file included from /usr/include/c++/7/bits/stl_algobase.h:64:0,
                 from /usr/include/c++/7/bits/char_traits.h:39,
                 from /usr/include/c++/7/ios:40,
                 from /usr/include/c++/7/ostream:38,
                 from /usr/include/c++/7/iostream:39,
                 from 2_max_val_of_loot.cpp:1:
/usr/include/c++/7/bits/stl_pair.h:503:5: note: declared here
     swap(pair<_T1, _T2>&, pair<_T1, _T2>&) = delete;

MY OBSERVATION

*

*next_permutation() is creating error, but why i don't understand why.

*next_permutation() requires bidirectional iterator and multimap iterator is a bidirectional iterator.

*I doubt as multimap are sorted always, that's why the error is shown ??
Please Help.
Thanking You.

A: You cannot use std::map or std::multimap (or unordered versions) as std::next_permutation requires:
-BidirIt must meet the requirements of ValueSwappable and LegacyBidirectionalIterator.

but std::multimap values are not swappable as key in the map is not mutable:

value_type std::pair<const Key, T>

(emphasis is mine)
Less formally order of elements in map is determined and cannot me changed. You have to use different container like std::vector to perform this operation.


text:
Q: How run/debug website which includes ReactJS components, but are included through their compiled javascript files I am a beginner in ReactJS, webpacks, NodeJS. I have a website which includes two main react components. These components are not directly included in the website, they are first built to produce .js files and then included like this:
1) In index.html file there is a search component in react and included to the .html file like this at the end of the file
<script src="assets/build/search.min.js"></script>

2) In post.html, same thing is happening:
<script src="assets/build/post.min.js"></script>

When I try to run this simply through index.html all the website works except the react components. I need a way to run and debug this on my local machine. Please advise.


text:
Q: How to create a SET-like type on postgresql I would like to create a column of week days such that we can select more then only one day.
I know the enum type can do that, but it can only contain one item.
How can I create a datatype in PostgreSQL such that I can have something that fuctions like a multiple-choice enum, just like a set on MySQL?

A: Use the HSTORE column type. HSTORE stores key/value pairs. You can use null values if you only care about checking if a key exists.
See https://www.postgresql.org/docs/current/static/hstore.html.
For example, to ask Is 'x' in my hstore?, do
CREATE EXTENSION HSTORE;  --create extension only has to be done once
SELECT * FROM 'x=>null,y=>null,z=>null'::HSTORE ? 'x';

I believe this is operation is O(1). In contrast, checking for containment in an ARRAY-type column, is O(n).

A: I guess an array is the closest match to the dreaded set data type.
But that solution is not normalized, and you will probably run into several issues because of that. I'd recommend to store that in a properly normalized table, especially if you plan to query on the selected values or do other reporting on that.

A: Bit Strings BIT(n) are the closest PostgreSQL has to MySQL's SET types.
For days of the week, use BIT(7).
Unlike MySQL's SET, the width of a BIT type is not constrained to 64 bits or less.


text:
Q: How to scale down the values so they could fit inside the min and max values I have 6 graph bars with the prices.
Each price number will represent its graphbar's height by respecting min and max heights.
What i want is that graph bar's height wouldn't go below or above the min and the max value.
So i have values of min = 55 and max = 110.
And price numbers are:

*

*49

*212

*717

*1081

*93

By which mathematical algorithm I could achieve expected results ?
It's some sort of dynamic scalable bar graphs.
Modified
So the min and max values from the price list will be: 49(min price) => 55(min) and 1081 (max price) => 110(max)

A: The solution is simple:

*

*Pick the smallest, and largest item and find the difference.

*(largest_item - smallest_item) maps to (max-min).

*Compute ratio = (max-min)/(largest_item-smallest_item)

*final_value = min_value + ratio*(value-smallest_item)
As a mathematical function:
f(x,max,min,largest,smallest) = min + (max-min)/(largest-smallest)*(x-smallest)
where:
x : Input item's price
max: Maximum value (here, 110)
min: Minimum value (here, 55)
largest: Largest item in input (Here, 1081)
smallest: Smallest item in input (Here, 49)

One check, as @amit correctly points out: Ensure largest and smallest item are distinct.

So let x = 93. We have other 4 values with us.
f(x,max,min,largest,smallest) = min + (max-min)/(largest-smallest)*(x-smallest)

value = 55  +   ((110-55)/(1081-49)) * (93-49)
value = 57.344961

Further,
f(93,110,55,1081,49) = 57.344961
f(49,110,55,1081,49) = 55
f(1081,110,55,1081,49) = 110

A: The function:
[(x - min ) / (max-min)*55] + 55

ensures the boundaries you are after - but you should also consider - what should the graph show? What do you want the reader to understand from it?
Why?

*

*(x-min) / (max-min) gives a number in range [0,1] - 0 for min,
1 for max.

*Multiplying it with 55 ensures a number in range [0,55].

*Adding 55 ensures a number in range [55,110] - as expected.

(*) Note: for max = min - the above fails because of division with 0, take care for these cases manually.


text:
Q: Compare elements of a tuple with a string Hi guys i have this tuple and when i print it :
for i in range(len(myresult)):
  print(myresult[i])

i get this results
('https://www.docenti.it',)
('www.feed.com',)
('feeeed.com',)

i would like to do somethik like
 for i in range(len(myresult)):
      if(myresult[i]=="www.feed.com")

But it doesn't work beacause of the  ",)" , i suppose , do you know how can i make it work ?

A: Its because each element of your tuple is itself a single-element tuple.
You could access that element directly by calling:
for i in range(len(myresult)):
    if myresult[i][0]=="www.feed.com":
        # put if-statement code here


text:
Q: How to run script after the CPack build step? I'd like to run a script after the 'package' target. add_custom_command with POST_BUILD doesn't work.
The make package command is expected to build, package and run the script. There should be no need for separate commands.


text:
Q: Unable to add magento-ecg/coding-standard to PHP_CodeSniffer: Unable to install magento-ecg/coding-standard to PHP_CodeSniffer:
Tried below command after cloning PHP_CodeSniffer from github:
phpcs --config-set installed_paths ./vendor/magento-ecg/coding-standard
But phpcs -i is showing only following standards.

The installed coding standards are PSR1, MySource, Zend, Squiz, PHPCS,
  PEAR and PSR2

A: facing the same problem solved it by
git clone https://github.com/magento-ecg/coding-standard
then added the complete path where you clone it
phpcs --config-set installed_paths /home/your_user/vendor/magento-ecg/coding-standard
End reuslt
phpcs -i
The installed coding standards are PSR1, PSR2, PEAR, MySource, PHPCS, Zend, Squiz, Ecg and EcgM2

A: i followed below steps in windows local system
first installed xammp

*

*cd C:\xampp\php

*pear install PHP_CodeSniffer
   pear install --alldeps PHP_CodeSniffer
(if there is any issue run cmd as Administrator)

phpcs -i

*then to follow Magento coding install  magento-ecg/coding-standard from composer

*after install it will be in C:\xampp\htdocs\magento217\vendor\magento-ecg\

*now run  (C:\xampp\php>)
phpcs --config-set installed_paths C:\xampp\htdocs\magento217\vendor\magento-ecg\coding-standard
now it will have all plugins need for M2
phpcs -i
The installed coding standards are PSR1, PSR2, PEAR, MySource, PHPCS, Zend, Squiz, Ecg and EcgM2
To test Module run below code
C:\xampp\php>phpcs C:\xampp\htdocs\magento217\app\code\NAMESPACE\MODULE_NAME

A: Install Magento coding standard using following approach

*

*composer require --dev magento/magento-coding-standard
when installed this way the Magento standard for phpcs cannot be added automatically. You can achieve this by adding the following to your project's composer.json
2.
 "scripts": {
    "post-install-cmd": [
      "([ $COMPOSER_DEV_MODE -eq 0 ] || vendor/bin/phpcs --config-set installed_paths ../../magento/magento-coding-standard/)"
    ],
    "post-update-cmd": [
      "([ $COMPOSER_DEV_MODE -eq 0 ] || vendor/bin/phpcs --config-set installed_paths ../../magento/magento-coding-standard/)"
    ]
}

For more information check https://github.com/magento/magento-coding-standard


text:
Q: How to create a sequence number based on database registers with concurrent users All this happens in a java web application, using JPA in the persistence layer.
I have entities A and B. A has many of B.
The user wanted a number to identify Bs, it would help them using the system. We used B's primary key for this purpose. The pk is a simple Oracle sequence.
After some time, the user didn't like the numbers generated. He would like B's numbers to be sequential, but in each instance of A.
Ex:
A 1  B1
A 1  B2
A 1  B3
A 2  B1
A 2  B2

and so on....
I had in mind this (naive) solution:
-Create a new colunm for the new B's number
-Create a unique clause with B's new number and A's FK.
-When creating a new instance of B, check the database for the last number of B given a instance of A.
-Since more than one user may create a instance of B, when inserting B, do a try catch. If more than one user inserts a B with the same number (for the same A instance), then catch the exception thrown from the database.
-If the exception was thrown, try to insert again with a new number.
The reason for my question is that I find this solution quite clumsy since it relies on the try-catch to do a new insertion when the concurrency problem happens. I believe there is a better way to deal with concurrency in this scenario, but I can't think of another way of solving it.

A: @Transactional
public void createB(informations){

    A a = informations.getA()
    session.get(A.class, a.getId(), LockMode.READ) //BD Lock here, no cluster, no Java

    //Only who got the lock first get here, anyone else waits for the lock release

    Long lastSequential = bService.findLastSequential()
    B newB = informations.getB()
    newB.setSequential(lastSequential + 1)
    session.persist(newB)

    //The lock is released when the transaction finishes and then the next
    //thread awaiting on the session.get may get a new lock and resume its
    //execution. That way only one thread at time will be able to execute
    //the critical area where the sequential is being created.
}

A: You're dealing with a rather unique situation here, I'd say...
if you really need to do this, try/catch/retry doesn't seem to be a good solution, since depending on the number of concurrent users, a single retry may result again in a DB failure and you'd have to retry again and the cycle goes on.
I guess you could try taking a look at surrogate keys for that. The "lookup tables" approach described here seems to be a good starting point for what you need: https://dba.stackexchange.com/questions/6108/should-every-table-have-a-single-field-surrogate-artificial-primary-key
There a few other articles/posts about hibernate and surrogate keys:
- Hibernate : Opinions in Composite PK vs Surrogate PK
- http://richmurnane.blogspot.de/2007/09/hibernate-and-surrogate-keys.html
Hope it helps!

A: The main catch you have the synchronization issue which can be handled many ways.

*

*Your sequence of B is dependent on the A id you are giving. So your query would be something like select max(B) from B where B.A = ?.

*Now let's say you got B10. Put the value of A on some collection, may be a map with A and max value of B. Use synchronization for getting/ adding a value from this map.

*Whenever you want a new A-B combination in the map, first check whether it is there. If there, wait and retry again after specified time to ensure you have the updated record.

*From point 2, after getting B10 as current, increment and insert B11 for corresponding A and delete the map entry, so the next thread will query and get B11 for that A.

Hope that helps.

A: If it's an option to use another column rather than PK, you could look at using a List with an @OrderColumn annotation which:

maintains a contiguous (non-sparse) ordering of the values of the
  order column

While zero based, it does have the advantage of being automatically updated to reflect any insertions, deletions etc.
https://docs.oracle.com/javaee/6/api/javax/persistence/OrderColumn.html


text:
Q: Dockerfile if else condition with external arguments I have dockerfile
FROM centos:7
ENV foo=42

then I build it
docker build -t my_docker .

and run it.
docker run -it -d  my_docker

Is it possible to pass arguments from command line and use it with if else in Dockerfile? I mean something like
FROM centos:7
if (my_arg==42)
     {ENV=TRUE}
else:
     {ENV=FALSE}

and build with this argument.
 docker build -t my_docker . --my_arg=42

A: Do not use build args described in other answers where at all possible.  This is an old messy solution.  Docker's target property solves for this issue.
Target Example
Dockerfile
FROM foo as base

RUN ...

# Build dev image
FROM base as image-dev

RUN ...
COPY ...

# Build prod image
FROM base as image-prod

RUN ...
COPY ...

docker build --target image-dev -t foo .

version: '3.4'

services:

  dev:
    build:
      context: .
      dockerfile: Dockerfile
      target: image-dev

Real World
Dockerfiles get complex in the real world.  Use buildkit & COPY --from for faster, more maintainable Dockerfiles:

*

*Docker builds every stage above the target, regardless of whether it is inherited or not.  Use buildkit to build only inherited stages. Docker must by v19+.  Hopefully this will be a default feature soon.

*Targets may share build stages.  Use COPY --from to simplify inheritance.

FROM foo as base
RUN ...
WORKDIR /opt/my-proj

FROM base as npm-ci-dev
# invalidate cache
COPY --chown=www-data:www-data ./package.json /opt/my-proj/package.json
COPY --chown=www-data:www-data ./package-lock.json /opt/my-proj/package-lock.json
RUN npm ci

FROM base as npm-ci-prod
# invalidate cache
COPY --chown=www-data:www-data ./package.json /opt/my-proj/package.json
COPY --chown=www-data:www-data ./package-lock.json /opt/my-proj/package-lock.json
RUN npm ci --only=prod

FROM base as proj-files
COPY --chown=www-data:www-data ./ /opt/my-proj

FROM base as image-dev
# Will mount, not copy in dev environment
RUN ...

FROM base as image-ci
COPY --from=npm-ci-dev /opt/my-proj .
COPY --from=proj-files /opt/my-proj .
RUN ...

FROM base as image-stage
COPY --from=npm-ci-prod /opt/my-proj .
COPY --from=proj-files /opt/my-proj .
RUN ...

FROM base as image-prod
COPY --from=npm-ci-prod /opt/my-proj .
COPY --from=proj-files /opt/my-proj .
RUN ...

Enable experimental mode.
sudo echo '{"experimental": true}' | sudo tee /etc/docker/daemon.json

Build with buildkit enabled.  Buildkit builds without cache by default - enable with --build-arg BUILDKIT_INLINE_CACHE=1
CI build job.
DOCKER_BUILDKIT=1 \
    docker build \
    --build-arg BUILDKIT_INLINE_CACHE=1 \
    --target image-ci\
    -t foo:ci
    .

Use cache from a pulled image with --cache-from
Prod build job
docker pull foo:ci
docker pull foo:stage

DOCKER_BUILDKIT=1 \
    docker build \
    --cache-from foo:ci,foo:stage \
    --target image-prod \
    -t prod
    .

A: Using Bash script and Alpine/Centos
Dockerfile
FROM alpine  #just change this to centos

ARG MYARG=""
ENV E_MYARG=$MYARG

ADD . /tmp
RUN chmod +x /tmp/script.sh && /tmp/script.sh

script.sh
#!/usr/bin/env sh

if [ -z "$E_MYARG" ]; then
    echo "NO PARAM PASSED"
else
    echo $E_MYARG
fi

Passing arg:
docker build -t test --build-arg MYARG="this is a test" .
....
Step 5/5 : RUN chmod +x /tmp/script.sh && /tmp/script.sh
 ---> Running in 10b0e07e33fc
this is a test
Removing intermediate container 10b0e07e33fc
 ---> f6f085ffb284
Successfully built f6f085ffb284

Without arg:
docker build -t test .
....
Step 5/5 : RUN chmod +x /tmp/script.sh && /tmp/script.sh
 ---> Running in b89210b0cac0
NO PARAM PASSED
Removing intermediate container b89210b0cac0
....

A: It might not look that clean but you can have your Dockerfile (conditional) as follow:
FROM centos:7
ARG arg
RUN if [[ -z "$arg" ]] ; then echo Argument not provided ; else echo Argument is $arg ; fi

and then build the image as:
docker build -t my_docker .  --build-arg arg=45
or
docker build -t my_docker .

A: From some reason most of the answers here didn't help me (maybe it's related to my FROM image in the Dockerfile)
So I preferred to create a bash script in my workspace combined with --build-arg in order to handle if statement while Docker build by checking if the argument is empty or not
Bash script:
#!/bin/bash -x

if test -z $1 ; then
    echo "The arg is empty"
    ....do something....
else
    echo "The arg is not empty: $1"
    ....do something else....
fi

Dockerfile:
FROM ...
....
ARG arg
COPY bash.sh /tmp/
RUN chmod u+x /tmp/bash.sh && /tmp/bash.sh $arg
....

Docker Build:
docker build --pull -f "Dockerfile" -t $SERVICE_NAME --build-arg arg="yes" .

Remark: This will go to the else (false) in the bash script
docker build --pull -f "Dockerfile" -t $SERVICE_NAME .

Remark: This will go to the if (true)
Edit 1:
After several tries I have found the following article and this one
which helped me to understand 2 things:
1) ARG before FROM is outside of the build
2) The default shell is /bin/sh which means that the if else is working a little bit different in the docker build. for example you need only one "=" instead of "==" to compare strings.
So you can do this inside the Dockerfile
ARG argname=false   #default argument when not provided in the --build-arg
RUN if [ "$argname" = "false" ] ; then echo 'false'; else echo 'true'; fi

and in the docker build:
docker build --pull -f "Dockerfile" --label "service_name=${SERVICE_NAME}" -t $SERVICE_NAME --build-arg argname=true .

A: Just use the "test" binary directly to do this. You also should use the noop command ":" if you don't want to specify an "else" condition, so docker does not stop with a non zero return value error.
RUN test -z "$YOURVAR" || echo "var is set" && echo "var is not set"
RUN test -z "$YOURVAR" && echo "var is not set" || :
RUN test -z "$YOURVAR" || echo "var is set" && :

A: The accepted answer may solve the question, but if you want multiline if conditions in the dockerfile, you can do that placing \ at the end of each line (similar to how you would do in a shell script) and ending each command with ;. You can even define someting like set -eux as the 1st command.
Example:
RUN set -eux; \
  if [ -f /path/to/file ]; then \
    mv /path/to/file /dest; \
  fi; \
  if [ -d /path/to/dir ]; then \
    mv /path/to/dir /dest; \
  fi

In your case:
FROM centos:7
ARG arg
RUN if [ -z "$arg" ] ; then \
    echo Argument not provided; \
  else \
    echo Argument is $arg; \
  fi

Then build with:
docker build -t my_docker . --build-arg arg=42

A: There is an interesting alternative to the proposed solutions, that works with a single Dockerfile, require only a single call to docker build per conditional build and avoids bash.
Solution:
The following Dockerfile solves that problem. Copy-paste it and try it yourself.
ARG my_arg

FROM centos:7 AS base
RUN echo "do stuff with the centos image"

FROM base AS branch-version-1
RUN echo "this is the stage that sets VAR=TRUE"
ENV VAR=TRUE

FROM base AS branch-version-2
RUN echo "this is the stage that sets VAR=FALSE"
ENV VAR=FALSE

FROM branch-version-${my_arg} AS final
RUN echo "VAR is equal to ${VAR}"

Explanation of Dockerfile:
We first get a base image (centos:7 in your case) and put it into its own stage. The base stage should contain things that you want to do before the condition. After that, we have two more stages, representing the branches of our condition: branch-version-1 and branch-version-2. We build both of them. The final stage than chooses one of these stages, based on my_arg. Conditional Dockerfile. There you go.
Output when running:
(I abbreviated this a little...)
my_arg==2
docker build --build-arg my_arg=2 .
Step 1/12 : ARG my_arg
Step 2/12 : ARG ENV
Step 3/12 : FROM centos:7 AS base
Step 4/12 : RUN echo "do stuff with the centos image"
do stuff with the centos image
Step 5/12 : FROM base AS branch-version-1
Step 6/12 : RUN echo "this is the stage that sets VAR=TRUE"
this is the stage that sets VAR=TRUE
Step 7/12 : ENV VAR=TRUE
Step 8/12 : FROM base AS branch-version-2
Step 9/12 : RUN echo "this is the stage that sets VAR=FALSE"
this is the stage that sets VAR=FALSE
Step 10/12 : ENV VAR=FALSE
Step 11/12 : FROM branch-version-${my_arg}
Step 12/12 : RUN echo "VAR is equal to ${VAR}"
VAR is equal to FALSE

my_arg==1
docker build --build-arg my_arg=1 .
...
Step 11/12 : FROM branch-version-${my_arg}
Step 12/12 : RUN echo "VAR is equal to ${VAR}"
VAR is equal to TRUE

Thanks to Tõnis for this amazing idea!

A: According to the doc for the docker build command, there is a parameter called --build-arg.
Example usage:
docker build --build-arg HTTP_PROXY=http://10.20.30.2:1234 .

IMO it's what you need :)

A: Exactly as others told, shell script would help.
Just an additional case, IMHO it's worth mentioning (for someone else who stumble upon here, looking for an easier case), that is Environment replacement.

Environment variables (declared with the ENV statement) can also be used in certain instructions as variables to be interpreted by the Dockerfile.
The ${variable_name} syntax also supports a few of the standard bash modifiers as specified below:

*

*${variable:-word} indicates that if variable is set then the result will be that value. If variable is not set then word will be the result.

*${variable:+word} indicates that if variable is set then word will be the result, otherwise the result is the empty string.

A: I had a similar issue for setting proxy server on a container.
The solution I'm using is an entrypoint script, and another script for environment variables configuration. Using RUN, you assure the configuration script runs on build, and ENTRYPOINT when you run the container.
--build-arg is used on command line to set proxy user and password.
As I need the same environment variables on container startup, I used a file to "persist" it from build to run.
The entrypoint script looks like:
#!/bin/bash
# Load the script of environment variables
. /root/configproxy.sh
# Run the main container command
exec "$@"

configproxy.sh
#!/bin/bash

function start_config {
read u p < /root/proxy_credentials

export HTTP_PROXY=http://$u:$p@proxy.com:8080
export HTTPS_PROXY=https://$u:$p@proxy.com:8080

/bin/cat <<EOF > /etc/apt/apt.conf
Acquire::http::proxy "http://$u:$p@proxy.com:8080";
Acquire::https::proxy "https://$u:$p@proxy.com:8080";
EOF
}

if [ -s "/root/proxy_credentials" ]
then
start_config
fi

And in the Dockerfile, configure:
# Base Image
FROM ubuntu:18.04

ARG user
ARG pass

USER root

# -z the length of STRING is zero
# [] are an alias for test command
# if $user is not empty, write credentials file
RUN if [ ! -z "$user" ]; then echo "${user} ${pass}">/root/proxy_credentials ; fi

#copy bash scripts
COPY configproxy.sh /root
COPY startup.sh .

RUN ["/bin/bash", "-c", ". /root/configproxy.sh"]

# Install dependencies and tools
#RUN apt-get update -y && \
#    apt-get install -yqq --no-install-recommends \
#    vim iputils-ping

ENTRYPOINT ["./startup.sh"]
CMD ["sh", "-c", "bash"]

Build without proxy settings
docker build -t img01 -f Dockerfile .

Build with proxy settings
docker build -t img01 --build-arg user=<USER> --build-arg pass=<PASS> -f Dockerfile .

Take a look here.

A: You can just add a simple check:
RUN [ -z "$ARG" ] \
    && echo "ARG argument not provided." \
    && exit 1 || exit 0

A: I saw a lot of possible solutions, but no one fits on the problem I faced today. So, I'm taking time to answer the question with one another possible solution that worked to me.
In my case I toke advantage of the well known if [ "$VAR" == "this" ]; then echo "do that"; fi. The caveat is that Docker, I don't know explain why, doesn't like the double equal on this case. So we need to write like that if [ "$VAR" = "this" ]; then echo "do that"; fi.
There is the full example that worked in my case:
FROM node:16

# Let's set args and envs
ARG APP_ENV="dev"
ARG NPM_CMD="install"
ARG USER="nodeuser"
ARG PORT=8080
ENV NPM_CONFIG_PREFIX=/home/node/.npm-global
ENV PATH=$PATH:/home/node/.npm-global/bin
ENV NODE_ENV=${APP_ENV}

# Let's set the starting point
WORKDIR /app

# Let's build a cache
COPY package*.json .
RUN date \
 # If the environment is production or staging, omit dev packages
 # If any other environment, install dev packages
 && if [ "$APP_ENV" = "production" ]; then NPM_CMD="ci --omit=dev"; fi \
 && if [ "$APP_ENV" = "staging" ]; then NPM_CMD="ci --omit=dev"; fi \
 && npm ${NPM_CMD} \
 && usermod -d /app -l ${USER} node

# Let's add the App
COPY . .

# Let's expose the App port
EXPOSE ${PORT}

# Let's set the user
USER ${USER}

# Let's set the start App command
CMD [ "node", "server.js" ]

So if the user pass the proper build argument, the docker build command will create an image of app for production. If not, it will create an image of the app with dev Node.js packages.
To make it works, you can call like this:
# docker build --build-arg APP_ENV=production -t app-node .

A: For any one trying to build Windows based image, you need to access argument with %% for cmd.
# Dockerfile Windows
# ...
ARG SAMPLE_ARG
RUN if %SAMPLE_ARG% == hello_world ( `
    echo hehe %SAMPLE_ARG% `
    ) else ( `
    echo haha %SAMPLE_ARG% `
)
# ...

BTW, ARG declaration must be placed after FROM, otherwise the argument will not be available.

A:

# The ARGs in front of FROM is for image
ARG IMLABEL=xxxx \
    IMVERS=x.x

FROM ${IMLABEL}:${IMVERS}

# The ARGs after FROM is for parameters to be used in the script
ARG  condition-x

RUN if [ "$condition-x" = "condition-1" ]; then \
      echo "$condition-1"; \
    elif [ "$condition-x" = "condition-1" ]; then \
      echo "$condition-2"; \
    else
      echo "$condition-others"; \
    fi

build -t --build-arg IMLABEL --build-arg IMVERS --build-arg condition-x -f Dockerfile -t image:version .


text:
Q: Программа не читает один из делителей(питон) Cовершенным называется число, равное сумме всех своих делителей, строго меньших его самого. Например, число 6 является совершенным, так как 6 = 1 + 2 + 3. На вход программе подаётся натуральное число N, определите, является ли оно совершенным.
Формат входных данных
На вход программе подаётся натуральное число N.
Формат выходных данных
Если число N является совершенным, выведите строку "Число N является совершенным". В противном случае выведите строку "Число N не является совершенным". Конечно же, вместо символа "N" должно быть выведено само число.
Sample Input 1:

6

Sample Output 1:

Число 6 является совершенным

Sample Input 2:

37

Sample Output 2:

Число 37 не является совершенным

есть код к этой задаче:
N = int(input())
i = 1
a = 0
while i * i <= N:
    if N % i == 0:
        a += i
        if i != N // i:
            a += N // i
    i += 1
if N == a:
    print("Число " + str(N) + " является совершенным")
else:
    print("Число " + str(N) + " не является совершенным")

прога не читает 1 как делитель, как это исправить?

A: В этом коде есть некоторые неточности:
N = int(input())
i = 1
a = 0
while i * i <= N: # Здесь идёт проверка делителей данного числа до его корня.
    if N % i == 0:
        a += i
        if i != N // i: # Здесь мы проверяем не является ли i корнем N
            a += N // i # (i != N // i) => i * i != N
    i += 1
if N == a:
    print("Число " + str(N) + " является совершенным")
else:
    print("Число " + str(N) + " не является совершенным")

Допустим если взять число 36, то его корень - это 6, но у данного числа есть делители большие 6 - это 9, 12, 18 - мы видим, что делители числа доходят до его половины включительно.
Вот исправленный код:
N = int(input())
i = 1
a = 0
while i * 2 <= N: # Делители числа не больше его половины
    if N % i == 0:
        a += i
    i += 1
if N == a:
    print("Число " + str(N) + " является совершенным")
else:
    print("Число " + str(N) + " не является совершенным")

A: *

*Непонятно для чего вы используете эти строки:

if i != N // i:
    a += N // i

*У вас неверное условие в цикле.

*Проще использовать цикл for:

N = int(input())
a = 0  # сумма делителей
for i in range(1, N):
    if N%i == 0:
        a += i
# вывод

*Если нужен именно while:

N = int(input())
a = 0 # сумма делителей
i = 1
while i<N:
    if N%i == 0:
        a += i
    i+=1
# вывод

"Однострочник"
N = int(input())
print(f'Число {N} ', '' if N==sum(i for i in range(1, N) if not N%i) else 'не ', 'является совершенным.'


text:
Q: Jquery only working in window.onload=function() I'm using the angular-fullstack yeoman generator in my project.
It contains Jquery by default.
<script src="bower_components/jquery/dist/jquery.js"></script> is correctly inside the index.html
Curiously, in my js file, Jquery works perfectly inside this:
window.onload=function() {
  //my jquery code working here
    }

But, it doesn't work at all if I put in this instead :
$(document).ready(function() {
  // my code is not working here :(
});

And from there, I'm getting some trouble. When I switch from a page to an another one, Jquery stopped. I need to refresh the page to keep Jquery working.
I might not have this problem if my Jquery code was inside $(document).ready(function()
As I'm using angular-fullstack generator which already makes almost every thing in my project, I don't know where I need to make some change to make it works ..
Any suggestion ? Thanks a lot. :)

A: As far as I know using jQuery with AngularJS is not a good practice. Generally if in your angular project you need to use jQuery it means you have to create a custom directive to have some logic there or less ideal alternative is to use angular.element which comes with jQuery lite features.
Regarding your problem please test if this will work:
jQuery(document).ready(function($) {
  // example $('.btn').hide();
});


text:
Q: bouncycastle fails NTRU generation There are three types of default security levels of NTRU, implemented in bouncy-castle:
 1. NTRUSigningKeyGenerationParameters.TEST157
 2. NTRUSigningKeyGenerationParameters.APR2011_439
 3. NTRUSigningKeyGenerationParameters.APR2011_743

First two are generated normally, but when I try to generate the tird one, I get the next Exception:

SEVERE: Servlet.service() for servlet [mvc-dispatcher] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: Signing failed: too many retries (max=100)] with root cause
  java.lang.IllegalStateException: Signing failed: too many retries (max=100)

Here is piece of my code:
NTRUSigningPrivateKeyParameters ntruSigningPrivateKeyParameters1 = null;

    NTRUSigner ntruSigner = new NTRUSigner(ntruSigningKeyGenerationParameters.getSigningParameters());

    try {
        ntruSigningPrivateKeyParameters1 = new NTRUSigningPrivateKeyParameters(ntruSigningPrivateKeyParameters.getEncoded(), ntruSigningKeyGenerationParameters);
    } catch (IOException e) {

        e.printStackTrace();
    }

    ntruSigner.init(true, ntruSigningPrivateKeyParameters);
    byte [] res = ntruSigner.generateSignature();

Calling ntruSigner.generateSignature() with the third set of parameters leads to a such Exception.
Does anyone knows how to solve it?

A: Currently, it's a bug, so there are two solutions:

*

*use another library - tbuktu's github project (bouncy-castle is using it with some modifications, as I see)

*download sources, catch the bug of this generation parameter, solve it and pack into library for a project

A: It's not really a bug in the code. The problem is that the norm bound in the APR2011_743 and APR2011_743_PROD parameter sets is too low which means that the signer is unable to generate a valid signature.
For N=743, q=2048 and beta=0.127 you should choose a norm bound of around 545 (see equation 10 in J. Hoffstein et al, Performance improvements and a baseline parameter generation algorithm for NTRUSign) but the parameter sets in BouncyCastle use normBound=405. Changing this solves the issue.

A: Updating the normBound does appear to fix the issue, however I should point out the NTRUSigner class is now deprecated in Bouncy Castle. The NTRU signing algorithm was shown to be badly broken just over a year ago. See:
http://www.di.ens.fr/~ducas/NTRUSign_Cryptanalysis/DucasNguyen_Learning.pdf
for details.


text:
Q: Visual Studio 2017 and angular integration This is a fundamental question, but I would like to understand how Visual Studio handles Angular projects.
By using the Angular template provided within Visual Studio 2017 (C#), can you please explain how an angular application works?

*

*For the development environment, I believe Visual Studio runs two servers: one is IIS for the Web API calls, and the other one is the node.js for the Angular project (am I right?)

*However, in the development environment the application uses the address of the Web API project (e.g. localhost:5000) instead of Angular application address provided by the node.js (e.g. localhost:66328). How does this happen?

*What about the production environment? Both the Web API (C#) and the Angular work within IIS?

*How about if the Angular project is developed outside of Visual Studio such using Eclipse/Visual Studio Code/Webstorm? How can I integrate the two projects for production purposes?
I know these are very basic questions but will be glad if you can provide answers / references / links.

A: The magic is not done in Visual Studio. The magic is done in .NET.
That's why you can create and develop ASP.NET Core Angular projects on Mac, with VS Code or even vim!
To simplify, what ASP.NET Core does is:

*

*In development, they redirect all URLs to the output of ng serve, but this happens after all routes all added, so that URLs going to controllers would still work

*In production, they redirect these URLs to a static file handler, that looks at the dist folder, where the result of ng build is added.

The code is not entirely hidden from you.
See the Startup.cs file from the project template which I used as source for above.
They also use the ASP.NET Node services (.NET <-> Node interop) to implement server-side rendering. This means if you use that, you need Node on the server. See server-side rendering docs for details.
The same docs page also points out how they have an optional proxy for development in case you wanted to run ng serve manually, that just proxies (sends) all the URLs (after all routes checked against the URL and not matched) to the Angular development server.

A: I use VS Code for all of my Angular development, so I can't answer the first part of your question. Consider consulting the Microsoft docs on the Angular template here: https://learn.microsoft.com/en-us/aspnet/core/client-side/spa/angular?view=aspnetcore-2.2&tabs=visual-studio
I can answer the last part of your question.

How about if the angular project is developed outside of the visual
  studio such using eclipse/visual code/web storm? How can I integrate
  the two projects for production purposes?

You can build your Angular application for production. This generates several packages and other files (such as the index.html file) into a dist folder. You can then take those files and deploy them to your IIS or whatever server you use for production.
You can find some general information here:
https://angular.io/guide/deployment
Though it is mostly general and not specific to a particular server, it does have some specific instructions for IIS.
And be sure to follow the instructions here: https://angular.io/guide/deployment#the-base-tag to set the base tag to the appropriate IIS folder.


text:
Q: How to place relative divs below absolute ones? I have a background image and over that a carousel with text and an image both 1024x287px.
I want to add more info below that image and underneath I want to place the footer.
I can solve this with just a px margin on top, but once you're-size the browser it looks bad.
I have the following markup:

.img-background {
  @media (max-width: 1035px) {
    display: none;
  }
  position:absolute;
  margin-left:50%;
  left:-512px;
  top:0px;
  width: 100%;
}

.infoblock {
  z-index: 2;
}

.carousel-control.right {
  left: auto;
  right: -50px;
}

.carousel-control.left {
  left: -100px;
  right: auto;
}

.carousel {
  position: absolute;
  margin-left: 50%;
  left: -512px;
  top: 60px;
  z-index: 2;
}

wrapper {
  position: relative;
  top: 60px;
  width: 100%;
  height: auto;
}

.carousel .item {
  width: 100%;
  /*slider width*/
  height: auto;
  /*slider height*/
  z-index: 2;
}

.carousel .item img {
  @media (max-width: 1035px) {
    display: none;
  }
  margin-left: 0%;
  width: 100%;
  /*img width*/
}

/*full width container*/

@media (max-width: 767px) {
  .block {
    margin-left: -20px;
    margin-right: -20px;
  }
}

@import 'bootstrap-responsive';
.navbar-inner {
  @include box-shadow(none !important);
  border: 0;
}

.navbar .nav>li>a {
  padding: 25px 10px 5px
}

.footer {
  color: $grayLight;
  a {
    color: $gray;
  }
}

This is how it's not supposed to look like:

The problem with placing the Android, iPhone, etc. logos in the carousel is that when you downsize the browser they're all the way to the left, so invisible.
How can I place a div just underneath the carousel and when the screen is small, the carousel is not showing, so it should just be on top of the page.

A: You can not place two relatively positioned DIV's on top of each other, to my knowledge, at least.
What you can do, is use absolute positioning of the images, inside a relatively positioned DIV.
Take a look at this jsFiddle, I made earlier.
The Red DIV is semi-transparent and on top of the Blue DIV, using position: absolute;, top: 0;, left: 0;, these two are placed, inside a container
 with position: relative; and margin: 0 auto; to center the container.


text:
Q: Acessing image folder outside wamp folder i have my web folder in c:/wamp/www/ which is the default webroot for wamp. Then i have a folder image in c:/image/ that contains images been processed by another application which i wont like to relocate. I want to be able to load up an image with its file name from c:/image/
e.g. img src = "c:/image/FA12.jpg"
within my PHP scripts. I really Need Help on this Please. Thanks for your support.

A: If you need to read a file into php use "c:\image\FA12.jpg". You may also create a link "file://c\image\FA12.jpg". There's no way to create a relative path, since it is outside root dir.

A: As per my knowledge it is better to create a folder of your images under your localhost or server ('var/www/images') to have a proper relative URL to that images.
Url's like c:\image\fa12.jpg can create problems when you make your product online. Other wise you can do provide static urls as kirilloid suggest or you can copy that images to some proper folder in your localhost sever with use of php function "copy" and use that folder as a reference. avoid static url's if possible.:)
as i have linux system now i tested below code locally. create one file test.php under /www and put below code in it and run file in browser. see if this can be your solution
<?php $link  = $_SERVER['DOCUMENT_ROOT'];
$domain = strstr($link, '/www');
echo $domain;//this will output /www

$root = strstr($link, '/www', true);
echo "<br>".$root;//this will output /var
?>

You can try this by putting "/wamp/www" instead of "/www" in above code and you will get c:/ (perhaps) in $root and then appeng folder name images and path accordingly to $root.
May this will help you


text:
Q: Unable to create channel in Hyperledger fabric using custom crypto graphic material I am following the below link to run the first network sample using the custom crypto graphic material.
First Network with custom cryptographic material
Post generation of certificates from the Third Party CA. i have places all the certificates in the required dir structure. Following other steps now when i start the docker containers they come up. but when i try to create channell i get below error
Error: got unexpected status: BAD_REQUEST -- Error authorizing update: Error validating DeltaSet: Policy for [Groups] /Channel/Application not satisfied: Failed to reach implicit threshold of 1 sub-policies, required 1 remaining
when i check the docker logs for the orderer container i find
DEBU 29f Checking if identity satisfies ADMIN role for Org1MSP
2017-11-13 07:21:36.533 UTC [cauthdsl] func2 -> DEBU 2a0 0xc420111280 identity 0 does not satisfy principal: **This identity is not an admin**
2017-11-13 07:21:36.533 UTC [cauthdsl] func2 -> DEBU 2a1 0xc420111280 principal evaluation fails
2017-11-13 07:21:36.533 UTC [cauthdsl] func1 -> DEBU 2a2 0xc420111280 gate 1510557696533528831 evaluation fails
2017-11-13 07:21:36.533 UTC [policies] Evaluate -> DEBU 2a3 Signature set did not satisfy policy /Channel/Application/Org1MSP/Admins
2017-11-13 07:21:36.533 UTC [policies] Evaluate -> DEBU 2a4 == Done Evaluating *cauthdsl.policy Policy /Channel/Application/Org1MSP/Admins
2017-11-13 07:21:36.533 UTC [policies] Evaluate -> DEBU 2a5 == Evaluating *cauthdsl.policy Policy /Channel/Application/Org2MSP/Admins ==
2017-11-13 07:21:36.533 UTC [cauthdsl] func1 -> DEBU 2a6 0xc420111290 gate 1510557696533664185 evaluation starts
2017-11-13 07:21:36.533 UTC [cauthdsl] func2 -> DEBU 2a7 0xc420111290 signed by 0 principal evaluation starts (used [false])

So I think identity might not be in the admin list,
but when I go and check the below paths i find they have same admin cert
/crypto-config/peerOrganizations/org1.aexp.com/users/Admin@org1.aexp.com/msp/admincerts
and
crypto-config/peerOrganizations/org1.aexp.com/msp/admincerts

If i am supposed to make the identity as admin what steps do i need to follow.
Kindly suggest
TIA