问:
How can I add a value in my list when a condition is true?
I have a dict with alot of items:

```<code>{'id-quantity-60': u'1', 'id-quantity-35': u'3','id-product-35': u'on', 'id-product-60': u'on',}
</code>```

I need to create a list with all three elements inside.
I'm expecting a list like this:

```<code><type 'list'>: [['60', u'1', u'on'], ['35', u'3', u'on'],]
</code>```

I have only 2 values above, but 2 times the same product-id. So it should add the quantity and the 'on off' together to the same product-id.

How can I do that? I tried it with something like this:

```<code>for key, value in request.params.items():
  if key[:12] == 'id-quantity-':
    if key[12:] in list:
      list.insert(key[12:], value)
    else:
      list.append([key[12:], value])

  if key[:11] == 'id-product-':
    if key[11:] in list:
      list.insert(key[11:], value)
    else:
      list.append([key[11:], value])
</code>```

The problem is I get this list all time splitet:

```<code><type 'list'>: [['60', u'1'], ['35', u'3'], ['35', u'on'], ['60', u'on'],]
</code>```

finally I should be able to fill the data in here (60, 1, True for example):

data = request.registry['website']._subscription_exclude_product(cr, uid, [{'product_id': int(60), 'qty': int(1), 'like': bool(True)}], context=context)

Thank you very much.

答:
Assuming keys for quantity and product are in the same format across the dictionary:

```<code>d={'id-quantity-60': u'1', 'id-quantity-35': u'3','id-product-35': u'on', 'id-product-60': u'on',}

l=[]
for k,v in d.items():
    if 'id-quantity' in k:
        x = k.replace('id-quantity-','')
        y = 'id-product-'+str(x)
        l.append([x, v, d[y]])

print(l)
</code>```

Output

```<code>[['60', '1', 'on'], ['35', '3', 'on']]
</code>```

Body:
I have a dict with alot of items:

{'id-quantity-60': u'1', 'id-quantity-35': u'3','id-product-35': u'on', 'id-product-60': u'on',}

I need to create a list with all three elements inside.
I'm expecting a list like this:

<type 'list'>: [['60', u'1', u'on'], ['35', u'3', u'on'],]

I have only 2 values above, but 2 times the same product-id. So it should add the quantity and the 'on off' together to the same product-id.

How can I do that? I tried it with something like this:

for key, value in request.params.items():
  if key[:12] == 'id-quantity-':
    if key[12:] in list:
      list.insert(key[12:], value)
    else:
      list.append([key[12:], value])

  if key[:11] == 'id-product-':
    if key[11:] in list:
      list.insert(key[11:], value)
    else:
      list.append([key[11:], value])

The problem is I get this list all time splitet:

<type 'list'>: [['60', u'1'], ['35', u'3'], ['35', u'on'], ['60', u'on'],]

finally I should be able to fill the data in here (60, 1, True for example):

data = request.registry['website']._subscription_exclude_product(cr, uid, [{'product_id': int(60), 'qty': int(1), 'like': bool(True)}], context=context)

Thank you very much.

Body:
Assuming keys for quantity and product are in the same format across the dictionary:

d={'id-quantity-60': u'1', 'id-quantity-35': u'3','id-product-35': u'on', 'id-product-60': u'on',}

l=[]
for k,v in d.items():
    if 'id-quantity' in k:
        x = k.replace('id-quantity-','')
        y = 'id-product-'+str(x)
        l.append([x, v, d[y]])

print(l)

Output

[['60', '1', 'on'], ['35', '3', 'on']]


来源: stackexchange

问:
How to get data in Array category wise?
I have below data coming from loop:

```<code>$array = Array(
[0]=>Array(
    [0]=>Cat 1
    [1]=> Q1
    [2]=> A1
    )
[1]=>Array(
    [0]=>Cat 1
    [1]=> Q2
    [2]=> A2
    )
[2]=>Array(
    [0]=>Cat 2
    [1]=> Q1
    [2]=> A1
    )
[3]=>Array(
    [0]=>Cat 3
    [1]=>Sub Cat 3
    [2]=>Q1
    [3]=>A1
    )
[4]=>Array(
    [0]=>Cat 3
    [1]=>Sub Cat 3
    [2]=>Q2
    [3]=>A2
    )
)
)
</code>```

I need data in Array like

```<code>$array_res = Array(
['Cat 1']=>Array(
    [0]=>Array(
        [0]=> Q1
        [1]=> A1
        )
    [1]=>Array(
        [0]=> Q2
        [1]=> A2
        )
    )
['Cat 2']=>Array(
    [0]=>Array(
        [0]=> Q1
        [1]=> A1
        )
    )
['Cat 3']=>Array(
    ['Sub Cat 3']=>Array(
        [0]=>Array(
            [0]=> Q1
            [1]=> A1
        )
        [1]=>Array(
            [0]=> Q2
            [1]=> A2
        )
        )
    )

)
</code>```

It should return data in Array/Associative Array. So can fetch data loop wise & print it. I want the arrays created dynamically when there are array values inside an array like sub cat 3.

答:
Nothing much to explain.. Have taken care of sub category as well.</p>

```<code>    <?php

        $array = Array(
        Array(
            "Cat 1",
            "Q1",
            "A1"
            ),
        Array(
            "Cat 1",
            "Q2",
            "A2"
            ),
        Array(
            "Cat 2",
            "Q1",
            "A1"
            ),
        Array(
            "Cat 3",
            "Sub Cat 3",
            "Q1",
            "A1"
            ),
        Array(
            "Cat 3",
            "Sub Cat 3",
            "Q2",
            "A2"
            ),
            Array(
                "Cat 2",
                "Q2",
                "A2"
            )
        );

        $array_res = array();

        foreach($array as $key=> $val) {
            if(is_array($val)) {
                $catName = $val[0];
                //echo "category = $catName <br>";
                //echo count($val) . "<br>";
                if(count($val) === 3) {
                    // no sub category
                    $this_arr = array();
                    foreach($val as $key1 => $val1) {
                        if($key1 !=0) {
                           //echo "$key1 => $val1 <br>";
                            $this_arr[] = $val1;
                        }
                    }

                    $array_res[$catName][] = $this_arr;
                }
                else {
                    // there is subcategory as well
                    $subCatName = $val[1];
                    $this_arr = array();
                    foreach($val as $key1 => $val1) {
                        if($key1 !=0 && $key1 !=1 ) {
                            //echo "$key1 => $val1 <br>";
                            $this_arr[] = $val1;
                        }
                    }

                    $array_res[$catName][$subCatName][] = $this_arr;
                }

            }
            else {
               // echo "$key => $val <br/>";
            }

        }

        echo "<br/>Result Array <br>";
        foreach($array_res as $key => $val) {
            if(is_array($val)) {
                echo "$key<br>";
                foreach($val as $key1 => $val1) {
                    echo "$key1 <br>";
                    if(is_array($val1)) {
                        foreach($val1 as $key2 => $val2) {
                            if(is_array($val2)) {
                                //echo "$key2 <br>";
                                foreach($val2 as $key3 => $val3) {
                                    echo "$key3 => $val3 <br>";
                                }
                            }
                            else {
                                echo "$key2 => $val2 <br>";
                            }
                        }
                    }
                }
            }
            else {
                echo "$key => $val <br/>";
            }

        }

    ?>
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to get data in Array category wise?

Body:
I have below data coming from loop:

$array = Array(
[0]=>Array(
    [0]=>Cat 1
    [1]=> Q1
    [2]=> A1
    )
[1]=>Array(
    [0]=>Cat 1
    [1]=> Q2
    [2]=> A2
    )
[2]=>Array(
    [0]=>Cat 2
    [1]=> Q1
    [2]=> A1
    )
[3]=>Array(
    [0]=>Cat 3
    [1]=>Sub Cat 3
    [2]=>Q1
    [3]=>A1
    )
[4]=>Array(
    [0]=>Cat 3
    [1]=>Sub Cat 3
    [2]=>Q2
    [3]=>A2
    )
)
)

I need data in Array like

$array_res = Array(
['Cat 1']=>Array(
    [0]=>Array(
        [0]=> Q1
        [1]=> A1
        )
    [1]=>Array(
        [0]=> Q2
        [1]=> A2
        )
    )
['Cat 2']=>Array(
    [0]=>Array(
        [0]=> Q1
        [1]=> A1
        )
    )
['Cat 3']=>Array(
    ['Sub Cat 3']=>Array(
        [0]=>Array(
            [0]=> Q1
            [1]=> A1
        )
        [1]=>Array(
            [0]=> Q2
            [1]=> A2
        )
        )
    )

)

It should return data in Array/Associative Array. So can fetch data loop wise & print it. I want the arrays created dynamically when there are array values inside an array like sub cat 3.

Body:
Nothing much to explain.. Have taken care of sub category as well.

    <?php

        $array = Array(
        Array(
            "Cat 1",
            "Q1",
            "A1"
            ),
        Array(
            "Cat 1",
            "Q2",
            "A2"
            ),
        Array(
            "Cat 2",
            "Q1",
            "A1"
            ),
        Array(
            "Cat 3",
            "Sub Cat 3",
            "Q1",
            "A1"
            ),
        Array(
            "Cat 3",
            "Sub Cat 3",
            "Q2",
            "A2"
            ),
            Array(
                "Cat 2",
                "Q2",
                "A2"
            )
        );

        $array_res = array();

        foreach($array as $key=> $val) {
            if(is_array($val)) {
                $catName = $val[0];
                //echo "category = $catName <br>";
                //echo count($val) . "<br>";
                if(count($val) === 3) {
                    // no sub category
                    $this_arr = array();
                    foreach($val as $key1 => $val1) {
                        if($key1 !=0) {
                           //echo "$key1 => $val1 <br>";
                            $this_arr[] = $val1;
                        }
                    }

                    $array_res[$catName][] = $this_arr;
                }
                else {
                    // there is subcategory as well
                    $subCatName = $val[1];
                    $this_arr = array();
                    foreach($val as $key1 => $val1) {
                        if($key1 !=0 && $key1 !=1 ) {
                            //echo "$key1 => $val1 <br>";
                            $this_arr[] = $val1;
                        }
                    }

                    $array_res[$catName][$subCatName][] = $this_arr;
                }

            }
            else {
               // echo "$key => $val <br/>";
            }

        }

        echo "<br/>Result Array <br>";
        foreach($array_res as $key => $val) {
            if(is_array($val)) {
                echo "$key<br>";
                foreach($val as $key1 => $val1) {
                    echo "$key1 <br>";
                    if(is_array($val1)) {
                        foreach($val1 as $key2 => $val2) {
                            if(is_array($val2)) {
                                //echo "$key2 <br>";
                                foreach($val2 as $key3 => $val3) {
                                    echo "$key3 => $val3 <br>";
                                }
                            }
                            else {
                                echo "$key2 => $val2 <br>";
                            }
                        }
                    }
                }
            }
            else {
                echo "$key => $val <br/>";
            }

        }

    ?>


问:
Find if the passed times are in the range in a php array
```<code>$MyArr = array(
 array('1', 'Morning', '09:00:00','10:30:00'),
 array('2', 'Late Morning', '10:31:00','12:00:00'),
 array('3', 'Lunch', '12:01:00','14:00:00'),
 array('4', 'Afternoon', '14:01:00','16:00:00'),
 array('5', 'Evening', '16:01:00','19:00:00'),
);
</code>```

I would like to create a function to check something like this

if '14:00:00', '16:00:00' is passed and can be found in that array it should return the first 2 values i.e. 4 and Afternoon

Here's the Test scenario:

'09:10:00','10:30:00' -> pass (return '1', 'Morning' )

'12:00:00','14:30:00' -> Fail

'10:30:00','12:00:00' -> should also pass (yeah, i need to add 1 minute to start time if it doesnt fit) (return '2', ' Late Morning' )

'09:00:00','16:00:00' -> Fail

How can i write code for this?

答:
I Think this is what you meant. I did a couple of different versions, but you can try them locally and see what they do (or take a look at the ideone working example)

```<code>  <?php
    header('Content-Type: text/plain');

    $MyArr = array(
      array('1', 'Morning', '09:00:00','10:30:00'),
      array('2', 'Late Morning', '10:31:00','12:00:00'),
      array('3', 'Lunch', '12:01:00','14:00:00'),
      array('4', 'Afternoon', '14:01:00','16:00:00'),
      array('5', 'Evening', '16:01:00','19:00:00'),
    );

    // first one, find array entries that fall between the time specified
    function in_date_range($array, $start = '00:00:00',$end = '23:59:59')
    {
      $start = strtotime(date('Y-m-d '.$start));
      $end = strtotime(date('Y-m-d '.$end));

      $results = Array();
      foreach ($array as $arr)
      {
        // check if $arr times fall within $start/$end
        //if (strtotime(date('Y-m-d '.$arr[2])) >= $start && strtotime(date('Y-m-d '.$arr[3])) <= $end)
        // check if $start/end fall within $arr times
        if ($start >= strtotime(date('Y-m-d '.$arr[2])) && $end <= strtotime(date('Y-m-d '.$arr[3])))
          $results[] = Array($arr[0],$arr[1]);
      }
      return $results;
    }

    // secon one, find array entries that surround the time supplied
    function in_date_range2($array, $time = '12:00:00')
    {
      $time = strtotime(date('Y-m-d '.$time));

      $results = Array();
      foreach ($array as $arr)
      {
        if ($time >= strtotime(date('Y-m-d '.$arr[2])) && $time <= strtotime(date('Y-m-d '.$arr[3])))
          $results[] = Array($arr[0],$arr[1]);
      }
      return $results;
    }

    print_r(in_date_range($MyArr,'14:00:00','16:00:00'));
    print_r(in_date_range($MyArr,'09:00:00','12:00:00'));
    echo "\r\n\r\n";
    print_r(in_date_range2($MyArr,'14:00:00'));
    print_r(in_date_range2($MyArr,'16:00:00'));
  ?>
</code>```

EDIT

updated: See the comments in the in_date_range function (regarding how it looks at the data).

ContentLicense: CC BY-SA 2.5

Body:
$MyArr = array(
 array('1', 'Morning', '09:00:00','10:30:00'),
 array('2', 'Late Morning', '10:31:00','12:00:00'),
 array('3', 'Lunch', '12:01:00','14:00:00'),
 array('4', 'Afternoon', '14:01:00','16:00:00'),
 array('5', 'Evening', '16:01:00','19:00:00'),
);

I would like to create a function to check something like this

if '14:00:00', '16:00:00' is passed and can be found in that array it should return the first 2 values i.e. 4 and Afternoon

Here's the Test scenario:

'09:10:00','10:30:00' -> pass (return '1', 'Morning' )

'12:00:00','14:30:00' -> Fail

'10:30:00','12:00:00' -> should also pass (yeah, i need to add 1 minute to start time if it doesnt fit) (return '2', ' Late Morning' )

'09:00:00','16:00:00' -> Fail

How can i write code for this?

Body:
I Think this is what you meant. I did a couple of different versions, but you can try them locally and see what they do (or take a look at the ideone working example)

  <?php
    header('Content-Type: text/plain');

    $MyArr = array(
      array('1', 'Morning', '09:00:00','10:30:00'),
      array('2', 'Late Morning', '10:31:00','12:00:00'),
      array('3', 'Lunch', '12:01:00','14:00:00'),
      array('4', 'Afternoon', '14:01:00','16:00:00'),
      array('5', 'Evening', '16:01:00','19:00:00'),
    );

    // first one, find array entries that fall between the time specified
    function in_date_range($array, $start = '00:00:00',$end = '23:59:59')
    {
      $start = strtotime(date('Y-m-d '.$start));
      $end = strtotime(date('Y-m-d '.$end));

      $results = Array();
      foreach ($array as $arr)
      {
        // check if $arr times fall within $start/$end
        //if (strtotime(date('Y-m-d '.$arr[2])) >= $start && strtotime(date('Y-m-d '.$arr[3])) <= $end)
        // check if $start/end fall within $arr times
        if ($start >= strtotime(date('Y-m-d '.$arr[2])) && $end <= strtotime(date('Y-m-d '.$arr[3])))
          $results[] = Array($arr[0],$arr[1]);
      }
      return $results;
    }

    // secon one, find array entries that surround the time supplied
    function in_date_range2($array, $time = '12:00:00')
    {
      $time = strtotime(date('Y-m-d '.$time));

      $results = Array();
      foreach ($array as $arr)
      {
        if ($time >= strtotime(date('Y-m-d '.$arr[2])) && $time <= strtotime(date('Y-m-d '.$arr[3])))
          $results[] = Array($arr[0],$arr[1]);
      }
      return $results;
    }

    print_r(in_date_range($MyArr,'14:00:00','16:00:00'));
    print_r(in_date_range($MyArr,'09:00:00','12:00:00'));
    echo "\r\n\r\n";
    print_r(in_date_range2($MyArr,'14:00:00'));
    print_r(in_date_range2($MyArr,'16:00:00'));
  ?>

EDIT

updated: See the comments in the in_date_range function (regarding how it looks at the data).


问:
Scrape the dynamic content using python scrapy
I would like to scrape the 'calendar' content in this link:
https://gomore.dk/lejebil/27035

I wonder if i could use python scrapy without using selenium to crawl this content. As i cant find any info from the network tab. Thanks!

答:
after half day research and i noticed i could use scrapy-splash to retrieve the JS-processed content, which gimme the full content of the webpage, including the calendar information. However, the calendar information is not tally with the expected. e.g. hour 1 for weekday1 should be "danger" but it is not.

The webpage use hour to represent 24 hours each day, and data-weekday 0 - 6 to represent sunday, monday, ..., saturday. And class="danger" to represent calendar is blocked (e.g. red color)

```<code>   <tr data-hour="0">
      <td class="hour">
        <div>
          <small>00.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4" class="danger"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="1">
      <td class="hour">
        <div>
          <small>01.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4" class="danger"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="2">
      <td class="hour">
        <div>
          <small>02.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4" class="danger"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="3">
      <td class="hour">
        <div>
          <small>03.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4" class="danger"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="4">
      <td class="hour">
        <div>
          <small>04.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4" class="danger"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="5">
      <td class="hour">
        <div>
          <small>05.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4" class="danger"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="6">
      <td class="hour">
        <div>
          <small>06.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4" class="danger"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="7">
      <td class="hour">
        <div>
          <small>07.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4" class="danger"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="8">
      <td class="hour">
        <div>
          <small>08.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4" class="danger"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="9">
      <td class="hour">
        <div>
          <small>09.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4" class="danger"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="10">
      <td class="hour">
        <div>
          <small>10.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4" class="danger"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="11">
      <td class="hour">
        <div>
          <small>11.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4" class="danger"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="12">
      <td class="hour">
        <div>
          <small>12.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4" class="danger"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="13">
      <td class="hour">
        <div>
          <small>13.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2" class="danger"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="14">
      <td class="hour">
        <div>
          <small>14.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2" class="danger"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="15">
      <td class="hour">
        <div>
          <small>15.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2" class="danger"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4"></td>
      <td data-weekday="5" class="danger"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="16">
      <td class="hour">
        <div>
          <small>16.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2" class="danger"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4"></td>
      <td data-weekday="5" class="danger"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="17">
      <td class="hour">
        <div>
          <small>17.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2" class="danger"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4"></td>
      <td data-weekday="5" class="danger"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="18">
      <td class="hour">
        <div>
          <small>18.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2" class="danger"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4"></td>
      <td data-weekday="5" class="danger"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend"></td>
    </tr>

    <tr data-hour="19">
      <td class="hour">
        <div>
          <small>19.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2" class="danger"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4"></td>
      <td data-weekday="5" class="danger"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend"></td>
    </tr>

    <tr data-hour="20">
      <td class="hour">
        <div>
          <small>20.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2" class="danger"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4"></td>
      <td data-weekday="5" class="danger"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend"></td>
    </tr>

    <tr data-hour="21">
      <td class="hour">
        <div>
          <small>21.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2" class="danger"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4"></td>
      <td data-weekday="5" class="danger"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend"></td>
    </tr>

    <tr data-hour="22">
      <td class="hour">
        <div>
          <small>22.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2" class="danger"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4"></td>
      <td data-weekday="5" class="danger"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend"></td>
    </tr>
</code>```

By any chance the rendered HTML from scrapy-splash can go wrong? The rest of the content seems correct except this calendar table.

ContentLicense: CC BY-SA 4.0

Body:
after half day research and i noticed i could use scrapy-splash to retrieve the JS-processed content, which gimme the full content of the webpage, including the calendar information. However, the calendar information is not tally with the expected. e.g. hour 1 for weekday1 should be "danger" but it is not.

The webpage use hour to represent 24 hours each day, and data-weekday 0 - 6 to represent sunday, monday, ..., saturday. And class="danger" to represent calendar is blocked (e.g. red color)

   <tr data-hour="0">
      <td class="hour">
        <div>
          <small>00.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4" class="danger"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="1">
      <td class="hour">
        <div>
          <small>01.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4" class="danger"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="2">
      <td class="hour">
        <div>
          <small>02.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4" class="danger"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="3">
      <td class="hour">
        <div>
          <small>03.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4" class="danger"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="4">
      <td class="hour">
        <div>
          <small>04.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4" class="danger"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="5">
      <td class="hour">
        <div>
          <small>05.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4" class="danger"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="6">
      <td class="hour">
        <div>
          <small>06.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4" class="danger"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="7">
      <td class="hour">
        <div>
          <small>07.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4" class="danger"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="8">
      <td class="hour">
        <div>
          <small>08.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4" class="danger"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="9">
      <td class="hour">
        <div>
          <small>09.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4" class="danger"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="10">
      <td class="hour">
        <div>
          <small>10.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4" class="danger"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="11">
      <td class="hour">
        <div>
          <small>11.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4" class="danger"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="12">
      <td class="hour">
        <div>
          <small>12.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4" class="danger"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="13">
      <td class="hour">
        <div>
          <small>13.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2" class="danger"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="14">
      <td class="hour">
        <div>
          <small>14.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2" class="danger"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4"></td>
      <td data-weekday="5"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="15">
      <td class="hour">
        <div>
          <small>15.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2" class="danger"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4"></td>
      <td data-weekday="5" class="danger"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="16">
      <td class="hour">
        <div>
          <small>16.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2" class="danger"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4"></td>
      <td data-weekday="5" class="danger"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="17">
      <td class="hour">
        <div>
          <small>17.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2" class="danger"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4"></td>
      <td data-weekday="5" class="danger"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend danger"></td>
    </tr>

    <tr data-hour="18">
      <td class="hour">
        <div>
          <small>18.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2" class="danger"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4"></td>
      <td data-weekday="5" class="danger"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend"></td>
    </tr>

    <tr data-hour="19">
      <td class="hour">
        <div>
          <small>19.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2" class="danger"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4"></td>
      <td data-weekday="5" class="danger"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend"></td>
    </tr>

    <tr data-hour="20">
      <td class="hour">
        <div>
          <small>20.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2" class="danger"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4"></td>
      <td data-weekday="5" class="danger"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend"></td>
    </tr>

    <tr data-hour="21">
      <td class="hour">
        <div>
          <small>21.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2" class="danger"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4"></td>
      <td data-weekday="5" class="danger"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend"></td>
    </tr>

    <tr data-hour="22">
      <td class="hour">
        <div>
          <small>22.00</small>
        </div>
      </td>
      <td data-weekday="1"></td>
      <td data-weekday="2" class="danger"></td>
      <td data-weekday="3" class="danger"></td>
      <td data-weekday="4"></td>
      <td data-weekday="5" class="danger"></td>
      <td data-weekday="6" class="cal-weekend danger"></td>
      <td data-weekday="0" class="cal-weekend"></td>
    </tr>

By any chance the rendered HTML from scrapy-splash can go wrong? The rest of the content seems correct except this calendar table.


问:
ExecuteNonQuery is not running
```<code>foreach (GridViewRow g1 in GridView1.Rows)
{
      SqlCommand cmd = new SqlCommand("INSERT INTO Order VALUES(@buyersName, @deliveryAddress, @productID, @productName, @category, CONVERT(VARBINARY(MAX), @image), @price, @paymentMode, @holderName)", con);

      cmd.Parameters.AddWithValue("@buyersName", Label2.Text);
      cmd.Parameters.AddWithValue("@deliveryAddress", TextBox1.Text);
      cmd.Parameters.AddWithValue("@productID", g1.Cells[0].Text);
      cmd.Parameters.AddWithValue("@productName", g1.Cells[1].Text);
      cmd.Parameters.AddWithValue("@category", g1.Cells[2].Text);
      cmd.Parameters.AddWithValue("@image", g1.Cells[3].Text);
      cmd.Parameters.AddWithValue("@price", g1.Cells[4].Text);
      cmd.Parameters.AddWithValue("@paymentMode", checkRadioButton());
      cmd.Parameters.AddWithValue("@holderName", TextBox2.Text);

      int r = cmd.ExecuteNonQuery();
 }
</code>```

When I run this code, it is showing an error that there is a syntax error near "Order". checkRadioButton() is returning the label of the selected RadioButton.

答:
Contrary to the statement in the other answer, it should be possible to CONVERT within the VALUES-section.
But there are multiple flaws or things that could be improved:

ORDER is a reserved word in sql server, put it in square brackets: [Order]

Don't use AddWithValue otherwise sql server infers the datatype, which could be problematic. Use Add instead. See here for more information.

You can convert the value of g1.Cells[3].Text to a byte-array (byte[]) before setting the parameter value. For conversion to byte[] see here.

Specify the columns in your query, to not break it when table changes in future

Change your code like following (column-names and datatypes may vary):

```<code>SqlCommand cmd = new SqlCommand(@"INSERT INTO [Order] (buyersName, deliveryAddress, productID, productName, category, image, price, paymentMode, holderName)
                                  VALUES(@buyersName, @deliveryAddress, @productID, @productName, @category, @image, @price, @paymentMode, @holderName)", con);

cmd.Parameters.Add("@buyersName", SqlDbType.VarChar).Value = Label2.Text;
cmd.Parameters.Add("@deliveryAddress", SqlDbType.VarChar).Value = TextBox1.Text;
cmd.Parameters.Add("@productID", SqlDbType.VarChar).Value = g1.Cells[0].Text;
cmd.Parameters.Add("@productName", SqlDbType.VarChar).Value = g1.Cells[1].Text;
cmd.Parameters.Add("@category", SqlDbType.VarChar).value = g1.Cells[2].Text;
cmd.Parameters.Add("@image", SqlDbType.VarBinary).Value =  g1.Cells[3].Text; //convert g1.Cells[3].Text to a byte array
cmd.Parameters.Add("@price", SqlDbType.Money) = g1.Cells[4].Text;
cmd.Parameters.Add("@paymentMode", SqlDbType.VarChar).Value = checkRadioButton();
cmd.Parameters.Add("@holderName", SqlDbType.VarChar).Value = TextBox2.Text;
int r=cmd.ExecuteNonQuery();
</code>```

Title: ExecuteNonQuery is not running

Body:
foreach (GridViewRow g1 in GridView1.Rows)
{
      SqlCommand cmd = new SqlCommand("INSERT INTO Order VALUES(@buyersName, @deliveryAddress, @productID, @productName, @category, CONVERT(VARBINARY(MAX), @image), @price, @paymentMode, @holderName)", con);

      cmd.Parameters.AddWithValue("@buyersName", Label2.Text);
      cmd.Parameters.AddWithValue("@deliveryAddress", TextBox1.Text);
      cmd.Parameters.AddWithValue("@productID", g1.Cells[0].Text);
      cmd.Parameters.AddWithValue("@productName", g1.Cells[1].Text);
      cmd.Parameters.AddWithValue("@category", g1.Cells[2].Text);
      cmd.Parameters.AddWithValue("@image", g1.Cells[3].Text);
      cmd.Parameters.AddWithValue("@price", g1.Cells[4].Text);
      cmd.Parameters.AddWithValue("@paymentMode", checkRadioButton());
      cmd.Parameters.AddWithValue("@holderName", TextBox2.Text);

      int r = cmd.ExecuteNonQuery();
 }

When I run this code, it is showing an error that there is a syntax error near "Order". checkRadioButton() is returning the label of the selected RadioButton.

Body:
Contrary to the statement in the other answer, it should be possible to CONVERT within the VALUES-section.
But there are multiple flaws or things that could be improved:

ORDER is a reserved word in sql server, put it in square brackets: [Order]

Don't use AddWithValue otherwise sql server infers the datatype, which could be problematic. Use Add instead. See here for more information.

You can convert the value of g1.Cells[3].Text to a byte-array (byte[]) before setting the parameter value. For conversion to byte[] see here.

Specify the columns in your query, to not break it when table changes in future

Change your code like following (column-names and datatypes may vary):

SqlCommand cmd = new SqlCommand(@"INSERT INTO [Order] (buyersName, deliveryAddress, productID, productName, category, image, price, paymentMode, holderName)
                                  VALUES(@buyersName, @deliveryAddress, @productID, @productName, @category, @image, @price, @paymentMode, @holderName)", con);

cmd.Parameters.Add("@buyersName", SqlDbType.VarChar).Value = Label2.Text;
cmd.Parameters.Add("@deliveryAddress", SqlDbType.VarChar).Value = TextBox1.Text;
cmd.Parameters.Add("@productID", SqlDbType.VarChar).Value = g1.Cells[0].Text;
cmd.Parameters.Add("@productName", SqlDbType.VarChar).Value = g1.Cells[1].Text;
cmd.Parameters.Add("@category", SqlDbType.VarChar).value = g1.Cells[2].Text;
cmd.Parameters.Add("@image", SqlDbType.VarBinary).Value =  g1.Cells[3].Text; //convert g1.Cells[3].Text to a byte array
cmd.Parameters.Add("@price", SqlDbType.Money) = g1.Cells[4].Text;
cmd.Parameters.Add("@paymentMode", SqlDbType.VarChar).Value = checkRadioButton();
cmd.Parameters.Add("@holderName", SqlDbType.VarChar).Value = TextBox2.Text;
int r=cmd.ExecuteNonQuery();


问:
DataStore/Datapusher error determining header type
I am trying to upload a CSV file to a CKAN DataStore and one of its columns was determined as type Numeric even though one of the values in that column was alphanumeric. The result is an error when Datapusher tries to load this very record.

Is there a way I can correct the Datastore type for a particular column in the file?

Versions:

Ubuntu 14.04.5 LTS

CKAN version 2.6.0 (installed from package)

Postgresql 9.3

答:
Final answer:

The datapusher is guessing datatypes based on data at the beginning of the file, later this turns out to be a bad guess and a string cannot be turned into a number. The latest CKAN (try it on beta.ckan.org) has a workaround for this: try the upload/datapush once, then after it is finished (with failure), use the data dictionary (e.g. https://beta.ckan.org/dataset/{dataset name here}/dictionary/{resource id here} to override the data type of the column, then go to the datastore and do the push again.

Original answer:

Does it manage to load the file but just not that record, or does it give up? If you upgrade to 2.7 and use the latest Datapusher code, I think you can use the Data Dictionary feature to set the type manually, manually start the push to datastore again, and it will use the type you have set instead of the guess.


问:
Getting list of all users registered on server with online/offline status using Smack API on android
Im connecting to an ejabberd XMPP server using Smack API -

```<code>        username = "admin";
        password = "admin";
        port = "5222";
        serviceName = "davids-macbook-pro.local";
        host = "192.168.20.8";

     config = XMPPTCPConnectionConfiguration.builder()
                    .setUsernameAndPassword(username, password)
                    .setHost(host)
                    .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
                    .setServiceName(serviceName)
                    .setPort(Integer.parseInt(port))
                    .build();

            connection = new XMPPTCPConnection(config);
            try {
                connection.connect();
                connection.login();
            } catch (SmackException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (XMPPException e) {
                e.printStackTrace();
            }
</code>```

I want to get a list of all online users. How is it possible ?

When I try -

```<code>Roster roster = Roster.getInstanceFor(connection);
Collection<RosterEntry> entries = roster.getEntries();
Log.i("entry", entries+"");
for (RosterEntry entry : entries) {

}
</code>```

Getting a null array for

```<code>Collection<RosterEntry> entries = roster.getEntries();
</code>```

答:
User getPresence in Roaster as below.

```<code>        Roster roster = Roster.getInstanceFor(connection);
        Collection<RosterEntry> entries = roster.getEntries();
        for (RosterEntry rosterEntry : entries){

            System.out.println("xmpp.Roster.presence "+ roster.getPresence(rosterEntry.getUser()).getType());
        }
</code>```

Body:
Im connecting to an ejabberd XMPP server using Smack API -

        username = "admin";
        password = "admin";
        port = "5222";
        serviceName = "davids-macbook-pro.local";
        host = "192.168.20.8";

     config = XMPPTCPConnectionConfiguration.builder()
                    .setUsernameAndPassword(username, password)
                    .setHost(host)
                    .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
                    .setServiceName(serviceName)
                    .setPort(Integer.parseInt(port))
                    .build();

            connection = new XMPPTCPConnection(config);
            try {
                connection.connect();
                connection.login();
            } catch (SmackException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (XMPPException e) {
                e.printStackTrace();
            }

I want to get a list of all online users. How is it possible ?

When I try -

Roster roster = Roster.getInstanceFor(connection);
Collection<RosterEntry> entries = roster.getEntries();
Log.i("entry", entries+"");
for (RosterEntry entry : entries) {

}

Getting a null array for

Collection<RosterEntry> entries = roster.getEntries();

Body:
User getPresence in Roaster as below.

        Roster roster = Roster.getInstanceFor(connection);
        Collection<RosterEntry> entries = roster.getEntries();
        for (RosterEntry rosterEntry : entries){

            System.out.println("xmpp.Roster.presence "+ roster.getPresence(rosterEntry.getUser()).getType());
        }


问:
SQL pivot / VLOOKUP query
I have the following simplified table so each stock code has
multiple warehouses and I want to "pivot" it so I can get
the cost for each warehouse just in 1 line for the stockcode

```<code>Stockcode | Warehouse | Cost
A100        WH          100$
A100        ZZ          200$
</code>```

What I would like to have is the following.
So only 1 stockcode line with the warehouse costs pivoted.

```<code>Stockcode | Cost WH | Cost ZZ
A100        100$      200$
</code>```

I currently did it by exporting it to excell, creating a new sheet and add a new column to the sheet using a VLOOKUP to the main table and add the ZZ cost like that.

How would you turn this around in SQL? I am a bit stuck with understanding how to transform this tabular data in such a way.

答:
I think (Stockcode,Warehouse) is unique in your table.
And I think you can use PIVOT like it

```<code>SELECT Stockcode,[WH],[ZZ]
FROM TestData PIVOT(MAX(Cost) FOR Warehouse IN([WH],[ZZ])) p
</code>```

And use dynamic query for generate query for all the warehouses

```<code>DECLARE @Warehouses varchar(500)=''

SELECT @Warehouses+=CONCAT(',[',Warehouse,']')
FROM
  (
    SELECT DISTINCT Warehouse
    FROM TestData
  ) q
ORDER BY Warehouse

SET @Warehouses=STUFF(@Warehouses,1,1,'')

PRINT @Warehouses

DECLARE @query varchar(2000)=CONCAT('SELECT Stockcode,',@Warehouses,'
FROM TestData PIVOT(MAX(Cost) FOR Warehouse IN(',@Warehouses,')) p')

PRINT @query

EXEC(@query)
</code>```

My another answer similar to it - Display count results of requests with results of jobs horizontally and locations vertically 3 tables

Title: SQL pivot / VLOOKUP query

Body:
I have the following simplified table so each stock code has
multiple warehouses and I want to "pivot" it so I can get
the cost for each warehouse just in 1 line for the stockcode

Stockcode | Warehouse | Cost
A100        WH          100$
A100        ZZ          200$

What I would like to have is the following.
So only 1 stockcode line with the warehouse costs pivoted.

Stockcode | Cost WH | Cost ZZ
A100        100$      200$

I currently did it by exporting it to excell, creating a new sheet and add a new column to the sheet using a VLOOKUP to the main table and add the ZZ cost like that.

How would you turn this around in SQL? I am a bit stuck with understanding how to transform this tabular data in such a way.

Body:
I think (Stockcode,Warehouse) is unique in your table.
And I think you can use PIVOT like it

SELECT Stockcode,[WH],[ZZ]
FROM TestData PIVOT(MAX(Cost) FOR Warehouse IN([WH],[ZZ])) p

And use dynamic query for generate query for all the warehouses

DECLARE @Warehouses varchar(500)=''

SELECT @Warehouses+=CONCAT(',[',Warehouse,']')
FROM
  (
    SELECT DISTINCT Warehouse
    FROM TestData
  ) q
ORDER BY Warehouse

SET @Warehouses=STUFF(@Warehouses,1,1,'')

PRINT @Warehouses

DECLARE @query varchar(2000)=CONCAT('SELECT Stockcode,',@Warehouses,'
FROM TestData PIVOT(MAX(Cost) FOR Warehouse IN(',@Warehouses,')) p')

PRINT @query

EXEC(@query)

My another answer similar to it - Display count results of requests with results of jobs horizontally and locations vertically 3 tables


问:
HTML table: same cell size
I know this should be easy and I've found many threads covering this but I must be missing something. After having tried out a couple of things this is my current code fiddle which should do the trick according to sources. But the cells do not have the same size.

#calendar {
  table-layout: fixed;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table border=1 id='calendar'>
  <tr>
    <td class='calendar_head'>hi</td>
    <td colspan=5 class='calendar_head_month' id='calendar_month'>
      ---</td>
    <td class='calendar_head'>hello</td>
  </tr>
  <tr>
    <td class='calendar_day'>Mo</td>
    <td class='calendar_day'>Di</td>
    <td class='calendar_day'>Mi</td>
    <td class='calendar_day'>Do</td>
    <td class='calendar_day'>Fr</td>
    <td class='calendar_day'>Sa</td>
    <td class='calendar_day'>So</td>
  </tr>
  <tr>
    <td class='calendar_entry' id='calendar_entry_1'></td>
    <td class='calendar_entry' id='calendar_entry_2'></td>
    <td class='calendar_entry' id='calendar_entry_3'></td>
    <td class='calendar_entry' id='calendar_entry_4'></td>
    <td class='calendar_entry' id='calendar_entry_5'></td>
    <td class='calendar_entry' id='calendar_entry_6'></td>
    <td class='calendar_entry' id='calendar_entry_7'></td>
  </tr>
</table></code>```

答:
I'm not sure if this answers your question. But you can declare the size of the cells with CSS:

Edit: I haven't used the correct percentage. Don't forget that the p tag is 18px in height, so you have to add that in your calculation.

table {
table-layout: fixed;
width:100%
}
td {
  padding-bottom: 10%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <table border=1 id='calendar'>
        <tr>
            <td class='calendar_head'>hi</td>
            <td class='calendar_head_month' id='calendar_month'>
            <td class='calendar_head_month' id='calendar_month'>
            <td class='calendar_head_month' id='calendar_month'>
            <td class='calendar_head_month' id='calendar_month'>
            <td class='calendar_head_month' id='calendar_month'>
               </td>
            <td class='calendar_head'>hello</td>
        </tr>
        <tr>
            <td class='calendar_day'>Mo</td>
            <td class='calendar_day'>Di</td>
            <td class='calendar_day'>Mi</td>
            <td class='calendar_day'>Do</td>
            <td class='calendar_day'>Fr</td>
            <td class='calendar_day'>Sa</td>
            <td class='calendar_day'>So</td>
        </tr>
        <tr>
            <td class='calendar_entry' id='calendar_entry_1'></td>
            <td class='calendar_entry' id='calendar_entry_2'></td>
            <td class='calendar_entry' id='calendar_entry_3'></td>
            <td class='calendar_entry' id='calendar_entry_4'></td>
            <td class='calendar_entry' id='calendar_entry_5'></td>
            <td class='calendar_entry' id='calendar_entry_6'></td>
            <td class='calendar_entry' id='calendar_entry_7'></td>
        </tr>
    </table>
</body></code>```

Title: HTML table: same cell size

Body:
I know this should be easy and I've found many threads covering this but I must be missing something. After having tried out a couple of things this is my current code fiddle which should do the trick according to sources. But the cells do not have the same size.

#calendar {
  table-layout: fixed;
}

    hi

      ---
    hello

    Mo
    Di
    Mi
    Do
    Fr
    Sa
    So

Body:
I'm not sure if this answers your question. But you can declare the size of the cells with CSS:

Edit: I haven't used the correct percentage. Don't forget that the p tag is 18px in height, so you have to add that in your calculation.

table {
table-layout: fixed;
width:100%
}
td {
  padding-bottom: 10%;
}

<body>
    <table border=1 id='calendar'>
        <tr>
            <td class='calendar_head'>hi</td>
            <td class='calendar_head_month' id='calendar_month'>
            <td class='calendar_head_month' id='calendar_month'>
            <td class='calendar_head_month' id='calendar_month'>
            <td class='calendar_head_month' id='calendar_month'>
            <td class='calendar_head_month' id='calendar_month'>
               </td>
            <td class='calendar_head'>hello</td>
        </tr>
        <tr>
            <td class='calendar_day'>Mo</td>
            <td class='calendar_day'>Di</td>
            <td class='calendar_day'>Mi</td>
            <td class='calendar_day'>Do</td>
            <td class='calendar_day'>Fr</td>
            <td class='calendar_day'>Sa</td>
            <td class='calendar_day'>So</td>
        </tr>
        <tr>
            <td class='calendar_entry' id='calendar_entry_1'></td>
            <td class='calendar_entry' id='calendar_entry_2'></td>
            <td class='calendar_entry' id='calendar_entry_3'></td>
            <td class='calendar_entry' id='calendar_entry_4'></td>
            <td class='calendar_entry' id='calendar_entry_5'></td>
            <td class='calendar_entry' id='calendar_entry_6'></td>
            <td class='calendar_entry' id='calendar_entry_7'></td>
        </tr>
    </table>
</body>


问:
square numbers given in an sequence
Given a positive integer sequence of numbers in an array with common difference 2
for e.g 2 4 6 8
Now replace each number by its square. Perform the computations efficiently.
I was asked this question in an interview and i gave him o(n) solution using bitwise operator since it is operation in the multiples of 2.If there is any better method please suggest.</p>

答:
```<code>class Square
{
  public static int[] sequence(int[] array)
  {
    int[] result=new int[array.length];
    for(int i=0;i<array.length;i++)
    {
      result[i]=array[i]*array[i];
    }
    return result;
  }
}

// test cases:
// Square.sequence(new int[]{2,4,6,8})
//out put->{ 4, 16, 36, 64 }
</code>```

Title: square numbers given in an sequence

LastEditorDisplayName: Aryabhatta


问:
How to create a Multi-Language Alexa Skill using Java?
I'm quite new to VUI and Alexa. I developed a good working Skill for Alexa Voice Services. Now I want to add a second language. I've found a tutorial in  the develop documation, but I'm using Eclipse and Java to create my Lambda function like this walkthrough.
The problem is, that I have no idea how to enable a second language option in the Lambda function. I have to use the same Lambda function for both languages.

My StreamRequestHandler:

```<code>public class ApiOmatBlogSpeechletStreamRequestHandler extends SpeechletRequestStreamHandler {
private static final Set<String> supportedApplicationIds = new HashSet<String>();
static {
    /*
     * This Id can be found on https://developer.amazon.com/edw/home.html#/ "Edit" the relevant
     * Alexa Skill and put the relevant Application Ids in this Set.
     */
    supportedApplicationIds.add("amzn1.ask.skill.xxxxxxxx");
}

public ApiOmatBlogSpeechletStreamRequestHandler() {
    super(new ApiOmatBlogSkillSpeechlet(), supportedApplicationIds);
    System.out.println("Super ApiOmatBlogSpeechletStreamRequestHandler");
}
</code>```

}

My Spechlet:

```<code>public SpeechletResponse onIntent(IntentRequest intentRequest, Session session) {
    Intent intent = intentRequest.getIntent();
    String intentName = (intent != null) ? intent.getName() : null;
    System.out.println("onIntent requestId={ " + intentRequest.getRequestId() + " }, sessionId={ "
            + session.getSessionId() + " } ");

    Integer step = (Integer) session.getAttribute("step");
    System.out.println("IntentName= " + intentName + " | step = " + step);

    if ("AMAZON.HelpIntent".equals(intentName)) {
        return getHelpResponse();
    } else if ("AMAZON.StopIntent".equals(intentName)) {
        return getStopResponse();
    } else if (step != null) {
        return testing(intent, session, step);
    } else {
        if ("TestIntent".equals(intentName)) {
            step = 1;
            session.setAttribute("step", step);
            return testing(intent, session, step);
        } else {
            SsmlOutputSpeech speechText = new SsmlOutputSpeech();

            speechText.setSsml("<speak> " + "The intent is invalid." + "Please repeat your demand. "
                    + "<break time='0.5s'/> " + "  </speak>");

            // Create reprompt
            PlainTextOutputSpeech speech2 = new PlainTextOutputSpeech();
            speech2.setText("I'm sorry. Please repeat your statement.");
            Reprompt reprompt = new Reprompt();
            reprompt.setOutputSpeech(speech2);

            return SpeechletResponse.newAskResponse(speechText, reprompt);
        }
    }
}

/**
 * This function will be called if you say 'start'
 */
public SpeechletResponse onLaunch(final LaunchRequest request, final Session session) throws SpeechletException {
    System.out.println(
            "onLaunch requestId={ " + request.getRequestId() + " }, sessionId={ " + session.getSessionId() + " } ");

    return getHelpResponse();
}
</code>```

Thank you

答:
It's quite difficult to settle it up.
I solved it by asking, which language the user speaks.

In the Spechlet.java I added the code:

```<code>private Boolean german;
    public SpeechletResponse onIntent(IntentRequest intentRequest, Session session) {
        if (intentRequest.getLocale().getLanguage().equals(new Locale("de").getLanguage())){
            System.out.println("Spoken language == Deutsch");
            german=true;
        }else{
            System.out.println("Spoken language == Englisch");
            german=false;
        }
...
}
</code>```

and follwing I can work with the Boolean german and set up my response.

If there is a better solution, which works on two languages, than I would looking forward to a posted answer or comment. But for the moment this is the best workaround to handle multiple language in Java.

Body:
I'm quite new to VUI and Alexa. I developed a good working Skill for Alexa Voice Services. Now I want to add a second language. I've found a tutorial in  the develop documation, but I'm using Eclipse and Java to create my Lambda function like this walkthrough.
The problem is, that I have no idea how to enable a second language option in the Lambda function. I have to use the same Lambda function for both languages.

My StreamRequestHandler:

public class ApiOmatBlogSpeechletStreamRequestHandler extends SpeechletRequestStreamHandler {
private static final Set<String> supportedApplicationIds = new HashSet<String>();
static {
    /*
     * This Id can be found on https://developer.amazon.com/edw/home.html#/ "Edit" the relevant
     * Alexa Skill and put the relevant Application Ids in this Set.
     */
    supportedApplicationIds.add("amzn1.ask.skill.xxxxxxxx");
}

public ApiOmatBlogSpeechletStreamRequestHandler() {
    super(new ApiOmatBlogSkillSpeechlet(), supportedApplicationIds);
    System.out.println("Super ApiOmatBlogSpeechletStreamRequestHandler");
}

}

My Spechlet:

public SpeechletResponse onIntent(IntentRequest intentRequest, Session session) {
    Intent intent = intentRequest.getIntent();
    String intentName = (intent != null) ? intent.getName() : null;
    System.out.println("onIntent requestId={ " + intentRequest.getRequestId() + " }, sessionId={ "
            + session.getSessionId() + " } ");

    Integer step = (Integer) session.getAttribute("step");
    System.out.println("IntentName= " + intentName + " | step = " + step);

    if ("AMAZON.HelpIntent".equals(intentName)) {
        return getHelpResponse();
    } else if ("AMAZON.StopIntent".equals(intentName)) {
        return getStopResponse();
    } else if (step != null) {
        return testing(intent, session, step);
    } else {
        if ("TestIntent".equals(intentName)) {
            step = 1;
            session.setAttribute("step", step);
            return testing(intent, session, step);
        } else {
            SsmlOutputSpeech speechText = new SsmlOutputSpeech();

            speechText.setSsml("<speak> " + "The intent is invalid." + "Please repeat your demand. "
                    + "<break time='0.5s'/> " + "  </speak>");

            // Create reprompt
            PlainTextOutputSpeech speech2 = new PlainTextOutputSpeech();
            speech2.setText("I'm sorry. Please repeat your statement.");
            Reprompt reprompt = new Reprompt();
            reprompt.setOutputSpeech(speech2);

            return SpeechletResponse.newAskResponse(speechText, reprompt);
        }
    }
}

/**
 * This function will be called if you say 'start'
 */
public SpeechletResponse onLaunch(final LaunchRequest request, final Session session) throws SpeechletException {
    System.out.println(
            "onLaunch requestId={ " + request.getRequestId() + " }, sessionId={ " + session.getSessionId() + " } ");

    return getHelpResponse();
}

Thank you

Body:
It's quite difficult to settle it up.
I solved it by asking, which language the user speaks.

In the Spechlet.java I added the code:

private Boolean german;
    public SpeechletResponse onIntent(IntentRequest intentRequest, Session session) {
        if (intentRequest.getLocale().getLanguage().equals(new Locale("de").getLanguage())){
            System.out.println("Spoken language == Deutsch");
            german=true;
        }else{
            System.out.println("Spoken language == Englisch");
            german=false;
        }
...
}

and follwing I can work with the Boolean german and set up my response.

If there is a better solution, which works on two languages, than I would looking forward to a posted answer or comment. But for the moment this is the best workaround to handle multiple language in Java.


问:
read.csv into nested list and set element names
I'm reading .csv files from several different directories into a nested list. Along the lines of

```<code>filenames <- list(a = list.files("/some_dir_1", pattern = "*.csv"), # not a reproducible example but for demonstration purposes
                  b = list.files("/some_dir_2", pattern = "*.csv"),
                  c = list.files("/some_dir_3", pattern = "*.csv"))
                  # creates a nested of list of file paths

dat.list <- lapply(filenames, lapply, read.csv)
            # creates a nested list of dataframes, with the same structure as filenames
</code>```

I'd like to name each element with their file path.

This could be done by naming them one by one, e.g.

```<code>    names(dat.list[["a"]]) <- filenames[["a"]]
</code>```

or by putting this in a for-loop, but is there a more versatile method? Preferably a tidyverse friendly solution, along the lines of...

```<code>filenames %>% lapply(., lapply, read_csv) %>% #some naming call#
</code>```

Or am I going about this in the wrong way?

Any help would be greatly appreciated, thanks.

答:
Based on the description, either we can use lapply to loop through the sequence of 'filenames' or with for loop to change the names of each of the dat.list[[i]] elements

```<code>lapply(seq_along(filenames), function(i) setNames(dat.list[[i]], filenames[[i]]))
</code>```

Or with Map

```<code>Map(setNames, dat.list, filenames)
</code>```

Or

```<code>for(i in seq_along(filenames)) names(dat.list[[i]]) <- filenames[[i]]
</code>```

If we want to use tidyverse, the equivalent option based on base R Map would be

```<code>library(purrr)
map2(dat.list, filenames, setNames)
</code>```

NOTE: The for loop assignment will reflect on the original 'dat.list', while we have to assign the lapply back to dat.list to update the 'dat.list'

data

```<code>filenames <- list(a = c('a1.csv', 'a2.csv'), b = c('b1.csv', 'b2.csv'))
set.seed(24)
dat.list <- lapply(1:2, function(i) replicate(2, as.data.frame(matrix(sample(1:5, 5*5,
        replace = TRUE), 5, 5)), simplify = FALSE))
</code>```

Body:
I'm reading .csv files from several different directories into a nested list. Along the lines of

filenames <- list(a = list.files("/some_dir_1", pattern = "*.csv"), # not a reproducible example but for demonstration purposes
                  b = list.files("/some_dir_2", pattern = "*.csv"),
                  c = list.files("/some_dir_3", pattern = "*.csv"))
                  # creates a nested of list of file paths

dat.list <- lapply(filenames, lapply, read.csv)
            # creates a nested list of dataframes, with the same structure as filenames

I'd like to name each element with their file path.

This could be done by naming them one by one, e.g.

    names(dat.list[["a"]]) <- filenames[["a"]]

or by putting this in a for-loop, but is there a more versatile method? Preferably a tidyverse friendly solution, along the lines of...

filenames %>% lapply(., lapply, read_csv) %>% #some naming call#

Or am I going about this in the wrong way?

Any help would be greatly appreciated, thanks.

Body:
Based on the description, either we can use lapply to loop through the sequence of 'filenames' or with for loop to change the names of each of the dat.list[[i]] elements

lapply(seq_along(filenames), function(i) setNames(dat.list[[i]], filenames[[i]]))

Or with Map

Map(setNames, dat.list, filenames)

Or

for(i in seq_along(filenames)) names(dat.list[[i]]) <- filenames[[i]]

If we want to use tidyverse, the equivalent option based on base R Map would be

library(purrr)
map2(dat.list, filenames, setNames)

NOTE: The for loop assignment will reflect on the original 'dat.list', while we have to assign the lapply back to dat.list to update the 'dat.list'

data

filenames <- list(a = c('a1.csv', 'a2.csv'), b = c('b1.csv', 'b2.csv'))
set.seed(24)
dat.list <- lapply(1:2, function(i) replicate(2, as.data.frame(matrix(sample(1:5, 5*5,
        replace = TRUE), 5, 5)), simplify = FALSE))


问:
Jackson Mapper - how to fail on null or empty values
We're using Jackson JSON mapper in our code to de-serialize some configuration objects. We'd like for Jackson to fail on de-serialization when specific fields are missing or empty

The only feature in Jackson to support this behavior is for primitives :

```<code>final DeserializationConfig.Feature failOnPremitives = DeserializationConfig.Feature.FAIL_ON_NULL_FOR_PRIMITIVES;
</code>```

The thing is the fields in question are mainly strings

Any help is highly appreciated

答:
There is an option called: FAIL_ON_NULL_FOR_CREATOR_PARAMETERS.

So I assume it would be accessible at: DeserializationConfig.Feature.FAIL_ON_NULL_FOR_CREATOR_PARAMETERS;

Or in yml:

```<code>jackson:
    serialization:
      indent-output: false
    deserialization:
      fail-on-unknown-properties: true
      fail-on-missing-creator-properties: true
      fail-on-null-creator-properties: true
</code>```

This works on all types, strings, ints, doubles etc..

Body:
We're using Jackson JSON mapper in our code to de-serialize some configuration objects. We'd like for Jackson to fail on de-serialization when specific fields are missing or empty

The only feature in Jackson to support this behavior is for primitives :

final DeserializationConfig.Feature failOnPremitives = DeserializationConfig.Feature.FAIL_ON_NULL_FOR_PRIMITIVES;

The thing is the fields in question are mainly strings

Any help is highly appreciated

Body:
There is an option called: FAIL_ON_NULL_FOR_CREATOR_PARAMETERS.

So I assume it would be accessible at: DeserializationConfig.Feature.FAIL_ON_NULL_FOR_CREATOR_PARAMETERS;

Or in yml:

jackson:
    serialization:
      indent-output: false
    deserialization:
      fail-on-unknown-properties: true
      fail-on-missing-creator-properties: true
      fail-on-null-creator-properties: true

This works on all types, strings, ints, doubles etc..


问:
Java 8 Stream extract datas from Map
I have a Map<String,ExtractedData> extractedDatas and I want to extract some data as return result.  I'm quite new with the Stream API and I don't understand what I have to do.  I tried with

```<code>public Map<String,ExtractedData> getExtractedData(String name)
{
    return extractedDatas.entrySet().stream()
            .filter(entry -> entry.getKey().startsWith(name))
            .filter(entry -> entry.getValue().getFieldValue() != null && entry.getValue().getFieldValue() != "")
            .collect(Collectors.toMap(...);
}
</code>```

What do I have to put in the Collectors.toMap ?

答:
you could do it a bit different if you are OK altering the initial Map:

```<code>extractedDatas
     .entrySet()
     .removeIf(entry ->
                 !(entry.getKey().startsWith(name) ||
                   entry.getValue().getFieldValue() != null && entry.getValue().getFieldValue() != "")
                  )
              );
</code>```

Title: Java 8 Stream extract datas from Map

Body:
I have a Map<String,ExtractedData> extractedDatas and I want to extract some data as return result.  I'm quite new with the Stream API and I don't understand what I have to do.  I tried with

public Map<String,ExtractedData> getExtractedData(String name)
{
    return extractedDatas.entrySet().stream()
            .filter(entry -> entry.getKey().startsWith(name))
            .filter(entry -> entry.getValue().getFieldValue() != null && entry.getValue().getFieldValue() != "")
            .collect(Collectors.toMap(...);
}

What do I have to put in the Collectors.toMap ?

Body:
you could do it a bit different if you are OK altering the initial Map:

extractedDatas
     .entrySet()
     .removeIf(entry ->
                 !(entry.getKey().startsWith(name) ||
                   entry.getValue().getFieldValue() != null && entry.getValue().getFieldValue() != "")
                  )
              );


问:
Inline style using asset pipeline in rails

<%= link_to root_path do %>

        <div style="background-image:<%= image_tag " image1.png "%>">

Title

Paragraph

<% end %>```

I want to pull the image from the asset pipeline to put as my background.
I could do it in .sass file.  But I made a template for each one and think it would be easier to input each photo in.

<div style="background-image:<%= image_tag "image1.png"%>">
 This is the line that I'm sure about the syntax about.

答:
If you use ERB to be interpreted by asset pipeline, then asset_path 'image.png' will return the full path of the image located in one of the asset load paths, which you can then use inside url(). So your inline div may look like:

```<code><div style="background-image: url(<%= asset_path 'image1.png' %>)">
</code>```

Ref: CSS and ERB (note the underscore (_) in asset_path helper)

If you use Sass, the following helpers will help you to make it more concise:

image-url("rails.png") returns url(/assets/rails.png)

image-path("rails.png") returns "/assets/rails.png"

The more generic form can also be used:

asset-url("rails.png") returns url(/assets/rails.png)

asset-path("rails.png") returns "/assets/rails.png"

Ref: CSS and Sass (note the dash (-) in above helpers)

Body:
<%= link_to root_path do %>

        <div style="background-image:<%= image_tag " image1.png "%>">

Title

Paragraph

<% end %>

I want to pull the image from the asset pipeline to put as my background.
I could do it in .sass file.  But I made a template for each one and think it would be easier to input each photo in.

<div style="background-image:<%= image_tag "image1.png"%>">
 This is the line that I'm sure about the syntax about.

Body:
If you use ERB to be interpreted by asset pipeline, then asset_path 'image.png' will return the full path of the image located in one of the asset load paths, which you can then use inside url(). So your inline div may look like:

<div style="background-image: url(<%= asset_path 'image1.png' %>)">

Ref: CSS and ERB (note the underscore (_) in asset_path helper)

If you use Sass, the following helpers will help you to make it more concise:

image-url("rails.png") returns url(/assets/rails.png)

image-path("rails.png") returns "/assets/rails.png"

The more generic form can also be used:

asset-url("rails.png") returns url(/assets/rails.png)

asset-path("rails.png") returns "/assets/rails.png"

Ref: CSS and Sass (note the dash (-) in above helpers)


问:
Compare Items in two Lists and return non matching Items
So I have two Lists.

```<code>List<Farmer> CSVFarmer;
List<Farmer> Farmers;
</code>```

CSVFarmer List gets its items from a method that will read a csv file.

Farmers List gets its items from a table in a sql database;

Now what I want to do is compare the two lists and return a list of non matching items;

For example if List CSVFarmer has:

```<code>FarmerName     ContractNumber   ContactNumber
John           2468             12345
Mike           13579            15790
</code>```

And List Farmers has:

```<code>FarmerName     ContractNumber   ContactNumber
Mike           13579            15790
</code>```

The list being returned should only have one item in it : Farmer John.
Farmer Class:

```<code> public class Farmer:INotifyPropertyChanged
{
    int _id;
    string _firstName;
    string _farmerNo;
    string _contactNumber;

    public Farmer()
    {
        _firstName = string.Empty;
        _farmerNo = string.Empty;
        _contactNumber = string.Empty;
    }

    public int Id
    {
        get { return _id; }
        set
        {
            _id = value;
            OnPropertyChanged("Id");
        }
    }
    public string FirstName
    {
        get { return _firstName; }
        set
        {
            _firstName = value;
            OnPropertyChanged("FirstName");
        }
    }
    public string FarmerNo
    {
        get { return _farmerNo; }
        set
        {
            _farmerNo = value;
            OnPropertyChanged("FarmerNo");
        }
    }
    public string ContactNumber
    {
        get { return _contactNumber; }
        set
        {
            _contactNumber = value;
            OnPropertyChanged("ContactNumber");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged (string property)
    {
        if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(property));
    }

}
</code>```

Ive tried this:

```<code>public class vmUserManagement
{
public List<Farmer> Farmer { get; set; }
public List<Farmer> CSVFarmers { get; set; }
public List<Farmer> Farmers { get; set; }

public vmUserManagement()
    {
        CSVFarmers = new List<Farmer>();
        Farmers = new List<Farmer>();
        Farmer = new List<Farmer>();
   }

public List<Farmer> getAllFarmers()
    {
        Farmers = RepoDapper.getAllFarmers();
        return Farmers;
    }

public List<Farmer> CSVImportFarmer()
    {
        OpenFileDialog openFile = new OpenFileDialog();
        openFile.DefaultExt = ".csv";
        openFile.Filter = "(.csv) | *.csv";

        var browseFile = openFile.ShowDialog();
        if (browseFile == true)
        {
            string FilePath = openFile.FileName;
            List<Farmer> values = File.ReadAllLines(FilePath).Select(v => FromFarmerCsv(v)).ToList();
            CSVFarmers = values;
        }
        return CSVFarmers;
    }

 public static Farmer FromFarmerCsv(string csvLine)
    {
        string[] values = csvLine.Split(',');
        Farmer farmer = new Farmer();
        farmer.FirstName = values[0];
        farmer.FarmerNo = values[1];
        farmer.ContactNumber = values[2];
        return farmer;
    }

public List<Farmer> validateFarmerList()
    {

        foreach (var a in CSVFarmers)
        {
            foreach (var b in Farmers)
            {

                    if (a != b)
                    {
                        Farmer.Add(a);
                    }

            }
        }

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

The problem I'm having is that  I will end up with two entries in List Farmer. Both for Farmer John and Farmer Mike. When I should only be getting a List containing Farmer John. Why is that?

I've also tried using Except:

```<code> public List<Farmer> validateFarmerList()
    {

        Farmer = CSVFarmers.Except(Farmers).ToList();
        return Farmer;
    }
</code>```

But I still get two items in my Farmer List (Farmer John and Mike) instead of one.
Am I missing something? Any help will be much appreciated.

答:
You have't overridden Equals and GethashCode in your Farmer class. That's why (a != b) doesn't work and also Enumerable.Except fails for the same reason: only references are compared and both are different instances.

How should .NET know that the ContractNumber of the farmer is relevant to identify him? One wayy is to tell it by overriding Equals and GetHashCode:

```<code>public class Farmer : IEquatable<Farmer>
{
    public string FarmerName { get; set; }
    public string ContractNumber { get; set; }

    // .... other properties etc

    public bool Equals(Farmer other)
    {
        if (ReferenceEquals(null, other)) return false;
        if (ReferenceEquals(this, other)) return true;
        return string.Equals(ContractNumber, other.ContractNumber);
    }
    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != this.GetType()) return false;
        return Equals((Farmer) obj);
    }

    public override int GetHashCode()
    {
        return (ContractNumber != null ? ContractNumber.GetHashCode() : 0);
    }
}
</code>```

Now you can use Except:

```<code>Farmer = CSVFarmers.Except(Farmers).ToList();
</code>```

2nd way is to implement a custom IEqualityComparer<Farmer>, f.e if you can't change the Farmer class itself or you don't want to change it's behaviour and just want a custom comparer:

```<code>public class FarmerContractComparer : IEqualityComparer<Farmer>
{
    public bool Equals(Farmer x, Farmer y)
    {
        if (ReferenceEquals(x, y)) return true;
        if (ReferenceEquals(null, x) || ReferenceEquals(null, y)) return false;
        return x.ContractNumber == y.ContractNumber;
    }
    public int GetHashCode(Farmer obj)
    {
        return (obj.ContractNumber != null ? obj.ContractNumber.GetHashCode() : 0);
    }
}public class FarmerContractComparer : IEqualityComparer<Farmer>
{
    public bool Equals(Farmer x, Farmer y)
    {
        if (ReferenceEquals(x, y)) return true;
        if (ReferenceEquals(null, x) || ReferenceEquals(null, y)) return false;
        return x.ContractNumber == y.ContractNumber;
    }
    public int GetHashCode(Farmer obj)
    {
        return (obj.ContractNumber != null ? obj.ContractNumber.GetHashCode() : 0);
    }
}
</code>```

You can use this comparer in many LINQ methods, for example also in Enumerable.Except:

```<code>Farmer = CSVFarmers.Except(Farmers, new FarmerContractComparer()).ToList();
</code>```

This approach has the advantage that you could provide different comparers for different tasks.

3rd approach:  use LINQ and don't create a new class(less reusable and efficient but less work):

```<code>Farmer = CSVFarmers.Where(f => !Farmers.Any(f2 => f.ContractNumber == f2.ContractNumber)).ToList();
</code>```

Body:
So I have two Lists.

List<Farmer> CSVFarmer;
List<Farmer> Farmers;

CSVFarmer List gets its items from a method that will read a csv file.

Farmers List gets its items from a table in a sql database;

Now what I want to do is compare the two lists and return a list of non matching items;

For example if List CSVFarmer has:

FarmerName     ContractNumber   ContactNumber
John           2468             12345
Mike           13579            15790

And List Farmers has:

FarmerName     ContractNumber   ContactNumber
Mike           13579            15790

The list being returned should only have one item in it : Farmer John.
Farmer Class:

 public class Farmer:INotifyPropertyChanged
{
    int _id;
    string _firstName;
    string _farmerNo;
    string _contactNumber;

    public Farmer()
    {
        _firstName = string.Empty;
        _farmerNo = string.Empty;
        _contactNumber = string.Empty;
    }

    public int Id
    {
        get { return _id; }
        set
        {
            _id = value;
            OnPropertyChanged("Id");
        }
    }
    public string FirstName
    {
        get { return _firstName; }
        set
        {
            _firstName = value;
            OnPropertyChanged("FirstName");
        }
    }
    public string FarmerNo
    {
        get { return _farmerNo; }
        set
        {
            _farmerNo = value;
            OnPropertyChanged("FarmerNo");
        }
    }
    public string ContactNumber
    {
        get { return _contactNumber; }
        set
        {
            _contactNumber = value;
            OnPropertyChanged("ContactNumber");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged (string property)
    {
        if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(property));
    }

}

Ive tried this:

public class vmUserManagement
{
public List<Farmer> Farmer { get; set; }
public List<Farmer> CSVFarmers { get; set; }
public List<Farmer> Farmers { get; set; }

public vmUserManagement()
    {
        CSVFarmers = new List<Farmer>();
        Farmers = new List<Farmer>();
        Farmer = new List<Farmer>();
   }

public List<Farmer> getAllFarmers()
    {
        Farmers = RepoDapper.getAllFarmers();
        return Farmers;
    }

public List<Farmer> CSVImportFarmer()
    {
        OpenFileDialog openFile = new OpenFileDialog();
        openFile.DefaultExt = ".csv";
        openFile.Filter = "(.csv) | *.csv";

        var browseFile = openFile.ShowDialog();
        if (browseFile == true)
        {
            string FilePath = openFile.FileName;
            List<Farmer> values = File.ReadAllLines(FilePath).Select(v => FromFarmerCsv(v)).ToList();
            CSVFarmers = values;
        }
        return CSVFarmers;
    }

 public static Farmer FromFarmerCsv(string csvLine)
    {
        string[] values = csvLine.Split(',');
        Farmer farmer = new Farmer();
        farmer.FirstName = values[0];
        farmer.FarmerNo = values[1];
        farmer.ContactNumber = values[2];
        return farmer;
    }

public List<Farmer> validateFarmerList()
    {

        foreach (var a in CSVFarmers)
        {
            foreach (var b in Farmers)
            {

                    if (a != b)
                    {
                        Farmer.Add(a);
                    }

            }
        }

        return Farmer;
    }
}

The problem I'm having is that  I will end up with two entries in List Farmer. Both for Farmer John and Farmer Mike. When I should only be getting a List containing Farmer John. Why is that?

I've also tried using Except:

 public List<Farmer> validateFarmerList()
    {

        Farmer = CSVFarmers.Except(Farmers).ToList();
        return Farmer;
    }

But I still get two items in my Farmer List (Farmer John and Mike) instead of one.
Am I missing something? Any help will be much appreciated.

Body:
You have't overridden Equals and GethashCode in your Farmer class. That's why (a != b) doesn't work and also Enumerable.Except fails for the same reason: only references are compared and both are different instances.

How should .NET know that the ContractNumber of the farmer is relevant to identify him? One wayy is to tell it by overriding Equals and GetHashCode:

public class Farmer : IEquatable<Farmer>
{
    public string FarmerName { get; set; }
    public string ContractNumber { get; set; }

    // .... other properties etc

    public bool Equals(Farmer other)
    {
        if (ReferenceEquals(null, other)) return false;
        if (ReferenceEquals(this, other)) return true;
        return string.Equals(ContractNumber, other.ContractNumber);
    }
    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != this.GetType()) return false;
        return Equals((Farmer) obj);
    }

    public override int GetHashCode()
    {
        return (ContractNumber != null ? ContractNumber.GetHashCode() : 0);
    }
}

Now you can use Except:

Farmer = CSVFarmers.Except(Farmers).ToList();

2nd way is to implement a custom IEqualityComparer<Farmer>, f.e if you can't change the Farmer class itself or you don't want to change it's behaviour and just want a custom comparer:

public class FarmerContractComparer : IEqualityComparer<Farmer>
{
    public bool Equals(Farmer x, Farmer y)
    {
        if (ReferenceEquals(x, y)) return true;
        if (ReferenceEquals(null, x) || ReferenceEquals(null, y)) return false;
        return x.ContractNumber == y.ContractNumber;
    }
    public int GetHashCode(Farmer obj)
    {
        return (obj.ContractNumber != null ? obj.ContractNumber.GetHashCode() : 0);
    }
}public class FarmerContractComparer : IEqualityComparer<Farmer>
{
    public bool Equals(Farmer x, Farmer y)
    {
        if (ReferenceEquals(x, y)) return true;
        if (ReferenceEquals(null, x) || ReferenceEquals(null, y)) return false;
        return x.ContractNumber == y.ContractNumber;
    }
    public int GetHashCode(Farmer obj)
    {
        return (obj.ContractNumber != null ? obj.ContractNumber.GetHashCode() : 0);
    }
}

You can use this comparer in many LINQ methods, for example also in Enumerable.Except:

Farmer = CSVFarmers.Except(Farmers, new FarmerContractComparer()).ToList();

This approach has the advantage that you could provide different comparers for different tasks.

3rd approach:  use LINQ and don't create a new class(less reusable and efficient but less work):

Farmer = CSVFarmers.Where(f => !Farmers.Any(f2 => f.ContractNumber == f2.ContractNumber)).ToList();


问:
What is this es6 syntax called?
I am relatively new to es6. I came across the following syntax and can't figure out what is it called.</p>

```<code>let parameter = 'key1';
const obj = {
    'key1': 'value1',
    'key2': 'value2',
    'key3': 'value3',
  }[parameter];
</code>```

答:
That concept is not specific to ES6.

That's just an object, out of which you're getting 1 value, depending on the parameter.

It is similar to:

```<code>let parameter = 'key1';
const temp = {
    'key1': 'value1',
    'key2': 'value2',
    'key3': 'value3',
}
const obj = temp[parameter];
</code>```

Except temp is never declared.

Title: What is this es6 syntax called?

Body:
I am relatively new to es6. I came across the following syntax and can't figure out what is it called.

let parameter = 'key1';
const obj = {
    'key1': 'value1',
    'key2': 'value2',
    'key3': 'value3',
  }[parameter];

Body:
That concept is not specific to ES6.

That's just an object, out of which you're getting 1 value, depending on the parameter.

It is similar to:

let parameter = 'key1';
const temp = {
    'key1': 'value1',
    'key2': 'value2',
    'key3': 'value3',
}
const obj = temp[parameter];

Except temp is never declared.


问:
Google Calendar API - Status Tentative
I'm using the Google Calendar V3 API and I notice some calendar events are coming from the API with a status of Tentative.  Can anyone tell me how this status comes about and how I can replicate it?

This is causing issues as my app is only syncing with calendar events which have a status of confirmed.

I've tried replicating using the online version of Google Calendar and app on Android but there doesn't seem to be a way to set tentative.

I've tried adding myself and others as guests and then setting attending to "maybe" - this isn't the answer and still comes through as "confirmed".

答: I did find a flow where the event status turned out to be "tentative". I created an event in Outlook calendar and set the status of the calendar as "tentative" (this can be done in outlook calendar UI). Now, I shared that event to my google calendar by adding my google calendar ID as participant. Since the ics file has the status to be "tentative", the event status was set as "tentative"  when fetched with Google Calendar API. However, I did not find a way to directly create a tentative event in Google Calendar UI itself.</p>

Title: Google Calendar API - Status Tentative


问:
Pass value on styled-component within usage
I want to make Header (own component) to be a styled-component. However I get

Uncaught TypeError:
  WEBPACK_IMPORTED_MODULE_4_styled_components.a.Header is not a function

```<code>class Header extends Component {
    render() {
        return (
            <div className={this.props.className}>
                <NavBar>
                    <Nav>
                        <NavItem>Item1</NavItem>
                        <NavItem>Item2</NavItem>
                    </Nav>
                </NavBar>
            </div>
        );
    }
}
export default Header;
</code>```

Desired Usage:

```<code>const StyledHeader = styled.Header`
  background: ${props => props.background ||  'goldenrod'};
`;
class HomePage extends Component {
    render() {
        return(
            <StyledHeader background={"#d3d9df"}/>
            <Content />
        );
    }
}
export default HomePage;
</code>```

am I doing the right approach? I just want different background colors for Header every page.

答:
You might want to look into using the ThemeProvider then you declare a theme and just provide it in your mainApp after this has happened you can for example do, with the () syntax you extend that existing component:

```<code>const StyledHeader = styled(Header)`
  background: ${{{ theme }} => theme.headerBg};
`;
</code>```

If you need any help feel free to hit me up.

Body:
I want to make Header (own component) to be a styled-component. However I get

Uncaught TypeError:
  WEBPACK_IMPORTED_MODULE_4_styled_components.a.Header is not a function

class Header extends Component {
    render() {
        return (

                <NavBar>

                        <NavItem>Item1</NavItem>
                        <NavItem>Item2</NavItem>

                </NavBar>

        );
    }
}
export default Header;

Desired Usage:

const StyledHeader = styled.Header`
  background: ${props => props.background ||  'goldenrod'};
`;
class HomePage extends Component {
    render() {
        return(

Body:
You might want to look into using the ThemeProvider then you declare a theme and just provide it in your mainApp after this has happened you can for example do, with the () syntax you extend that existing component:

const StyledHeader = styled(Header)`
  background: ${{{ theme }} => theme.headerBg};
`;

If you need any help feel free to hit me up.


问:
GWT code fragments (.cache.js) do not trigger service worker fetch event
GWT compiler produces code fragments as a result of code splitting (see details here)

The initial download file is named as {alphanumeric}.cache.js (e.g 1805B2053A824F148DB6D05B2186F955.cache.js) and other fragments {number}.cache.js (e.g. 1.cache.js) in the figure below.

I'm trying to develop a GWT app with Service Worker as I want the app to work offline. Once cached and offline, the GET request for initial download file triggers FETCH event in ServiceWorker but individual code fragments won't trigger the event. For some reason they seem to bypass the Service Worker.

For demonstration, check the app at https://gwt-pwa-demo.herokuapp.com/pwademo.html. It is a GWT app which uses Service Worker. It's not my app, I'm just using it for demonstration.

When you load the app, all the files will get cached. No go offline from chrome dev tools, and refresh the app. The app still shows and you will notice that initial download file is loaded from Service Worker. Now click on, Paris/Berlin/London, which will load fragments 1.cache.js and so on. Notice that these are coming from disk cache and not Cache Storage through ServiceWorker. If you look at console output, you don't see a log for these fragments which is printed from ServiceWorker Fetch event.

To clarify more, the app works offline only because the fragments are pulled from disk cache. If these fragment are not present in disk cache, the app won't work. Even if the fragments are present in Cache Storage, since ServiceWorker can't intercept these requests, they won't get loaded. Follow these steps to see this in action.

Assuming you have loaded the app once, open dev tools -> Application -> Clear Storage and clear site data. Make sure that cache in Cache Storage is also cleared.

Now load the app again https://gwt-pwa-demo.herokuapp.com/pwademo.html.

The cache will be created again and you will see the fragments in the cache.

Reload the app using "Empty Cache & Hard Reload" in Chrome while your Dev Tools are open.

This will clear disk cache but the Cache Storage is still there.

Go offline, and refresh the app and the initial app still loads from Cache Storage.

But when you click on, Paris or London, which triggers loading of code fragments, it fails.

答:
OK, I guess I found the chromium bug report @ https://bugs.chromium.org/p/chromium/issues/detail?id=439697 and related ServiceWorker spec issue @ https://github.com/w3c/ServiceWorker/issues/612.

GWT loads code fragments by creating iframes internally. These iframes are not controlled by parents Service Worker. The chrome bug is still open but w3c closed the spec issue @ https://github.com/w3c/ServiceWorker/issues/1163.