问:
Error running headless Chromium on Ubuntu
I installed Chromium 59.0, and I'm trying to run it in headless mode using the following command:

sudo /opt/google/chrome/chrome --headless --disable-gpu --no-sandbox

but I'm getting the following errors:

[0512/174717.638937:WARNING:audio_manager.cc(295)] Multiple instances of AudioManager detected
[0512/174717.639027:WARNING:audio_manager.cc(254)] Multiple instances of AudioManager detected

Has anyone encountered this and found a way to get past it?

答:
I encountered the exact same thing under dockerized ubuntu running karma.js tests.

You will need to have pulseaudio or similar running.

Try:

```<code>apt-get install pulseaudio
</code>```

And before you run chrome

```<code>pulseaudio --daemonize
</code>```

You can see it in my docker-entrypoint.sh:
https://github.com/codeclou/docker-nodejs-chrome-xvfb

When running with docker you will need to run docker with:

```<code>--shm-size=128M
</code>```

Since chrome will complain about small /dev/shm which is 64MB by default.

Body:
I encountered the exact same thing under dockerized ubuntu running karma.js tests.

You will need to have pulseaudio or similar running.

Try:

apt-get install pulseaudio

And before you run chrome

pulseaudio --daemonize

You can see it in my docker-entrypoint.sh:
https://github.com/codeclou/docker-nodejs-chrome-xvfb

When running with docker you will need to run docker with:

--shm-size=128M

Since chrome will complain about small /dev/shm which is 64MB by default.


来源: stackexchange

问:
Yarn error : Not able to initialize app-log directories in any of the configured local directories
I am facing an error while using MapReduce :

```<code>Not able to initialize app-log directories in any of the configured local directories
</code>```

Here is my yarn-site.xml:

```<code><configuration>

<!-- Site specific YARN configuration properties -->

<property>
  <name>yarn.nodemanager.resource.memory-mb</name>
    <value>2200</value>
      <description>Amount of physical memory, in MB, that can be allocated for containers.</description>
      </property>

<property>
  <name>yarn.scheduler.minimum-allocation-mb</name>
    <value>500</value>
    </property>

<property>
  <name>yarn.scheduler.maximum-allocation-mb</name>
      <value>2000</value>
          </property>

<property>
  <name>yarn.scheduler.minimum-allocation-vcores</name>
        <value>1</value>
                  </property>

<property>
  <name>yarn.scheduler.maximum-allocation-vcores</name>
          <value>2</value>
                            </property>

<property>
        <name>yarn.nodemanager.disk-health-checker.enable</name>
                <value>false</value>
                </property>

<property>
      <name>yarn.log-aggregation-enable</name>
            <value>true</value>
              </property>
<property>
 <name>yarn.nodemanager.local-dirs</name>
 <value>/tmp/yarn_logs</value>
 </property>

<property>
 <name>app-log directories</name>
  <value>/tmp/yarn_logs</value>
   </property>

</configuration>
</code>```

As you see I disabled the healthy check to clearly see where the problem is.

Here is what I've already tried :

Delete the content of the usercache directory from yarn local dirs

Change the chmod with 777 to be sure there's no problem with this

Restart all the hadoop services

I keep getting the exact same error. I really don't know what to do next.. Any idea? Thx by advance!

PS : I already checked : all my hadoop services seem up.

答: Solution : i just removed every files into the hadoop/logs, formated the namenode and restart everything. And my node is healthy again!</p>

ContentLicense: CC BY-SA 3.0

Body:
I am facing an error while using MapReduce :

Not able to initialize app-log directories in any of the configured local directories

Here is my yarn-site.xml:

<configuration>

<property>
  <name>yarn.nodemanager.resource.memory-mb</name>
    <value>2200</value>
      <description>Amount of physical memory, in MB, that can be allocated for containers.</description>
      </property>

<property>
  <name>yarn.scheduler.minimum-allocation-mb</name>
    <value>500</value>
    </property>

<property>
  <name>yarn.scheduler.maximum-allocation-mb</name>
      <value>2000</value>
          </property>

<property>
  <name>yarn.scheduler.minimum-allocation-vcores</name>
        <value>1</value>
                  </property>

<property>
  <name>yarn.scheduler.maximum-allocation-vcores</name>
          <value>2</value>
                            </property>

<property>
        <name>yarn.nodemanager.disk-health-checker.enable</name>
                <value>false</value>
                </property>

<property>
      <name>yarn.log-aggregation-enable</name>
            <value>true</value>
              </property>
<property>
 <name>yarn.nodemanager.local-dirs</name>
 <value>/tmp/yarn_logs</value>
 </property>

<property>
 <name>app-log directories</name>
  <value>/tmp/yarn_logs</value>
   </property>

</configuration>

As you see I disabled the healthy check to clearly see where the problem is.

Here is what I've already tried :

Delete the content of the usercache directory from yarn local dirs

Change the chmod with 777 to be sure there's no problem with this

Restart all the hadoop services

I keep getting the exact same error. I really don't know what to do next.. Any idea? Thx by advance!

PS : I already checked : all my hadoop services seem up.


问:
visual mxml creator - fireworks, photoshop, others
I have a mature Flex app that visually sucks.

If i could, i would use photoshop craft a killer design and then use fireworks, line up my slices and export as mxmxl with the assets... and manually retrofit my project.

Issue is fireworks wont crop out the slices when going to mxml, it takes the stage as one big image.

What tool/process is 'like' using fireworks to create the flex ui?

I must be missing something.  Thansk in advance.

答:
I think you are looking for Flash Catalyst.  It takes your Adobe assets and lets you skin them as Flex components.

My designer is using Illustrator to build a beautiful UI, and then she morphs it into a Flex project using Catalyst.  I'd be lying if I said it was that easy... I need to do some real massaging of the Catalyst export... but the export IS a Flex project and the workflow works well enough to make my app look like her design.

ContentLicense: CC BY-SA 2.5


问:
program wont sort array after one previous sorting
This is what i have so far:

```<code>import java.util.*;
public class ProcessArray {

    public static void main(String[] args) {

        int[] arr = {3, 8, 1, 9, 2};
        System.out.println(Arrays.toString(arr));
        selectionSort(arr);
        System.out.println(Arrays.toString(arr));
        ProcessArray.oddArray(arr);
        System.out.println(Arrays.toString(arr));
        ProcessArray.evenArray(arr);
        System.out.println(Arrays.toString(arr));

    }

    public static void selectionSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            int index = 0;
            for (int k = 0; k < arr.length - i; k++) {
                if (arr[k] > arr[index]) {
                    index = k;
                }
            }
            //swap
            int tmp = arr[index];
            arr[index] = arr[arr.length - 1 - i];
            arr[arr.length - 1 - i] = tmp;
        }
    }

    public static int[] oddArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] % 2 == 0) {
                arr[i] = arr[i];
            }
        }
        return arr;
    }

    public static int[] evenArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] % 2 != 0) {
                arr[i] = arr[i];
            }
        }
        return arr;
    }

}
</code>```

For some reason when i go to run it, this is what im outputted with:

```<code>[3, 8, 1, 9, 2]
[1, 2, 3, 8, 9]
[1, 2, 3, 8, 9]
[1, 2, 3, 8, 9]
</code>```

How do i make odd Array and even Array work? Because the logic make sense, at least to me it does, but the program still just prints the output it got from selectionSort. Im sorry if this basic computer science knowledge, we just recently started learning about sorting.

答:
Here now it works

```<code>  import java.util.*;
    public class ProcessArray {

        public static void main(String[] args) {

            int[] arr = {3, 8, 1, 9, 2};
            System.out.println(Arrays.toString(arr));
            selectionSort(arr);
            System.out.println(Arrays.toString(arr));
            System.out.println((ProcessArray.oddArray(arr)));
            System.out.println( ProcessArray.evenArray(arr));

        }

        public static void selectionSort(int[] arr) {
            for (int i = 0; i < arr.length - 1; i++) {
                int index = 0;
                for (int k = 0; k < arr.length - i; k++) {
                    if (arr[k] > arr[index]) {
                        index = k;
                    }
                }
                //swap
                int tmp = arr[index];
                arr[index] = arr[arr.length - 1 - i];
                arr[arr.length - 1 - i] = tmp;
            }
        }

        public static List<Integer> oddArray(int[] arr) {
            List<Integer> oddArr = new ArrayList<>();
            for (int i = 0; i < arr.length; i++) {
                if (arr[i] % 2 != 0) {
                  oddArr.add(arr[i]);
                }
            }
            return oddArr;
        }

        public static List<Integer> evenArray(int[] arr) {
            List<Integer> evenArray = new ArrayList<>();
            for (int i = 0; i < arr.length; i++) {
                if (arr[i] % 2 == 0) {
                    evenArray.add(arr[i]);
                }
            }
            return evenArray;
        }

    }
</code>```

Your have to use List<> since you dont know the length of your collection, you dont know how many odd/even numbers there will be

2nd: you methods are wrong

```<code>   public static int[] evenArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] % 2 != 0) {
                arr[i] = arr[i];
            }
        }
        return arr;
    }
</code>```

Here if you can see on                     arr[i] = arr[i]; So you are saying in the same array that i passed in to the method if lets say if arr[3] is even make arr[3] = arr[3] It's a very basic mistake that i made my self as well in the beggining

Body:
This is what i have so far:

import java.util.*;
public class ProcessArray {

    public static void main(String[] args) {

        int[] arr = {3, 8, 1, 9, 2};
        System.out.println(Arrays.toString(arr));
        selectionSort(arr);
        System.out.println(Arrays.toString(arr));
        ProcessArray.oddArray(arr);
        System.out.println(Arrays.toString(arr));
        ProcessArray.evenArray(arr);
        System.out.println(Arrays.toString(arr));

    }

    public static void selectionSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            int index = 0;
            for (int k = 0; k < arr.length - i; k++) {
                if (arr[k] > arr[index]) {
                    index = k;
                }
            }
            //swap
            int tmp = arr[index];
            arr[index] = arr[arr.length - 1 - i];
            arr[arr.length - 1 - i] = tmp;
        }
    }

    public static int[] oddArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] % 2 == 0) {
                arr[i] = arr[i];
            }
        }
        return arr;
    }

    public static int[] evenArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] % 2 != 0) {
                arr[i] = arr[i];
            }
        }
        return arr;
    }

}

For some reason when i go to run it, this is what im outputted with:

[3, 8, 1, 9, 2]
[1, 2, 3, 8, 9]
[1, 2, 3, 8, 9]
[1, 2, 3, 8, 9]

How do i make odd Array and even Array work? Because the logic make sense, at least to me it does, but the program still just prints the output it got from selectionSort. Im sorry if this basic computer science knowledge, we just recently started learning about sorting.

Body:
Here now it works

  import java.util.*;
    public class ProcessArray {

        public static void main(String[] args) {

            int[] arr = {3, 8, 1, 9, 2};
            System.out.println(Arrays.toString(arr));
            selectionSort(arr);
            System.out.println(Arrays.toString(arr));
            System.out.println((ProcessArray.oddArray(arr)));
            System.out.println( ProcessArray.evenArray(arr));

        }

        public static void selectionSort(int[] arr) {
            for (int i = 0; i < arr.length - 1; i++) {
                int index = 0;
                for (int k = 0; k < arr.length - i; k++) {
                    if (arr[k] > arr[index]) {
                        index = k;
                    }
                }
                //swap
                int tmp = arr[index];
                arr[index] = arr[arr.length - 1 - i];
                arr[arr.length - 1 - i] = tmp;
            }
        }

        public static List<Integer> oddArray(int[] arr) {
            List<Integer> oddArr = new ArrayList<>();
            for (int i = 0; i < arr.length; i++) {
                if (arr[i] % 2 != 0) {
                  oddArr.add(arr[i]);
                }
            }
            return oddArr;
        }

        public static List<Integer> evenArray(int[] arr) {
            List<Integer> evenArray = new ArrayList<>();
            for (int i = 0; i < arr.length; i++) {
                if (arr[i] % 2 == 0) {
                    evenArray.add(arr[i]);
                }
            }
            return evenArray;
        }

    }

Your have to use List<> since you dont know the length of your collection, you dont know how many odd/even numbers there will be

2nd: you methods are wrong

   public static int[] evenArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] % 2 != 0) {
                arr[i] = arr[i];
            }
        }
        return arr;
    }

Here if you can see on                     arr[i] = arr[i]; So you are saying in the same array that i passed in to the method if lets say if arr[3] is even make arr[3] = arr[3] It's a very basic mistake that i made my self as well in the beggining


问:
Deleting unwanted columns starting at a specific row - excel vba
For some reason I can't figure out how to do this... it seems so basic:

Trying to delete unwanted columns starting at a specific row.

Example:
Want to delete Columns C, D, E, M, N and L all starting at row 10 of Wsh2.

```<code>'deleting columns that are unwanted
Cells(wsh2.Cells("C10"), wsh2.Cells("C10").End(xlDown)).EntireColumn.Delete
Cells(wsh2.Cells("D10"), wsh2.Cells("C10").End(xlDown)).EntireColumn.Delete
Cells(wsh2.Cells("E10"), wsh2.Cells("C10").End(xlDown)).EntireColumn.Delete
Cells(wsh2.Cells("M10"), wsh2.Cells("C10").End(xlDown)).EntireColumn.Delete
Cells(wsh2.Cells("N10"), wsh2.Cells("C10").End(xlDown)).EntireColumn.Delete
Cells(wsh2.Cells("L10"), wsh2.Cells("C10").End(xlDown)).EntireColumn.Delete
End Sub
</code>```

I've adapted a previous code that I found on here that used Range. I've also attempted using Union and Range but cant seem to figure it out.

Basically: Trying to delete only specific columns starting at a particular row after I've copied a range of rows from a previous worksheet.

Any help would be great. Thank you!

答:
You do not actually want to delete the entire column, as you stated.  You want to clear cells C10:Cend, D10:Dend, E10:Eend, M10:Mend, N10:Nend, and L10:Lend.  This is what you want to have your code do.  Navigate to the cell of choice, and clear all cells below that specific coordinate.

For ease, you could just loop through all cells from C10 to C10000 and delete the contents of each cell, for example, which would be very simple to implement, though potentially not the most efficient.

Body:
For some reason I can't figure out how to do this... it seems so basic:

Trying to delete unwanted columns starting at a specific row.

Example:
Want to delete Columns C, D, E, M, N and L all starting at row 10 of Wsh2.

'deleting columns that are unwanted
Cells(wsh2.Cells("C10"), wsh2.Cells("C10").End(xlDown)).EntireColumn.Delete
Cells(wsh2.Cells("D10"), wsh2.Cells("C10").End(xlDown)).EntireColumn.Delete
Cells(wsh2.Cells("E10"), wsh2.Cells("C10").End(xlDown)).EntireColumn.Delete
Cells(wsh2.Cells("M10"), wsh2.Cells("C10").End(xlDown)).EntireColumn.Delete
Cells(wsh2.Cells("N10"), wsh2.Cells("C10").End(xlDown)).EntireColumn.Delete
Cells(wsh2.Cells("L10"), wsh2.Cells("C10").End(xlDown)).EntireColumn.Delete
End Sub

I've adapted a previous code that I found on here that used Range. I've also attempted using Union and Range but cant seem to figure it out.

Basically: Trying to delete only specific columns starting at a particular row after I've copied a range of rows from a previous worksheet.

Any help would be great. Thank you!


问:
Getting data between two dates and grouping it by individual dates
The title of the question might be a bit confusing but, essentially, what I'm trying to do is to retrieve DAILY data from a database that is in a certain date range using PHP.

For example, assume that I have a table like so:

```<code>ID  |  Value  |  Date
1   |  12     |  2017-01-01
2   |  8      |  2017-01-01
3   |  10     |  2017-01-02
</code>```

I need to retrieve the daily total value.

```<code>TotalValue  |  Date
   20       |  2017-01-01
   10       |  2017-01-02
</code>```

At the current time, I'm using a query that retrieves the total value for a given date and I do this for every single day in the date range. As you can imagine, this is not an efficient way of doing this, especially if you are retrieving records for the past year. I've not found an answer which closely resembles my problem.

答:
you could use group by and between </p>

```<code>   select sum(value) as TotalValue, Date
   from my_table
   where date between '2017-01-01' and '2017-01-02'
   group by date
</code>```

Body:
The title of the question might be a bit confusing but, essentially, what I'm trying to do is to retrieve DAILY data from a database that is in a certain date range using PHP.

For example, assume that I have a table like so:

ID  |  Value  |  Date
1   |  12     |  2017-01-01
2   |  8      |  2017-01-01
3   |  10     |  2017-01-02

I need to retrieve the daily total value.

TotalValue  |  Date
   20       |  2017-01-01
   10       |  2017-01-02

At the current time, I'm using a query that retrieves the total value for a given date and I do this for every single day in the date range. As you can imagine, this is not an efficient way of doing this, especially if you are retrieving records for the past year. I've not found an answer which closely resembles my problem.

Body:
you could use group by and between

   select sum(value) as TotalValue, Date
   from my_table
   where date between '2017-01-01' and '2017-01-02'
   group by date


问:
Unable to read XBee Api frame on Raspberry Pi 3 with Node-RED v0.17.3
I hope you'll help me to find out what's wrong with my configuration.

I have to ZigBee nodes, one connected via usb to my mac and one connected via tx/rx ports to the raspberry pi 3.

I wrote two scripts, one that sends Xee Api frame packets (from mac) and one that reads packets (to the pi). The two scripts are based on the python-xbee library.

The scripts are the following - on mac:

```<code>import serial
from xbee import XBee, ZigBee

serial_port = serial.Serial('/dev/tty.usbserial-A5025UGJ', 9600)
xbee = ZigBee(serial_port, escaped=True)

# coordinator = 00 13 A2 00 40 8B B1 5A

while True:
    try:
        # Send AT packet
        xbee.send('tx',frame_id='A', dest_addr_long='\x00\x13\xA2\x00\x40\x8B\xB1\x5A', data='test')
        parameter = xbee.wait_read_frame()
        print 'parameter='
        print parameter

    except KeyboardInterrupt:
        break

serial_port.close()
</code>```

On Pi:

```<code>import serial
from xbee import XBee, ZigBee

serial_port = serial.Serial('/dev/serial0', 9600)
xbee = ZigBee(serial_port, escaped=True)

while True:
    try:

        # Receive AT packet
        parameter = xbee.wait_read_frame()
        print 'parameter='
        print parameter

    except KeyboardInterrupt:
        break

serial_port.close()
</code>```

The output of the first script is the following (the sender):

parameter=
  {'retries': '\x00', 'frame_id': 'A', 'deliver_status': '\x00',
  'dest_addr': '\x00\x00', 'discover_status': '\x00', 'id': 'tx_status'}

The output of the second script is the following (the receiver):

parameter= {'source_addr_long': '\x00\x13\xa2\x00@\x8b\xb1L',
  'rf_data': 'test', 'source_addr': '\xa3\x19', 'id': 'rx',
  'options': '\x01'}

Now if I start Node-Red 0.17.3 and I use the "serial input" module, connected to a debug output module, i cannot see anything incoming if the newline is base on the char "\n". The port is the same of the script (/dev/serial0).

```<code>[
    {
        "id": "e6aa5379.9fd8c",
        "type": "debug",
        "z": "35e84ae.5ae88b6",
        "name": "",
        "active": true,
        "console": "false",
        "complete": "true",
        "x": 432.5,
        "y": 213,
        "wires": []
    },
    {
        "id": "63563843.bba178",
        "type": "serial in",
        "z": "35e84ae.5ae88b6",
        "name": "",
        "serial": "fbf0b4fa.9b2918",
        "x": 209.5,
        "y": 201,
        "wires": [
            [
                "e6aa5379.9fd8c"
            ]
        ]
    },
    {
        "id": "fbf0b4fa.9b2918",
        "type": "serial-port",
        "z": "",
        "serialport": "/dev/serial0",
        "serialbaud": "9600",
        "databits": "8",
        "parity": "none",
        "stopbits": "1",
        "newline": "\\n",
        "bin": "false",
        "out": "char",
        "addchar": false
    }
]
</code>```

If I change the configuration of "serial in" node, setting the split "after a timeour of 5000 ms" and deliver "binary buffers", this is the result in debug view:

[126,0,125,49,144,0,125,51,162,0,64,139,177,76,163,25,1,112,114,111,118,97,13]

Does anyone know how to find the correct way to split input with XBee API frames?

答: I don't know anything about node-red, but you need to parse the stream of bytes to extract the frames.  It would require more work to escape the data going in and out, but I think you can use API mode 2 (ATAP = 2) where the start of frame byte (0x7E) is escaped when appearing in the frame, so you could potentially split on that byte.

Body:
I hope you'll help me to find out what's wrong with my configuration.

I have to ZigBee nodes, one connected via usb to my mac and one connected via tx/rx ports to the raspberry pi 3.

I wrote two scripts, one that sends Xee Api frame packets (from mac) and one that reads packets (to the pi). The two scripts are based on the python-xbee library.

The scripts are the following - on mac:

import serial
from xbee import XBee, ZigBee

serial_port = serial.Serial('/dev/tty.usbserial-A5025UGJ', 9600)
xbee = ZigBee(serial_port, escaped=True)

# coordinator = 00 13 A2 00 40 8B B1 5A

while True:
    try:
        # Send AT packet
        xbee.send('tx',frame_id='A', dest_addr_long='\x00\x13\xA2\x00\x40\x8B\xB1\x5A', data='test')
        parameter = xbee.wait_read_frame()
        print 'parameter='
        print parameter

    except KeyboardInterrupt:
        break

serial_port.close()

On Pi:

import serial
from xbee import XBee, ZigBee

serial_port = serial.Serial('/dev/serial0', 9600)
xbee = ZigBee(serial_port, escaped=True)

while True:
    try:

        # Receive AT packet
        parameter = xbee.wait_read_frame()
        print 'parameter='
        print parameter

    except KeyboardInterrupt:
        break

serial_port.close()

The output of the first script is the following (the sender):

parameter=
  {'retries': '\x00', 'frame_id': 'A', 'deliver_status': '\x00',
  'dest_addr': '\x00\x00', 'discover_status': '\x00', 'id': 'tx_status'}

The output of the second script is the following (the receiver):

parameter= {'source_addr_long': '\x00\x13\xa2\x00@\x8b\xb1L',
  'rf_data': 'test', 'source_addr': '\xa3\x19', 'id': 'rx',
  'options': '\x01'}

Now if I start Node-Red 0.17.3 and I use the "serial input" module, connected to a debug output module, i cannot see anything incoming if the newline is base on the char "\n". The port is the same of the script (/dev/serial0).

[
    {
        "id": "e6aa5379.9fd8c",
        "type": "debug",
        "z": "35e84ae.5ae88b6",
        "name": "",
        "active": true,
        "console": "false",
        "complete": "true",
        "x": 432.5,
        "y": 213,
        "wires": []
    },
    {
        "id": "63563843.bba178",
        "type": "serial in",
        "z": "35e84ae.5ae88b6",
        "name": "",
        "serial": "fbf0b4fa.9b2918",
        "x": 209.5,
        "y": 201,
        "wires": [
            [
                "e6aa5379.9fd8c"
            ]
        ]
    },
    {
        "id": "fbf0b4fa.9b2918",
        "type": "serial-port",
        "z": "",
        "serialport": "/dev/serial0",
        "serialbaud": "9600",
        "databits": "8",
        "parity": "none",
        "stopbits": "1",
        "newline": "\\n",
        "bin": "false",
        "out": "char",
        "addchar": false
    }
]

If I change the configuration of "serial in" node, setting the split "after a timeour of 5000 ms" and deliver "binary buffers", this is the result in debug view:

[126,0,125,49,144,0,125,51,162,0,64,139,177,76,163,25,1,112,114,111,118,97,13]

Does anyone know how to find the correct way to split input with XBee API frames?


问:
How to complete a function execution before starting to execute another function
Please I have used .done() to ensure a function is completely executed before starting to execute next function. I borrowed the idea from Ajax. But it is not working. I keep getting error message done() is not a function.
Is done() only for Ajax? If yes, how can I accomplish my wish.

```<code>document.onreadystatechange = function () {
  if (document.readyState === "complete") {
    //do somethings

  }
}

//This must be completely executed before addNu()
$( "#mybutton" ).click(function() {
  //Do some things

}).done(addNu());

function addNu() {
  //do some things
}
</code>```

Note that none of the script is async. each must be completed before running the next

答:
Why you dont just call the function at the end of .click event?</p>

```<code>document.onreadystatechange = function () {
  if (document.readyState === "complete") {
    //do somethings

  }
}

//This must be completely executed before addNu()
$( "#mybutton" ).click(function() {
  //Do some things

   addNu()
});

function addNu() {
  //do some things
}
</code>```

Body:
Please I have used .done() to ensure a function is completely executed before starting to execute next function. I borrowed the idea from Ajax. But it is not working. I keep getting error message done() is not a function.
Is done() only for Ajax? If yes, how can I accomplish my wish.

document.onreadystatechange = function () {
  if (document.readyState === "complete") {
    //do somethings

  }
}

//This must be completely executed before addNu()
$( "#mybutton" ).click(function() {
  //Do some things

}).done(addNu());

function addNu() {
  //do some things
}

Note that none of the script is async. each must be completed before running the next

Body:
Why you dont just call the function at the end of .click event?

document.onreadystatechange = function () {
  if (document.readyState === "complete") {
    //do somethings

  }
}

//This must be completely executed before addNu()
$( "#mybutton" ).click(function() {
  //Do some things

   addNu()
});

function addNu() {
  //do some things
}


问:
Why does creating a blank matrix return null instead of 0.0?
I have a Java method fill0s() that inputs a smaller matrix into a larger matrix, supposedly filled with 0s:

```<code>public class PoolingFunctions {

    // Fill needed spaces with 0
    public static Double[][] fill0s(Double[][] image, int filter_size){
        int columns_remaining = filter_size - (image[0].length%filter_size);
        int rows_remaining = filter_size - (image.length%filter_size);
        // CREATE A MATRIX: HERE LIES THE PROBLEM: //////////////////////////////
        Double [][] blank_matrix = new Double [(image.length)+columns_remaining][(image[0].length)+rows_remaining];
            for (int i = 0; i<image.length; i++) {
                for (int j = 0; j<image[i].length; j++) {
                    blank_matrix[i][j] = image[i][j];
                }
            }

        return blank_matrix;
    }
}
</code>```

And after calling this method:

```<code>public class MainPooling{
    public static void main(String[] args) {
        Double[][] image =  {   {1.0,1.0,1.0,1.0},
                                {1.0,1.0,1.0,1.0},
                                {1.0,1.0,1.0,1.0},
                                {1.0,1.0,1.0,1.0}
                            };

        Double[][] formatted_image;
        formatted_image = PoolingFunctions.fill0s(image,3);
        TestMatricesJava.print2dMatrix(formatted_image);
    }
}
</code>```

I get the following result:

```<code>1.0 1.0 1.0 1.0 null null
1.0 1.0 1.0 1.0 null null
1.0 1.0 1.0 1.0 null null
1.0 1.0 1.0 1.0 null null
null null null null null null
null null null null null null
</code>```

My question is: Why does the function return a null instead of a 0.0?

答: Double is a wrapper class whose value will be null if not initialized. Use primitive type double and it will give you a correct result.</p>

Body:
I have a Java method fill0s() that inputs a smaller matrix into a larger matrix, supposedly filled with 0s:

public class PoolingFunctions {

    // Fill needed spaces with 0
    public static Double[][] fill0s(Double[][] image, int filter_size){
        int columns_remaining = filter_size - (image[0].length%filter_size);
        int rows_remaining = filter_size - (image.length%filter_size);
        // CREATE A MATRIX: HERE LIES THE PROBLEM: //////////////////////////////
        Double [][] blank_matrix = new Double [(image.length)+columns_remaining][(image[0].length)+rows_remaining];
            for (int i = 0; i<image.length; i++) {
                for (int j = 0; j<image[i].length; j++) {
                    blank_matrix[i][j] = image[i][j];
                }
            }

        return blank_matrix;
    }
}

And after calling this method:

public class MainPooling{
    public static void main(String[] args) {
        Double[][] image =  {   {1.0,1.0,1.0,1.0},
                                {1.0,1.0,1.0,1.0},
                                {1.0,1.0,1.0,1.0},
                                {1.0,1.0,1.0,1.0}
                            };

        Double[][] formatted_image;
        formatted_image = PoolingFunctions.fill0s(image,3);
        TestMatricesJava.print2dMatrix(formatted_image);
    }
}

I get the following result:

1.0 1.0 1.0 1.0 null null
1.0 1.0 1.0 1.0 null null
1.0 1.0 1.0 1.0 null null
1.0 1.0 1.0 1.0 null null
null null null null null null
null null null null null null

My question is: Why does the function return a null instead of a 0.0?


问:
How can I make a dynamic width for elements based on the screen size?
Here is my code:

.container{
  border:1px solid;
  width: 70%;
}

.el {
  border: 1px solid red;
  display: inline-block;
  min-width: 250px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="el">one</div>
  <div class="el">two</div>
  <div class="el">three</div>
  <div class="el">four</div>
  <div class="el">five</div>
  <div class="el">six</div>
  <div class="el">seven</div>
  <div class="el">eight</div>
</div></code>```

Please run the code snippet above, click on Full page button and resize the page. I want to divide div.container to equal parts.

So if there are three elements (div.el) in a row, then the width of them should be 33%. If two elements in a row, then the width should be 50%.

How can I do that? Noted that I don't want to use any framework like Bootstrap.

答:
Given I did this myself, I'm almost totally certain the best way is with flexbox's flex-wrap to make the items overflow and flex-grow to make them take up as much space as possible.

```<code><div id="cont">
  <div>asdf</div>
  <div>asdf</div>
  <div>asdf</div>
  <div>asdf</div>
  <div>asdf</div>
  <div>asdf</div>
  <div>asdf</div>
  <div>asdf</div>
  <div>asdf</div>
  <div>asdf</div>
</div>
</code>```

```<code>#cont {
  display: flex;
  flex-wrap: wrap;
}

#cont div {
  flex-grow: 1;
  background: red;
  padding: 10px;
  margin: 10px;
}
</code>```

See here, or on my own website.

Note that this isn't a grid system, so the last row isn't going to obey the same column width as all the previous (full ones). If you want the cells to spill over if the space is available and also look like a grid given the last line, you'll need to tack on some JavaScript.

Body:
Here is my code:

.container{
  border:1px solid;
  width: 70%;
}

.el {
  border: 1px solid red;
  display: inline-block;
  min-width: 250px;
}

one

two

three

four

five

six

seven

eight

Please run the code snippet above, click on Full page button and resize the page. I want to divide div.container to equal parts.

So if there are three elements (div.el) in a row, then the width of them should be 33%. If two elements in a row, then the width should be 50%.

How can I do that? Noted that I don't want to use any framework like Bootstrap.

Body:
Given I did this myself, I'm almost totally certain the best way is with flexbox's flex-wrap to make the items overflow and flex-grow to make them take up as much space as possible.

<div id="cont">
  <div>asdf</div>
  <div>asdf</div>
  <div>asdf</div>
  <div>asdf</div>
  <div>asdf</div>
  <div>asdf</div>
  <div>asdf</div>
  <div>asdf</div>
  <div>asdf</div>
  <div>asdf</div>
</div>

#cont {
  display: flex;
  flex-wrap: wrap;
}

#cont div {
  flex-grow: 1;
  background: red;
  padding: 10px;
  margin: 10px;
}

See here, or on my own website.

Note that this isn't a grid system, so the last row isn't going to obey the same column width as all the previous (full ones). If you want the cells to spill over if the space is available and also look like a grid given the last line, you'll need to tack on some JavaScript.


问:
Sorting by part of a line in a list from a file
This is for a C++ program. I'm not entirely sure how to formulate the problem I'm having. It's for a school assignment and I'm not looking for the answer just a point in the right direction. we need to read in a file with 75,000+ lines that look similar to this:

Census Tract 201, Autauga County, Alabama|9.84473419420788|1808|183.651479494869

Census Tract 202, Autauga County, Alabama|3.34583234555866|2355|703.860730836106

Census Tract 203, Autauga County, Alabama|5.35750339330735|3057|570.60159846447

wherein we need to sort by that last number in bold (using Quick and Merge sort from two different programs). I've got the sorting down to where if I only had to deal with the bold numbers I'd be set, but I'm having an issue getting the whole thing into a vector or array and being able to access specifically that part and sort by it. At the risk of making this way too long I'm not going to post the code I have so far. I'd just like a concept of how to attack this issue.

答:
I recommend the following:

1. Create a class or structure with one member for each field.

2. Overload operator>> for your class.

3. Create a std::vector of your class.

4. Read the data file into your std::vector of class objects.

You can sort the std::vector by writing functors (function objects) that compare by a field, then passing that functor to the std::sort algorithm.


问:
Can I allow my app to create Issues on my private GitHub repo?
I want my app X to be able to create issues on the private repo Y for app X.

Basically in app X I want to create an input form similar to that of the new issue form on GitHub. Where there's a title, comment, and just labels.

Is there an API out there that will allow me to do this?

答:
Use official github api for creating issues via any app. Here is a link to the github issues api. Below is an example.

POST /repos/:owner/:repo/issues

You have to include parameters required for creating issues like title, body, assignees etc.

Also you have check github oauth flow for github api since you are creating issues in private repository


问:
Photo as website home page background dimensions?
hope this question is ok on stackoverflow. I want to use a photo as the background for the homepage of a website. The photo will be take up the entire page. However i don't know what resolution i should make the photo. I was thinking 1920 x 1200px so that people with 24 inch screen don't see the 'ends' of the photo. However is that big enough? I'm worried about the site looking ok on screens larger than 24 inches.

Also anyone know how i should optimize the photo so it loads as fast as possible? Thanks.

答:
Overall, this seems to be a question of trade-offs.  The better the resolution, the slower the page load for a do-nothing page.  Is it worth the slow-down to have the better resolution and avoid pixellation?

Also, I think you're asking the wrong question, since a 24-inch screen can be in multiple resolutions.

I would approach this in the following manner:

what is the largest resolution you MUST have your photo look "good" on?   Then make your photo that resolution.  If 24" is your target, look at what resolutions this size monitor "typically" supports and target that.

What number of colors you want?  (or perhaps b&w / grayscale).  If you reduce the number of colors (preferably to "web-safe" colors), you can load faster with the same resolution.

A program like Photoshop (or Gimp) will probably give you the most power in tuning these parameters.

Do you care if only a portion of the photo displays when your viewer has a smaller window?

I know this isn't a cut and dried answer, but these things seldom are (IMHO).


问:
Handling exceptions in a ViewModel without a View (in ReactiveUI)
I am currently building an application in C# using ReactiveUI that contains many views/viewmodels. Some of these viewmodels perform a network request at a preset interval. These network requests may fail at any time. I implemented this as follows:

```<code>public ReactiveCommand<Unit, IReactiveList<IJob>> RefreshJobList { get; }
public Interaction<Exception, Unit> RefreshError { get; } = new Interaction<Exception, Unit>();

...

RefreshJobList = ReactiveCommand.CreateFromTask(() => DoNetworkRequest());
RefreshJobList.ThrownExceptions.Subscribe(ex =>
{
    log.Error("Failed to retrieve job list from server.", ex);
    RefreshError.Handle(ex).Subscribe();
});
Observable.Interval(TimeSpan.FromMilliseconds(300)).Select(x => Unit.Default).InvokeCommand(RefreshJobList);
</code>```

In the corresponding views, I handle the exceptions as follows:

```<code>this.WhenActivated(d => d(
    this.ViewModel.RefreshError.RegisterHandler(interaction =>
    {
        MessageBox.Show("Failed to load joblist.", "Error", MessageBoxButton.OK);
        interaction.SetOutput(new Unit());
    })
));
</code>```

This works fine, except when the viewmodel isn't associated with a view. My application uses tabs, and when the user switches to a different tab, the previous view is destroyed. This leaves the viewmodel running, still making requests, without a view. Then, when an error occurs in RefreshJobList, no handlers are associated with RefreshError, ReactiveUI throws an UnhandledInteractionError and my application crashes.

I am not sure how to deal with this cleanly. My first thought would be to pause the ViewModel until a View is attached, which would also save network traffic. However, I can't seem any way to check whether or not a View is attached to the ViewModel. Any ideas?

答:
If your view implements IViewFor and you view model implements ISupportsActivation you can dispose the subscription to ThrownExceptions when navigating away from the view:

```<code>// In your VM

this.WhenActivated(d=>
{
    RefreshJobList
        .ThrownExceptions
        .Do(ex => log.Error("Failed to retrieve job list from server.", ex))
        .SelectMany(ex => RefreshError.Handle(ex))
        .Subscribe()
        .DisposeWith(d); // This will dispose of the subscription when the view model is deactivated
});
</code>```

This will make the ReactiveCommand throw an exception if an exception occurs when the view model is not active. To get around that you could either stop the running operation when deactivating the view model. Alternatively you could catch the exception as jamie suggested: RefreshError.Handle(ex).Catch(ex => Observable.Empty<Exception>())

Body:
I am currently building an application in C# using ReactiveUI that contains many views/viewmodels. Some of these viewmodels perform a network request at a preset interval. These network requests may fail at any time. I implemented this as follows:

public ReactiveCommand<Unit, IReactiveList<IJob>> RefreshJobList { get; }
public Interaction<Exception, Unit> RefreshError { get; } = new Interaction<Exception, Unit>();

...

RefreshJobList = ReactiveCommand.CreateFromTask(() => DoNetworkRequest());
RefreshJobList.ThrownExceptions.Subscribe(ex =>
{
    log.Error("Failed to retrieve job list from server.", ex);
    RefreshError.Handle(ex).Subscribe();
});
Observable.Interval(TimeSpan.FromMilliseconds(300)).Select(x => Unit.Default).InvokeCommand(RefreshJobList);

In the corresponding views, I handle the exceptions as follows:

this.WhenActivated(d => d(
    this.ViewModel.RefreshError.RegisterHandler(interaction =>
    {
        MessageBox.Show("Failed to load joblist.", "Error", MessageBoxButton.OK);
        interaction.SetOutput(new Unit());
    })
));

This works fine, except when the viewmodel isn't associated with a view. My application uses tabs, and when the user switches to a different tab, the previous view is destroyed. This leaves the viewmodel running, still making requests, without a view. Then, when an error occurs in RefreshJobList, no handlers are associated with RefreshError, ReactiveUI throws an UnhandledInteractionError and my application crashes.

I am not sure how to deal with this cleanly. My first thought would be to pause the ViewModel until a View is attached, which would also save network traffic. However, I can't seem any way to check whether or not a View is attached to the ViewModel. Any ideas?

Body:
If your view implements IViewFor and you view model implements ISupportsActivation you can dispose the subscription to ThrownExceptions when navigating away from the view:

// In your VM

this.WhenActivated(d=>
{
    RefreshJobList
        .ThrownExceptions
        .Do(ex => log.Error("Failed to retrieve job list from server.", ex))
        .SelectMany(ex => RefreshError.Handle(ex))
        .Subscribe()
        .DisposeWith(d); // This will dispose of the subscription when the view model is deactivated
});

This will make the ReactiveCommand throw an exception if an exception occurs when the view model is not active. To get around that you could either stop the running operation when deactivating the view model. Alternatively you could catch the exception as jamie suggested: RefreshError.Handle(ex).Catch(ex => Observable.Empty<Exception>())


问:
Initially set all checkboxes to checked
I have jquery code that has the ability to set all checkboxes to 'checked' state on the click of a 'check all' checkbox. However, I would like to initially, start a html page by already having all checkboxes checked without having to click on that 'check all' checkbox. Please bear in mind, though, that I would like to keep the 'check all' checkbox since it has the ability to uncheck all checkboxes as well.

Here's my jquery code :

```<code>$('.chk_boxes').click(function(){
    var chk = $(this).attr('checked')?true:false;
    $('.chk_boxes1').attr('checked',chk);
});
</code>```

答:
I would just use html attributes

```<code><input name="name" id="id" type="checkbox" checked="checked">
</code>```

I wouldn't recommend using javascript to set these initial values because it will unnecessarily waste resources in the client machines.

Title: Initially set all checkboxes to checked

Body:
I have jquery code that has the ability to set all checkboxes to 'checked' state on the click of a 'check all' checkbox. However, I would like to initially, start a html page by already having all checkboxes checked without having to click on that 'check all' checkbox. Please bear in mind, though, that I would like to keep the 'check all' checkbox since it has the ability to uncheck all checkboxes as well.

Here's my jquery code :

$('.chk_boxes').click(function(){
    var chk = $(this).attr('checked')?true:false;
    $('.chk_boxes1').attr('checked',chk);
});

Body:
I would just use html attributes

<input name="name" id="id" type="checkbox" checked="checked">

I wouldn't recommend using javascript to set these initial values because it will unnecessarily waste resources in the client machines.


问:
How do I know if a C program will written on Linux will work elsewhere
I need you to explain me how do I know if my C program will work for example on Windows if I write it on Linux and it works on that Linux and vice-versa (program written in Windows)

Also what standards do I have to follow to write programs that will run on different operating systems? How do I detect whether functions from libraries or whole libraries will work on different operating systems?

For example I have functions fread, fwrite, fopen, fclosefrom library stdio.h - how do I know if I can work with them properly on other systems than Linux? Same with functions that work with file descriptors: open, creat, close, read, write from libraries: sys/types.h, sys/stat.h, fcntl.h.

答:
Well, this is kind of simple: Your program will work on Windows as long as it only uses two things:

The C standard library, as described in the C standard. See e.g. n1570.pdf, the latest draft version that's very close to the actual standard. Note that a lot of C standard libraries come with all sorts of extensions, of course you can't use these. If in doubt, compile e.g. with the -std=c11 option (gcc or clang) which should hide all declarations for extensions.

There's an additional pitfall here: Microsoft's implementation of the C standard isn't complete. It depends on your compiler which C standard library is actually linked, in case of MinGW, it's the very old msvcrt.dll that only conforms to C89, so you might want to read an older standard instead for which functions you can use, e.g. here's a description of the standard library in C89 With Microsoft's C compilers, you get different levels of C99 support also in the standard libraries (they link their own runtime DLLs), depending on the version.

Third party libraries that are available for Windows, like e.g. SDL, GTK+, etc.

By using open, creat, close, read, write etc., you're using extensions specified in POSIX. Some of the POSIX functions are available on Windows, some are slightly different, some are just missing. You better shouldn't use these if you want to stay portable to Windows. The exception to this rule is if you plan to compile your code with Cygwin, which is a complete POSIX compatibility layer for Windows.

As per IanAbbott's comment, it's also crucial to use integer types correctly and not implicitly assume things like "a long has 64 bits" or "an int can hold a pointer", which are wrong in the general case. Always use the <stdint.h> types for fixed widths, uintptr_t for pointer values, size_t for object sizes, and so on.

Although not directly related to your question: For most non-trivial programs, you will sooner or later need to use some platform-specific functionality. Often, there are libraries abstracting this away, like e.g. if you need to handle I/O events efficiently, instead of using epoll on Linux, kqueue on FreeBSD, IO completion ports on Windows and so on, you could just use libevent. But in case you don't find such a library, here's a tip:

Clearly separate platform-specific code into its own modules (translation units). This way, the work for porting the whole thing to a different platform gets significantly smaller.


问:
With Bootstrap 4, how to build a layout that has a div when the device is large?
I'm looking to build a layout/grid with Bootstrap 4 that is similar to the screenshots attached.

Notice how on the large device screens, there is a column on the left which on smaller device is removed and the main column is re-centered.

source URL: https://projects.invisionapp.com/d/login

How can this be done with Bootstrap 4?

答:
Simply put, Bootstrap 4 has a lot of abilities with regards to Media Queries. I'd start by taking a look here:
http://getbootstrap.com/css/#grid-media-queries

I think people are down voting this because it's so general. For someone with your reputation, I'd stick to the guidelines that got you there. For more general questions in the future, use a reddit or something... Just my advice.

ContentLicense: CC BY-SA 4.0


问:
Change cart item prices for specific product categories in Woocommerce
I would like to change regular price to custom price of products in the cart for specific categories only ('t-shirts-d','socks-d','joggers-d','boxers-d') as each of the products share 2 different categories.

I tried doing so and it worked but the custom price affects on other categories too, and I want to only show the original price for other categories('t-shirts','socks','joggers','boxers').

I Need help on this.

Here is my code so far:

```<code>function changeprice($html, $cart_item, $cart_item_key){
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        //$thepro = $woocommerce->cart->get_cart();
$product = $cart_item['data'];
 $heading_nicename = array('t-shirts-d','socks-d','joggers-d','boxers-d');
 //$heading_nicename1 = array('t-shirts','socks','joggers','boxers');
   $termsother =  $heading_nicename;
 foreach( $termsother as $termsnew ) {
  if (is_cart()) {
            $price_adjusted = 666.666666667; // your adjustments here
            $price_base = $cart_item['data']->sale_price;
            if (!empty($price_adjusted)) {
                if (intval($price_adjusted) > 0) {
                    $cart_item['data']->set_price($price_adjusted);
                } /*else {
                    $html = '<span class="amount">' . wc_price($price_base)
  . '</span>';
                }*/
            }
        }
     }
   }
   }
    add_filter('woocommerce_cart_item_price', 'changeprice', 100, 3);
</code>```

答:
THE RIGHT WORKING HOOK (Updated):

```<code>add_action( 'woocommerce_before_calculate_totals', 'change_cart_items_prices', 10, 1 );
function change_cart_items_prices( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    foreach ( $cart->get_cart() as $cart_item ) {
        if( has_term( array('t-shirts-d','socks-d','joggers-d','boxers-d'), 'product_cat', $cart_item['product_id'] ) ){
            $price_adjusted = 666.666666667; // your adjustments here
            if ( ! empty( $price_adjusted ) && intval( $price_adjusted ) > 0) {
                $cart_item['data']->set_price( $price_adjusted );
            }
        }
    }
}
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This time everything work on cart and on checkout pages. Totals are updated too.

Body:
I would like to change regular price to custom price of products in the cart for specific categories only ('t-shirts-d','socks-d','joggers-d','boxers-d') as each of the products share 2 different categories.

I tried doing so and it worked but the custom price affects on other categories too, and I want to only show the original price for other categories('t-shirts','socks','joggers','boxers').

I Need help on this.

Here is my code so far:

function changeprice($html, $cart_item, $cart_item_key){
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        //$thepro = $woocommerce->cart->get_cart();
$product = $cart_item['data'];
 $heading_nicename = array('t-shirts-d','socks-d','joggers-d','boxers-d');
 //$heading_nicename1 = array('t-shirts','socks','joggers','boxers');
   $termsother =  $heading_nicename;
 foreach( $termsother as $termsnew ) {
  if (is_cart()) {
            $price_adjusted = 666.666666667; // your adjustments here
            $price_base = $cart_item['data']->sale_price;
            if (!empty($price_adjusted)) {
                if (intval($price_adjusted) > 0) {
                    $cart_item['data']->set_price($price_adjusted);
                } /*else {
                    $html = '' . wc_price($price_base)
  . '';
                }*/
            }
        }
     }
   }
   }
    add_filter('woocommerce_cart_item_price', 'changeprice', 100, 3);

Body:
THE RIGHT WORKING HOOK (Updated):

add_action( 'woocommerce_before_calculate_totals', 'change_cart_items_prices', 10, 1 );
function change_cart_items_prices( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    foreach ( $cart->get_cart() as $cart_item ) {
        if( has_term( array('t-shirts-d','socks-d','joggers-d','boxers-d'), 'product_cat', $cart_item['product_id'] ) ){
            $price_adjusted = 666.666666667; // your adjustments here
            if ( ! empty( $price_adjusted ) && intval( $price_adjusted ) > 0) {
                $cart_item['data']->set_price( $price_adjusted );
            }
        }
    }
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This time everything work on cart and on checkout pages. Totals are updated too.


答:
The key to the solution was using WhenActivated, supplied by ISupportsActivation on the ViewModel.

I am now using the following code in de viewmodel:

```<code>public class ViewModel : ReactiveObject, ISupportsActivation
    public ViewModelActivator Activator { get; } = new ViewModelActivator();

    public ReactiveCommand<Unit, IReactiveList<IJob>> RefreshJobList { get; }
    public Interaction<Exception, Unit> RefreshError { get; } = new Interaction<Exception, Unit>();

    ...

    public ViewModel(){
        RefreshJobList = ReactiveCommand.CreateFromTask(() => DoNetworkRequest());
        RefreshJobList.ThrownExceptions.Subscribe(ex =>
        {
            log.Error("Failed to retrieve job list from server.", ex);
            RefreshError.Handle(ex).Subscribe();
        });
        this.WhenActivated(d => d(
            Observable.Interval(TimeSpan.FromMilliseconds(300)).Select(x => Unit.Default).InvokeCommand(RefreshJobList)
        ));
    }
}
</code>```

This works perfectly.

Title: Handling exceptions in a ViewModel without a View (in ReactiveUI)

Body:
The key to the solution was using WhenActivated, supplied by ISupportsActivation on the ViewModel.

I am now using the following code in de viewmodel:

public class ViewModel : ReactiveObject, ISupportsActivation
    public ViewModelActivator Activator { get; } = new ViewModelActivator();

    public ReactiveCommand<Unit, IReactiveList<IJob>> RefreshJobList { get; }
    public Interaction<Exception, Unit> RefreshError { get; } = new Interaction<Exception, Unit>();

    ...

    public ViewModel(){
        RefreshJobList = ReactiveCommand.CreateFromTask(() => DoNetworkRequest());
        RefreshJobList.ThrownExceptions.Subscribe(ex =>
        {
            log.Error("Failed to retrieve job list from server.", ex);
            RefreshError.Handle(ex).Subscribe();
        });
        this.WhenActivated(d => d(
            Observable.Interval(TimeSpan.FromMilliseconds(300)).Select(x => Unit.Default).InvokeCommand(RefreshJobList)
        ));
    }
}

This works perfectly.


问:
SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value
I'm implementing full calendar API into my project .I have a problem when I try to save an event , I keep on getting the following error:

```<code>SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '2017-07-1415:41:03' for column 'start' at row 1 (SQL: insert into `event3s` (`title`, `start`, `end`, `color`) values (New event, 2017-07-1415:41:03, , #9e1515))
</code>```

I have changed to the right time(time zone) in phpmyadmin but I still got the same error.

This is my table in phpmyadmin :
[![enter image description here][1]][1]

This is the calendar.blade.php class :

```<code><!doctype html>
<html lang="{{ config('calendar.locale') }}">
<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <title>Full Calendar</title>

    {!! Html::style('vendor2/seguce92/bootstrap/css/bootstrap.min.css') !!}
    {!! Html::style('vendor2/seguce92/fullcalendar/fullcalendar.min.css') !!}
    {!! Html::style('vendor2/seguce92/bootstrap-datetimepicker/css/bootstrap-material-datetimepicker.css') !!}
    {!! Html::style('vendor2/seguce92/bootstrap-colorpicker/css/bootstrap-colorpicker.min.css') !!}

</head>
<div id='app'></div>
<div class='container'></div>

{{ Form::open(['route' => 'user.events.store', 'method' => 'post', 'role' => 'form']) }}
<div id="responsive-modal" class="modal fade" tabindex="-1" data-backdrop="static"->

    <div class="modal-dialog">
        <div class="modal-content">

        <div class="modal-header">
        <h4>Registration of new Event</h4>

        </div>

        <div class="modal-body">

            <div class="form-group">
                {{Form::label('title','Date Start') }}
                {{Form::text('title',old('title'),['class' => 'form-control'])}}
            </div>

        <div class="form-group">
            {{Form::label('date_start','Date Start') }}
            {{Form::text('date_start',old('date_start'),['class' => 'form-control','readonly'=>'true'])}}
        </div>

            <div class="form-group">
                {{Form::label('time_start','Time Start') }}
                {{Form::text('time_start',old('time_start'),['class' => 'form-control'])}}
            </div>

            <div class="form-group">
                {{Form::label('date_end','Time Finish') }}
                {{Form::text('date_end',old('date_end'),['class' => 'form-control'])}}
            </div>

            <div class="form-group">
                {{Form::label('color','COLOR') }}
                <div class="input-group colorpicker">
                    {{ Form::text('color',old('color'),['class' => 'form-control']) }}
                    <span class ="input-group-addon">

                        <i></i>
                    </span>
                </div>
            </div>
        </div>

        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
            {!! Form::submit('Save',['class' => 'btn-btn-success'])!!}

        </div>
    </div>
    </div>

</div>
{{Form::close()}}
<div id='calendar'></div>

</body>

{!! Html::script('vendor2/seguce92/jquery.min.js') !!}
{!! Html::script('vendor2/seguce92/bootstrap/js/bootstrap.min.js') !!}
{!! Html::script('vendor2/seguce92/fullcalendar/lib/moment.min.js') !!}
{!! Html::script('vendor2/seguce92/fullcalendar/fullcalendar.min.js') !!}
{!! Html::script('vendor2/seguce92/bootstrap-datetimepicker/js/bootstrap-material-datetimepicker.js') !!}
{!! Html::script('vendor2/seguce92/bootstrap-colorpicker/js/bootstrap-colorpicker.min.js') !!}
    <script type="text/javascript">
    var BASEURL="{{url('/')}}";
        $(document).ready(function() {

            $('#calendar').fullCalendar({
                header: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'month,basicWeek,basicDay'
                },

                navLinks: true, // can click day/week names to navigate views
                editable: true,
                selectable:true,
                selectHelper:true,

                select:function(start){
                    start = moment(start.format());

                    $('#date_start').val(start.format('YYYY-MM-DD'));
                    $('#responsive-modal').modal('show');
                },
                events: BASEURL+'/events'

            });

        });

        $('.colorpicker').colorpicker();

        $('#time_start').bootstrapMaterialDatePicker({

                date:false,
                shortTime: false,
                format: 'HH:mm:ss'
        });

    $('#date_end').bootstrapMaterialDatePicker({

        date:true,
        shortTime: false,
        format: 'YYYY-MM-DD'
    });
</code>```

One thing to note is that I had to create the table through phpmyadmin ,I was not able to migrate table from my code .

Also I have tried to change YYYY-MM-DD to Y-m-d H:i:s

This is my migration class:

```<code>class CreateEvent3sTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('event3s', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->datetime('start');
            $table->datetime('end');
            $table->string('color', 7);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('event3s');
    }
}
</code>```

This is my controller where the saving process is meant to happen:

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Event3;
class EventsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = Event3::get(['title','start','end','color']);

       return Response()->json($data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
       $event = new Event3();
       $event->title = $request->title;
       $event->start = $request->date_start .''. $request->time_start;
       $event->end = $request->data_end;
       $event->color = $request->color;
        $event->save();

        return redirect('/');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
</code>```

答:
take a closer look at the error message ...datetime value: '2017-07-1415:41:03' for... The date and time values are not separated by a whitespace.

It would be very helpful to see the php-script which actually tries to write into the database

Body:
I'm implementing full calendar API into my project .I have a problem when I try to save an event , I keep on getting the following error:

SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '2017-07-1415:41:03' for column 'start' at row 1 (SQL: insert into `event3s` (`title`, `start`, `end`, `color`) values (New event, 2017-07-1415:41:03, , #9e1515))

I have changed to the right time(time zone) in phpmyadmin but I still got the same error.

This is my table in phpmyadmin :
[![enter image description here][1]][1]

This is the calendar.blade.php class :

<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>Full Calendar</title>

    {!! Html::style('vendor2/seguce92/bootstrap/css/bootstrap.min.css') !!}
    {!! Html::style('vendor2/seguce92/fullcalendar/fullcalendar.min.css') !!}
    {!! Html::style('vendor2/seguce92/bootstrap-datetimepicker/css/bootstrap-material-datetimepicker.css') !!}
    {!! Html::style('vendor2/seguce92/bootstrap-colorpicker/css/bootstrap-colorpicker.min.css') !!}

{{ Form::open(['route' => 'user.events.store', 'method' => 'post', 'role' => 'form']) }}

Registration of new Event

                {{Form::label('title','Date Start') }}
                {{Form::text('title',old('title'),['class' => 'form-control'])}}

            {{Form::label('date_start','Date Start') }}
            {{Form::text('date_start',old('date_start'),['class' => 'form-control','readonly'=>'true'])}}

                {{Form::label('time_start','Time Start') }}
                {{Form::text('time_start',old('time_start'),['class' => 'form-control'])}}

                {{Form::label('date_end','Time Finish') }}
                {{Form::text('date_end',old('date_end'),['class' => 'form-control'])}}

                {{Form::label('color','COLOR') }}

                    {{ Form::text('color',old('color'),['class' => 'form-control']) }}

            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
            {!! Form::submit('Save',['class' => 'btn-btn-success'])!!}

{{Form::close()}}

{!! Html::script('vendor2/seguce92/jquery.min.js') !!}
{!! Html::script('vendor2/seguce92/bootstrap/js/bootstrap.min.js') !!}
{!! Html::script('vendor2/seguce92/fullcalendar/lib/moment.min.js') !!}
{!! Html::script('vendor2/seguce92/fullcalendar/fullcalendar.min.js') !!}
{!! Html::script('vendor2/seguce92/bootstrap-datetimepicker/js/bootstrap-material-datetimepicker.js') !!}
{!! Html::script('vendor2/seguce92/bootstrap-colorpicker/js/bootstrap-colorpicker.min.js') !!}


答: MySQL retrieves and displays DATETIME values in YYYY-MM-DD HH:MM:SS. Looks like you are missing a space in your datetime value and it should be '2017-07-14 15:41:03' instead

Title: SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value


答:
You could place your checkAll function outside of your click function, call it once the page load and when you click on the check all button

```<code>$(document).ready(function(){
    checkAll(true);

    $('.chk_boxes').click(function(){
        var chk = $(this).attr('checked')?true:false;
        checkAll(chk)
    });

    function checkAll(isCheck){
        $('.chk_boxes1').attr('checked',isCheck);
    }
})
</code>```

I also like @Univ approach.

Title: Initially set all checkboxes to checked

Body:
You could place your checkAll function outside of your click function, call it once the page load and when you click on the check all button

$(document).ready(function(){
    checkAll(true);

    $('.chk_boxes').click(function(){
        var chk = $(this).attr('checked')?true:false;
        checkAll(chk)
    });

    function checkAll(isCheck){
        $('.chk_boxes1').attr('checked',isCheck);
    }
})

I also like @Univ approach.


问:
V Json Data is not getting read in Hive Table
I am reading one line json data from Twitter in a Hive External Table. The table gets created but while reading the data, I get an error. I want to read the hashtags. I've followed the below steps:

```<code>hive (test)> add jar /usr/lib/hive/lib/hive-serdes-1.0-SNAPSHOT.jar;
Added /usr/lib/hive/lib/hive-serdes-1.0-SNAPSHOT.jar to class path
Added resource: /usr/lib/hive/lib/hive-serdes-1.0-SNAPSHOT.jar
</code>```

Data in file:

```<code>hive (test)> dfs -cat abhijit_hdfs/flume2/tweets/Twitter_test.js;

"entities":{"symbols":[],"urls":[],"hashtags":[{"text":"AchieveMore","indices":[56,68]}]}
</code>```

DDL statement

```<code>hive (test)> create external table tt4
           > (entities struct<hashtags:array<struct<text:string>>>)
           > row format serde 'com.cloudera.hive.serde.JSONSerDe'
           > LOCATION '/user/training/abhijit_hdfs/flume2/tweets/' ;
OK

Time taken: 0.193 seconds.
hive (test)> select * from tt4;
OK
Failed with exception java.io.IOException:org.apache.hadoop.hive.serde2.SerDeException: org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.LinkedHashMap out of VALUE_STRING token
 at [Source: java.io.StringReader@1cc892e; line: 1, column: 1]
Time taken: 0.384 seconds
</code>```

Please Guide.

答:
It does work after adding surrounding curl brackets ({...}), when using the hcatalog JsonSerDe

```<code>create external table tt4
(
    entities    struct<hashtags:array<struct<text:string>>>
)
row format serde 'org.apache.hive.hcatalog.data.JsonSerDe'
;
</code>```

```<code>select * from tt4
;
</code>```

```<code>+---------------------------------------+
|               entities                |
+---------------------------------------+
| {"hashtags":[{"text":"AchieveMore"}]} |
+---------------------------------------+
</code>```

The JsonSerDe for JSON files is available in Hive 0.12 and later.

In some distributions, a reference to hive-hcatalog-core.jar is
  required. ADD JAR /usr/lib/hive-hcatalog/lib/hive-hcatalog-core.jar;

...

The JsonSerDe was moved to Hive from HCatalog and before it was in
  hive-contrib project. It was added to the Hive distribution by
  HIVE-4895.

https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL#LanguageManualDDL-RowFormats&SerDe

Body:
I am reading one line json data from Twitter in a Hive External Table. The table gets created but while reading the data, I get an error. I want to read the hashtags. I've followed the below steps:

hive (test)> add jar /usr/lib/hive/lib/hive-serdes-1.0-SNAPSHOT.jar;
Added /usr/lib/hive/lib/hive-serdes-1.0-SNAPSHOT.jar to class path
Added resource: /usr/lib/hive/lib/hive-serdes-1.0-SNAPSHOT.jar

Data in file:

hive (test)> dfs -cat abhijit_hdfs/flume2/tweets/Twitter_test.js;

"entities":{"symbols":[],"urls":[],"hashtags":[{"text":"AchieveMore","indices":[56,68]}]}

DDL statement

hive (test)> create external table tt4
           > (entities struct<hashtags:array<struct<text:string>>>)
           > row format serde 'com.cloudera.hive.serde.JSONSerDe'
           > LOCATION '/user/training/abhijit_hdfs/flume2/tweets/' ;
OK

Time taken: 0.193 seconds.
hive (test)> select * from tt4;
OK
Failed with exception java.io.IOException:org.apache.hadoop.hive.serde2.SerDeException: org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.LinkedHashMap out of VALUE_STRING token
 at [Source: java.io.StringReader@1cc892e; line: 1, column: 1]
Time taken: 0.384 seconds

Please Guide.

Body:
It does work after adding surrounding curl brackets ({...}), when using the hcatalog JsonSerDe

create external table tt4
(
    entities    struct<hashtags:array<struct<text:string>>>
)
row format serde 'org.apache.hive.hcatalog.data.JsonSerDe'
;

select * from tt4
;

+---------------------------------------+
|               entities                |
+---------------------------------------+
| {"hashtags":[{"text":"AchieveMore"}]} |
+---------------------------------------+

The JsonSerDe for JSON files is available in Hive 0.12 and later.

In some distributions, a reference to hive-hcatalog-core.jar is
  required. ADD JAR /usr/lib/hive-hcatalog/lib/hive-hcatalog-core.jar;

...

The JsonSerDe was moved to Hive from HCatalog and before it was in
  hive-contrib project. It was added to the Hive distribution by
  HIVE-4895.

https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL#LanguageManualDDL-RowFormats&SerDe


问:
Flexbox ignores padding & width on links
Basically, I have a navigation that uses flexbox and it is all working perfectly fine. However, when going back over it recently I noticed that the 's inside the Li's are not the same size as the Li itself and therefore does not make the whole Li clickable.

I have tried many different ways to get the 's to be the same size, when I add padding to the links they display in inspector as having padding but the padding is not clickable...

.header .navigation {
  display: block;
  width: 100%;
  position: relative;
}

.header .navigation ul {
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: row;
}

.header .navigation ul li {
  float: none;
  display: inline-block;
  background-color: #9dabc0;
  border-right: 1px solid #7e899a;
  border-left: 1px solid #bdc6d4;
  text-align: center;
  flex-grow: 1;
}

.header .navigation ul li:last-child {
  background-color: #b4a042;
  border-right: none;
}

.header .navigation ul li:last-child:hover {
  background-color: #b49242;
}

.header .navigation ul li:last-child a {
  padding: 0 5px;
  text-align: center;
}

.header .navigation ul li:first-child {
  border-left: none;
}

.header .navigation ul li:hover {
  background: #3a495e;
}

.header .navigation ul li a {
  font-size: 16px;
  font-family: "Open Sans";
  color: #fff;
  font-weight: bold;
  line-height: 59px;
  text-shadow: 0.5px 0.866px 0 rgba(1, 1, 1, 0.39);
  padding: 0 5px;
  text-align: center;
  width: 100%;
}

.header .navigation ul li ul {
  left: 0px;
  top: 0px;
  margin-left: 0px;
  display: none;
  /* hide all sub menus from view */
  position: absolute;
  z-index: 100;
  background: #9dabc0;
  top: 59px;
  /* this should be the same height as the top level menu -- height + padding + borders */
  margin-left: 0px;
  width: 100%;
}

.header .navigation ul li ul li {
  border-top: 1px solid #7e899a;
  border-bottom: 1px solid #bdc6d4;
  border-left: none;
  border-right: none;
  background-color: #9dabc0;
  height: 42px;
  display: block;
}

.header .navigation ul li ul li:last-child {
  border-bottom: none;
  background-color: #9dabc0;
}

.header .navigation ul li ul li:last-child a {
  padding: 10px 24px;
}

.header .navigation ul li ul li a {
  font-size: 16px;
  font-family: "Open Sans";
  width: 100%;
  color: #fff;
  font-weight: bold;
  text-shadow: 0.5px 0.866px 0px rgba(1, 1, 1, 0.39);
  display: block;
  line-height: 18px;
  padding: 10px 24px;
}

.header .navigation ul li ul li:hover {
  background: #3a495e;
}

.header .navigation ul li {
  position: relative;
}

.header .navigation ul li:hover>ul {
  display: block;
}

.header .navigation ul li li.has-children>a:after {
  color: green;
  content: ' ►';
  font-size: 10px;
  float: right;
  padding-right: 10px;
  vertical-align: 1px;
}

.header .navigation ul .current-menu-item:after {
  color: green;
  content: '▲';
  position: absolute;
  top: 100%;
  left: 30%;
}

.header .navigation ul .sub-menu .current-menu-item:after {
  content: none;
}

.header .navigation ul li.has-children>a:after {
  color: green;
  content: '▼';
  font-size: 10px;
  padding-left: 5px;
  vertical-align: 1px;
}

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  <div class="navigation">
    <ul>
      <li>Home</li>
      <li>Engineering Castings
        <ul>
          <li>Example</li>
          <li>Example</li>
          <li>Example</li>
        </ul>
      </li>
      <li>Architectural Castings
        <ul>
          <li>Example</li>
          <li>Example</li>
        </ul>
      </li>
      <li>Decorative Castings
        <ul>
          <li>Example</li>
          <li>Example</li>
          <li>Example</li>
          <li>Example</li>
        </ul>
      </li>
      <li>
        Downloads</li>
      <li>
        Gallery</li>
      <li>
        Contact</li>
      <li>
        Blog</li>
      <li>
        FREE Castings Guide</li>
    </ul>
  </div>
</div></code>```

Here's the codepen: https://codepen.io/danielvickerssa/pen/ZyjqRr

答:
If you add display: flex to your list items, they will force the child element (, in this case) to stretch the full height of the container.

This is a default setting in a flex container – align-items: stretch

Just add this to your code:

```<code>li {
    display: flex;
}
</code>```

https://codepen.io/anon/pen/JJBePq

Body:
Basically, I have a navigation that uses flexbox and it is all working perfectly fine. However, when going back over it recently I noticed that the 's inside the Li's are not the same size as the Li itself and therefore does not make the whole Li clickable.

I have tried many different ways to get the 's to be the same size, when I add padding to the links they display in inspector as having padding but the padding is not clickable...

.header .navigation {
  display: block;
  width: 100%;
  position: relative;
}

.header .navigation ul {
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: row;
}

.header .navigation ul li {
  float: none;
  display: inline-block;
  background-color: #9dabc0;
  border-right: 1px solid #7e899a;
  border-left: 1px solid #bdc6d4;
  text-align: center;
  flex-grow: 1;
}

.header .navigation ul li:last-child {
  background-color: #b4a042;
  border-right: none;
}

.header .navigation ul li:last-child:hover {
  background-color: #b49242;
}

.header .navigation ul li:last-child a {
  padding: 0 5px;
  text-align: center;
}

.header .navigation ul li:first-child {
  border-left: none;
}

.header .navigation ul li:hover {
  background: #3a495e;
}

.header .navigation ul li a {
  font-size: 16px;
  font-family: "Open Sans";
  color: #fff;
  font-weight: bold;
  line-height: 59px;
  text-shadow: 0.5px 0.866px 0 rgba(1, 1, 1, 0.39);
  padding: 0 5px;
  text-align: center;
  width: 100%;
}

.header .navigation ul li ul {
  left: 0px;
  top: 0px;
  margin-left: 0px;
  display: none;
  /* hide all sub menus from view */
  position: absolute;
  z-index: 100;
  background: #9dabc0;
  top: 59px;
  /* this should be the same height as the top level menu -- height + padding + borders */
  margin-left: 0px;
  width: 100%;
}

.header .navigation ul li ul li {
  border-top: 1px solid #7e899a;
  border-bottom: 1px solid #bdc6d4;
  border-left: none;
  border-right: none;
  background-color: #9dabc0;
  height: 42px;
  display: block;
}

.header .navigation ul li ul li:last-child {
  border-bottom: none;
  background-color: #9dabc0;
}

.header .navigation ul li ul li:last-child a {
  padding: 10px 24px;
}

.header .navigation ul li ul li a {
  font-size: 16px;
  font-family: "Open Sans";
  width: 100%;
  color: #fff;
  font-weight: bold;
  text-shadow: 0.5px 0.866px 0px rgba(1, 1, 1, 0.39);
  display: block;
  line-height: 18px;
  padding: 10px 24px;
}

.header .navigation ul li ul li:hover {
  background: #3a495e;
}

.header .navigation ul li {
  position: relative;
}

.header .navigation ul li:hover>ul {
  display: block;
}

.header .navigation ul li li.has-children>a:after {
  color: green;
  content: ' ►';
  font-size: 10px;
  float: right;
  padding-right: 10px;
  vertical-align: 1px;
}

.header .navigation ul .current-menu-item:after {
  color: green;
  content: '▲';
  position: absolute;
  top: 100%;
  left: 30%;
}

.header .navigation ul .sub-menu .current-menu-item:after {
  content: none;
}

.header .navigation ul li.has-children>a:after {
  color: green;
  content: '▼';
  font-size: 10px;
  padding-left: 5px;
  vertical-align: 1px;
}

}

Home

Engineering Castings

Example

Example

Example

Architectural Castings

Example

Example

Decorative Castings

Example

Example

Example

Example

        Downloads

        Gallery

        Contact

        Blog

        FREE Castings Guide

Here's the codepen: https://codepen.io/danielvickerssa/pen/ZyjqRr

Body:
If you add display: flex to your list items, they will force the child element (<a>, in this case) to stretch the full height of the container.

This is a default setting in a flex container – align-items: stretch

Just add this to your code:

li {
    display: flex;
}

https://codepen.io/anon/pen/JJBePq


答:
If you want to have all your checkboxes checked the moment the page is loaded without the need to click anything, use:

```<code>$(document).ready(function(){
    $("input:checkbox").prop("checked", "true");
});
</code>```

Or just generate your HTML input tag like so:

```<code><input type="checkbox" checked="checked" />
</code>```

Hope this helps!

Title: Initially set all checkboxes to checked

Body:
If you want to have all your checkboxes checked the moment the page is loaded without the need to click anything, use:

$(document).ready(function(){
    $("input:checkbox").prop("checked", "true");
});

Or just generate your HTML input tag like so:

<input type="checkbox" checked="checked" />

Hope this helps!


问:
Rails helper method that works differently in different environments
In a Ruby on Rails application, I have a controller where I'd like some functionality to conditionally run, where the condition is dependent on the environment the application is running in. As a contrived example, in development mode I'd like it to do:

```<code>if foo == 5:
    ...
end
</code>```

And in production mode, I'd like:

```<code>if foo > 6:
    ...
end
</code>```

The difference between the two conditions is more complicated than a single constant (5 or 6 in the example above).

What is the most idiomatic way to do this in Rails? Would I write helper methods directly in the environments/ files? Or add a method to the application controller that checks the current environment? Or something else?

答:
I often need to do this in my apps too, in various places. E.g., I don't want to include analytics code in development mode. And so I set up an instance variable or two in the application controller:

```<code>before_filter :setup_variables

def setup_variables
  @development = (ENV['RAILS_ENV'] == "development")
  @production  = (ENV['RAILS_ENV'] == "production")
end
</code>```

I can now test whether I'm in development mode both in controllers as well as views.

One other note, though. If you're doing a lot of case-based switching (if development / if production), you might want to refactor this into a separate set of objects that you swap out depending on the environment.  E.g., have a DevelopmentLogic lib, and a ProductionLogic lib.

Body:
In a Ruby on Rails application, I have a controller where I'd like some functionality to conditionally run, where the condition is dependent on the environment the application is running in. As a contrived example, in development mode I'd like it to do:

if foo == 5:
    ...
end

And in production mode, I'd like:

if foo > 6:
    ...
end

The difference between the two conditions is more complicated than a single constant (5 or 6 in the example above).

What is the most idiomatic way to do this in Rails? Would I write helper methods directly in the environments/ files? Or add a method to the application controller that checks the current environment? Or something else?

Body:
I often need to do this in my apps too, in various places. E.g., I don't want to include analytics code in development mode. And so I set up an instance variable or two in the application controller:

before_filter :setup_variables

def setup_variables
  @development = (ENV['RAILS_ENV'] == "development")
  @production  = (ENV['RAILS_ENV'] == "production")
end

I can now test whether I'm in development mode both in controllers as well as views.

One other note, though. If you're doing a lot of case-based switching (if development / if production), you might want to refactor this into a separate set of objects that you swap out depending on the environment.  E.g., have a DevelopmentLogic lib, and a ProductionLogic lib.


问:
OBIEE 12.2.1.2 Export Metadata in RPD and Catalog
Metadata export within the RPD (utilitys -> RPD documentation) of the latest OBI release works fine:

The displayed data ranges from Subject Area to different stages of the RPD to the physical table and physical column.

I am facing problems exporting metadata (Create Catalog Report, see pic.) using the catalogmanager: ideally I want to extract the information of elements within dashboards connected to the subject area/tables. In this case: establishing a link between metadata (rpd) and metadata (catalog).

I have tried to use Dashboard as type to report on (choosing analysis in the dropdown and generating output works fine - Dashboard generates inconsistent output):

The advanced options somehow have no impact on the generated file:

Ideas and suggestions are much appreciated. (I did not try this option yet: I can use the catmanager in the command line along with wlst scripting - generating the prospective of automation of this process).

答:
a) Dashboards do not reference RPD presentation layer objects. Only analyses, prompts, filters or the likes do
b) As soon as your presentation layer has aliases for any object it won't work anymore anyways</p>


问:
send data from ajax to controller codeigniter
I'm trying to send data from javascript to function in controller with ajax. But ajax wont send. I post my code below:

In javascript function

```<code>var day = $(obj).text();
var base_url = $('#baseurl').val();

$.ajax({
    url: base_url + "Front_end_controller/eventi",
    method: 'POST',
    data: {date: day},
    success:function(result) {
        alert(result); // alert your date variable value here
    }
});
</code>```

In controller

```<code>public function eventi()
{
    $day = $this->input->post('date');
    var_dump($day);
}
</code>```

答:
You should probably try echo instead of var_dump. Also, check that the input is actually there and echo a message saying so if it is not.

```<code>public function eventi()
{
    $day = $this->input->post('date');
    if(isset($day)) //not NULL
    {
        echo $day;
    }
    else
    {
        echo "No Data";
    }
}
</code>```

You could also use a ternary to decide what to echo. This line produces the same result as the if/else statement above.

```<code>echo isset($day) ? $day : "No Data";
</code>```

Body:
I'm trying to send data from javascript to function in controller with ajax. But ajax wont send. I post my code below:

In javascript function

var day = $(obj).text();
var base_url = $('#baseurl').val();

$.ajax({
    url: base_url + "Front_end_controller/eventi",
    method: 'POST',
    data: {date: day},
    success:function(result) {
        alert(result); // alert your date variable value here
    }
});

In controller

public function eventi()
{
    $day = $this->input->post('date');
    var_dump($day);
}

Body:
You should probably try echo instead of var_dump. Also, check that the input is actually there and echo a message saying so if it is not.

public function eventi()
{
    $day = $this->input->post('date');
    if(isset($day)) //not NULL
    {
        echo $day;
    }
    else
    {
        echo "No Data";
    }
}

You could also use a ternary to decide what to echo. This line produces the same result as the if/else statement above.

echo isset($day) ? $day : "No Data";


答:
Look at regex. You basically need to match the content after the last |.

This pattern should work (working example at regexr.com):

```<code>/\|([\d\.]+)$/gm
</code>```

Explanation

\| matches a literal |

(...) creates a capture group (this is the group that you will want to extract)

[...] creates a character set

\d captures digits

\. captures literal .s

+ tells the parser to grab 1 or more of the previous token (in this case, the character group)

$ matches the end of the line

g, m match globally and multi-line, respectively

Thus the entire regex says match starting at a | and then group all digits and . in a capture group until the end of the line.

Title: Sorting by part of a line in a list from a file

Body:
This is for a C++ program. I'm not entirely sure how to formulate the problem I'm having. It's for a school assignment and I'm not looking for the answer just a point in the right direction. we need to read in a file with 75,000+ lines that look similar to this:

Census Tract 201, Autauga County, Alabama|9.84473419420788|1808|183.651479494869

Census Tract 202, Autauga County, Alabama|3.34583234555866|2355|703.860730836106

Census Tract 203, Autauga County, Alabama|5.35750339330735|3057|570.60159846447

wherein we need to sort by that last number in bold (using Quick and Merge sort from two different programs). I've got the sorting down to where if I only had to deal with the bold numbers I'd be set, but I'm having an issue getting the whole thing into a vector or array and being able to access specifically that part and sort by it. At the risk of making this way too long I'm not going to post the code I have so far. I'd just like a concept of how to attack this issue.

Body:
Look at regex. You basically need to match the content after the last |.

This pattern should work (working example at regexr.com):

/\|([\d\.]+)$/gm

Explanation

\| matches a literal |

(...) creates a capture group (this is the group that you will want to extract)

[...] creates a character set

\d captures digits

\. captures literal .s

+ tells the parser to grab 1 or more of the previous token (in this case, the character group)

$ matches the end of the line

g, m match globally and multi-line, respectively

Thus the entire regex says match starting at a | and then group all digits and . in a capture group until the end of the line.


问:
Java 8 JavaDoc generation fails with IllegalArgumentException when it reaches constant value
In my Java Maven project I'm using Java 8 JDK (v1.8.0_112), Maven 3 and maven-javadoc-plugin v2.10.4.

My code is the following (reduced):

```<code>public class DummyData {

    public static final String USE_CURSOR = "&useCursor";

    // fields, constructor, methods omitted...

}
</code>```

While generating class JavaDoc uing Maven goal, the following error appears

```<code>1 error
[ERROR] MavenReportException: Error while generating Javadoc:
Exit code: 1 - javadoc: error - com.sun.tools.doclets.internal.toolkit.util.DocletAbortException: java.lang.IllegalArgumentException: "&useCursor"

Command line was: "C:\Program Files\Java\jdk1.8.0_112\jre\..\bin\javadoc.exe" @options @packages

Refer to the generated Javadoc files in 'C:\Users\xan\git\Demo\demo\target\apidocs' dir.

org.apache.maven.reporting.MavenReportException:
Exit code: 1 - javadoc: error - com.sun.tools.doclets.internal.toolkit.util.DocletAbortException: java.lang.IllegalArgumentException: "&useCursor"
</code>```

Do you know why is this an issue?
My best guess is the '&' character which confuses JavaDoc but don't know how to do alternative (without changing the constant)?

Thanks

答:
Searching for the reported error, I found some results that point to a same problem.

Eclipse JavaDoc Generation fails with IllegalArgumentException?

Javadoc creation failes with IlegalArgumentExpection

According to these posts, it can be an issue with the CLASSPATH variable. Since you are using Eclipse, building and generating javadoc does not require further configuration outside the IDE.

The suggested solution is to clear the CLASSPATH variable (set classpath=). Hope it helps solve the problem.

Body:
In my Java Maven project I'm using Java 8 JDK (v1.8.0_112), Maven 3 and maven-javadoc-plugin v2.10.4.

My code is the following (reduced):

public class DummyData {

    public static final String USE_CURSOR = "&useCursor";

    // fields, constructor, methods omitted...

}

While generating class JavaDoc uing Maven goal, the following error appears

1 error
[ERROR] MavenReportException: Error while generating Javadoc:
Exit code: 1 - javadoc: error - com.sun.tools.doclets.internal.toolkit.util.DocletAbortException: java.lang.IllegalArgumentException: "&useCursor"

Command line was: "C:\Program Files\Java\jdk1.8.0_112\jre\..\bin\javadoc.exe" @options @packages

Refer to the generated Javadoc files in 'C:\Users\xan\git\Demo\demo\target\apidocs' dir.

org.apache.maven.reporting.MavenReportException:
Exit code: 1 - javadoc: error - com.sun.tools.doclets.internal.toolkit.util.DocletAbortException: java.lang.IllegalArgumentException: "&useCursor"

Do you know why is this an issue?
My best guess is the '&' character which confuses JavaDoc but don't know how to do alternative (without changing the constant)?

Thanks


问:
web2py write in lowercase in UPEERCASE field
i've got a " requires = IS_UPPER()" field in my table, i need to sometimes write in lowercase, there is a way to do that?
I have tried to use html quote or unicode tag but without any results.
Thank you</p>

答:
You can set the validator conditionally:</p>

```<code>if some_condition:
    db.mytable.myfield.requires = None # or some other validator
</code>```

Body:
You can set the validator conditionally:

if some_condition:
    db.mytable.myfield.requires = None # or some other validator


问:
cocos2d change sprite texture with animation
i want to change a sprite texture dynamically within animation.here is my code..

```<code>smileTexture=[[CCTextureCache sharedTextureCache] addImage:@"Monkey-smile_pad.png"];
angryTexture=[[CCTextureCache sharedTextureCache] addImage:@"Monkey-angry_pad.png"];
</code>```

and to change the texture of sprite _monkeyone i do this..

```<code>_monkeyOne.texture=smileTexture;
</code>```

and it change the sprite texture successfully.....but it's instant....i want this change within animation duration.....

can anyone help me...??

答: I don't know of a way to do what you are asking right off, but to "cheat" you could make a new sprite directly on top of the old sprite and have the new sprite contain the old texture.  Change the underlying texture.  Then fade out the top sprite (and remove it) when finished.</p>

Body:
i want to change a sprite texture dynamically within animation.here is my code..

smileTexture=[[CCTextureCache sharedTextureCache] addImage:@"Monkey-smile_pad.png"];
angryTexture=[[CCTextureCache sharedTextureCache] addImage:@"Monkey-angry_pad.png"];

and to change the texture of sprite _monkeyone i do this..

_monkeyOne.texture=smileTexture;

and it change the sprite texture successfully.....but it's instant....i want this change within animation duration.....

can anyone help me...??


问:
shared_ptr to an array
How can you dynamically allocate "n number of elements" to which a shared_ptr will point to?

I was able to create a static array that a shared pointer will point to, but I'd like the user to enter a number and then allocate n number of elements.

```<code>shared_ptr<int[10]> p = make_shared<int[10]>();
</code>```

答:
I think better for this problem is unique_ptr template.</p>

```<code>int amount = 10;
std::unique_ptr<int[]> name(new int[amount]);
</code>```

Title: shared_ptr to an array

Body:
How can you dynamically allocate "n number of elements" to which a shared_ptr will point to?

I was able to create a static array that a shared pointer will point to, but I'd like the user to enter a number and then allocate n number of elements.

shared_ptr<int[10]> p = make_shared<int[10]>();

Body:
I think better for this problem is unique_ptr template.

int amount = 10;
std::unique_ptr<int[]> name(new int[amount]);


问:
how to copy a value from an url into the html
I want to copy a value from the url into the html-code.

i.e:

when my url is

```<code>www.website.com/page?destination=other_page
</code>```

i want to copy everything from the "?" to the action of form:

```<code><form action="/user/register/" method="post" accept-charset="UTF-8">
</code>```

should become:

```<code><form action="/user/register/?destination=other_page" method="post" accept-charset="UTF-8">
</code>```

Any suggestions?

答:
You can get the entire querystring using window.location.search. You can then append that to the current action attribute using attr(), like this:

```<code>$('form').attr('action', function(i, a) {
  return a + window.location.search;
});
</code>```

Body:
I want to copy a value from the url into the html-code.

i.e:

when my url is

www.website.com/page?destination=other_page

i want to copy everything from the "?" to the action of form:

<form action="/user/register/" method="post" accept-charset="UTF-8">

should become:

<form action="/user/register/?destination=other_page" method="post" accept-charset="UTF-8">

Any suggestions?

Body:
You can get the entire querystring using window.location.search. You can then append that to the current action attribute using attr(), like this:

$('form').attr('action', function(i, a) {
  return a + window.location.search;
});


问:
How to complete a function execution before starting to execute another function
Please I have used .done() to ensure a function is completely executed before starting to execute next function. I borrowed the idea from Ajax. But it is not working. I keep getting error message done() is not a function.
Is done() only for Ajax? If yes, how can I accomplish my wish.

```<code>document.onreadystatechange = function () {
  if (document.readyState === "complete") {
    //do somethings

  }
}

//This must be completely executed before addNu()
$( "#mybutton" ).click(function() {
  //Do some things

}).done(addNu());

function addNu() {
  //do some things
}
</code>```

Note that none of the script is async. each must be completed before running the next

答:
Unfortunately the .done method is reserved for promises returned from an AJAX request.

You can achieve the same result by creating your own JS Promise that does not require AJAX.

A good website that demonstrates how promises work is https://scotch.io/tutorials/javascript-promises-for-dummies

Body:
Please I have used .done() to ensure a function is completely executed before starting to execute next function. I borrowed the idea from Ajax. But it is not working. I keep getting error message done() is not a function.
Is done() only for Ajax? If yes, how can I accomplish my wish.

document.onreadystatechange = function () {
  if (document.readyState === "complete") {
    //do somethings

  }
}

//This must be completely executed before addNu()
$( "#mybutton" ).click(function() {
  //Do some things

}).done(addNu());

function addNu() {
  //do some things
}

Note that none of the script is async. each must be completed before running the next