Unable to connect to the internet on a Ubuntu 14.0.4 laptop using zte(reliance cdma) AC2739 USB modem

Question: Many Linux/Ubuntu users face this problem -->(connect to internet using modem zte/etc.....) because modern dongles have USB storage + modem+CD ROM,
usb_modes switch blablabla.......................
what is my problem?
--> I am not able**(sometimes able to)** to connect internet using ZTE(Reliance cdma) AC2739 .
How Ubuntu Detect my USB dongle?
Ans : in 3 Ways :
1) do not detect USB device but lsusb show the device.
2) detect the device (1 in 10 case after inserting USB) but network manager does not detect it as broadband connection.
3) detect the device(1 in 15 case after inserting USB) and also network manager detect it as broadband connection-----> this is case when I am able to connect to internet.
System logs for all 3 cases:
Common logs (this is what system logs shows every time when I insert USB dongle)
'May 20 20:51:19 pcp kernel: [ 2724.187204] usb 3-3: new full-speed USB device number 10 using xhci_hcd

May 20 20:51:19 pcp kernel: [ 2724.205404] usb 3-3: New USB device found, idVendor=19d2, idProduct=fff1

May 20 20:51:19 pcp kernel: [ 2724.205415] usb 3-3: New USB device strings: Mfr=1, Product=2, SerialNumber=3

May 20 20:51:19 pcp kernel: [ 2724.205420] usb 3-3: Product: ZTE CDMA Tech

May 20 20:51:19 pcp kernel: [ 2724.205425] usb 3-3: Manufacturer: ZTE, Incorporated
May 20 20:51:19 pcp kernel: [ 2724.205430] usb 3-3: SerialNumber: 000000000002
May 20 20:51:19 pcp kernel: [ 2724.208710] usb-storage 3-3:1.5: USB Mass Storage device detected
May 20 20:51:19 pcp kernel: [ 2724.208930] scsi14 : usb-storage 3-3:1.5
May 20 20:51:19 pcp mtp-probe: checking bus 3, device 10: "/sys/devices/pci0000:00/0000:00:14.0/usb3/3-3"
May 20 20:51:19 pcp mtp-probe: bus: 3, device: 10 was not an MTP device'

case 1: (not sowing common logs -->above one)
May 20 18:52:15 pcp usb_modeswitch: switch device 19d2:fff5 on 003/003
May 20 18:52:42 pcp kernel: [ 3082.599319] scsi 7:0:0:0: CD-ROM            ZTE      USB Storage FFF1 2.31 PQ: 0 ANSI: 2
May 20 18:52:42 pcp kernel: [ 3082.601400] scsi 7:0:0:1: Direct-Access     ZTE      USB Storage FFF1 2.31 PQ: 0 ANSI: 2
May 20 18:52:43 pcp kernel: [ 3083.337421] sr1: scsi3-mmc drive: 0x/0x caddy
May 20 18:52:43 pcp kernel: [ 3083.337618] sr 7:0:0:0: Attached scsi CD-ROM sr1
May 20 18:52:43 pcp kernel: [ 3083.337689] sr 7:0:0:0: Attached scsi generic sg2 type 5
May 20 18:52:43 pcp kernel: [ 3083.338257] sd 7:0:0:1: Attached scsi generic sg3 type 0
May 20 18:52:43 pcp kernel: [ 3083.346309] sd 7:0:0:1: [sdb] Attached SCSI removable disk
May 20 18:52:43 pcp kernel: [ 3083.386955] systemd-udevd[5293]: Failed to apply ACL on /dev/sr1: No such file or directory
May 20 18:52:43 pcp kernel: [ 3083.386971] systemd-udevd[5293]: Failed to apply ACL on /dev/sr1: No such file or directory
May 20 18:52:43 pcp kernel: [ 3083.391821] systemd-udevd[5293]: Failed to apply ACL on /dev/sr1: No such file or directory
May 20 18:52:43 pcp kernel: [ 3083.391832] systemd-udevd[5293]: Failed to apply ACL on /dev/sr1: No such file or directory

case 2 (not sowing common logs -->provided at top)
May 20 19:35:52 pcp kernel: [  910.651091] usb 3-3: reset full-speed USB device number 8 using xhci_hcd
May 20 19:35:52 pcp kernel: [  910.667601] xhci_hcd 0000:00:14.0: xHCI xhci_drop_endpoint called with disabled ep ffff8800777e6180
May 20 19:35:52 pcp kernel: [  910.667613] xhci_hcd 0000:00:14.0: xHCI xhci_drop_endpoint called with disabled ep ffff8800777e61c0
May 20 19:35:52 pcp kernel: [  910.672647] scsi 12:0:0:0: CD-ROM            ZTE      USB Storage FFF1 2.31 PQ: 0 ANSI: 2
May 20 19:35:52 pcp kernel: [  910.674693] scsi 12:0:0:1: Direct-Access     ZTE      USB Storage FFF1 2.31 PQ: 0 ANSI: 2
May 20 19:35:52 pcp kernel: [  910.679319] sr1: scsi3-mmc drive: 372x/372x writer dvd-ram cd/rw xa/form2 cdda
May 20 19:35:52 pcp kernel: [  910.679996] sr 12:0:0:0: Attached scsi CD-ROM sr1
May 20 19:35:52 pcp kernel: [  910.681364] sr 12:0:0:0: Attached scsi generic sg2 type 5
May 20 19:35:52 pcp kernel: [  910.682692] sd 12:0:0:1: Attached scsi generic sg3 type 0
May 20 19:35:52 pcp kernel: [  910.689527] sd 12:0:0:1: [sdb] Attached SCSI removable disk
May 20 19:35:52 pcp kernel: [  910.789754] sr1: CDROM (ioctl) error, command: Xdread, Read track info 52 01 00 00 00 01 00 00 08 00
May 20 19:35:52 pcp kernel: [  910.789777] sr: Sense Key : Hardware Error [current]
May 20 19:35:52 pcp kernel: [  910.789783] sr: Add. Sense: No additional sense information
May 20 19:35:52 pcp kernel: [  911.234442] ISO 9660 Extensions: Microsoft Joliet Level 1
May 20 19:35:52 pcp kernel: [  911.247345] ISOFS: changing to secondary root
May 20 19:35:52 pcp udisksd[2223]: Mounted /dev/sr1 at /media/prakash/Reliance on behalf of uid 1000

case 3: (not sowing common logs -->provided at top)
    May 20 20:51:19 pcp kernel: [ 2724.248971] usbcore: registered new interface driver usbserial
    May 20 20:51:19 pcp kernel: [ 2724.248989] usbcore: registered new interface driver usbserial_generic
    May 20 20:51:19 pcp kernel: [ 2724.249002] usbserial: USB Serial support registered for generic
   May 20 20:51:19 pcp kernel: [ 2724.264994] usbcore: registered new interface driver option
    May 20 20:51:19 pcp kernel: [ 2724.265650] usbserial: USB Serial support registered for GSM modem (1-port)
    May 20 20:51:19 pcp kernel: [ 2724.265826] option 3-3:1.0: GSM modem (1-port) converter detected
    May 20 20:51:19 pcp kernel: [ 2724.265979] usb 3-3: GSM modem (1-port) converter now attached to ttyUSB0
    May 20 20:51:19 pcp kernel: [ 2724.266042] option 3-3:1.1: GSM modem (1-port) converter detected
    May 20 20:51:19 pcp kernel: [ 2724.266161] usb 3-3: GSM modem (1-port) converter now attached to ttyUSB1
    May 20 20:51:19 pcp kernel: [ 2724.266218] option 3-3:1.2: GSM modem (1-port) converter detected
    May 20 20:51:19 pcp kernel: [ 2724.266334] usb 3-3: GSM modem (1-port) converter now attached to ttyUSB2
    May 20 20:51:19 pcp kernel: [ 2724.266390] option 3-3:1.3: GSM modem (1-port) converter detected
    May 20 20:51:19 pcp kernel: [ 2724.266505] usb 3-3: GSM modem (1-port) converter now attached to ttyUSB3
    May 20 20:51:19 pcp kernel: [ 2724.266562] option 3-3:1.4: GSM modem (1-port) converter detected
    May 20 20:51:19 pcp kernel: [ 2724.266687] usb 3-3: GSM modem (1-port) converter now attached to ttyUSB4
   May 20 20:51:19 pcp kernel: [ 2724.266757] option 3-3:1.6: GSM modem (1-port) converter detected
    May 20 20:51:19 pcp kernel: [ 2724.266885] usb 3-3: GSM modem (1-port) converter now attached to ttyUSB5
    May 20 20:51:20 pcp ModemManager[720]: <warn>  (ttyUSB5): port attributes not fully set
    May 20 20:51:20 pcp ModemManager[720]: <warn>  (ttyUSB2): port attributes not fully set
    May 20 20:51:20 pcp ModemManager[720]: <warn>  (ttyUSB3): port attributes not fully set
    May 20 20:51:20 pcp ModemManager[720]: <warn>  (ttyUSB1): port attributes not fully set
    May 20 20:51:20 pcp ModemManager[720]: <warn>  (ttyUSB0): port attributes not fully set
    May 20 20:51:20 pcp ModemManager[720]: <warn>  (ttyUSB4): port attributes not fully set

    May 20 20:51:20 pcp usb_modeswitch: switched to 19d2:ffffffff on 003/009
    May 20 20:51:20 pcp kernel: [ 2725.207972] scsi 14:0:0:0: CD-ROM            ZTE      USB Storage FFF1 2.31 PQ: 0 ANSI: 2
    May 20 20:51:20 pcp kernel: [ 2725.210011] scsi 14:0:0:1: Direct-Access     ZTE      USB Storage FFF1 2.31 PQ: 0 ANSI: 2
   May 20 20:51:21 pcp usb_modeswitch[4855]: usb_modeswitch: switched to 19d2:fff1 on 3/10
    May 20 20:51:21 pcp kernel: [ 2725.888378] sr1: scsi3-mmc drive: 372x/372x writer dvd-ram cd/rw xa/form2 cdda
    May 20 20:51:21 pcp kernel: [ 2725.888912] sr 14:0:0:0: Attached scsi CD-ROM sr1
    May 20 20:51:21 pcp kernel: [ 2725.889419] sr 14:0:0:0: Attached scsi generic sg2 type 5
    May 20 20:51:21 pcp kernel: [ 2725.893403] sd 14:0:0:1: Attached scsi generic sg3 type 0

May 20 20:51:21 pcp kernel: [ 2725.910131] sd 14:0:0:1: [sdb] Attached SCSI removable disk
    May 20 20:51:21 pcp kernel: [ 2726.006326] sr1: CDROM (ioctl) error, command: Xdread, Read track info 52 01 00 00 00 01 00 00 08 00
    May 20 20:51:21 pcp kernel: [ 2726.006351] sr: Sense Key : Hardware Error [current]
    May 20 20:51:21 pcp kernel: [ 2726.006357] sr: Add. Sense: No additional sense information

    May 20 20:51:22 pcp usb_modeswitch[4855]: usb_modeswitch: add device ID 19d2:fff1 to driver option
    May 20 20:51:22 pcp usb_modeswitch[4855]: usb_modeswitch: please report the device ID to the Linux USB developers!

    May 20 20:51:22 pcp kernel: [ 2726.597676] ISO 9660 Extensions: Microsoft Joliet Level 1
   May 20 20:51:22 pcp kernel: [ 2726.608596] ISOFS: changing to secondary root
    May 20 20:51:22 pcp udisksd[2228]: Mounted /dev/sr1 at /media/prakash/Reliance on behalf of uid 1000
   May 20 20:51:38 pcp ModemManager[720]: <info>  Creating modem with plugin 'ZTE' and '6' ports
    May 20 20:51:38 pcp ModemManager[720]: <warn>  Could not grab port (tty/ttyUSB4): 'Cannot add port 'tty/ttyUSB4', unhandled serial type'
    May 20 20:51:38 pcp ModemManager[720]: <warn>  Could not grab port (tty/ttyUSB2): 'Cannot add port 'tty/ttyUSB2', unhandled serial type'
    May 20 20:51:38 pcp ModemManager[720]: <warn>  Could not grab port (tty/ttyUSB5): 'Cannot add port 'tty/ttyUSB5', unhandled serial type'

May 20 20:51:38 pcp ModemManager[720]: <warn>  (ttyUSB0): port attributes not fully set
    May 20 20:51:38 pcp ModemManager[720]: <info>  Modem for device at '/sys/devices/pci0000:00/0000:00:14.0/usb3/3-3' successfully created
    May 20 20:51:39 pcp ModemManager[720]: <warn>  Couldn't load unlock retries: 'Unknown error'
    May 20 20:51:39 pcp ModemManager[720]: <warn>  couldn't load list of Own Numbers: 'Failed to parse NV MDN command result: -17'
    May 20 20:51:39 pcp ModemManager[720]: <warn>  couldn't load current allowed/preferred modes: 'Unknown error'

May 20 20:51:39 pcp ModemManager[720]: <info>  Modem: state changed (unknown -> disabled)
    May 20 20:51:39 pcp NetworkManager[784]: <warn> (ttyUSB0): failed to look up interface index
    May 20 20:51:39 pcp NetworkManager[784]: <info> (ttyUSB0): new Broadband device (driver: 'option1' ifindex: 0)
    May 20 20:51:39 pcp NetworkManager[784]: <info> (ttyUSB0): exported as /org/freedesktop/NetworkManager/Devices/2
    May 20 20:51:39 pcp NetworkManager[784]: <info> (ttyUSB0): device state change: unmanaged -> unavailable (reason 'managed') [10 20 2]
    May 20 20:51:39 pcp NetworkManager[784]: <info> (ttyUSB0): deactivating device (reason 'managed') [2]
    May 20 20:51:39 pcp NetworkManager[784]: <info> (ttyUSB0): device state change: unavailable -> disconnected (reason 'none') [20 30 0]

If anyone want text file of whole log please let me know. This problem is in many USB dongles. If any one can provide any solution to this problem please do it. I am trying from 3 days hope I will get solution now.
Answer: I had a pretty similar problem with my ZTE USB modem and it turns out it was getting mounted as a CD unit.
This is how I solve it:
Step 1: Use lsusb to verify your usb modem is detected
sergiotca@sergiotca-Dell-System-XPS-L502X:~$ lsusb
Bus 002 Device 003: ID 8086:0189 Intel Corp.
Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 003: ID 046d:c07e Logitech, Inc.
Bus 003 Device 009: ID 19d2:2000 ZTE WCDMA Technologies MSM
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 003: ID 0408:2fb1 Quanta Computer, Inc.
Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Step 2: Use dmesg | tail to know how it has been detected
sergiotca@sergiotca-Dell-System-XPS-L502X:~$ dmesg | tail
[ 6136.744009] usb 3-1: Manufacturer: ZTE,Incorporated
[ 6136.744012] usb 3-1: SerialNumber: MF1800ZTED010000
[ 6136.747257] usb-storage 3-1:1.0: USB Mass Storage device detected
[ 6136.747504] scsi19 : usb-storage 3-1:1.0
[ 6137.748200] scsi 19:0:0:0: CD-ROM            ZTE      USB SCSI CD-ROM  2.31 PQ: 0 ANSI: 2
[ 6137.751676] sr1: scsi-1 drive
[ 6137.752168] sr 19:0:0:0: Attached scsi CD-ROM sr1
[ 6137.752731] sr 19:0:0:0: Attached scsi generic sg2 type 5

Step 3: Use usb_modeswitch to change the mode of your usb modem by "ejecting it" using the -K parameter. Use the vendor and product ID from your own modem (lsusb)
sergiotca@sergiotca-Dell-System-XPS-L502X:~$ sudo usb_modeswitch -v 0x19d2 -p 0x2000 -K
[sudo] password for sergiotca:
Look for default devices ...
   product ID matched
Found devices in default mode (1)
Access device 010 on bus 003
Current configuration number is 1
Use interface number 0
Use endpoints 0x01 (out) and 0x81 (in)

USB description data (for identification)
-------------------------
Manufacturer: ZTE,Incorporated
     Product: ZTE WCDMA Technologies MSM
  Serial No.: MF1800ZTED010000
-------------------------
Sending standard EJECT sequence
Looking for active driver ...
 No active driver found. Detached before or never attached
Set up interface 0
Use endpoint 0x01 for message sending ...
Trying to send message 1 to endpoint 0x01 ...
 OK, message successfully sent
Read the response to message 1 (CSW) ...
 Response successfully read (13 bytes).
Trying to send message 2 to endpoint 0x01 ...
 OK, message successfully sent
Read the response to message 2 (CSW) ...
 Response successfully read (13 bytes).
Reset response endpoint 0x81
Reset message endpoint 0x01
-> Run lsusb to note any changes. Bye!

Step 4: Finally use dmesg | tail to verify that your usb modem has changed to Direct-Access mode
sergiotca@sergiotca-Dell-System-XPS-L502X:~$ dmesg | tail
[ 6874.527436] usb 3-1: GSM modem (1-port) converter now attached to ttyUSB0
[ 6874.527700] option 3-1:1.1: GSM modem (1-port) converter detected
[ 6874.527894] usb 3-1: GSM modem (1-port) converter now attached to ttyUSB1
[ 6874.528148] option 3-1:1.2: GSM modem (1-port) converter detected
[ 6874.528305] usb 3-1: GSM modem (1-port) converter now attached to ttyUSB2
[ 6874.528510] usb-storage 3-1:1.3: USB Mass Storage device detected
[ 6874.528704] scsi20 : usb-storage 3-1:1.3
[ 6875.529082] scsi 20:0:0:0: Direct-Access     ZTE      MMC Storage      2.31 PQ: 0 ANSI: 2
[ 6875.532997] sd 20:0:0:0: Attached scsi generic sg2 type 0
[ 6875.535452] sd 20:0:0:0: [sdb] Attached SCSI removable disk

Step 5: Your modem should be detected now by the network manager.
Answer: after analyzing  System logs carefully this solution worked for me
Cause Of Problem: Multiple modes of modern dongles.

Solution:
1.

gedit /etc/usb_modeswitch.conf

2.add this code to diable usb switching  at the top.

DisableSwitching=1

3.save it.
4.insert usb again
5.eject usb cdrom by right click eject it or using.

sudo eject /dev/sr1

6.Wait for 5-10 sec(time to detect it as modem)
7.now go to network manager
8.Reliance network will be listed in network manager connect to it by creating new connection.
7.now go to network manager
8.Reliance network will be listed in network manager connect to it by
creating new connection.that's all
Reliance provide UI software also
simply install it using

sudo ./file name

run it using

sudo ztemtapp

this is working for me.


How to use jest.fn() on an individually imported function

Question: I'm having trouble mocking the call of an individually imported function to my tests. The test is a simple function that I put within my Redux actions to be able to set a variable based on a condition.
Here's the function in Body.duck.js:
export const getCurrentOrPrevSelection = isExecutedFromPagination => (dispatch, getState) => {
  const {
    editor: { selection },
    body: { queryRequest },
  } = getState();

  if (isExecutedFromPagination && queryRequest.breadcrumb) {
    const {
      query: { branch, includeSplits, primaryFa, split, isInitial },
    } = queryRequest.breadcrumb;
    return {
      branch,
      includeSplits,
      primaryFa,
      split,
      isInitial,
    };
  }
  return selection;
};

And here's the test file:
import reudcer, { ...other exported functions, getCurrentOrPrevSelection } from '../Body.duck';

it ('should use selection in breadcrumb state when fetching new data from pagination action', () => {
    let isExecutedFromPagination = false;
    const bodyState = {
      ...initialState.body,
      queryRequest: {
        ...initialState.body.queryRequest,
        breadcrumb: {
          ...initialState.body.breadcrumb,
          query: {
            name: 'Full Book Performance',
            branch: null,
            includeSplits: true,
            primaryFa: 'AXFO',
            split: null,
            isInitial: true,
          },
        },
      },
    };
    const selection = {
      branch: null,
      includeSplits: true,
      primaryFa: 'AXFO',
      split: null,
      isInitial: true,
    };

    expect(getCurrentOrPrevSelection(isExecutedFromPagination)(jest.fn(), () => ({
      body: { ...bodyState },
      editor: { faidSelection },
    }))).toHaveReturnedWith({
      branch: null,
      includeSplits: true,
      primaryFa: 'AXFO',
      split: null,
      isInitial: true,
    });
  });

If I don't include any sort of mock reference to getCurrentOrPrevSelection, I get this error below, but it returns the correct value as expected:
    expect(jest.fn())[.not].toHaveReturnedWith()

    jest.fn() value must be a mock function or spy.
    Received:
      object: {"branch": null, "includeSplits": true, "isInitial": true, "primaryFa": "AXFO", "split": null}

If I do something like getCurrentOrPrevFaidSelection = jest.fn();, I get an error saying getCurrentOrPrevFaidSelection is read-only
What can I do differently here?
Answer: You want to test this function. So you don't need to mock that.
Just call function and verify result with expect().toEqual or expect().toMatchObject.
expect(getCurrentOrPrevSelection(isExecutedFromPagination)(.....)).toMatchObject({
      branch: null,
      ...
    });

Also passing jest.fn() directly as argument does not really make sense: you cannot either verify it has been called or provide mock return.
const dispatchMock = jest.fn();
expect(getCurrentOrPrevSelection(isExecutedFromPagination)(dispatchMock, ....);
expect(dispatchMock).toHaveBeenCalledWith(...)

Once it's just not expected to be called as it is in your sample you better explicitly provide noop function () => {} instead of jest.fn(). This way you make it's explicit so nobody will be confused if it's expected there is no assertions against this function or not.
Offtop: actually this is not really good way to test redux action creators. See you actually test implementation details. What if you migrate from redux-thunk to redux-saga or redux-loop? Or split single action into 2 for better flexibility? By now it would mean you have to rewrite all your tests.
What if instead of testing action creator in isolation you connect action to real(not mocked) store? You could dispatch action(after mocking calls to external API) and validate store's state.


System.Diagnostics.Process.Start with WindowStyle.Hidden doesn't retun handle

Question: I am trying to open simple .net exe/notepad.exe using process.start in hidden mode. and I need the process handle later to make the application.exe to make it visible after some time.

Able to get handle only in WindowStyle.Minimized, WindowStyle.Maximized, WindowStyle.Normal. In Hidden style, it gives me 0 always.
How to get handle without using Thread.Sleep. It requires us to wait few seconds, to get handle. some  exe requires more wait time, based on its performance(huge data).
public static void LaunchExe()
{
    var proc = new Process
    {
        StartInfo =
        {
            FileName = "Notepad.exe", //or any simple .net exe
            WindowStyle = ProcessWindowStyle.Hidden
        }
    };

    proc.Start();

    proc.WaitForInputIdle(800); //is it possible to avoid this.
    Thread.Sleep(3000); //is it possible to avoid this.

    Console.WriteLine("handle {0}", proc.MainWindowHandle);

    //ShowWindowAsync(proc.MainWindowHandle, 1); //planned to use, to make it visible.
}

Answer: You can do something like this:
        IntPtr ptr = IntPtr.Zero;
        while ((ptr = proc.MainWindowHandle) == IntPtr.Zero)
        { proc.WaitForInputIdle(1 * 60000); Thread.Sleep(10); }   // (1*60000 = 1min, will give up after 1min)

That way you're not wasting any more time than you need to.
You can't get the handle of a hidden process.
According to MS: A process has a main window associated with it only if the process has a graphical interface. If the associated process does not have a main window, the MainWindowHandle value is zero. The value is also zero for processes that have been hidden, that is, processes that are not visible in the taskbar.
I think your only choice would be to start it normally, get the handle, then set it hidden.
This might cause some flicker, but it should work. To mitigate the flicker, you could start it minimized...
Comment: Yes that would help. Is there any option to get handle of hidden process?
Comment: thanks. My actual requirement is opening an exe developed by team developer, get the handle and show the exe inside the .net winform. minimized option is not working for that exe. but it works for winform.exe, notepad.
Comment: If you have control of the other application (as in someone in your company is making it) I would recommend to use some form of [IPC](http://msdn.microsoft.com/en-us/library/windows/desktop/aa365574%28v=vs.85%29.aspx) to pass handles / commands / etc. It's much cleaner.


How to fix a Method 'Location' of object '_AppointmentItem' failed error?

Question: I read various elements of an open appointment item and display it in a message box:
Private Sub MessageAppointmentInfo()

    Dim objItem As Object
    Dim objApp As Outlook.Application
    Dim mySubject As String
    Dim myLocation As String
    Dim myStartDate As Date

    Set objApp = Application

    Set objItem = objApp.ActiveExplorer.Selection.Item(1)

    With objItem

        mySubject = .Subject
        myLocation = .Location
        myStartDate = .Start

    End With

    MsgBox mySubject & myStartDate & myLocation

End Sub

If I comment out myLocation and myStartDate, it runs.
Why won't the location and the start date work the same as the subject?
I get:

Method 'Location' of object '_AppointmentItem' failed

When I hit debug, it highlights myLocation = .Location.
I'm not familiar with Outlook VBA--I'm much more comfortable with Access and Excel.
Comment: Are you sure you have selected an `AppointmentItem`?  A MailItem, for example, has a `Subject` but not a `Location` or a `Start`.  If you had selected a `MailItem`, these are the errors you would expect.
Comment: I definitely have an AppointmentItem selected, according to the locals window and based on the subject that I get when I've commented out location (it is the subject of the appointment that I'm trying to work with). In the Locals window I noticed that it says     : Location :  : String and    : Start :  : Date
Comment: An AppoitnmentItem has a property MeetingStatus.  Values for MeetingStatus include olMeetingCanceled = 5 = "The scheduled meeting has been cancelled".  Could the selected AppointmentItem have a MeetingStatus for which Location and Start are meaningless?
Comment: Like you I started with Excel.  I found the Outlook Object model confusing and poorly documented.  I did buy a highly recommended book but I was not impressed.  I learnt (and am still learning) through experimentation.  Can you access some of the other properties?
Comment: The other properties that I can access are the ones that don't show "The operation failed" under value in the Locals window. So, for example, I can show the CreationTime with no problem at all. I can show the EntryID and Organizer. Why would some operations fail and others not? I do have a Location for the appointment. MeetingStatus property has "the operation failed" for the value in the locals window.
Comment: I am a home user and have no `AppointmentItem`s to experiment with. My reading around this type of issue suggests the code that creates an Outlook object need not initialise every property of the object and Outlook does not provide default values.  You could try using an `On Error` block around the access to these properties. Perhaps one of `IsNull`, `IsEmpty`, `IsMissing` or `IsError` will return a useful value.
Answer: If you mainly want to avoid the error where the Location is not available anyway, let the execution simply continue with next instruction in case of failure and supply blank Location instead:
...

With objItem

    mySubject = .Subject
    myLocation = ""
    On Error Resume Next
    myLocation = .Location
    On Error Goto 0 ' switch off error handling
    myStartDate = .Start

End With

...


Is the free version of Portal identical to the paid version?

Question: Portal is currently free (through Sept 20th, 2011) to download with Steam. Are there any restrictions on the free version, or is it completely identical to the paid version? For example, does this count as owning a Source game for the purposes of mods that require you to have a game with the Source engine installed?
Comment: How do you find out about when they have free offers for games?  I'd jump on just about any offer they have if I knew when it would happen, most of the time I don't.
Comment: @Jeff in this case, I noticed when Jeff Atwood retweeted [something about it](https://twitter.com/#!/siracusa/status/114827428693676034). In the past I've heard about offers through various tech blogs, twitter, etc. I don't know of any official source from Valve that lists current offers.
Answer: The last time Valve made Portal free, it was identical in every way save one: You couldn't get the Source SDK with the free version, which you need to play mods.
However, Valve used to give you the SDK when you purchased Team Fortress 2, which is now free to play, so that may have changed.
Comment: This is good info. If somebody can provide confirmation that these same things apply to the current offer, that would be helpful.
Comment: @nhinkle http://cl.ly/GeAU/Screenshot%202012-05-14%20at%207.30.33%20pm.png
Answer: Portal is absolutely free—it's the same version, it applies to the current offer. Again, you will not get the SDK. Enjoy your free game! If you have the sequel, it is a big...demake, GLaDOS' voice has no expression, TOO robotic.

 You know, Caroline and stuff..

Enjoy.
Comment: The markup for spoilers is `>!` at the beginning of the line.
Comment: Do you have any reference for "it's the same version and applies to the current offer"? If you could provide that, I'd appreciate it; otherwise, you're just repeating what was said above.
Comment: @nhinkle I e-mailed Valve personally. Their Steamworks staff. [Their reply.](http://cl.ly/GeAU/Screenshot%202012-05-14%20at%207.30.33%20pm.png) This is for TF2 mostly, but I also later found out it applies to Portal.


How to create percentage column by year and type in R

Question:
I have table such as this one
Year Type Value
1991  A  4945
1991  B  525
1991  C  764
1992  A  640
1992  B  3935
1992  D  49
1993  K  49

I would like to generate a new column that calculates the percentage of each type for each year. The types may change per year, and some years only have one type
Eg. The first percentage should be 4945/(4945+525+764)
Any help would be very welcome. Thank you very much!
Answer: Do a group by 'Year' and get the proportions of 'Value'
library(dplyr)
df1 %>%
    group_by(Year) %>%
    mutate(new = proportions(Value) * 100) %>%
    ungroup

-output
# A tibble: 6 × 4
   Year Type  Value   new
  <int> <chr> <int> <dbl>
1  1991 A      4945 79.3
2  1991 B       525  8.42
3  1991 C       764 12.3
4  1992 A       640 13.8
5  1992 B      3935 85.1
6  1992 D        49  1.06

Or use base R with ave
df1$new <-  with(df1, ave(Value, Year, FUN = proportions) * 100)

data
df1 <- structure(list(Year = c(1991L, 1991L, 1991L, 1992L, 1992L, 1992L
), Type = c("A", "B", "C", "A", "B", "D"), Value = c(4945L, 525L,
764L, 640L, 3935L, 49L)), class = "data.frame", row.names = c(NA,
-6L))


Should I add a second main branch to this water supply layout?

Question: This image roughly represents the layout of a renovation house that I am working on. Due to a few layout changes and the plumbing nightmare that I inherited (a maze of piping, inaccessible shut-off valves, sloppy soldering), I am planning on re-plumbing most of the house. I attempted to search for some easy-to-understand articles and images regarding branch systems and pipe sizing but I didn't come up with anything that I found as very helpful.
My main question here is, should I use a single supply line (as indicated by the solid darker blue line) or should I end the bathroom line and add a second supply line (indicated by the dashed dark blue line) back to the kitchen and downstairs half-bath? Dark blue represents 3/4 copper pipe and light blue represents 1/2 copper pipe.
What would be the advantages and disadvantages of each layout?
Comment: Using sizing methods outlined in Appendix E of the IPC, either way will make very little difference as the same demand factor is applied to the supply either way. The additional friction loss through 3 reducing tees is very small. There's not enough information to say if the sizes are adequate in general.
Answer: Just a note that I'm not a plumber. That said -- anyone can install some pipes and have a plumbing system, but a GOOD plumbing system is a balanced system. To design one, you have to know the fundamentals.
Permit me to lightly delve into some physics (which may only be for the benefit of some other person with a similar question) --
The water in your pipes and its distribution are affected by: Gravity, Inlet Pressure, Inlet Volume, Outlet Pressure, Outlet Volume. As long as your upstream supply can provide the necessary pressure and volume, and your downstream outlet pressure and volume, accounting for gravity, doesn't exceed this, it should be fine.
That said, it is what happens when you overwhelm the system that would matter. Lets (just as an example) say that your outside faucet nearest your supply uses 75% of the available system GPM because it is on a 3/4" line, then you start to run hot water in a bath (1/2" lines) that would normally use another 50% of the available system. In a well balanced system, the faucet would drop to around 60% and the shower would use the other 40%. Now -- lets say the system is fairly balanced, except that your outside faucet is 5 feet below the supply and the shower is 5 feet above. Gravity reduces the water pressure of the bath, while increasing the pressure of the lower faucet allowing the faucet to "suck" more out of the system -- your shower may end up with only 25 or 30% of the water, while the faucet get 70 to 75%.
This is the reason the your main supply running through the house is larger, while each branch is a reduced side. The area of a 1/2" pipe, is half that of a 3/4" pipe. A 1/4" pipe is only 10% of the size of a 3/4" pipe. This is also the reason that each branch uses a T pipe, with the main pipe being the straight. This does a better job of letting each branch have a better chance of pulling from the main line equally, and why you'll often see the main line terminate with a cap after your last branch, rather than simply being an elbow directed into your last branch. There are some exceptions (2nd floor fixtures, outside faucets) where you may want this advantage. Restrictors at the fixtures can also assist in balancing your system by lowering the outlet volumes of individual fixtures.
Finally -- to answer your actual question, unless you've noticed problems with your system when more than one fixture is in use, you're probably fine in this layout with a first floor configuration, but I don't think that moving the three separate branches for the bathroom to a single branch off the main line is a bad idea by any means. But, I don't know that you're going to get a significant return on your work. If you go that route, consider making the branch to the bathroom a 1/2" off the main line, rather than a 3/4" to 1/2". Lastly, well located shutoffs for each branch are fantastic for when you're eventually want to make a repair without shutting of the water to the entire house.
Whether the 1/2" branch for the bath would be big enough -- seriously, who runs their toilet, shower and faucet at the same time in a single bathroom. :)
Hope that helped.
Comment: "seriously, who runs their toilet, shower and faucet at the same time in a single bathroom." I do, we have a single bathroom and it is my and me girlfriend so I use the bathroom as nature calls which doesn't always miss her showers. The toilet is filling up when I wash my hands so all 3 are running simultaneously.
Comment: Fair enough, but I pose that even doing so shouldn't be enough to overwhelm the system. Most Sinks are plumbed with 1/4" connections and many of todays toilets use lower flow of water to "quiet fill" the tank. Even so, it should only result in a slight drop in the cold water supply to the shower, which is typically being restricted or is rarely turned on completely, unless you're taking a cold shower :-). But, your point is valid.


Need help logging to site using CURL

Question: I have some problems logging to a site using CURL.
I think my problem is related to cookie file.
I use cookiejar when I'm logging in to collect the information and then
I use cookiefile to retrieve the information.
The problem is that from some reason the SMIDENTITY is added to the GET request from the browser and my CURL GET request does not contain such thing.
How do I get the SMIDENTITY value?
Do I need to include the  __UT* stuff?
Here is what was going on from the brower side:
<code>   GET https://direct.orange.co.il/selfservice/customer/bill4u HTTP/1.1
Host: direct.orange.co.il
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:22.214.171.124) Gecko/20101026 Firefox/3.6.12
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://www.orange.co.il/he-il/support/InnerHelpAssistence_lobby/
Cookie: __utma=242473949.486197456.1287994666.1288193684.1288790469.7; __utmz=242473949.1288176356.3.2.utmcsr=bill4u.orange.co.il|utmccn=(referral)|utmcmd=referral|utmcct=/action/mainAction; __utmv=242473949.|1=VisitorsStatus=LoggedInClient=1,; SMIDENTITY=BTDjG3qPjKo2JuOv2Kpny5x67dINOqb769XHS+ha7VNtqmmNSSHPlKhwQU/5sQmk9LdGud2nmf0ycs+yiZsU3Bc84Q9o7tJHN1BeuR7Q/49VA936+twTqsTPW/6+bR9Xk0Mcz94EsyovINIHGbC0FTbk7Lu9LcYlBoUMhOrt38NQ6spJubzVXQHNjZ1ah4wRWSLC0fcHHR0YA0sfHi6wc//wd31CNJxJOzCEX3aKmmMMgEVY4rjlKLu9SDDaQy3IqS+nZDcni1i1mUN9XrSg++dG7JNKWE5GFiZYsU9trcSJPfluFr4CBTKshmQziX8/oLIlUQrdu8XtC/p+MiKIv7AFhh0N8f8wZHcqcthgokXPo8Pe7v3W8PRkEyBqVhVFAt+oILmwGihySU8of5JDAdC/ZW/GuX42wZy6dIvNPdtcHzZXEV7yoiRElFplyFYzbt/w2kkJXI745nwY0R99RfK41o/tDdZq9t4Vh/zLqyZpGlqrc5n+6WmoX+eH6x7Kc/7KsycqbqUheVkpMqhMB7jbiMR9sVV27G0BJd2AL1mO6DNImrg5oB3hbs5cXVeiRaJSqJEXe2D2nmwzlFTlWsMEortuv3q/; __utmb=242473918.104.22.1688790469; __utmc=242473949; SMSESSION=1fXQyP10q6P5cAYfxnKws3NULK6iKjlX1lhtCzXJbCy2tpIFvPwObyaNQdV/HZ1m/ijgY8C0tWdVp9LHuIumQsEh94m8wLF6epNrU8/01Ac9ePCy/ArMR/ur3u0bchyzbWkD4q60qGzKojyqrkRedJ6eWHLz3pxFxbHkiDGxfor66heZYIZFR7aFzYBcH7XjR8dEju8sWJoM5+eRDE7OTw5oxYCzJi2w5kLD7PzpWc9yVOCK0hVuvjQTuln+RfhPzzB/yniBQCJDJt/Zk8wk8/Bs1Ks4M8wBMobAbywMTe+gSQkwZBqGhEu72QFa9F3+TLbzERr6ovLbU89OrguJTCP8aXcObRhiluqc47ZaBvIUFhBhX6l4+YXlMimJLtjG5+tBwgqbggZkI9zbzja13kl5Lhdl234Zn4WppmNy3EkpEIbX6BUtkxtwGaRieKFXpzui7cFzg/3MHXcWki+7accjryvuPOviHa9dn6VLXbnHJIFjo6KaqCHU/PjbObyGCy6QXA2d15J5rS9mLfWHrCVjWGLTqEqT/Knhy2rOHhQqHBeYrYyCgA0bdfcfo2Dfxqkb2cMNpB9UbqccGKwGsN1hMYhWkGPO29EQ6VTa+SXTwtnCLO18rYxjuYIH9PBbvndpLq+yfmPUAUw2KAIyB+hrwYtB5nn+IC1pXicyJkjN93lnc4R91BGJkWnC8bK7QoRERwM9+mww0QmcEkjp2sQd70PE7Xj0zQ02Gb0k9uL831B5Hvd4t2YM5PTFMRFAmR7BILYnqad/YeqIHAz1h9XX4tsXlKCICHn1ujmQbP5OwOoYaxIdRTQ2HWloJKmfdQ5PYs/Um8i5nOtvFbRCIor2QCRHPqMlMpwEseqSkJSzzOUaJMzlAMMfqR2gxz31W0uRZ5uhMoe8mMps4ZFLC462aGiw0vHOVDqXuKdqed+M54WLvo+PtF2x4V86/COspRZAqWmcBiAg+OnByQOSS5UAScE+RaB9MrY6ac22EWSSo6TNcZI7mDm/yejRA/SSwMpTWMxXg2aFnGI21fnmFFS7yZYWIRVTXYlr+PJ3RpqSFVch+sKQ3pVj/gP+E00nTtqtkGRBjL1bFJlxThCopkqbu8+UBxJk; JSESSIONID=MRvhpHlnRZ9Hps2JcX8kvpQNLRGKRTksCRyTQQkNG82Gkfj8yHGg!574440962
</code>
And this is from my CURL request:
<code>    GET /selfservice/customer/bill4u HTTP/1.1

Host: direct.orange.co.il

Accept: */*

Referer: https://registration.orange.co.il/copa/pages/protected/protectedredirect.aspx?original=http://www.orange.co.il/

Cookie: SMSESSION=gKf3lG8FdhNz+pezIUshjM42Hz1hhPssLATeIYZnLCi1iohEqpMo7H86kO4GtSTIfF04Fnu++qYlIkb+DAbMTwxd/pTEOsh94F/2iAaHqS2gSWn1dbWhlcasKAxBP7kYohdgDGsx5B90JBtbJQg0dj9Y305pcBhMjXnqcsuSEo/WzRNn/GAWoaaGJPwmFy9DSofVWB3/RZmaiugdOtWw8mJfneQNiui2Xvqx5PES9hnBx+fQNXKB6kaJPLFt0qsX4Atp5EhgJnbs6bOPPQaYc2FmmJF9YnNeHPsvPZJEcHf7FV75NGZN7760G6tFRC43mTO522CI5VB+QohM/AjUbILg1EJgnbSaDy8m/OVha+jMOsI11ZzYSSeR4f8SFd8gtlBVWe2UbWwocHqLJmvrw6rAOHt1WKU5EhBOGzfb2LYGjTHODLLcOx9PiCXaEzD/HKYlE17Yxec238+bE5qXtfmHPzxkCHdT7M7wC2/YpVucRYalc+lcMVvk7vENiAg1aXDvxl3K9YxUGDdngkF+CtkjdDqYP/R9SrKnd5kP36oCop8mRFPNsO30hXjHXCBSZgNoDA4/YkPEFJ68KLWXJUbgzSRwmF5c38ntlgC5kapc2XWREYqIkzCrdFbXLzP+1BZpOVaOe8umU/jMwCC8lgNilU+hA8qRSZJtB3Ni4oAdLe0Sgq28A6r2pngF0yrTVqlasRYQP1+ud6Z2uRqHQv4nEKh45sHi6fBeAFaVOo/Yp/B49/fnzd6SRC6JUT5r1vToluD2f/AouJAtV6zkeyXN0YP5njHVhpq2sCdB/3Iap8hJ+386pmzAFBTquJ6ko5BpII0Zhsy4YGa7OUh+1bt4e0WuUC0nzsckENrXtJphiJQEUDAQ63xTBKTegGKOtdWRfbEAj1QE7E7LSrIubWn9T92vRQdF63l3aX6LwegoiLqRa9092ILP94R3mt7J+UVmwUgHcX4K91yqqhSqYJOs6TlShIB2htYCB/+KCvkT4bnv+PlFB1SbPzCNdMK687rd7cKcsZ4KN/IaUzRBhckBuxujTta53y5WejTbI2VecOXHFV9QKWIdDhRzhay5YgVwBzt5XEHWXoYy1z67nunIku5dbKfc;
JSESSIONID=MHmJyFmbNZJxLpprzDW4m0d3Z90RYQdZ6rzzLWTtdLy4H1HBf7VP!-1366797818
</code>
How do I overcome this issue?
Thanks
Comment: What code are you using?
Comment: curl_easy_setopt(_curl, CURLOPT_POST, FALSE);
 curl_easy_setopt(_curl, CURLOPT_FOLLOWLOCATION, TRUE);
 curl_easy_setopt(_curl, CURLOPT_URL, https://direct.orange.co.il/selfservice/customer/bill4u);
 curl_easy_setopt(_curl, CURLOPT_COOKIEJAR, COOKIE_FILE1);
 curl_easy_setopt(_curl, CURLOPT_CONNECTTIMEOUT , 20);
Comment: This is weird, sometimes I do manage to get the required page.
But this works like 1 out of 10 attempts.
Comment: Do you have the 1 after FILE like that in your code?
Answer: Instead of curl how about use a tool that is meant for this kind of use case, such as mechanize.

Need help logging to site using CURL


Recyclerview : how to mix some post with image and no image?

Question: I want to display in same recycle-view which is some post have image and some post does not have images.
I can retrieve all the post with image and non-image,
but i want to change the size of the post when the user only post text(no image).
I expect the output like twitter feed..some post with image and without image have their own size.
Comment: You Can set Visibility to Gone or Visible for the Imageview depending on the condition.
Comment: You can show one image view when there is no image you can hide it else show
Comment: What you want to do is to create an adapter with multiple view types.

Possible duplication of: https://stackoverflow.com/questions/26245139/how-to-create-recyclerview-with-multiple-view-type
Comment: I would suggest to use default image which will override if no image is available.
Comment: https://stackoverflow.com/questions/26245139/how-to-create-recyclerview-with-multiple-view-type/51153083#51153083
Answer: Simple way to achieve this scenario is, All you have to do is create a view with both image and text, in recycler adapter check if image data is available make visibility of image visible else Image visibility gone.
Second Approach for this to make multiple view for RecyclerView.
 @Override
 public void onBindViewHolder(ViewHolder holder, int position) {

        Log.d(TAG, "onBindViewHolder called");
        ContentItem item = mContentItems.get(position);

        if(item.getName()!=null){
             holder.textName.setVisibility(View.Visible);
             holder.textName.setText(item.getName());
        }else{
             holder.textName.setVisibility(View.GONE);
        }

       if(item.getPreviewImageDefault()!=null){
             holder.imageIcon.setVisibility(View.Visible)
             Picasso.with(mContext).load("file://" + item.getPreviewImageDefault()).into(holder.imageIcon);
       }else{
             holder.imageIcon.setVisibility(View.GONE)
       }
 }

Answer: Another possible solution is create 2 xml layouts and use ViewType in your RecyclerView.
look this How to create RecyclerView with multiple view type?
Answer: If you want to hide the image when it is ic_launcher you could do that (suppposing that data.getImage() returns the id of the drawable as integer):
@Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {

   if(mItems!=null){
      AdapterData data = mItems.get(i);
      viewHolder.text.setText(data.getText());
      viewHolder.image.setImageResource(data.getImage());

      if(TextUtils.isEmpty(data.getText())){
         viewHolder.text.setVisibility(View.GONE);
      }else{
         viewHolder.text.setVisibility(View.VISIBLE);
      }

      if(data.getImage()==R.drawable.ic_launcher){
         viewHolder.image.setVisibility(View.GONE);
      }else{
         viewHolder.image.setVisibility(View.VISIBLE);
      }
  }

}

Answer: One possible solution, like some people have already said, is to hide/show the ImageView.
You could do that in the ViewHolder that you use for your RecyclerView.
class OptionalImageViewHolder extends RecyclerView.ViewHolder {
    private ImageView image;
    private TextView text;
    // any other views you have

    public OptionalImageViewHolder(View itemView) {
        super(itemView);
        image = itemView.findViewById(R.id.yourImageViewIdHere);
        text = itemView.findViewById(R.id.yourTextViewIdHere);
        // same for any other views you have
    }

    public void bindView(Tweet tweet) {
        // This is where the magic happens
        // Note: I make the assumption that you have a class called "Tweet"
        // that has a field for "text", a field for "image" (that can be
        // null if there's no image), and any other necessary fields.

        text.setText(tweet.getTweetText());
        if (tweet.hasImage() /* function that returns whether or not there is an image */) {
            image.setVisibility(View.VISIBLE);
            image.setImageBitmap(tweet.getImage()); // or however you are setting the image
        } else {
            // else just make the image invisible
            image.setVisibility(View.GONE);
        }
    }
}

Hopefully this gives you an idea.
Answer: RecyclerView supports different viewTypes (layouts) which is the proper way in such scenario. E.g.,
class MyAdapter : RecyclerView.Adapter<MyViewHolder>() {

  override fun getViewTypes(position:Int) =
    if (mydata[position].hasImage) return R.layout.mylayout_with_image
    else R.layout.mylayout_no_image;

  override fun onCreateViewHolder(viewType:Int, parent:ViewGroup) : MyViewHolder =
    // here viewType = layout id
    MyViewHolder(layoutInflater.inflate(viewType, parent))

  override fun onBindViewHolder(viewHolder:MyViewHolder, position:Int) {
    // guaranteed viewHolder.itemView is the view you want for that position
  }

}

Comment: `(mydata[position].hasImage)` i have user image and post image..


Prove that any power of $10$ can be written as sum of two squares

Question: I do know various techniques to solve this problem, but I need an elementary solution which can be explained to a fifth grader (that is, with as little algebra as possible, no modulo arithmetic).
Comment: Can the person who vote down this question, explain me why he did it? I just want to know what was wrong, with it.
Comment: There were several minor details wrong with it, but nothing that would compel me to downvote it. This is the closest you are going to get to an answer from the actual downvoter.
Answer: $3^2+1^2=10$, $8^2+6^2=100$, $30^2+10^2=1000$, $80^2+60^2=10000$, $300^2+100^2=100000$ etc.
Answer: If $n=2m$ is even, then
$$ 10^n=(10^m)^2+0^2$$
while if $n=2m+1$ is odd, then
$$ 10^n=(9+1)\cdot 10^{2m}=(3\cdot 10^m)^2+(10^m)^2$$


How to clean rust from a bathtub?

Question: I recently asked this question about our bath, and someone requested I make this cleaning query a separate follow-up.
We need to repair the enamel in the hole below, and to do this we need to clean out the rust etc. Does anyone have any advice about the tools / techniques to do this?

Thanks,
Andy
Comment: Some of that rust is likely on raw metal. The smaller crack above the pit probably extends down to metal.  You can't "clean" that away. Grind out the whole pit down to raw metal including the area up to the crack above it, then keep grinding a bigger area til you get to rust-free metal all around then  *immediately* prime it.  The little rust spot at bottom right can probably be removed with whatever stuff is recommended in the answers.
Answer: There are a couple of products that may help:

CLR - a calcium, lime, rust remover (I'm sure there are other brands as well, this is the one I know of).
Naval Jelly - This will do a great job of converting the rust from iron oxide to (??) something that won't rust any further. I used it on my table saw last summer.
A wire-wheel - an attachment for your drill with wire bristles that will (reasonably) gently grind the rust away. Note that this will also grind away some of the existing enamel if you're not careful, making for a larger repair area.
A wire brush - a hand operated version of the wire wheel. Less likely to do unintentional damage, but much slower and involves burning more calories to get the rust off.
Comment: I would go with CLR + but I would also grind that crack out , while cleaning that up you may not need anything more than grinding.
Comment: Think a slightly larger repair area would be a plus.  Want to make sure all the loose stuff is removed, rusty or not.
Comment: Naval as in fleet of warships, not navel as in belly button.
Comment: You know, @shoover, I looked at that 3 times... :/
Comment: Thanks folks! We're snowed under with stuff at the moment, but will see what's available at our local place soon (we're in Spain, so hoping I can translate some of this...)

How to clean rust from a bathtub?


Unable to "run:stop" on Heroku

Question: When I run heroku run lein repl, I don't seem to be able to shut down the process. I can do the following, and be exited from heroku's repl

    $ heroku  stop run.1
    Stopping run.1 process... done
    $ heroku  stop run.2
    Stopping run.2 process... done
    $ heroku  stop run.3
    Stopping run.3 process... done
    $ heroku stop run.4
    Stopping run.4 process... done

I hope to god I am not being billed. Both heroku stop and heroku ps:stop (as mentioned here) fail to remove the runs from a heroku ps listing.

    $ heroku ps
    Process  State             Command
    -------  ----------------  ------------------------
    run.1    complete for 26m  lein repl
    run.2    complete for 16m  lein repl
    run.3    complete for 7m   lein repl
    run.4    complete for 2s   lein repl

How do I do that? Or do I just need to wait for the complete listing to disappear?
Thanks
Answer: Those items are not running, but are complete.  A running instance will be showing as up for xm where xm is the time in minutes.  complete shows you how long that process has been stopped for.
For more info on heroku ps, see here.
To be extra sure you're not being billed, you could ask support.
Comment: Ok, just wanted to confirm. Thanks.

Unable to “run:stop” on Heroku


Is there some "types" of "discontinuous derivative"?

Question: I'm just started learning standard Calculus class in the university (It treats James Stewart's "Essential Calculus: Early transcendentals" for 1 semester, just letting you know) and I got some questions about the relationship between 'differentiability of a function' (i.e.the existence of $f'(a)$ regarding $x = a$) and 'continuity of a derivative of function'.
I made a derivative of a function on my own, which is
$$f'(x)=\begin{cases}-x + 2 & x<0, \\ 1 & x=0, \\ -x & x>0. \end{cases}$$
I said the integral constant $C = 0$ arbitrarily for convenience. Because $f'$ is defined at every $R$, then $f$ is continuous at every $R$ by theorem (don't remember the number of it...) By integrating $f'$ at every interval, then we get
$$f(x)=\begin{cases} -x^2/2 + 2x & x<0, \\ 0 & x=0, \\ -x^2/2 & x>0. \end{cases}$$
But by using the definition of $f'(0)$ and given $f(x)$, we have to say that $f'(0)$ doesn't exist! So this was a contradiction. I asked about this in my country's internet community, but the answers were the following.

"If $f'(a)$ exists, and $f'$ is not continuous at a, then there are 2 types.

Both left and right limit of $f'$ at $x = a$ exists but $f'$ is not continuous at $a$

Either left or right limit of $f'$ at $x = a$ doesn't exist, so $f'$ is not continuous at $a$.

$f'$ is only available at type 2.

I just accepted with no excuse, but after few days, I just wanted to know some prove about this.
I read about this but as I said before, I just started Calculus, so it was too hard for me to understand some comments at there.
I am not American or British, so I'm not very good at English and sorry about that.
Question is that could somebody prove that "if $f'(a)$ exists and $f'$ is discontinuous at $x = a$, then left-hand or right-hand limit of $f'$ at $x = a$ doesn't exist."
Thx for reading this awful long writing.
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Comment: if f'(a) exists and f' is discontinuous at x = a, then left-hand or right-hand limit of f' at x = a doesn't exist. You need an example for this?
Comment: Thx very much guys. I really didn't expect this much kindness. In fact, by discussing with my calculus professor yesterday, I knew that "if \lim_{x\to a+} f'(x) = A, \lim_{x\to a-} f'(x) = B and A\neqB, then f'(a) doesn't exist" by using similar method(M.V.T.) as the site @HansLundmark Lundmark attached. Now I'm curious about the following saying. "If f'(a) exists and f'(x) is not continuous at x = a, then neither \lim_{x\to a+} f'(x) nor \lim_{x\to a-} f'(x) doesn't exist.".
Comment: Lastly, I thought I could solve this problem by 'not using any hard stuff(real analysis, set theorem, etc. I don't even know what these disciplines talk about..)', but now I think I should study some of them. I think I couldn't solve this curiosity with the things I have learned until now...
Comment: I wrote the math symbols in code, but they just popped out without changing.. I think I should learn more about writing.. sorry for the disturbance.
Comment: @shlee: What you want to prove is equivalent to what's proved in the question I linked to. (Since "A implies B" is equivalent to "not B implies not A".)
Answer: The answer you quoted in your question is nonsense. Here is a well-known fact for a given function $f$:

If $f'(a)$ exists, then both left and right derivatives $f'_-(a)$ and $f'_+(a)$ exist and we have $f'(a) = f'_-(a) = f'_+(a)$.
If both $f'_-(a)$ and $f'_+(a)$ exist and $f'_-(a) = f'_+(a)$, then $f'(a)$ exists.

Two obvious consequences are:

If one of $f'_-(a)$ and $f'_+(a)$ does not exist, then $f'(a)$ does not exist.

If both $f'_-(a)$ and $f'_+(a)$ exist and $f'_-(a) \ne f'_+(a)$, then $f'(a)$ does not exist.

The continuity of $f'$ in $a$ does not have anything to do with  $f'_-(a)$ and $f'_+(a)$. First note that to speak about the continuity of $f'$ in $a$ requires that $f'(x)$ exists in some open interval containing $a$, and this is not guaranteed by the mere existence of $f'(a)$. But even if that is satisfied, the continuity of $f'$ in $a$ is an additional feature.
Let us look at your $f'$. First you should not write $f'$ because this suggests that your function is the derivative of some $f$ which you cannot know to be true without a proof. So write $g$ instead of $f'$ and ask

Is $g$ the derivative of some $f$?

As you have shown, the answer is "no". But this has nothing to do with the discontinuity of $g$ in $0$. There are examples of discontinuous functions appearing as derivatives. See malklera kwezibalo's answer.
The function $f$ which you found is continuous and has a (continuous) derivative in all $a \ne 0$. Moreover, $f'_-(0)$ and $f'_+(0)$ exist, but are different. Thus $f'(0)$ does not exist.
Comment: Why is nonsense? How do you define $f'(a)$? Isn't it the limit of $f(a+h)-f(a)/h$ for $h\to 0$? because if $f'(a)$ is defined in that way, my computation show that the limit exist, hence $f'(a)$. Could you explain better, please?
Comment: @malklerakwezibalo I did not claim that **your** answer is nonsense, but the answer quoted by the OP:  "I asked about this in my country's internet community, but the answers were the following." I made an update to clarify this point. I am sorry that the previous version led to a misunderstanding.
Comment: I have now a problem with your first statement. The example in my answer is a function where $f'(0)$ exists, the derivative exists also for all $x\in (-\epsilon,\epsilon)$ but the function $f'$ is not continuous in $0$. However, your first sentence claims that such a function does not exist.
Comment: @malklerakwezibalo No, I explained the relation between $f'(a), f'_+(a), f'_-(a)$. As I said, there is no connection to the continuity of $f'$ in the point $a$. Quotation from the question: "If $f'(a)$ exists, and $f'$ is not continuous at a, then there are 2 types.  1. Both left and right limit of $f'$ at $x = a$ exists but $f'$ is not continuous at $a$ .  2.  Either left or right limit of $f'$ at $x = a$ doesn't exist, so $f'$ is not continuous at $a$." This is nonsense.
Answer: Consider the function $f\colon\mathbb{R}\to\mathbb{R}$ given by $x\mapsto x^2\sin(\frac{1}{x})$. This function is continuos in $x=0$ because $\lim_{x\to0}f(x)=0$.
The derivative for $x\neq0$ is $$f'(x)=2x\sin(\frac{1}{x}) - x^2\cos(\frac{1}{x})\frac{1}{x^2}=2x\sin(\frac{1}{x}) - \cos(\frac{1}{x})\qquad x\neq0$$
and $f'(x)$ do not exists on $x=0$. However, doing the limit of incremental you have
$$\lim_{h\to 0}\frac{f(0+h)}{h}=\lim_{h\to 0}\frac{h^2\sin(\frac{1}{h})}{h}=\lim_{h\to 0}h\sin(\frac{1}{h})=0$$
because $-1<\sin(\alpha)\leq1$ is bounded and $h\to0$.
Comment: I know that is one kind of an example, but I want to know some kind of proof about that..
Comment: @shlee Maybe this answer your question? https://math.stackexchange.com/a/2332932/909032
Comment: Well... I don't know Darboux's theorem, so I think I should study that at first. I thought I could solve(prove) this problem by using just simple calculus knowledge, but I think that was just a misunderstanding.
Comment: $f''(0)$ exists as you have shown. But $f'$ is not continuous at $0$.
Comment: @PaulFrost you mean "$f'(0)$ exists". I never write about a second derivative.
Comment: @malklerakwezibalo Yes, it was a typo. You have shown that $f'(0)$ exists and has value $0$. But this contradicts your statement "$f′(x)$ does not exists on $x=0$". What is clear is that $\lim_{x\to 0} f'(x)$ does not exist.


How do I fill a html form with fields from my database in Django and postgresql?

Question: How do I fill a html form with fields from my database in Django and postgresql?
I need to select year from drop down and value of flag(0,1,2), with the combination of these
two I want my form to populate from the values stored previously in the table corresponding to the above combination.
Answer: You can collect the data that you want to pass to your html form inside the view and pass the data as context where you render the html file. E.g;
def yourview(request):
   data=Data.objects.all()
   return render('yourhtml.html', {'variables':data})

Later, inside the html, you can use this 'variables' in your dropdown like below;
<select name="cars" id="cars">
{% for eachvar in variables %}
  <option value="{{eachvar.id}}">{{eachvar.name}}</option>
{% endfor %}

</select>


PHP Call another Domain PHP Script

Question: I have one domain that is running a cron job every 15mins.
I starts a php script and from that script I do some general housekeeping.
I also now need to get that script to run some other php scripts on other domains.
eg:
www.domain2.com/this.php
www.domain3.com/this.php
how do I run these extra php scripts from the original domain?
Comment: Unless you control those domains and have access to the actual `.php` files from the original PHP script, you can't do this.  All you would be able to get is the output of those scripts.
Comment: can I call the URLs from one domain?
Answer: You can run the other domain scripts with
<code>   file_get_contents("http://www.domain2.com/this.php");
</code>
Comment: You cannot have more than one URL as a parameter of `file_get_contents`
Comment: I made a wrong copy-paste. I don't think I deserve a negative vote for that.
Answer: If its really simple call to other URL. Add following to the end of your main server.
<code>for ($i=2; $i < $totalServers; $i++) {
    file_get_contents('www.domain' . $i . '.com/this.php');
}
</code>
Answer: This is something which you want to run the cron from one domain to another domain.. Before that you need to have access to this cron from those domains from which you need to run this cron. You can do that by editing the cron tab of those domains .. lets day cronme.pl you want to run from the d2.com, you can set cron tab in d2.com ...
~Gururaj

PHP Call another Domain PHP Script


How can i define something by switch?

Question: I am trying to setup a sorter of receiving the messages. However, the following code (actual outcome) is always undefined.
This program is a part of the roulette, in which a command is required to place a bet. The code itself is tried in Google Chrome.
var position;
function positionTypeConverter(betP) {
    if betP > 50 | betP < 0 | betP = NaN {
    throw ('invalid position');
    } else switch (betP) {
    case 1<=betP<=48:
        return position = ' '+betP+', single ';
        break;
    case 0:
        return position = ' zero ';
        break;
    case 49:
        return position = ' independent ';
        break;
    case 50:
        return position = ' LuckyEi ';
        break;

    };
    console.log(this.position);

};

by inputting positionTypeConverter(number), 'number' can be anything, it is all the way undefined.
but I would expect the result example of below:
positionTypeConverter(12) comes with 12, single
Comment: Your code contains syntax errors. Fix those first.
Comment: What is `console.log(this.position)` supposed to do?
Comment: @melpomene it is an outcome
Comment: What do you mean?
Comment: I made that line to log the result
Comment: First off, that line is never reached. `return` leaves the function. Second, you're logging `this.position`, not `position` or the return value of the function.
Comment: `break` after `default` case is redundant, to actually all the of the break are redundant as you're returning values, so once it hit `return` doesn't go to next line
Answer: Your code is not valid Javascript Syntax. Change it as follow
function positionTypeConverter(betP) {
  if( betP > 50 || betP < 0 || isNaN(betP)) {
     throw ('invalid position');
  } else {
    switch (betP) {
    case 0:
        return ' zero ';
    case 49:
        return ' independent ';
    case 50:
        return ' LuckyEi ';
    default:
        return betP+', single ';
    }
  }
};

And if you want to log the result inside the function:
function positionTypeConverter(betP) {
  if( betP > 50 || betP < 0 || isNaN(betP)) {
     throw ('invalid position');
  } else {
    var result = '';

    switch (betP) {
        case 0:
            result = ' zero ';
            break;
        case 49:
            result = ' independent ';
            break;
        case 50:
            result = ' LuckyEi ';
            break;
        default:
            result = betP+', single ';
    }

    console.log(result);
    return result;
  }
};

Comment: how can I add an output through console log?
Comment: You should first call this function and then log the output, for example.  `var result = positionTypeConverter(12); console.log(result)`
Comment: `break`after `default` case is redundant, to actually all the of the `break` are redundant as you're returning values, so once it hit `return` doesn't go to next line
Comment: Thanks for the hint, I update the answer.
Comment: that means if no `break` is needed if i use `return`?
Comment: Yup as @Code Maniac said, once your code hit the `return` statement, it doesn't go to the next line. So `break` would be useless. If you are not using `return` you should put `break` tho.
Comment: is that possible to show the outcome (like in console) within the code?
Comment: Yes why not, in that case you can simply replace for example this line `return ' zero ';` with something like this `console.log(' zero ');  break;`. Repeat this for all cases including `default:`.
Comment: but never was `positionTypeConverter` defined even that, even I've changed the code above and replaced the line like return into console.log
Comment: Check the answer again, I added what you want

How can i define something by switch?


How do I release tension on a McKinney spring hinge?

Question: Followup to my previous question about plumbing a door. Now I need to take off the spring hinges, but I don't know how to release the tension. Not a duplicate of this question, as my hinges are McKinney brand and no amount of pushing on the hex key will disengage the ratchet.
Both spring hinges have two tiny holes on the side -- one near the top on the door side, the other near the bottom on the jamb side, both less than 1/16" -- with a coiled piece of thin metal inserted. The top of each spring hinge accepts a 5/16" hex key. I can turn the hex key clockwise but not counterclockwise. When turned clockwise, the socket recedes into the hinge and then pops back out. Nothing happens at the two tiny holes when I do this.
I'm tempted to try just unscrewing the hinge while it's under tension. How bad of an idea is this? I bought an Everbilt spring hinge, with a pin tensioning mechanism, to replace the McKinney one if I can get it off.
Comment: Those hinges can clamp shut pretty fast and can pinch you real good. Get a pair of vice grips  or a "c" clamp and and clamp it over the top of the hinge to prevent it from slamming shut as you remove the screws.
Comment: There is supposed to be a removable pin that will allow you to unload the spring. One pin is the rolled pin you pictured, the other should be on the side of the barrel at the hex key end. It should be a solid very short pin, something that may take tweezers to remove when you hold the hex key in just the right spot to make the pin loose in its hole.
Comment: Thank you both! I ended up figuring out how to release the tension. These McKinney hinges work a bit different than the Everbilts - no removable pin.
Answer: I finally found a set of official instructions for "McKinney 1500 Series Single Acting Spring Hinge for 1502, 1502TRS, 1522, 1552, 1572".
The holes with coiled metal aren't part of the adjustment mechanism. Instead, there's a 1/16" hex set screw that's only accessible with the door open. I needed to loosen that to enable the tension release feature of the 5/32" hex on top of the hinges.


Is there any use for the hand that you find in the guest house?

Question: Early on in the game, while in the guest house, you can find a hand on the floor and are able to pick it up.
Is there any use for this hand at all? What is the point of being able to pick it up?

Spoiler to help clarify exactly what I mean:

 The hand I refer to is your own severed hand, that Mia chops off with the chainsaw. Once you get up you can pick it up from the floor nearby. I can also confirm that regardless of if you pick it up or not, it will still get re-attached the same way later in the game.
Answer: Regardless of picking up the hand or not, although most people do, when you are at the dinner table your hand is stapled back on. Even though it isn't realistic (but it is a game, with zombies, and first aid liquid etc), so yes Ethan shouldn't have any use of his hand after it is stapled back on but spoiler:

He's infected just like the Bakers are so that's the other reason why his arm is "healed" and again usable, that and it being a game and for the sake of progression it also works. The idea is that because he has the "Mold" he is able to coapt the limbs easily. The first aid liquid is supposedly something that just speeds up the process and helps you regenerate/heal quicker. -- You picking it up and then seeing it back on you working is supposed to hint to the fact that you are now infected.

So you can leave the hand if you want, it'll find its way back to you ;)

To directly answer your question in short: The use for the hand is quite literally you regain usability. And the point of picking it up: There isn't much other reason than because you can.

You can see more in this discussion.
Comment: Sorry for elaborating and going a bit off focus. But yeah that's about it, there is no reasoning behind it other than you can. Just another "creepy" element, that you can hold your own severed hand.
Comment: I think you have gone a bit off focus with this answer... for the most part you are basically just saying it will still get reattached either way, but I already mentioned this in my answer, so it doesn't provide any use. The only part that actually has any relevance as an answer is: `"There isn't much other reason than because you can"`


How can I use a Method from a class in a different class?

Question: I've been trying this for hours now with no avail.
I'm trying to use the paintComponent method in my Game.java class, but I'm not sure exactly how to do this.
I've tried calling the function directly but of course it does not work as it needs to return something.
The method I need to use is in this "Circles.java" class:

package testgame;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import javax.swing.JPanel;
import javax.swing.JPanel;

public class Circles extends JPanel {

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Bubbles(g); }

    private void Bubbles(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        RenderingHints rh
                = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        rh.put(RenderingHints.KEY_RENDERING,
                RenderingHints.VALUE_RENDER_QUALITY);
        g2d.setRenderingHints(rh);
        int x, y, size;
        x = (int) (Math.random() * 500) + 15;
        y = (int) (Math.random() * 450) + 15;
        size = (int) (Math.random() * 30) + 10;
        g2d.setColor(Color.green);
        g2d.drawOval(x, y, size, size); }
}

This is the class that needs the paintComponent method (Game.java):

package testgame;

import java.awt.EventQueue;
import javax.swing.JFrame;

public class Game extends JFrame {

    public static void LoadUI() {
        JFrame frame = new JFrame("Just a test!");
        frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
        frame.setSize(550, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true); }

public static void main(String[] args) {
     frame.add(new (Circles()));  }
}

The error I get is at the:
frame.add(new (Circles()));

The error being:
identifier expected

cannot find symbol
symbol:  method Circles()
location: class Game

cannot find symbol
symbol:  variable frame
location: class Game

Comment: Possible duplicate of [paint() and repaint() in Java](https://stackoverflow.com/questions/10768619/paint-and-repaint-in-java)
Comment: instead of frame.add(new (Circles())); write frame.add(new Circles());
Answer: First of all, It should be new Circle () instead of  new (Circle ())
Second thing as new and Circle() both are in different bracket ,java treat Circle() as method of Class Game hence you are getting error like that.
Answer: What you are trying to do here frame.add(new (Circles())); inside your main method is accessing a variable that is only available in your LoadUI() method.
To be able to access that variable you would need to declare it outside your LoadUI() method, something like this:
    ...
    public class Game extends JFrame {

    JFrame frame;

    public static void LoadUI()....

Secondly, as Manish Jaiswal mentioned above, your placement of brackets is wrong, meaning your way of initializing the Circles object is wrong.
To make this code work, you could do something like this in your main method:
LoadGUI();
frame.add(new Circles());

Though I would recommend using a separate class / object for your GUI / JFrame and not making the LoadUI() method static.
You could also indent your code in an easier to read way, just to make it easier for yourself as well :)
Comment: Ayy thanks mate, it worked! I declared the variable like this: public static JFrame frame = new JFrame("Just a test!"); and Java got it right! By the way do you think I should delegate each class to do a specific function (like drawing the circle, loading the UI) and then execute all of that in the main?
Comment: @GianfrancoStercoforti Well, in general Java is an object-oriented language, meaning that yes, you could use a separate class for each function. But what you should try to do is model classes (just partly) after some kind of object. That's why there is JFrame. It is supposed to represent a window, broadly speaking. You could do the same thing with the File class, which represents a file.

So I would recommend you use separate methods for loading the UI and so on, but maybe keep it in the same class and work with objects / classes for things like file management instead (separate purpose).


How to Fix the Instruction in Code which cause application crash

Question: The main application file is crashing becausing The server is affected by a format string bug when handles the players nicknames due the access to
an invalid memory zone.
The instruction executed is "cmp [EAX], 00000000" where EAX contains 4
of the bytes in the nickname and Crashes the Server.
I debugged and found that "%s" is missing before the logging string passed to the File_printf function. So i have tried to add this string via IDA Debugger and Successed. After entering these bytes now the server is crashing with the message "server is not vulnerable" before it was crashing with the message "server is vulnerable"
CODE
Bytes I have entered to patch the application:
RVA
    00400000

OFFSET
    0041dfad    cc  68          ; push 0061d0dc
           +    cc  |0061d0dc

           +    cc  e8          ; call 0040d270
           +    cc  ^0040d270

           +    cc  83          ; add esp,04
           +    cc  c4
           +    cc  04

           +    cc  e9          ; jmp 0041e059
           +    cc  ^0041e059

    0041e054    e8  e9          ; jmp 0041dfad
           +    ??  ^0041dfad

0055DD63 cmp     dword ptr [eax], 0

 /*source*/
if ( *(_DWORD *)a1 )
    a1 = sub_445D50();
  if ( v2 )
  {
    --*(_DWORD *)(v2 + 4);
    *(_DWORD *)a1 = *(_DWORD *)(v2 + 20);
    *(_DWORD *)(v2 + 20) = a1;
  }
  else
  {
    v3 = *(_DWORD *)((a1 - 4) & 0xFFFFFFFC);
    --dword_798ABD0;
    sub_445D50();
    memset(*(void **)(v3 + 8), 0xCDu, *(_DWORD *)(v3 + 16));
    free((void *)v3);
  }
}

/Hex Value/
0055DD63  83 38 00
After Testing the Server to Crash then the server Crashed with the message in the testing tool "Server is not Vulnerable" but Crashed.
And in the Debugger IDA i get this result with the detailed Message:
55dd63: The Instruction at 0x55DD63 referenced memory at 0x61616161, The memory could not be read -> 61616161 (exc.code c0000005, tid 4692)

Image 1
Image 2
Image 3
Image 4
Image 5
I can Share the testing tool also but not here because the testing tool has .simplese trojan and it may harm your pc, but i can share the Source code of the testing tool on Request.
Answer: The bug is caused by the logging function NetManager_LogMessage which
takes the text to dump, adds a timestamp (using snprintf) and then
passes the whole string to the function File_printf without the needed
format argument (%s) and you need to using the value 05 instead of 04 to make an ampty space to fool the bug. This trick work on many games and good luck


Integrate Spine with juggernaut

Question: I am trying to integrate Spine with Juggernaut. First I tried to clone fowa branch (https://github.com/maccman/spine.rails3/tree/fowa) but I am not able to clone that branch so I am doing app myself following by maccman/spine.rails3 instead of Pusher I used Juggernaut. For Juggernaut I followed maccman/Juggernaut (https://github.com/maccman/juggernaut/tree/)
I installed the redis server by
sudo apt-get install redis-server

Already I installed npm
spritle@ubuntu:~$ npm -v
1.0.106

For
npm install -g juggernaut

npm ERR! Could not create /usr/local/lib/node_modules/___juggernaut.npm
npm ERR! error installing email@example.com Error: EACCES, Permission denied '/usr/local/lib/node_modules/___juggernaut.npm'
npm ERR! Error: EACCES, Permission denied '/usr/local/lib/node_modules/___juggernaut.npm'
npm ERR! Report this *entire* log at:
npm ERR!     <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR!     <email@example.com>
npm ERR!
npm ERR! System Linux 2.6.32-21-generic
npm ERR! command "node" "/usr/local/bin/npm" "install" "-g" "juggernaut"
npm ERR! cwd /home/spritle
npm ERR! node -v v0.5.5-pre
npm ERR! npm -v 1.0.106
npm ERR! path /usr/local/lib/node_modules/___juggernaut.npm
npm ERR! code EACCES
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /home/spritle/npm-debug.log
npm not ok

I am getting this error
So I did
npm install juggernaut
For this I am getting

firstname.lastname@example.com ./node_modules/juggernaut
├── email@example.com
├── firstname.lastname@example.com
├── email@example.com (email@example.com)
└── firstname.lastname@example.com

After that I did
gem install juggernaut

For
spritle@ubuntu:~$ sudo /etc/init.d/redis-server start

I am getting
Starting redis-server: redis-server.

For
spritle@ubuntu:~$ juggernaut

I am getting
juggernaut: command not found

So for http://localhost:8080
I am getting
Unable to connect error

I installed the redis and juggernaut. When i run localhost:8080 I am getting error.
I don't know what i did wrong. Anyone can help me.
Answer: I am an idiot i want to start the juggernaut server at where i was installed. Instead of that i started the setver in other place. Now i can able to connect to juggernaut. I can access http://localhost:8080. Now i started juggernaut at
spritle@ubuntu:/usr/local/lib/node_modules/juggernaut$ juggernaut server.js

Integrate Spine with juggernaut


String Replace column data with data from another table

Question: I have two tables:
TableA:
ID       Values
---------------
1         Q
2         B
3         TA
4         BS

TableB:

RawValue    Value
------------------
[1][4]      QBS
[2][1][3]   BQTA

I need to generate TableB values with its given RawValues. each [X] in rawvalue is the ID coulmn of TableA and shoud be replace with its value .
[1][4]  means that Value of TableA with has ID of 1 (Q) and Value of TableA with has ID of 4 (BS) then should equal to QBS.
can anyone suggest a way to do it?
this is what I have already tried:
    update tableb set value=replace(rawvalue,'[' + (select id from tablea where id = cast(replace(replace(rawdata,'[',''),']','') as int)) + ']',
(select values from tablea where id = cast(replace(replace(rawdata,'[',''),']','') as int)))

By the way: this is still in test process and I can totally change tables, rowvalue format and replacement methods if anyone has a better idea.
Answer: declare @tableA table (id int, value varchar(50))
insert into @tableA (id, value)
select 1, 'Q' union all
select 2, 'B' union all
select 3, 'TA' union all
select 4, 'BS'

declare @tableB table (rawdata varchar(255), value varchar(255))
insert into @tableB (rawdata)
select '[1][4]' union all -- QBS
select '[2][1][3]' -- BQTA

update b
set value = (
        select a.value + ''
        from @tableA a
        cross apply (select charindex ('[' + cast (a.id as varchar(50)) + ']', b.rawdata) as pos) p
        where pos > 0
        order by pos
        for xml path('')
    )
from @tableB b

select * from @tableB

P.S. I would recommend not to name field similar to reserved keywords (I mean Values).
Comment: Thanks a lot it works like a charm. although I didn't understand a bit how code works.
Answer: Turn RawValue into XML, shred the XML to get one row for each value in RawValue and join to TableA to get the value.
Use the for xml path() trick to concatenate the values from TableA.
update TableB
set Value = (
            select T.Value as '*'
            from (
                 select row_number() over(order by T2.X) as SortOrder,
                        TableA.Value
                 from (select cast(replace(replace(TableB.RawValue, '[', '<x>'), ']', '</x>') as xml)) as T1(X)
                   cross apply T1.X.nodes('x') as T2(X)
                   inner join TableA
                     on TableA.ID = T2.X.value('text()[1]', 'int')
                 ) as T
            order by T.SortOrder
            for xml path('')
            )

SQL Fiddle


Autocomplete in a nested list when child is matched but parent is not

Question: Our web app has a "jurisdiction chooser" which is a 2-level nested list of all US states and many large US cities. Both cities and states are selectable. I'd like to add autocomplete to this list chooser. An interesting challenge is what to do when the autocomplete input matches a city but not its containing state.
My latest attempt is below, but it doesn't feel quite right. Any suggestions for how to handle this case better?
Answer: I don't think it's a bad solution, maybe a bit confusing.
The problem is to differentiate a syllable or word between two possible states. To do this you use three typographical variations:

Color (blue): to better visualize the syllables
Weight (bold): same objective

And an addition not raised: differentiate the state that doesn't contain that syllable in its city.

Style: italics

Three typographical variations for two results.
I propose to remove one and enhance the others to obtain a better perception. The Q example shows a simple result, but in case more cities result in a state, maintaining the same line spacing between states and cities will generate a bigger visual confusion. At least, the user is only interested in seeing the "river" formed by the results (Gestalt Principle of Similarity) to quickly find the needed item. Showing that a city belongs to a state is as simple as reducing the space between text lines, the text-indent does the rest.

Result
Simplifying noise by removing one of the visual typographic variation in different items and improving perception by associating cities and states by proximity.
(Gestalt Principle of Proximity)
Comment: good answer....


How do I print to console in assembly?

Question: I would like to learn Assembly language. Just to get started, I would just print the result of, let´s say 5+5 to the console. I am using Flat Assembler in Windows 7 64bit.
I have just begin writing a code and I would like the v1 and v2 strings be printed to the console, but I don´t succeed:
v1 db 'Enter value 1: ', 0
val1 db 80 dup(?)
v2 db 'Enter value 2: ', 0
val2 db 80 dup(?)

After compiling the code I try to run it with fasm.exe hello.ASM, but noting is displayed. I thought I would be promted to type a value.
What I am doing wrong?
Comment: You're declaring the data, but not doing anything with it. You can call Windows functions (e.g. OutputDebugString) or c-runtime functions (e.g. printf) to display something.
Answer: You have to write the code to actually print the data to the console -- right now, you're just defining some blocks of data.
You'd normally print the data with something like WriteFile or (if you want to get fancier) WriteConsoleOutput. Here's a sample "Hello World" program as a starting point:
.386
.MODEL flat, stdcall

getstdout = -11

WriteFile PROTO NEAR32 stdcall, \
        handle:dword,           \
        buffer:ptr byte,        \
        bytes:dword,            \
        written: ptr dword,     \
        overlapped: ptr byte

GetStdHandle PROTO NEAR32, device:dword

ExitProcess PROTO NEAR32, exitcode:dword

.stack 8192

.data
message db "Hello World!"
msg_size equ $ - offset message

.data?
written  dd ?

.code
main proc
    invoke GetStdHandle, getstdout
    invoke WriteFile,                   \
           eax,                         \
           offset message,              \
           msg_size,                    \
           offset written,              \
           0
    invoke ExitProcess, 0
main endp
        end main

Comment: Will also require input routines as well as perhaps some decimal/binary conversions.
Comment: @BrianKnoblauch: Yes, but since it's obviously homework, I didn't want to just hand it everything needed...
Comment: Comment wasn't aimed at you, it was for the OP's benefit, so he wouldn't be disappointed when it didn't solve all his problems.  :-)
Comment: Thank you for you answer. First of all, this is not homework (as some kind of proof for that, maybe you can look at my previous questions to see that I have a general interest in programming languages and have asked several questions regarding different programming languages, technices etc). I have never been in contact with assembly and would just like to know about the basics. So, to print to console, I have to import libraries in some way that have that functionality, and then call those methods in that library?
Comment: Yes, that's pretty much it. On older systems like DOS it was pretty common to just write the data to the screen buffer, but a modern system won't normally support/allow that.
Comment: How about assembly directives and instrcutions (like MOV, DB etc), I suppose they differ from architecture to architecture and from OS to OS? Any good book recomendation on this topic for att real assembly beginner like me?
Comment: @Rox: yes, they vary between systems. Most of the books I know of are specific to an individual system (e.g., manual for a particular assembler, OS, or processor). You might want to look at Randy Hyde's [The Art of Assembly Language](http://homepage.mac.com/randyhyde/webster.cs.ucr.edu/www.artofasm.com/index.html) -- though uses its own unique syntax.

How do I print to console in assembly?


What is the difference between Neural Damping and Neural Feedback?

Question: XCOM: Enemy Within introduced several new toys for the player to use, including the ability to genetically modify your soldiers. Most of the new gene mods are straightforward but there are still a few that leave out a detail or two.
Neural Damping gives +20 will when defending from psi attacks and gives immunity to panic and Mind Control.
Neural Feedback damages anything that attempts a psi attack and forces all of that enemy's psi attacks to go on cooldown.
Does Feedback also provide immunity to Mind Control? If a Sectoid Commander or Ethereal hits my soldier with Mind Control and lives, does the control still take place? Does Feedback also damage an Ethereal using it's Psi Lance?
I feel like Damping is better all around for preventing psi attacks, but does  Feedback provide that same level of protection, or is it more situational and gimmicky?
Answer: Neural Feedback provides no will bonus. It basically just hurts an enemy when they fail mind control. The practicality of this is to allow a psi-soldier with mind shield or psi-armor to kill sectoid commanders in droves. It is rather in effective against ethereals but does have a good chance to hurt them. Neural feedback does not prevent mind control or boost Will in any way. Neural feedback does not damage an ethereal using psi-lance.
Neural Dampening is for those who are going to be very susceptible to psionic attacks. This is mainly to provide a very stable case in which you will not be mind controlled. +20 will allows for a missive boost to your psionic defense. The only downside is that your soldier is stunned after a blocked mind control attempt.
They are mainly preference and one isn't particularly better than the other in my opinion. They both have very practical applications. Neither of these effect psi-lance, besides the defense provided by the Will boost with Neural Dampening.
References based on in-game descriptions and personal experience, as well as analysis of game play video relating to this topic.
Comment: I think Neural Feedback hurts an enemy regardless of success/failure.


In Banach algebra $A$ if $ab=ba$ prove that $e^{a+b}=e^ae^b$

Question: Let $A$ be a Banach algebra

if $ab=ba$ then  prove that $e^{a+b}=e^ae^b$

I've started by $e^a=\sum _{n=0}^{\infty }\frac{a^n}{n!}$, I want to know if this is correct way?
Any help will be greatly appreciated.
Comment: yes, and then multiply it with $e^{b}$. Do you know how to multiply two convergent series? There's a we'll known formula
Comment: @Dear Fakemistake, I think I have to youse Cachy formula
Comment: Correct it's Cauchy formula
Answer: Yes. Expand as power series, and you can rearrange the $a$'s and $b$'s because they commute (so $(a+b)^2=a^2+2ab+b^2$ for example), so you can pretend you are doing high-school maths with numbers. You might want to read about the BCH (Baker Campbell Hausdorff) expansion. A slightly harder result holds when $a$ and $b$ both commute with their commutator $[a,b]$, and if that fails then it gets harder ...
Comment: @DRichard Martinear , please explain a little more about, A slightly harder result holds when $a$ and $b$ both commute with their commutator $[a,b]$, and if that fails then it


XML-based query extremely slow through ADO.NET, instant through SSMS

Question: I'm in the perennial situation: a query that runs instantly through SSMS with a handful of reads, but slow enough to time out with thousands of reads when run through ADO.NET.  Unlike the other questions I could find on StackOverflow, clearing the query cache (or forcing myself to use the one SSMS uses) does not seem to be doing the trick.
Generally, when others have reported this situation on StackOverflow, they've had corrupt query caches.  In all of these cases, the fix has been either to run the ADO.NET queries with SET ARITHABORT ON (to match the session settings being used by SSMS) or to run DBCC DROPCLEANBUFFERS and DBCC FREEPROCCACHE to force the query cache to rebuild.  These techniques make no difference in my application, making me believe that there's something more fundamental going on.
The query in question is this (actual verbatim query captured by SQL Profiler, cleaned up only for formatting):
declare @p5 xml
set @p5=convert(xml,N'<r>
<n v="66ebc21b3bcb31e9a5ecbfb4b29fd2a47c37994c"/>
<n v="665919306fb23d9e685638a2d199e1e623745305"/>
<n v="a080c3b4e0c86e37b4d494d5efc09cebe20c6929"/>
<n v="245cb49bdeca9e37ef9bbd55877e21ade14e6282"/>
<n v="297650a6be65be332c1bb2aab426331a156ee342"/>
<n v="6a2668c8ab64fecf3b6925c7be613c61cef4dd7c"/>
<n v="09923f25f8b1de19f693bca1111bfa50d617856e"/>
<n v="0a7836d8e4e34f4ea92b2105eea5a99029949428"/></r>')
exec sp_executesql N'
            SELECT ixChangesetTag, ixRepo, ixChangeset, sTag, fBookmark
            FROM ChangesetTag
              INNER JOIN @p2.nodes(''/r/n'') X(n) ON X.n.value(''xs:hexBinary(@v)'', ''binary(20)'') = ixChangeset
            WHERE ixRepo = @p0 AND ixCustomer = @p1',N'@p0 bigint,@p1 int,@p2 xml',@p0=2,@p1=23363,@p2=@p5

(The XML parameter is in order to allow using a parameterized query where I'd normally have trouble doing so, since the number of objects I want to pass in varies.  Table-valued procedures would be the 2008 way to do this, but some of our customers run on 2005.)
Run through SSMS, the actual query plan used looks appropriate (index seeks), and takes about 200 reads over 4ms.  Run through the web application, it takes about 4500 reads over a second.
What am I missing here?  Could something be reinstating the bad query plan when run through the web application, despite the DBCC calls and ARITHABORT settings?
Comment: "it's a typical use-XML-to-do-a-parameterized-WHERE IN-clause hack" - run that one by me again?
Comment: BTW: "In all of these cases, the fix has been either to run the ADO.NET queries with SET ARITHABORT ON (to match the session settings being used by SSMS) or to run DBCC DROPCLEANBUFFERS and DBCC FREEPROCCACHE to force the query cache to rebuild" - none of those are actually fixes. That is treating the symptoms, and not the real cause.
Comment: @MitchWheat I cleaned up that explanation a tad.  This query replaced one with an arbitrary, potentially large number of elements in a `WHERE ixChangeset IN (...)` clause, allowing it to be parameterized and hit the query cache.
Comment: @MitchWheat And yeah, I know that `DBCC` and the like is treating the symptom, not the cause, but I'd hoped originally that setting `ARITHABORT OFF` in SSMS would at least give me the wrong query plan.  That sadly seems not to be the case.
Comment: Read this article written by Erland Sommarskog (SQL Server MVP): Slow in the Application, Fast in SSMS? (http://www.sommarskog.se/query-plan-mysteries.html)
Comment: @BogdanSahlean I have read that article, and have followed the advice best as I can (using the exact SQL, including variable definitions; checking the query plan where I can; etc.).  Is there something specific that you thought was appropriate?  The most helpful thing, seeing the bad plan, is something I can't easily figure out how to do, since it's not a sproc.
Comment: I have no explanation on the difference for you but in my experience the query optimizer can be a bit confused when mixing in XML stuff with a regular query so when I do this kind of multi parameter things I fill a table variable with the shredded XML and then use the table variable in the actual query.
Comment: @BenjaminPollack: Please run this query (https://gist.github.com/2217486) and publish the results. This query shows the settings for SSMS session and ASP.NET session. Replace  with the real ASP.NET session id.
Answer: Easy fix would be to put a multi-column index on (ixCustomer, ixRepo, ixChangeset). Without knowing what the columns actually are, whether they are unique etc its hard to come up with a better answer.
Comment: Given that the query runs instantly when run from SSMS, I'm disinclined to believe this is an index issue.
Comment: @Benjamin Pollack - When you run from SMS it's picking a better index then when you run from code, probably do to some ambiguous charset setting or something .NET does differently then the default SMS session. If you do the multi-column index it will always be inclined to use it.
Answer: The problem ended up being that SQL Server was generally picking an absolutely horrible execution strategy, basically looping over the XML repeatedly, rather than doing a sane join.  The fix was to put the XML into a temporary table and join on that instead, which reliably yielded good execution plans.


Probability 4 colored bags & 4 colored balls

Question: I came across this problem, and I do not understand how to solve it. Do I have to make an exhaustive list, or is there a simpler method?
QN:

There are 4 differently colored balls (red, blue, green, yellow) and 4 differently colored bags (red, blue, green, yellow) on a table. If each ball is randomly selected to be placed into a bag (one ball per bag), what is the probability that at least 1 ball will be in the bag of the same color?
Answer: Hint:  Since each ball is placed independently, you can more easily calculate the chance that no ball is in the matching bag and subtract from 1.  What is the chance that the red ball is not in the red bag?  Now do this four times-you need all of these.


Copying a user with ssh keys

Question: I am writing a kickstart install script that will set up a user on a server with the previous files and permissions it held before. The user I am setting up has ssh keys located in .ssh/ that I also copy over so that the authentication is not required to be set up again.
However every time I attempt to ssh to the server the keys are set up for, I am prompted for the password.
It was working after I set up the keys but has stopped working after I created the same user name with the keys that were originally created. I've checked permissions of the files and they are the same in .ssh.
Is this process possible?
Edit to show /var/log/secure on target server
Setting up as new user with ssh keys:
Jul  1 10:24:01 myuser sshd[14957]: Accepted password for targetserveruser from 192.168.55.55 port 33176 ssh2
Jul  1 10:24:02 myuser sshd[14957]: pam_unix(sshd:session): session opened for user targetserveruser by (uid=0)
Jul  1 10:24:02 myuser sshd[14977]: Received disconnect from 192.168.55.55: 11: disconnected by user
Jul  1 10:24:02 myuser sshd[14957]: pam_unix(sshd:session): session closed for user targetserveruser
Jul  1 10:24:21 myuser sshd[14980]: Accepted password for targetserveruser from 192.168.55.55 port 33177 ssh2
Jul  1 10:24:21 myuser sshd[14980]: pam_unix(sshd:session): session opened for user targetserveruser by (uid=0)
Jul  1 10:24:22 myuser sshd[14997]: Received disconnect from 192.168.55.55: 11: disconnected by user
Jul  1 10:24:22 myuser sshd[14980]: pam_unix(sshd:session): session closed for user targetserveruser
Jul  1 10:24:33 myuser sshd[15002]: Connection closed by 192.168.55.55 [preauth]

After repeating key copy process ssh-copy-id (I changed the key shown for security)
Jul  1 10:26:28 myuser sshd[15058]: Accepted publickey for targetserveruser from 192.168.55.55 port 33180 ssh2: RSA 3c:40:a1:dc:6d:05:1e:27:6b:b2:b5:98:f8:58:b6:96
Jul  1 10:26:28 myuser sshd[15058]: pam_unix(sshd:session): session opened for user targetserveruser by (uid=0)
Jul  1 10:26:28 myuser sshd[15061]: Received disconnect from 192.168.55.55: 11: disconnected by user
Jul  1 10:26:28 myuser sshd[15058]: pam_unix(sshd:session): session closed for user targetserveruser
Jul  1 10:26:28 myuser sshd[15064]: Accepted publickey for targetserveruser from 192.168.55.55 port 33181 ssh2: RSA 3c:40:a1:dc:6d:05:1e:27:6b:b2:b5:98:f8:58:b6:96
Jul  1 10:26:28 myuser sshd[15064]: pam_unix(sshd:session): session opened for user targetserveruser by (uid=0)
Jul  1 10:26:28 myuser sshd[15071]: Received disconnect from 192.168.55.55: 11: disconnected by user
Jul  1 10:26:28 myuser sshd[15064]: pam_unix(sshd:session): session closed for user targetserveruser

The log shows there is definitely a different process taking place. Even though the authorised keys is present on both runs with the same permission.
Is there another file somewhere that would need to be updated?
Answer: I think it's normal. Did you have installed keychain on the other server? Normally you need to enter the passphrase on every connection you try.
If you mean you need always the user password of the remote server try this to add the ssh keyfile:
ssh-add ~/.ssh/id_rsa

(Keychain is a tool which saves the password, so you didn't have to enter it on every ssh connection)
Comment: The other server has a similar script and I copied the authorised_keys file to the other server and gave it the same permissions as before. Is that the key chain you are referring to?
Comment: Ok, let's try this way. There should be a file called authorized_keys. In this file there should be your public key.

To connect to the server you have to use te username of the new server and your private key has to been on the old server. For exaple:

OLD:
private_rsa_key

NEW:
authorized_keys

To connect:
ssh userofthenewserverwithauthorizedkeys@newsever
Comment: The file is there and the usernames are exactly the same as before but still it prompts for a password
Comment: For mee it seems as your Public Key is missing. Pleas doing the following: 1. on the new server: *cp -p authorized_keys* then switch to the existing one and make *ssh-copy-id username@server* and add the new key. 2. Please compare the two files if there are differences.
Comment: The authorised keys are the same. I've printed the contents of the secure log in the question above
Answer: Please show me the content of the file /etc/ssh/sshd_config. Perhaps you've forgotten to enable SSH login with PubKey and/or RSA?
And please also try to connect from the new server to localhost via:
ssh -v localhost

and copy the Output WITHOUT Keys inside
Comment: Turns out it was an SE Linux issue! restorecon -vR /home/myuser/.ssh solved it

Copying a user with ssh keys