问:
Dynamic Bootstrap dropdown in Angular is not working
I'm trying to create a Bootstrap navbar with dropdowns from a two-level array. However, the dropdowns will only work when the dropdown class on
 and the dropdown-toggle class on
 are hard-coded.

Since some of my menu items should have a dropdown, and some should not, I want to set these using ng-class. Is there any way to delay ui-bootstrap untill the html has been compiled?

I found somewhere that jQuery('.dropdown-toggle').dropdown(); might reinitialize the dropdown, but the dropdown() function is not recognized in my case.

```<code><div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
        <li ng-repeat="navItem in structure.navItems" ng-class="{'active': structure.isActive(navItem), 'dropdown': navItem.subItems}"> <a href="{{navItem.href}}" ng-class="{'dropdown-toggle': navItem.subItems}" data-toggle="dropdown">
              {{navItem.name}}
              <span class="caret" ng-if="navItem.subItems"></span>
            </a>

            <!-- start dropdown menu -->
            <ul class="dropdown-menu">
                <li ng-repeat="subItem in navItem.subItems"> <a href="{{subItem.href}}" ng-class="{'active': structure.isActive(subItem)}">
                  {{subItem.name}}
                </a>

                </li>
                <!-- dit kan ook nog: <li class="divider"></li>
              <li class="dropdown-header">Nav header</li>
              -->
            </ul>
            <!-- end dropdown menu -->
        </li>
    </ul>
</div>
</code>```

答:
```<code><div class="card" ng-repeat="story in $ctrl.storiesToEstimate" ng-if="!$ctrl.isAdmin">
    <div class="row">
        <div class="col-10">
            <p>
                {{ story.storyContent[0] }}
            </p>
        </div>
        <div class="col-2">
            <div
                uib-dropdown
                dropdown-append-to-body
            >
                <a
                    class="btn"
                    uib-dropdown-toggle
                    id="dynamic-dropdown"
                    href="#"
                >
                    Select Scale
                </a>
                <ul
                    ng-if="$ctrl.arrayOfSessions[0].selected === 'Fibonacci'"
                    uib-dropdown-menu
                    aria-labelledby="dynamic-dropdown"
                    class="dropdown-menu"
                    role="menu"
                >
                    <li role="menuitem" ng-click="$ctrl.selectedValue(0)">0</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue(1)">1</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue(2)">2</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue(3)">3</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue(5)">5</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue(8)">8</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue(13)">13</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue(20)">20</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue(40)">40</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue(100)">100</a>
                </ul>
                <ul
                    ng-if="$ctrl.arrayOfSessions[0].selected === 'T-Shirt'"
                    uib-dropdown-menu
                    aria-labelledby="dynamic-dropdown"
                    role="menu"
                >
                    <li role="menuitem" ng-click="$ctrl.selectedValue('XS')">XS</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue('S')">S</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue('M')">M</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue('L')">L</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue('XL')">XL</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue('XXL')">XXL</li>
                </ul>
                <ul
                    ng-if="$ctrl.arrayOfSessions[0].selected === 'Gamer'"
                    uib-dropdown-menu
                    aria-labelledby="dynamic-dropdown"
                    role="menu"
                >
                    <li role="menuitem" ng-click="$ctrl.selectedValue('Easy')">Easy</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue('Medium')">Medium</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue('Hard')">Hard</li>
                </ul>
            </div>
        </div>
    </div>
</div>
</code>```

I have managed to get it working based on the solution from various posts.
The trick is that you use ui-bootstrap's option dropdown-append-to-body (something with rendering DOM) and that you use ng-if before applying other parameters like above.
Disclaimer: the dropdown is not as smooth as the twiter's bootstrap but it's working.

Body:
I'm trying to create a Bootstrap navbar with dropdowns from a two-level array. However, the dropdowns will only work when the dropdown class on
 and the dropdown-toggle class on
 are hard-coded.

Since some of my menu items should have a dropdown, and some should not, I want to set these using ng-class. Is there any way to delay ui-bootstrap untill the html has been compiled?

I found somewhere that jQuery('.dropdown-toggle').dropdown(); might reinitialize the dropdown, but the dropdown() function is not recognized in my case.

              {{navItem.name}}

                  {{subItem.name}}

Body:
<div class="card" ng-repeat="story in $ctrl.storiesToEstimate" ng-if="!$ctrl.isAdmin">
    <div class="row">
        <div class="col-10">
            <p>
                {{ story.storyContent[0] }}
            </p>
        </div>
        <div class="col-2">
            <div
                uib-dropdown
                dropdown-append-to-body
            >
                <a
                    class="btn"
                    uib-dropdown-toggle
                    id="dynamic-dropdown"
                    href="#"
                >
                    Select Scale
                </a>
                <ul
                    ng-if="$ctrl.arrayOfSessions[0].selected === 'Fibonacci'"
                    uib-dropdown-menu
                    aria-labelledby="dynamic-dropdown"
                    class="dropdown-menu"
                    role="menu"
                >
                    <li role="menuitem" ng-click="$ctrl.selectedValue(0)">0</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue(1)">1</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue(2)">2</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue(3)">3</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue(5)">5</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue(8)">8</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue(13)">13</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue(20)">20</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue(40)">40</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue(100)">100</a>
                </ul>
                <ul
                    ng-if="$ctrl.arrayOfSessions[0].selected === 'T-Shirt'"
                    uib-dropdown-menu
                    aria-labelledby="dynamic-dropdown"
                    role="menu"
                >
                    <li role="menuitem" ng-click="$ctrl.selectedValue('XS')">XS</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue('S')">S</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue('M')">M</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue('L')">L</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue('XL')">XL</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue('XXL')">XXL</li>
                </ul>
                <ul
                    ng-if="$ctrl.arrayOfSessions[0].selected === 'Gamer'"
                    uib-dropdown-menu
                    aria-labelledby="dynamic-dropdown"
                    role="menu"
                >
                    <li role="menuitem" ng-click="$ctrl.selectedValue('Easy')">Easy</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue('Medium')">Medium</li>
                    <li role="menuitem" ng-click="$ctrl.selectedValue('Hard')">Hard</li>
                </ul>
            </div>
        </div>
    </div>
</div>

I have managed to get it working based on the solution from various posts.
The trick is that you use ui-bootstrap's option dropdown-append-to-body (something with rendering DOM) and that you use ng-if before applying other parameters like above.
Disclaimer: the dropdown is not as smooth as the twiter's bootstrap but it's working.


来源: stackexchange

问:
How to remove unmatched data from two data frames, to create a new data frame in R
I am creating a graph that correlates the life expectancy age and the state pension age for each country. I have used web scraping packages to scrape 2 datasets from 2 Wikipedia pages.

One of the datasets contains the column "Country" and the other dataset contains the column "Country and regions". This is a problem because both datasets need to merge but are unbalanced due to the regions in the "Country and regions" column.

To solve this, I need to remove the regions in "Country and regions", before merging the datasets, so it is balanced. I need to find the unmatched data from "Country and regions" with "Country", remove it, and create one data frame with the 2 datasets.

```<code>library(xml2)
library(rvest)
library(stringr)

urlLifeExpectancy <- "https://en.wikipedia.org/wiki/List_of_countries_by_life_expectancy"

extractedLifeData = urlLifeExpectancy %>%
  read_html() %>%
  html_node(xpath = '//*[@id="mw-content-text"]/div/table[1]') %>%
  html_table(fill = TRUE)

urlPensionAge <- "https://en.wikipedia.org/wiki/Retirement_age#Retirement_age_by_country"

extractedPensionData = urlPensionAge %>%
  read_html() %>%
  html_node(xpath = '//*[@id="mw-content-text"]/div/table[3]') %>%
  html_table(fill = TRUE)
</code>```

答:
We can use merge by selecting the columns which we need from both the datasets

```<code>merge(extractedLifeData[c(1, 5, 7)], extractedPensionData[1:3],
       by.y = "Country", by.x = "Country and regions")
</code>```

Or use inner_join from dplyr

```<code>library(dplyr)

extractedLifeData %>% select(1, 5, 7) %>%
     inner_join(extractedPensionData %>% select(1:3),
                by = c("Country and regions" = "Country"))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am creating a graph that correlates the life expectancy age and the state pension age for each country. I have used web scraping packages to scrape 2 datasets from 2 Wikipedia pages.

One of the datasets contains the column "Country" and the other dataset contains the column "Country and regions". This is a problem because both datasets need to merge but are unbalanced due to the regions in the "Country and regions" column.

To solve this, I need to remove the regions in "Country and regions", before merging the datasets, so it is balanced. I need to find the unmatched data from "Country and regions" with "Country", remove it, and create one data frame with the 2 datasets.

library(xml2)
library(rvest)
library(stringr)

urlLifeExpectancy <- "https://en.wikipedia.org/wiki/List_of_countries_by_life_expectancy"

extractedLifeData = urlLifeExpectancy %>%
  read_html() %>%
  html_node(xpath = '//*[@id="mw-content-text"]/div/table[1]') %>%
  html_table(fill = TRUE)

urlPensionAge <- "https://en.wikipedia.org/wiki/Retirement_age#Retirement_age_by_country"

extractedPensionData = urlPensionAge %>%
  read_html() %>%
  html_node(xpath = '//*[@id="mw-content-text"]/div/table[3]') %>%
  html_table(fill = TRUE)

Body:
We can use merge by selecting the columns which we need from both the datasets

merge(extractedLifeData[c(1, 5, 7)], extractedPensionData[1:3],
       by.y = "Country", by.x = "Country and regions")

Or use inner_join from dplyr

library(dplyr)

extractedLifeData %>% select(1, 5, 7) %>%
     inner_join(extractedPensionData %>% select(1:3),
                by = c("Country and regions" = "Country"))


问:
How to free dynamic memory if exception occurs in constructor?
I came across a situation where constructor allocated the dynamic memory and if any exception occurs in the constructor, it was not freeing the dynamically allocated memory. To avoid such situation I used unique_ptr, and it is able to free the memory properly.

To showcase the situation here is a dummy code for that.

```<code>class ExceptionInConstructor
{
 unique_ptr<int> a;
public:
    ExceptionInConstructor()
    {
        a = std::unique_ptr<int>( new int(10));
        cout <<"Constructor called. Value of a is "<< *a<<endl;
        //some exception occurs after the mrmory allocation
        throw exception();
    }
    ~ExceptionInConstructor()
    {
        cout << "Dest called()"<<endl;
    }
};

int main()
{
    try
    {
        ExceptionInConstructor ex;
    }
    catch(...)
    {}
    return 0;
 }
</code>```

Is it a correct and efficient way for such a situation or is there any better option for such a scenario?

Edit 1: Removed the commented code in destructor which was left by mistake

答:
No, that is exactly the point and intended use case for smart pointers and RAII in general.

Also note that your delete a in your destructor is wrong in any case as the unique_ptr is not a pointer itself. Relatedly, destructors are also not called if there is an exception in the constructor.

Body:
I came across a situation where constructor allocated the dynamic memory and if any exception occurs in the constructor, it was not freeing the dynamically allocated memory. To avoid such situation I used unique_ptr, and it is able to free the memory properly.

To showcase the situation here is a dummy code for that.

class ExceptionInConstructor
{
 unique_ptr<int> a;
public:
    ExceptionInConstructor()
    {
        a = std::unique_ptr<int>( new int(10));
        cout <<"Constructor called. Value of a is "<< *a<<endl;
        //some exception occurs after the mrmory allocation
        throw exception();
    }
    ~ExceptionInConstructor()
    {
        cout << "Dest called()"<<endl;
    }
};

int main()
{
    try
    {
        ExceptionInConstructor ex;
    }
    catch(...)
    {}
    return 0;
 }

Is it a correct and efficient way for such a situation or is there any better option for such a scenario?

Edit 1: Removed the commented code in destructor which was left by mistake


问:
Split string in dataweave
I have a string like "Hi I am from "Kazan, Russia". The output should be

```<code>Hi
I
am
from
Kazan, Russia
</code>```

I tried the regex [^\s\"']+|\"([^\"]*)\"|'([^']*)', which works fine on regexp.com. But in dataweave it does nothing.
This is what I tried

```<code>%dw 1.0
%output application/json
%function split(data) {returnData: data splitBy "[^\s\"']+|\"([^\"]*)\"|'([^']*)'"}
---
split(payload)[0]
</code>```

Edit 1

I tried scan operator
This is what I did

```<code>%dw 1.0
%output application/json
---
{
payload: payload scan /[^\s\"']+|\"([^\"]*)\"|'([^']*)'/
}
</code>```

But I am getting NullPointerException

Stack trace

```<code>Message               : null (java.lang.NullPointerException).
Payload               :      com.mulesoft.weave.reader.DefaultSeekableStream@5d334a28
Element               : /logFlow/processors/0 @ log:log.xml:14 (Transform Message)
Element XML           : <dw:transform-message doc:name="Transform Message" metadata:id="87d4353c-240d-4b1c-84b4-171f6c11045b">
                    <dw:input-payload mimeType="plain/text"></dw:input-payload>
                    <dw:set-payload>%dw 1.0%output application/json---{payload: payload scan /[^\s\"']+|\"([^\"]*)\"|'([^']*)'/}</dw:set-payload>
                    </dw:transform-message>
</code>```

答:
It works for me:

%dw 2.0

%output application/json

payload map ((payload01 , indexOfPayload01) -> {
    accountType: payload01.accountType,
    address: payload01.street ++ payload01.city,
    country: payload01.country,
    creationDate: payload01.creationDate as :string,
    firstName: (payload01.name splitBy ' ')[0],
    id: payload01.accountID,
    lastName: (payload01.name splitBy ' ')[1],
    miles: payload01.miles,
    postal: payload01.postal
})

ContentLicense: CC BY-SA 3.0

Title: Split string in dataweave

Body:
I have a string like "Hi I am from "Kazan, Russia". The output should be

Hi
I
am
from
Kazan, Russia

I tried the regex [^\s\"']+|\"([^\"]*)\"|'([^']*)', which works fine on regexp.com. But in dataweave it does nothing.
This is what I tried

%dw 1.0
%output application/json
%function split(data) {returnData: data splitBy "[^\s\"']+|\"([^\"]*)\"|'([^']*)'"}
---
split(payload)[0]

Edit 1

I tried scan operator
This is what I did

%dw 1.0
%output application/json
---
{
payload: payload scan /[^\s\"']+|\"([^\"]*)\"|'([^']*)'/
}

But I am getting NullPointerException

Stack trace

Message               : null (java.lang.NullPointerException).
Payload               :      com.mulesoft.weave.reader.DefaultSeekableStream@5d334a28
Element               : /logFlow/processors/0 @ log:log.xml:14 (Transform Message)
Element XML           : <dw:transform-message doc:name="Transform Message" metadata:id="87d4353c-240d-4b1c-84b4-171f6c11045b">
                    <dw:input-payload mimeType="plain/text"></dw:input-payload>
                    <dw:set-payload>%dw 1.0%output application/json---{payload: payload scan /[^\s\"']+|\"([^\"]*)\"|'([^']*)'/}</dw:set-payload>
                    </dw:transform-message>


问:
Can we stop the perf test in gatling automatically when we reach a certain limit of 504s?
Is it possible to stop the performance tests automatically when you reach a certain amount of 504s instead of running the tests fully? Is there any options available in Gatling to achieve this?</p>

答:
I don't think this is possible - gatling users are (by design) not aware of results from others. Likewise simulation level assertions are not checked until after all the users are complete.

The best you can do is to have .exitHereIfFailed in your scenario so that individual users don't keep performing their own actions after a 504 or other error

Depending on your scenarios, you might also be able to rework them to improve matters - eg: if you're not dependent on each user having a distinct authorisation etc, you could use fewer users in a simulation with looping inside scenarios. But this will be highly dependant on what you're modelling.


问:
std::set deduction guide doesn't work as expected
Shouldn't the two set types be identical?

#include <array>
#include <set>
#include <iostream>

template <class Iter>
std::set(Iter, Iter) -> std::set<typename std::iterator_traits<Iter>::value_type>;

int main() {

    std::array a {1,2,3,4};
    std::set<int> si {a.begin(), a.end()};
    std::set       s {a.begin(), a.end()};

    for(auto& i: si) { std::cout << i << "\n"; }
    for(auto& i: s ) { std::cout << i << "\n"; }

}
```

<p>instead it yields:</p>

```1
2
3
4
0x7ffdf5bc9050
0x7ffdf5bc9060
```

even tried with additional Allocator :-(

答:
std::set provides a constructor which takes a std::initializer_list and is able to do the type deduction of T for std::set<T>. In this case, using the syntax std::set x{a.begin(), a.end() }; will use the initializer list constructor and deduces T from that. No user defined deduction guide takes place!

If you create your object with std::set x(a.begin(), a.end()); the initilizer list constructor will not be used. Now, as no other constructor matches, deduction guides take place!

Example how the effect is if you have initializer list constructors in your code:

```<code>template < typename U >
struct X
{
    // Directly makes the type deducable, because U can be deduced from the parameter of the constructor
    X( std::initializer_list<U> )
    {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
    }

    template < typename ... T>
        X( T... )
    {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
    }
};

struct ONE {};

template < typename Iter >
X( const Iter&, const Iter& ) -> X<ONE>;

template < typename U >
struct Y
{
    // type U can NOT deduced from the parameter!
    template < typename T>
    Y( std::initializer_list<T> )
    {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
    }

    template < typename ... T>
        Y( T... )
    {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
    }
};

struct TWO {};

template < typename Iter >
Y( const Iter&, const Iter& ) -> Y<TWO>;

int main()
{
    std::array a {1,2,3,4};
    X x1{a.begin(), a.end()};
    X x2(a.begin(), a.end());

    std::cout << "###" << std::endl;

    Y y1{a.begin(), a.end()};
    Y y2(a.begin(), a.end());
}
</code>```

That initializer list constructors are take preference over deduction guide was also new to me and answered here:
Why does using uniform initializer syntax result in different behavior to the "old" style ()?

The important new thing for me was:

[over.match.list]

[...] overload resolution selects the constructor in two phases:

Initially, the candidate functions are the initializer-list constructors ([dcl.init.list]) of the class T and the argument list
  consists of the initializer list as a single argument.

[...]

For details details see the linked question!

Body:
Shouldn't the two set types be identical?

#include <array>
#include <set>
#include <iostream>

template <class Iter>
std::set(Iter, Iter) -> std::set<typename std::iterator_traits<Iter>::value_type>;

int main() {

    std::array a {1,2,3,4};
    std::set<int> si {a.begin(), a.end()};
    std::set       s {a.begin(), a.end()};

    for(auto& i: si) { std::cout << i << "\n"; }
    for(auto& i: s ) { std::cout << i << "\n"; }

}

instead it yields:

1
2
3
4
0x7ffdf5bc9050
0x7ffdf5bc9060

even tried with additional Allocator :-(

Body:
std::set provides a constructor which takes a std::initializer_list and is able to do the type deduction of T for std::set<T>. In this case, using the syntax std::set x{a.begin(), a.end() }; will use the initializer list constructor and deduces T from that. No user defined deduction guide takes place!

If you create your object with std::set x(a.begin(), a.end()); the initilizer list constructor will not be used. Now, as no other constructor matches, deduction guides take place!

Example how the effect is if you have initializer list constructors in your code:

template < typename U >
struct X
{
    // Directly makes the type deducable, because U can be deduced from the parameter of the constructor
    X( std::initializer_list<U> )
    {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
    }

    template < typename ... T>
        X( T... )
    {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
    }
};

struct ONE {};

template < typename Iter >
X( const Iter&, const Iter& ) -> X<ONE>;

template < typename U >
struct Y
{
    // type U can NOT deduced from the parameter!
    template < typename T>
    Y( std::initializer_list<T> )
    {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
    }

    template < typename ... T>
        Y( T... )
    {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
    }
};

struct TWO {};

template < typename Iter >
Y( const Iter&, const Iter& ) -> Y<TWO>;

int main()
{
    std::array a {1,2,3,4};
    X x1{a.begin(), a.end()};
    X x2(a.begin(), a.end());

    std::cout << "###" << std::endl;

    Y y1{a.begin(), a.end()};
    Y y2(a.begin(), a.end());
}

That initializer list constructors are take preference over deduction guide was also new to me and answered here:
Why does using uniform initializer syntax result in different behavior to the "old" style ()?

The important new thing for me was:

[over.match.list]

[...] overload resolution selects the constructor in two phases:

Initially, the candidate functions are the initializer-list constructors ([dcl.init.list]) of the class T and the argument list
  consists of the initializer list as a single argument.

[...]

For details details see the linked question!


问:
If column A's value is within the range of Column B and C then copy
in this project i have to check column's A value between Column B and Column C. If  columnA's values>= Columns B value or Columns A value<= Columns C value then i need to copy column d and e values and need to put into sheet1 column G and H. Column A is in sheet1 and Column B, C, D and E in sheet2.

I am sorry with my wordings i know its difficult to understand. If someone can help me with this i would be forever grateful. Thank you

```<code>             A       B    c   D     E
             1       1    9   Dog   Naruto
             11      10   19  Cat   one piece
             21      20   30  Duck  lo

          i want the outcome like this
           A    G       H
           1    Dog     Naruto
           11   cat     One piece
           21    duck     lo
</code>```

答:
this is the code i have but this code is for to check if Column A values = Column G values then it returns the whole row

```<code>              Dim sht1 As Worksheet, sht2 As Worksheet

            Set sht1 = Worksheets("sheet1")
           Set sht2 = Worksheets("sheet2")

             sht1= Worksheets("sheet1").Range("G" & Rows.Count).End(xlUp).Row
             sht2= Worksheets("sheet2").Range("A" & Rows.Count).End(xlUp).Row

           For j = 1 To sht1

                   For i = 1 To sht2

        If sht1.Cells(j, 7).Value = sht2.Cells(i, 1).Value Then
            sht1.Cells(j, 11).Resize(1, 2).Value = _
                          sht2.Cells(i, 1).Resize(1, 2).Value

        Else

        End If

    Next i

Next j

End With
</code>```

Body:
in this project i have to check column's A value between Column B and Column C. If  columnA's values>= Columns B value or Columns A value<= Columns C value then i need to copy column d and e values and need to put into sheet1 column G and H. Column A is in sheet1 and Column B, C, D and E in sheet2.

I am sorry with my wordings i know its difficult to understand. If someone can help me with this i would be forever grateful. Thank you

             A       B    c   D     E
             1       1    9   Dog   Naruto
             11      10   19  Cat   one piece
             21      20   30  Duck  lo

          i want the outcome like this
           A    G       H
           1    Dog     Naruto
           11   cat     One piece
           21    duck     lo

Body:
this is the code i have but this code is for to check if Column A values = Column G values then it returns the whole row

              Dim sht1 As Worksheet, sht2 As Worksheet

            Set sht1 = Worksheets("sheet1")
           Set sht2 = Worksheets("sheet2")

             sht1= Worksheets("sheet1").Range("G" & Rows.Count).End(xlUp).Row
             sht2= Worksheets("sheet2").Range("A" & Rows.Count).End(xlUp).Row

           For j = 1 To sht1

                   For i = 1 To sht2

        If sht1.Cells(j, 7).Value = sht2.Cells(i, 1).Value Then
            sht1.Cells(j, 11).Resize(1, 2).Value = _
                          sht2.Cells(i, 1).Resize(1, 2).Value

        Else

        End If

    Next i

Next j

End With


问:
Hive external table delimited by commas, but comma present in data
I have some data coming in from an external source of the format:

```<code>user_id, user_name, project_name, position
"111", "Tom Petty", "Heartbreakers", "Vocals"
"222", "Ringo Starr", "Beatles, The", "Drummer"
"333", "Tom Brady", "Patriots", "QB"
</code>```

And I create my external table thusly:

```<code>CREATE EXTERNAL TABLE tab1 (
USER_ID String,
USER_NAME String,
PROJECT_NAME String,
POSITION String
)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
STORED AS TEXTFILE
LOCATION '/user/blah/foo'
</code>```

The problem occurs when data in some of the columns have embedded commas in them, Beatles, The for instance. This results in Hive putting the word The into the next column (position) and dropping the data in the last column.

All the incoming data fields are wrapped in double quotes but they are comma delimited even though they may have commas in them. Unfortunately having the sender clean the data is not an option.

How can I go about creating this table?

答:
You can try using Open CSV Serde in your hive table creation using specific serDe properties.

https://cwiki.apache.org/confluence/display/Hive/CSV+Serde

Body:
I have some data coming in from an external source of the format:

user_id, user_name, project_name, position
"111", "Tom Petty", "Heartbreakers", "Vocals"
"222", "Ringo Starr", "Beatles, The", "Drummer"
"333", "Tom Brady", "Patriots", "QB"

And I create my external table thusly:

CREATE EXTERNAL TABLE tab1 (
USER_ID String,
USER_NAME String,
PROJECT_NAME String,
POSITION String
)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
STORED AS TEXTFILE
LOCATION '/user/blah/foo'

The problem occurs when data in some of the columns have embedded commas in them, Beatles, The for instance. This results in Hive putting the word The into the next column (position) and dropping the data in the last column.

All the incoming data fields are wrapped in double quotes but they are comma delimited even though they may have commas in them. Unfortunately having the sender clean the data is not an option.

How can I go about creating this table?


问:
Message (alert) asking for confirmation
I'm beginner in JS.

I have this code:

```<code>            var fileLimit = parseInt(1);

            function refreshFileList() {
                $(".dz-preview").remove();
                $.ajax({
                    url: 'http://test/admin/showFilesDJS?type=SplashImage&id=1',
                    type: 'get',
                    dataType: 'json',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                    },
                    cache: false,
                    success: function (response) {

                        $.each(response, function (key, value) {
                            var mockFile = {
                                name: value.name,
                                size: value.size
                            };
                            dpzMultipleFiles.emit('addedfile', mockFile);
                            dpzMultipleFiles.emit('thumbnail', mockFile, value.path);
                            dpzMultipleFiles.emit('complete', mockFile)
                        })
                    },
                    error: function (response) {
                        alert('Nastąpił problem z JSON. Proszę o kontakt z administratorem serwisu.');
                    }
                });
            }

            Dropzone.options.dpzMultipleFiles =
                {
                    maxFiles: fileLimit,
                    clickable: true,
                    thumbnailWidth: 250,
                    thumbnailHeight: 250,
                    autoProcessQueue: true,
                    dictDefaultMessage: '',
                    uploadMultiple: true,
                    paramName: "myFile",
                    acceptedFiles: ".jpg,.jpeg",
                    addRemoveLinks: true,
                    timeout: 50000,
                    dictRemoveFile: 'Usuń plik',

                    init: function () {
                        dpzMultipleFiles = this;
                        refreshFileList();

                        this.on("thumbnail", function (file, dataUrl) {
                            $('.dz-image').last().find('img').attr({width: '100%', height: '100%'});
                        }),

                            this.on('completemultiple', function (file, json) {
                                //$('.sortable').sortable('enable');
                            });
                        this.on('success', function (file, json) {
                            //alert('aa');
                        });

                        this.on('addedfile', function (file) {
                            fileLimit = fileLimit - 1;
                        });

                        this.on('drop', function (file) {
                            fileLimit = fileLimit + 1;
                        });

                        this.on("maxfilesexceeded", function (file) {
                            alert('Plik ' + file.name + ' nie został wysłany na serwer. Limit plików został przekroczony!')
                            this.removeFile(file);
                        });
                    },

                    removedfile: function (file) {
                        $.ajax({
                            headers: {
                                'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                            },
                            cache: false,
                            type: 'POST',
                            url: 'http://test/admin/deleteDJS?id=' + file.name + 'type=SplashImage',
                            data: {filename: file.name, id: file.name, type: 'SplashImage'},
                            success: function (data) {
                                console.log("File has been successfully removed!!");
                                //refreshFileList();
                            },
                            error: function (e) {
                                console.log(e);
                            }
                        });

                        var fileRef;
                        return (fileRef = file.previewElement) != null ?
                            fileRef.parentNode.removeChild(file.previewElement) : void 0;
                    }
                };
            $(function () {
                $(".dropzone").sortable({
                    items: '.dz-preview',
                    cursor: 'move',
                    opacity: 0.5,
                    containment: '.dropzone',
                    distance: 20,
                    tolerance: 'pointer',
                    update: function (event, ui) {
                        $(".dz-filename span").each(function (index) {
                            $.ajax({
                                headers: {
                                    'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                                },
                                url: 'http://test/admin/changeOrderFilesDJS?type=SplashImage&id=1&index='+index+'&file='+ $(this).text(),
                                dataType: 'text',
                                type: 'post',
                                cache: false,
                                data: $(this).serialize(),
                                success: function (data, textStatus, jQxhr) {
                                },
                                error: function (jqXhr, textStatus, errorThrown) {
                                    alert('Nastąpił problem z JSON. Proszę o kontakt z administratorem serwisu.');
                                }
                            });
                        });
                    }
                });
            });
</code>```

This is Dropzone.JS. This code work fine.

I would like to add after clicking on the button remove (usuń plik) - the question: do you really want to delete this file? Only after clicking on YES the file would be deleted.

How to do it? I need a simple alert with a question in JS

答:
You can add confirm in the remove function :</p>

```<code>                    removedfile: function (file) {
                        if (!confirm('Are you sure?')) {
                            return;
                        }
                        $.ajax({
                            headers: {
                                'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                            },
                            cache: false,
                            type: 'POST',
                            url: 'http://test/admin/deleteDJS?id=' + file.name + 'type=SplashImage',
                            data: {filename: file.name, id: file.name, type: 'SplashImage'},
                            success: function (data) {
                                console.log("File has been successfully removed!!");
                                //refreshFileList();
                            },
                            error: function (e) {
                                console.log(e);
                            }
                        });

                        var fileRef;
                        return (fileRef = file.previewElement) != null ?
                            fileRef.parentNode.removeChild(file.previewElement) : void 0;
                    }
</code>```

Title: Message (alert) asking for confirmation

Body:
I'm beginner in JS.

I have this code:

            var fileLimit = parseInt(1);

            function refreshFileList() {
                $(".dz-preview").remove();
                $.ajax({
                    url: 'http://test/admin/showFilesDJS?type=SplashImage&id=1',
                    type: 'get',
                    dataType: 'json',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                    },
                    cache: false,
                    success: function (response) {

                        $.each(response, function (key, value) {
                            var mockFile = {
                                name: value.name,
                                size: value.size
                            };
                            dpzMultipleFiles.emit('addedfile', mockFile);
                            dpzMultipleFiles.emit('thumbnail', mockFile, value.path);
                            dpzMultipleFiles.emit('complete', mockFile)
                        })
                    },
                    error: function (response) {
                        alert('Nastąpił problem z JSON. Proszę o kontakt z administratorem serwisu.');
                    }
                });
            }

            Dropzone.options.dpzMultipleFiles =
                {
                    maxFiles: fileLimit,
                    clickable: true,
                    thumbnailWidth: 250,
                    thumbnailHeight: 250,
                    autoProcessQueue: true,
                    dictDefaultMessage: '',
                    uploadMultiple: true,
                    paramName: "myFile",
                    acceptedFiles: ".jpg,.jpeg",
                    addRemoveLinks: true,
                    timeout: 50000,
                    dictRemoveFile: 'Usuń plik',

                    init: function () {
                        dpzMultipleFiles = this;
                        refreshFileList();

                        this.on("thumbnail", function (file, dataUrl) {
                            $('.dz-image').last().find('img').attr({width: '100%', height: '100%'});
                        }),

                            this.on('completemultiple', function (file, json) {
                                //$('.sortable').sortable('enable');
                            });
                        this.on('success', function (file, json) {
                            //alert('aa');
                        });

                        this.on('addedfile', function (file) {
                            fileLimit = fileLimit - 1;
                        });

                        this.on('drop', function (file) {
                            fileLimit = fileLimit + 1;
                        });

                        this.on("maxfilesexceeded", function (file) {
                            alert('Plik ' + file.name + ' nie został wysłany na serwer. Limit plików został przekroczony!')
                            this.removeFile(file);
                        });
                    },

                    removedfile: function (file) {
                        $.ajax({
                            headers: {
                                'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                            },
                            cache: false,
                            type: 'POST',
                            url: 'http://test/admin/deleteDJS?id=' + file.name + 'type=SplashImage',
                            data: {filename: file.name, id: file.name, type: 'SplashImage'},
                            success: function (data) {
                                console.log("File has been successfully removed!!");
                                //refreshFileList();
                            },
                            error: function (e) {
                                console.log(e);
                            }
                        });

                        var fileRef;
                        return (fileRef = file.previewElement) != null ?
                            fileRef.parentNode.removeChild(file.previewElement) : void 0;
                    }
                };
            $(function () {
                $(".dropzone").sortable({
                    items: '.dz-preview',
                    cursor: 'move',
                    opacity: 0.5,
                    containment: '.dropzone',
                    distance: 20,
                    tolerance: 'pointer',
                    update: function (event, ui) {
                        $(".dz-filename span").each(function (index) {
                            $.ajax({
                                headers: {
                                    'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                                },
                                url: 'http://test/admin/changeOrderFilesDJS?type=SplashImage&id=1&index='+index+'&file='+ $(this).text(),
                                dataType: 'text',
                                type: 'post',
                                cache: false,
                                data: $(this).serialize(),
                                success: function (data, textStatus, jQxhr) {
                                },
                                error: function (jqXhr, textStatus, errorThrown) {
                                    alert('Nastąpił problem z JSON. Proszę o kontakt z administratorem serwisu.');
                                }
                            });
                        });
                    }
                });
            });

This is Dropzone.JS. This code work fine.

I would like to add after clicking on the button remove (usuń plik) - the question: do you really want to delete this file? Only after clicking on YES the file would be deleted.

How to do it? I need a simple alert with a question in JS

Body:
You can add confirm in the remove function :

                    removedfile: function (file) {
                        if (!confirm('Are you sure?')) {
                            return;
                        }
                        $.ajax({
                            headers: {
                                'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                            },
                            cache: false,
                            type: 'POST',
                            url: 'http://test/admin/deleteDJS?id=' + file.name + 'type=SplashImage',
                            data: {filename: file.name, id: file.name, type: 'SplashImage'},
                            success: function (data) {
                                console.log("File has been successfully removed!!");
                                //refreshFileList();
                            },
                            error: function (e) {
                                console.log(e);
                            }
                        });

                        var fileRef;
                        return (fileRef = file.previewElement) != null ?
                            fileRef.parentNode.removeChild(file.previewElement) : void 0;
                    }


问:
Error when using the std::allocator in the template class
Trying to figure out how to use std :: allocator.

#include <iostream>

template <typename T, typename A>
struct vector_base
{
  A       allocator;
  T*      data;
  size_t  size;
  size_t  space;

  vector_base(const A &alloc, size_t n)
    :allocator(alloc), data(alloc.allocate(n)), size(n), space(n)
  {}

  ~vector_base() {allocator.deallocate(data, space);}
};

int main() {
  std::allocator<int> my_allocator;
  vector_base<int, std::allocator<int>> vector(my_allocator, 10);

  return 0;
}
```

Error:

error: passing ‘const std::allocator’ as ‘this’ argument discards
  qualifiers [-fpermissive]
       :allocator(alloc), data(alloc.allocate(n)), size(n), space(n)

答:
alloc is a const&, you're trying to call allocate on it which is a non-const method, that's not allowed.

Call allocate on your initialized member instead:

```<code>  vector_base(const A &alloc, size_t n)
    :allocator(alloc), data(allocator.allocate(n)), size(n), space(n)
  {}
</code>```

Body:
Trying to figure out how to use std :: allocator.

#include <iostream>

template <typename T, typename A>
struct vector_base
{
  A       allocator;
  T*      data;
  size_t  size;
  size_t  space;

  vector_base(const A &alloc, size_t n)
    :allocator(alloc), data(alloc.allocate(n)), size(n), space(n)
  {}

  ~vector_base() {allocator.deallocate(data, space);}
};

int main() {
  std::allocator<int> my_allocator;
  vector_base<int, std::allocator<int>> vector(my_allocator, 10);

  return 0;
}

Error:

error: passing ‘const std::allocator’ as ‘this’ argument discards
  qualifiers [-fpermissive]
       :allocator(alloc), data(alloc.allocate(n)), size(n), space(n)

Body:
alloc is a const&, you're trying to call allocate on it which is a non-const method, that's not allowed.

Call allocate on your initialized member instead:

  vector_base(const A &alloc, size_t n)
    :allocator(alloc), data(allocator.allocate(n)), size(n), space(n)
  {}


问:
How to get value from jQuery UI slider?
I am working on http://gamercity.info/ymusic/.
And I am using UI slider as seek bar.
While the video is played I want to invoke a seekTo(seconds) function if user clicked anywhere on the seek bar. How to get new value of seconds after click event?

答:
JQuery ui slider </p>

```<code>var slider = $("#range_slider").slider({
    range: true,
    min: 0,
    max: 500,
    values: [0, 500],
    slide: function(event, ui) {
      var x = ui.values[0];
      var y = ui.values[1];
      $('#min').text( ui.values[0] )
      $('#max').text( ui.values[1] )
      $.ajax({
        url: '/search',
        type: 'GET',
        dataType: 'script',
        data: {min:x, max:y,term:food_item_name},
        success: function(repsonse){},
      });
    }
  });
});
</code>```

Title: How to get value from jQuery UI slider?

Body:
JQuery ui slider

var slider = $("#range_slider").slider({
    range: true,
    min: 0,
    max: 500,
    values: [0, 500],
    slide: function(event, ui) {
      var x = ui.values[0];
      var y = ui.values[1];
      $('#min').text( ui.values[0] )
      $('#max').text( ui.values[1] )
      $.ajax({
        url: '/search',
        type: 'GET',
        dataType: 'script',
        data: {min:x, max:y,term:food_item_name},
        success: function(repsonse){},
      });
    }
  });
});


问:
Printing last element in an array using if statement
I am currently trying to learn about using pointers and functions together in C, which I don't think is easy.
I am trying to print the last element in an array, it actually does the opposite and prints the first element.
I know people normally use for loops, but I can't figure out how to do that with exactly this kind of problem and therefore I thought that I would try it out with an if statement instead.

Edit:
Why is if statement not working in this case? It seems logic that it should work...

My main.c file:

#include <stdio.h>
#include <stdlib.h>
#include "functions.h"
#define Size 7

int main(void)
{

    int array1[] = { 11, 88, 5, 9, 447, 8, 68, 4 };

    maxValue(array1, Size);

    return 0;
}
```

<p>My functions.h file:</p>

<pre class="lang-cpp prettyprint-override"><code>#pragma once

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

int maxValue(const int *, int);

#endif

</code>```

My functions.c file:

#include "functions.h"
#include <stdio.h>
#include <stdlib.h>

int maxValue(const int *array1, int Size)
{

    int max = array1[0];

    if (max < array1[Size]) {
        Size++;
        max = array1[Size];
    }

    printf("Max value: %d \n", max);
}

```

答:
Why is if statement not working in this case? It seems logic that it should work...? Because here

```<code>if (max < array1[Size]) { }
</code>```

Size is defined as 7 and you are comparing array1[0] with array1[7] i.e 11 < 4 -> false, hence it doesn't enter into if block, so the last printf executes and that prints max. But its not a correct logic if if blocks becomes true then further Size++ will cause accessing out of bound array elements which cause undefined behavior.

```<code>int maxValue(const int *array1, int Size)
{
    int max = array1[0];
    if (max < array1[Size]) { /* 11 < 4 false, skips if block */
        //Size++; /* this is wrong as Size++ here and next accessing array1[Size] cause UB due to accessing out of bound array element */
        max = array1[Size];
    }
    printf("Max value: %d \n", max); /* max is stills array1[0] i.e 11 */
}
</code>```

Body:
I am currently trying to learn about using pointers and functions together in C, which I don't think is easy.
I am trying to print the last element in an array, it actually does the opposite and prints the first element.
I know people normally use for loops, but I can't figure out how to do that with exactly this kind of problem and therefore I thought that I would try it out with an if statement instead.

Edit:
Why is if statement not working in this case? It seems logic that it should work...

My main.c file:

#include <stdio.h>
#include <stdlib.h>
#include "functions.h"
#define Size 7

int main(void)
{

    int array1[] = { 11, 88, 5, 9, 447, 8, 68, 4 };

    maxValue(array1, Size);

    return 0;
}

My functions.h file:

#pragma once

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

int maxValue(const int *, int);

#endif

My functions.c file:

#include "functions.h"
#include <stdio.h>
#include <stdlib.h>

int maxValue(const int *array1, int Size)
{

    int max = array1[0];

    if (max < array1[Size]) {
        Size++;
        max = array1[Size];
    }

    printf("Max value: %d \n", max);
}

Body:
Why is if statement not working in this case? It seems logic that it should work...? Because here

if (max < array1[Size]) { }

Size is defined as 7 and you are comparing array1[0] with array1[7] i.e 11 < 4 -> false, hence it doesn't enter into if block, so the last printf executes and that prints max. But its not a correct logic if if blocks becomes true then further Size++ will cause accessing out of bound array elements which cause undefined behavior.

int maxValue(const int *array1, int Size)
{
    int max = array1[0];
    if (max < array1[Size]) { /* 11 < 4 false, skips if block */
        //Size++; /* this is wrong as Size++ here and next accessing array1[Size] cause UB due to accessing out of bound array element */
        max = array1[Size];
    }
    printf("Max value: %d \n", max); /* max is stills array1[0] i.e 11 */
}


问:
Getting error in DOM Parser
```<code>private String getNodeValue(Element e) {
    String str = "";
    Node node = e.getFirstChild();

    if (node instanceof CharacterData) {

        CharacterData cd = (CharacterData) node;
        str += cd.getData();
    }
    System.out.println("String ="+ str);
    return str;
}
</code>```

i am using this code for parse xml using DOM

EDIT!

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
<root status="1">
<reminder type= "timer" id="861">
<user fromid="48" toid="48" fromemail="xyz@xyz.com">Dharmendra Patel</user>
<title>10:00 AM Coffy?</title>
<desc>Let's go for coffy</desc>
<date>13/03/2011 09:22:00</date>
<repeat>MO</repeat>
<todo><category name="">
<item></item>
</category>
</todo>
</reminder>
</root>
</code>```

This is my XMl response and i am using this code

```<code>NodeList nldesc = elUser.getElementsByTagName("desc");

Element eldesc = (Element) nldesc.item(0);

String taskdesc = getNodeValue(eldesc);
</code>```

if node value contains String like "Let's go for coeffy" so this gives me string like "Lets go for coeffy" so what is the problem ? please help me..

答:
You can use Element.getTextContent() for getting an element text. Note, what this method can be accesed only in API level 8 and higher.

In APi level less than 8 you can use getNodeValue method. It will succeed only if your node is of type TEXT_NODE

EDIT

```<code>    try {
        Document doc =
                DocumentBuilderFactory
                        .newInstance()
                        .newDocumentBuilder().parse(
                            new StringBufferInputStream("<desc>let's go for Coffey </desc>"));
        NodeList list = doc.getElementsByTagName("desc");
        Log.d("MainActivity", list.item(0).getFirstChild().getNodeValue());
    } catch (ParserConfigurationException e) {
        // ignore
    } catch (IOException e) {
        // ignore
    } catch (SAXException e) {
        // ignore
    }
</code>```

The following code works just fine. After it is executed i've got at my logcat:

```<code>04-12 21:20:42.766: DEBUG/MainActivity(26843): let's go for Coffey
</code>```

EDIT 2:

To deal with #&... entities use Html.fromHtml(String) method on encoded string and then toString() on result.

```<code>Log.d("MainActivity",
    Html.fromHTML(
        list.item(0).getFirstChild().getNodeValue()
    ).toString());
</code>```

EDIT 3

Here is the complete solution for your case.

```<code>    String data = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?> <root status=\"1\"> <reminder type= \"timer\" id=\"861\"> <user fromid=\"48\" toid=\"48\" fromemail=\"xyz@xyz.com\">Dharmendra Patel</user> <title>10:00 AM Coffy?</title> <desc>Let's go for coffy</desc> <date>13/03/2011 09:22:00</date> <repeat>MO</repeat> <todo><category name=\"\"> <item></item> </category> </todo> </reminder> </root>";
    try {
        Document doc =
                DocumentBuilderFactory
                        .newInstance()
                        .newDocumentBuilder().parse(
                        new StringBufferInputStream(data));
        NodeList list = doc.getElementsByTagName("desc");
        Node node = list.item(0);
        NodeList charNodes = node.getChildNodes();
        StringBuilder builder = new StringBuilder();
        for(int i = 0, l = charNodes.getLength(); i < l; i++) {
            builder.append(Html.fromHtml(charNodes.item(i).getNodeValue()).toString());
        }
        Log.d("MainActivity", builder.toString());
    } catch (ParserConfigurationException e) {
        // ignore
    } catch (IOException e) {
        // ignore
    } catch (SAXException e) {
        // ignore
    }
</code>```

Title: Getting error in DOM Parser

Body:
private String getNodeValue(Element e) {
    String str = "";
    Node node = e.getFirstChild();

    if (node instanceof CharacterData) {

        CharacterData cd = (CharacterData) node;
        str += cd.getData();
    }
    System.out.println("String ="+ str);
    return str;
}

i am using this code for parse xml using DOM

EDIT!

<?xml version="1.0" encoding="ISO-8859-1"?>
<root status="1">
<reminder type= "timer" id="861">
<user fromid="48" toid="48" fromemail="xyz@xyz.com">Dharmendra Patel</user>
<title>10:00 AM Coffy?</title>
<desc>Let's go for coffy</desc>
<date>13/03/2011 09:22:00</date>
<repeat>MO</repeat>
<todo><category name="">
<item></item>
</category>
</todo>
</reminder>
</root>

This is my XMl response and i am using this code

NodeList nldesc = elUser.getElementsByTagName("desc");

Element eldesc = (Element) nldesc.item(0);

String taskdesc = getNodeValue(eldesc);

if node value contains String like "Let's go for coeffy" so this gives me string like "Lets go for coeffy" so what is the problem ? please help me..

Body:
You can use Element.getTextContent() for getting an element text. Note, what this method can be accesed only in API level 8 and higher.

In APi level less than 8 you can use getNodeValue method. It will succeed only if your node is of type TEXT_NODE

EDIT

    try {
        Document doc =
                DocumentBuilderFactory
                        .newInstance()
                        .newDocumentBuilder().parse(
                            new StringBufferInputStream("<desc>let's go for Coffey </desc>"));
        NodeList list = doc.getElementsByTagName("desc");
        Log.d("MainActivity", list.item(0).getFirstChild().getNodeValue());
    } catch (ParserConfigurationException e) {
        // ignore
    } catch (IOException e) {
        // ignore
    } catch (SAXException e) {
        // ignore
    }

The following code works just fine. After it is executed i've got at my logcat:

04-12 21:20:42.766: DEBUG/MainActivity(26843): let's go for Coffey

EDIT 2:

To deal with #&... entities use Html.fromHtml(String) method on encoded string and then toString() on result.

Log.d("MainActivity",
    Html.fromHTML(
        list.item(0).getFirstChild().getNodeValue()
    ).toString());

EDIT 3

Here is the complete solution for your case.

    String data = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?> <root status=\"1\"> <reminder type= \"timer\" id=\"861\"> <user fromid=\"48\" toid=\"48\" fromemail=\"xyz@xyz.com\">Dharmendra Patel</user> <title>10:00 AM Coffy?</title> <desc>Let&#039;s go for coffy</desc> <date>13/03/2011 09:22:00</date> <repeat>MO</repeat> <todo><category name=\"\"> <item></item> </category> </todo> </reminder> </root>";
    try {
        Document doc =
                DocumentBuilderFactory
                        .newInstance()
                        .newDocumentBuilder().parse(
                        new StringBufferInputStream(data));
        NodeList list = doc.getElementsByTagName("desc");
        Node node = list.item(0);
        NodeList charNodes = node.getChildNodes();
        StringBuilder builder = new StringBuilder();
        for(int i = 0, l = charNodes.getLength(); i < l; i++) {
            builder.append(Html.fromHtml(charNodes.item(i).getNodeValue()).toString());
        }
        Log.d("MainActivity", builder.toString());
    } catch (ParserConfigurationException e) {
        // ignore
    } catch (IOException e) {
        // ignore
    } catch (SAXException e) {
        // ignore
    }


问:
Regex for currency symbol and amount html pattern
I'm currently using the pattern attribute in an input field on my html form.

I have prefixed my form with a £ symbol therefore I need the regex to match the symbol as well as ONLY DIGITS after.
The regex must not match the currency symbol on it's own but should match the currency symbol with any amount of digits after it.

I currently have pattern="(\£\d+)" however it seems like it does not work as it allows characters to be entered and also it matches the £ symbol on its own when it's supposed to match it with digits after only.

I used https://regexr.com/3gi1e which shows it is correct but doesn't work with pattern.

答:
You could use the HTML entity £ in your expression which seems to achieve what you're after:

<form>
  <input type="text" pattern="£\d+" value="£"/>
  <input type="submit"/>
</form>```

Body:
You could use the HTML entity &pound; in your expression which seems to achieve what you're after:

<form>
  <input type="text" pattern="&pound;\d+" value="&pound;"/>
  <input type="submit"/>
</form>


问:
How can I create object of certain (big) size?
I wonder if there's a way to create let's say 1 MB object other than a very big list. It could be anything as long as it's reference type.
I want to use it in memory profiler tests so I don't need any special behavior. Maybe some unit test engine or Moq have such feature?</p>

答:
An array is pretty straightforward to create.

```<code>Console.WriteLine($"Allocated memory: {GC.GetTotalMemory(false)}");
var array = new byte[1024 * 1024];
Console.WriteLine($"Allocated memory: {GC.GetTotalMemory(false)}");
</code>```

Output:

```<code>Allocated memory: 160872
Allocated memory: 1209504
</code>```

Body:
An array is pretty straightforward to create.

Console.WriteLine($"Allocated memory: {GC.GetTotalMemory(false)}");
var array = new byte[1024 * 1024];
Console.WriteLine($"Allocated memory: {GC.GetTotalMemory(false)}");

Output:

Allocated memory: 160872
Allocated memory: 1209504


问:
How to write addEventListener inside string literals?
I want to create new HTML element using string literals. I added all the parameters I needed using the element as an object and writing parameters to it using setAttribute and methods like this. Now I need to rewrite this code using string literals, where less code and more understandable code.

I was created string literals and throw into them all element except addeventListener:

```<code>this.parent.innerHTML +=`<${tagName} title="${title} id="${results.id}" href="${title}" onclick=>${title} </a>`;
</code>```

How correctly rewrite addEventListner using string literals?

```<code>let newElem = document.createElement(tagName);
      newElem.addEventListener(
        "click",
        function(evt) {
          evt.preventDefault();
          this.removeElements();
          this.createElem("h3", title);
        }.bind(this),
        false
      );
</code>```

答:
Because of js scoping behavior, I think finding a solution to do this in-line in your template strings will likely cause you more problems than it's worth. But there's two ways to do this that should play well with your existing code.

But first, fix the errors that will make this not run such as the missing " and also using tagName to close the html tag as well.

Method 1:

Simply assign the event listener to the parent instead of any of the children. You can use evt.target to check if the target is the tag you're expecting, get its properties, etc. Depending on how your code is set up, this might be the optimal solution.

Keep in mind that this event listener should only be added once.

const parent = document.querySelector('.parent')
const tagName = 'a'
const title = 'Click Me'
const results = {
  id: 1234567
}

parent.innerHTML += `<${tagName} title="${title}" id="el-${results.id}" href="${title}">${title} </${tagName}>`;

parent.addEventListener('click', function(evt) {
    evt.preventDefault();
    console.log(evt.target.title)
    // this.removeElements();
    // this.createElem("h3", title);
  })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent" /></code>```

Method 2:

Once you assign innerHTML the element is added to the document and can be fetched using querySelector.
You seem to be assigning some id to each tag, so you can just simply use that id to select the tag and then add your event listener.

A class will be better for selecting multiple elements simultaneously.

const parent = document.querySelector('.parent')
const tagName = 'a'
const title = 'Click Me'
const results = {
  id: 1234567
}

parent.innerHTML += `<${tagName} title="${title}" id="el-${results.id}" href="${title}">${title} </${tagName}>`;

parent.querySelector(`#el-${results.id}`)
  .addEventListener('click', function(evt) {
    evt.preventDefault();
    // this.removeElements();
    // this.createElem("h3", title);
  })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='parent' /></code>```

Body:
I want to create new HTML element using string literals. I added all the parameters I needed using the element as an object and writing parameters to it using setAttribute and methods like this. Now I need to rewrite this code using string literals, where less code and more understandable code.

I was created string literals and throw into them all element except addeventListener:

this.parent.innerHTML +=`<${tagName} title="${title} id="${results.id}" href="${title}" onclick=>${title} </a>`;

How correctly rewrite addEventListner using string literals?

let newElem = document.createElement(tagName);
      newElem.addEventListener(
        "click",
        function(evt) {
          evt.preventDefault();
          this.removeElements();
          this.createElem("h3", title);
        }.bind(this),
        false
      );

Body:
Because of js scoping behavior, I think finding a solution to do this in-line in your template strings will likely cause you more problems than it's worth. But there's two ways to do this that should play well with your existing code.

But first, fix the errors that will make this not run such as the missing " and also using tagName to close the html tag as well.

Method 1:

Simply assign the event listener to the parent instead of any of the children. You can use evt.target to check if the target is the tag you're expecting, get its properties, etc. Depending on how your code is set up, this might be the optimal solution.

Keep in mind that this event listener should only be added once.

const parent = document.querySelector('.parent')
const tagName = 'a'
const title = 'Click Me'
const results = {
  id: 1234567
}

parent.innerHTML += `<${tagName} title="${title}" id="el-${results.id}" href="${title}">${title} </${tagName}>`;

parent.addEventListener('click', function(evt) {
    evt.preventDefault();
    console.log(evt.target.title)
    // this.removeElements();
    // this.createElem("h3", title);
  })

<div class="parent" />

Method 2:

Once you assign innerHTML the element is added to the document and can be fetched using querySelector.
You seem to be assigning some id to each tag, so you can just simply use that id to select the tag and then add your event listener.

A class will be better for selecting multiple elements simultaneously.

const parent = document.querySelector('.parent')
const tagName = 'a'
const title = 'Click Me'
const results = {
  id: 1234567
}

parent.innerHTML += `<${tagName} title="${title}" id="el-${results.id}" href="${title}">${title} </${tagName}>`;

parent.querySelector(`#el-${results.id}`)
  .addEventListener('click', function(evt) {
    evt.preventDefault();
    // this.removeElements();
    // this.createElem("h3", title);
  })

<div class='parent' />


问:
How to get dynamic location direction on map in iphone
I am creating a map application.I want that as a person travels from his current location to some other location the same should be simultaneously plotted on the map.how is this possible.Please if anybody have source code regarding this please provide me.
Thanks.</p>

答:
In order to draw routes the easiest you can do is make use of MKPolyline class, which is quite straight forward. The only thing is that it only works from iOS SDK 4.0. If you want it to be compatible with iOS 3, you should make use of the MKAnnotation protocol and the MKAnnotationView class. It is a little more complicated but fortunately it is easy to find help. The best tutorial I have found out there is this one. Check it out.

I hope this helps you


问:
rvest Error in open.connection(x, "rb") : HTTP error 404
I was trying to scrape a website to extract the data from many pages using rvest and purrr. but everytime I run the code the "Error in open.connection(x, "rb") : HTTP error 404." appears.</p>
```<code>url <- "http://books.toscrape.com/catalogue/page-%d"

map_df(1:10, function(i){

  page <- read_html(sprintf(url, i))
   cat(".")

  booksdf <- data.frame(safely( title <- html_nodes(page, "h3, #title") %>% html_text(),
                       price <- html_nodes(page, ".price_color") %>% html_text() %>% gsub("£", "", .),
                       rating <- html_nodes(page, ".star-rating") %>% html_attrs() %>% str_remove("star-rating") %>%str_replace_all(c("One" = "1", "Two" = "2", "Three" = "3", "Four" = "4", "Five" = "5")) %>%  as.numeric()
                       )

  )

}
)
</code>```
```<code>Error in open.connection(x, "rb") : HTTP error 404.
</code>```

答:
We can create the URL's to scrape and then use map_df to bind the dataframes together.

```<code>library(tidyverse)
library(rvest)

url <- "http://books.toscrape.com/catalogue/page-"
pages <- paste0(url, 1:10, ".html")

map_df(pages, function(i){
     page <- read_html(i)
     data.frame(title = html_nodes(page, "h3, #title") %>% html_text(),
                price = html_nodes(page, ".price_color") %>% html_text() %>%
                        gsub("£", "", .),
                rating = html_nodes(page, ".star-rating") %>% html_attrs() %>%
                         str_remove("star-rating") %>%
                         str_replace_all(c("One" = "1", "Two" = "2",
                         "Three" = "3", "Four" = "4", "Five" = "5")) %>%
                          as.numeric())
})

#                                            title price rating
#1                               A Light in the ... 51.77      3
#2                               Tipping the Velvet 53.74      1
#3                                       Soumission 50.10      1
#4                                    Sharp Objects 47.82      4
#5                     Sapiens: A Brief History ... 54.23      5
#6                                  The Requiem Red 22.65      1
#7                     The Dirty Little Secrets ... 33.34      4
#8                          The Coming Woman: A ... 17.93      3
#.....
</code>```

Body:
I was trying to scrape a website to extract the data from many pages using rvest and purrr. but everytime I run the code the "Error in open.connection(x, "rb") : HTTP error 404." appears.

url <- "http://books.toscrape.com/catalogue/page-%d"

map_df(1:10, function(i){

  page <- read_html(sprintf(url, i))
   cat(".")

  booksdf <- data.frame(safely( title <- html_nodes(page, "h3, #title") %>% html_text(),
                       price <- html_nodes(page, ".price_color") %>% html_text() %>% gsub("£", "", .),
                       rating <- html_nodes(page, ".star-rating") %>% html_attrs() %>% str_remove("star-rating") %>%str_replace_all(c("One" = "1", "Two" = "2", "Three" = "3", "Four" = "4", "Five" = "5")) %>%  as.numeric()
                       )

  )

}
)

Error in open.connection(x, "rb") : HTTP error 404.

Body:
We can create the URL's to scrape and then use map_df to bind the dataframes together.

library(tidyverse)
library(rvest)

url <- "http://books.toscrape.com/catalogue/page-"
pages <- paste0(url, 1:10, ".html")

map_df(pages, function(i){
     page <- read_html(i)
     data.frame(title = html_nodes(page, "h3, #title") %>% html_text(),
                price = html_nodes(page, ".price_color") %>% html_text() %>%
                        gsub("£", "", .),
                rating = html_nodes(page, ".star-rating") %>% html_attrs() %>%
                         str_remove("star-rating") %>%
                         str_replace_all(c("One" = "1", "Two" = "2",
                         "Three" = "3", "Four" = "4", "Five" = "5")) %>%
                          as.numeric())
})

#                                            title price rating
#1                               A Light in the ... 51.77      3
#2                               Tipping the Velvet 53.74      1
#3                                       Soumission 50.10      1
#4                                    Sharp Objects 47.82      4
#5                     Sapiens: A Brief History ... 54.23      5
#6                                  The Requiem Red 22.65      1
#7                     The Dirty Little Secrets ... 33.34      4
#8                          The Coming Woman: A ... 17.93      3
#.....


问:
Hibernate delete user and user_type instead of deleting only user
I'm developing a webapp with spring and angular7. I noticed that something is happening... I have generic DAOs and generic Services to do CRUD operations.
When I do a delete of a user with X id (for example, but that happens with all entities), the user type with X id is deleted too! but that user type wasn't the user type of the user that I wanted to delete.

I wanted to delete this user:

```<code>User {id: 5, name: hector, pass: blabla, id_user_type: {id: 2, desc: Admin}}
</code>```

The server deleted that user, and the user type with id 5 --> user type{id: 5, desc: Anonymous}

I checked "On delete set null" and "On update cascade" in phpmyadmin, and It's correctly set up.

I debugged generic delete DAO method and it's called only once.

I think that is a problem from hibernate, i should specify that only want to delete object that I specify on the method, not his children.

Generic Delete dao:

```<code>import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Override
    public <T> String delete(final T o) {
        sessionFactory.getCurrentSession().delete(o);
        return "Deleted";
    }
</code>```

Entity:

```<code>import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.SecondaryTable;
import javax.persistence.SecondaryTables;
import javax.persistence.Table;

import org.hibernate.annotations.DynamicUpdate;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.sun.istack.NotNull;

@Entity()
@Table(name="usuario")
@SecondaryTables({
    @SecondaryTable(name = "tipo_usuario", pkJoinColumns = { @PrimaryKeyJoinColumn(name = "id") })
})
@DynamicUpdate(value=true)
public class UsuarioBean {

...

@ManyToOne()
    @JoinColumn(name = "id_tipo_usuario")
    @NotNull
    private TipoUsuarioBean id_tipo_usuario;

...

}

</code>```

I only want to delete that user, and hibernate delete the user(id=14) row and the user_type(id=14) row:

答: I dont get why have you used secondary table annotation when you have control over the application better design would be to create separate entity and then map them using manytoone annotaion, as with secondary  table my guess is its default behaviour that operations performed in primary table are reflected in secondary table.</p>

Body:
I'm developing a webapp with spring and angular7. I noticed that something is happening... I have generic DAOs and generic Services to do CRUD operations.
When I do a delete of a user with X id (for example, but that happens with all entities), the user type with X id is deleted too! but that user type wasn't the user type of the user that I wanted to delete.

I wanted to delete this user:

User {id: 5, name: hector, pass: blabla, id_user_type: {id: 2, desc: Admin}}

The server deleted that user, and the user type with id 5 --> user type{id: 5, desc: Anonymous}

I checked "On delete set null" and "On update cascade" in phpmyadmin, and It's correctly set up.

I debugged generic delete DAO method and it's called only once.

I think that is a problem from hibernate, i should specify that only want to delete object that I specify on the method, not his children.

Generic Delete dao:

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Override
    public <T> String delete(final T o) {
        sessionFactory.getCurrentSession().delete(o);
        return "Deleted";
    }

Entity:

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.SecondaryTable;
import javax.persistence.SecondaryTables;
import javax.persistence.Table;

import org.hibernate.annotations.DynamicUpdate;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.sun.istack.NotNull;

@Entity()
@Table(name="usuario")
@SecondaryTables({
    @SecondaryTable(name = "tipo_usuario", pkJoinColumns = { @PrimaryKeyJoinColumn(name = "id") })
})
@DynamicUpdate(value=true)
public class UsuarioBean {

...

@ManyToOne()
    @JoinColumn(name = "id_tipo_usuario")
    @NotNull
    private TipoUsuarioBean id_tipo_usuario;

...

}

I only want to delete that user, and hibernate delete the user(id=14) row and the user_type(id=14) row:


问:
Get application version name using adb
Is there an easy way to get the version name of an application on an Android device using adb shell?

I found the application version number (not the version name) in /data/system/packages.xml.

It would be nice if there was a file that contained the Application Info.

答:
If you want to get all package versions, try this awk script:</p>

```<code>adb shell dumpsys package | awk '/^[ ]*Package \[.*\] (.*)/ { i = index($0, "[") + 1; pkg = substr($0, i, index($0, "]") - i); } /[ ]*versionName=/ { { print pkg "\t" substr($0, index($0, "=") + 1); pkg = ""; } }'
</code>```

Title: Get application version name using adb

Body:
If you want to get all package versions, try this awk script:

adb shell dumpsys package | awk '/^[ ]*Package \[.*\] (.*)/ { i = index($0, "[") + 1; pkg = substr($0, i, index($0, "]") - i); } /[ ]*versionName=/ { { print pkg "\t" substr($0, index($0, "=") + 1); pkg = ""; } }'


问:
Reduce sum of digits recursively down to one digit number
How do I make a function return the sum of all digits until it becomes a 1 digit number, using recursion?  I was able to make a function that gets the sum of all digits, but cant seem to find a way to recursively sum the digits of the sum itself:

```<code>class sum_of_digits
{

    static int sum_of_digit(int n)
    {
        if (n == 0)
            return 0;
        return (n % 10 + sum_of_digit(n / 10));
    }

    public static void main(String args[])
    {
        int num = 12345;
        int result = sum_of_digit(num);
        System.out.println("Sum of digits in " +
                           num + " is " + result);
    }
}
</code>```

This code prints the sum of '12345', which is 15. But I need to change it so it prints the sum of 1 + 5, which is 6.

答:
There are several ways to do it, one would be like this if global variables are allowed :

```<code>public class Sum_of_digits{
        static int sum = 0;

    public static void main(String args[]){

        int n = 12345;
        System.out.println(sum_of_digit(n));
        sum = 0;

    }
    static int sum_of_digit(int n){

        if(n==0){
            if(sum/10 == 0){
                return sum;
            }else{
                n=sum;
                sum=0;
            }
        }
        sum = sum+(n%10);
        n=n/10;
        return sum_of_digit(n);

    }
}
</code>```

and if Global variable are not allowed then passing sum as a parameter will help :

```<code>public class Sum_of_digits{

        public static void main(String args[]){

            int n = 12345;
            int sum = 0;
            System.out.println(sum_of_digit(n,sum));

        }
        static int sum_of_digit(int n,int sum){

            if(n==0){
                if(sum/10 == 0){
                    return sum;
                }else{
                    n=sum;
                    sum=0;
                }
            }
            sum = sum+(n%10);
            n=n/10;
            return sum_of_digit(n,sum);

        }
    }
</code>```

Here we are just shifting the focus from n to sum to evaluate the condition when the loop/recursion will terminate.

Body:
How do I make a function return the sum of all digits until it becomes a 1 digit number, using recursion?  I was able to make a function that gets the sum of all digits, but cant seem to find a way to recursively sum the digits of the sum itself:

class sum_of_digits
{

    static int sum_of_digit(int n)
    {
        if (n == 0)
            return 0;
        return (n % 10 + sum_of_digit(n / 10));
    }

    public static void main(String args[])
    {
        int num = 12345;
        int result = sum_of_digit(num);
        System.out.println("Sum of digits in " +
                           num + " is " + result);
    }
}

This code prints the sum of '12345', which is 15. But I need to change it so it prints the sum of 1 + 5, which is 6.

Body:
There are several ways to do it, one would be like this if global variables are allowed :

public class Sum_of_digits{
        static int sum = 0;

    public static void main(String args[]){

        int n = 12345;
        System.out.println(sum_of_digit(n));
        sum = 0;

    }
    static int sum_of_digit(int n){

        if(n==0){
            if(sum/10 == 0){
                return sum;
            }else{
                n=sum;
                sum=0;
            }
        }
        sum = sum+(n%10);
        n=n/10;
        return sum_of_digit(n);

    }
}

and if Global variable are not allowed then passing sum as a parameter will help :

public class Sum_of_digits{

        public static void main(String args[]){

            int n = 12345;
            int sum = 0;
            System.out.println(sum_of_digit(n,sum));

        }
        static int sum_of_digit(int n,int sum){

            if(n==0){
                if(sum/10 == 0){
                    return sum;
                }else{
                    n=sum;
                    sum=0;
                }
            }
            sum = sum+(n%10);
            n=n/10;
            return sum_of_digit(n,sum);

        }
    }

Here we are just shifting the focus from n to sum to evaluate the condition when the loop/recursion will terminate.


问:
how to not display duplicated data?
i want to show the categorie list without showing duplicated ones

my controller code :

public function showActualite(){

```<code>    $actualites=DB::table('actualites')->distinct('categorie')->orderBy('created_at', 'DESC')->paginate(6);
    return view ('AllActualite',['actualites' => $actualites]);
}
</code>```

My view :

@foreach ($actualites as $act)

```<code>      <span style="text-transform: capitalize;" > <a href="/actualites/{{$act->categorie}}"> {{$act->categorie}} </a></span>

     <span style="text-transform: capitalize;">  </span>
    @endforeach
    </div>
    <div class="row">

        @foreach($actualites as $act)
      <div class="col-lg-6">
        <div class="box wow fadeInLeft">
          <div class="icon"><i class="fa fa-newspaper-o"></i></div>
          <h4 class="title"><a href="/actualites/consulter/{{$act->id}}">{{$act->categorie}}</a></h4>
          <p class="description">{{$act->titre}}</p>

        </div>
      </div>

      @endforeach
</code>```

答:
All your answer can be found in this post

$actualites= Actuality::distinct()->get(['categorie']);
```

Eloquent is used.

Title: how to not display duplicated data?

Body:
i want to show the categorie list without showing duplicated ones

my controller code :

public function showActualite(){

    $actualites=DB::table('actualites')->distinct('categorie')->orderBy('created_at', 'DESC')->paginate(6);
    return view ('AllActualite',['actualites' => $actualites]);
}

My view :

@foreach ($actualites as $act)

       categorie}}"> {{$act->categorie}}

    @endforeach

        @foreach($actualites as $act)

id}}">{{$act->categorie}}

{{$act->titre}}

      @endforeach

Body:
All your answer can be found in this post

$actualites= Actuality::distinct()->get(['categorie']);

Eloquent is used.


问:
c#.net function
```<code>namespace csfunction
{
    class Program
    {
        static void Main(string[] args)
        {
            public int AddNumbers(int number1, int number2)
            {
                int result = AddNumbers(10, 5);
                Console.WriteLine(result);
            }
        }
    }
}
</code>```

is my code...am getting error like.....Error Type or namespace definition, or end-of-file expected

..hw can i over come this error

答:
```<code>static void Main(string[] args)
        {
            public int AddNumbers(int number1, int number2)
            {
                int result = AddNumbers(10, 5);
                Console.WriteLine(result);
            }
        }
</code>```

You're defining your method AddNumbers inside another method Main. That is not possible in C#.

Title: c#.net function

Body:
namespace csfunction
{
    class Program
    {
        static void Main(string[] args)
        {
            public int AddNumbers(int number1, int number2)
            {
                int result = AddNumbers(10, 5);
                Console.WriteLine(result);
            }
        }
    }
}

is my code...am getting error like.....Error Type or namespace definition, or end-of-file expected

..hw can i over come this error

Body:
static void Main(string[] args)
        {
            public int AddNumbers(int number1, int number2)
            {
                int result = AddNumbers(10, 5);
                Console.WriteLine(result);
            }
        }

You're defining your method AddNumbers inside another method Main. That is not possible in C#.

OwnerDisplayName: anon


问:
How to exclude the hovered td from table's hover?
I want to apply the filter called "blur" on a table (just on hover in css) excluding the td that has the hover in that moment. Otherwise the filter blur is applied from the page load.
So, how can I exclude a td hovered from a table's hover, only by using CSS?</p>

```<code>table td {
    filter: blur(1px);
}

td:hover {
    filter:blur(0px)
}
</code>```

答:
So that the table is blurred only when hovered, you have to use the selector table:hover. Now, because the filter applied to an element is also applied to its children elements, and because you want one of the cell (which is a child element) not to have that filter, you cannot apply it to the whole table. Instead, you need to apply it to every individual cell inside the hovered table, just like you did but with the added pseudo-selector: table:hover td.

Then, to remove the filter from the hovered cell, you would naturally apply the filter to the following selector: td:hover. The problem here is that you're already targeting all the table cells with the previous selector (table:hover td), and that first selector has a higher specificity (12) than the second one (11). So that the second selector wins, it has to have at least the same specificity and be placed after the first one.

To increase its specificity by 1, you can simply add table followed by a space in front of it. It means it targets the hovered cell in the table, which is what you want.

You end up with the following working code:

table:hover td { /* Specificity 12 */
  filter: blur(1px);
}

table td:hover { /* Also specificity 12, but placed after, so it wins */
  filter: blur(0px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td>Cell</td>
    <td>Cell</td>
    <td>Cell</td>
  </tr>
</table></code>```

Does that help?

Body:
I want to apply the filter called "blur" on a table (just on hover in css) excluding the td that has the hover in that moment. Otherwise the filter blur is applied from the page load.
So, how can I exclude a td hovered from a table's hover, only by using CSS?

table td {
    filter: blur(1px);
}

td:hover {
    filter:blur(0px)
}

Body:
So that the table is blurred only when hovered, you have to use the selector table:hover. Now, because the filter applied to an element is also applied to its children elements, and because you want one of the cell (which is a child element) not to have that filter, you cannot apply it to the whole table. Instead, you need to apply it to every individual cell inside the hovered table, just like you did but with the added pseudo-selector: table:hover td.

Then, to remove the filter from the hovered cell, you would naturally apply the filter to the following selector: td:hover. The problem here is that you're already targeting all the table cells with the previous selector (table:hover td), and that first selector has a higher specificity (12) than the second one (11). So that the second selector wins, it has to have at least the same specificity and be placed after the first one.

To increase its specificity by 1, you can simply add table followed by a space in front of it. It means it targets the hovered cell in the table, which is what you want.

You end up with the following working code:

table:hover td { /* Specificity 12 */
  filter: blur(1px);
}

table td:hover { /* Also specificity 12, but placed after, so it wins */
  filter: blur(0px);
}

<table>
  <tr>
    <td>Cell</td>
    <td>Cell</td>
    <td>Cell</td>
  </tr>
</table>

Does that help?


问:
laravel how to optimize a simple where query in one table
i have a simple where query that repeats in a foreach for some times that can be a lot really so here is my query :

```<code>    for ($i = 0; $i < count($hasdate); $i++) {
        $roomprice = RoomPricingHistory::
             Where('accommodation_room_id', $hasroom[$i])
            ->where('from_date', '<=', $hasdate[$i])
            ->where('to_date', '>=', $hasdate[$i])
            ->get()->sortBy('created_at');

        $lastget = last($roomprice);
        $last_price = last($lastget);
        if ($last_price) {
            $final_price[] = $last_price->sales_price;
        } else {
            $has_not_capacity = $hasdate[$i];
        }
    }
</code>```

so each time this runs it takes a bout 2,509.10ms   in telescope and here is what the telescope shows me as the query which is running on table

```<code>  select
  *
from
  `room_pricing_histories`

    where
      `accommodation_room_id` = 3
      and `from_date` <= "2019-06-01 09:00:00"
      and `to_date` >= "2019-06-01 09:00:00"
</code>```

so any idea on how to optimize this query ??

答:
Well, as a rule of thumb - don't run a query inside a loop.

You can use whereIn() for the querying multiple IDs

```<code>$roomIds = $hasroom // assume this has array of ids

$roomprice = RoomPricingHistory::
        whereIn('accommodation_room_id', $roomIds)
        ->where('from_date', '<=', $fromDate)
        ->where('to_date', '>=', $toDate)
        ->get()->sortBy('created_at');
</code>```

Body:
i have a simple where query that repeats in a foreach for some times that can be a lot really so here is my query :

    for ($i = 0; $i < count($hasdate); $i++) {
        $roomprice = RoomPricingHistory::
             Where('accommodation_room_id', $hasroom[$i])
            ->where('from_date', '<=', $hasdate[$i])
            ->where('to_date', '>=', $hasdate[$i])
            ->get()->sortBy('created_at');

        $lastget = last($roomprice);
        $last_price = last($lastget);
        if ($last_price) {
            $final_price[] = $last_price->sales_price;
        } else {
            $has_not_capacity = $hasdate[$i];
        }
    }

so each time this runs it takes a bout 2,509.10ms   in telescope and here is what the telescope shows me as the query which is running on table

  select
  *
from
  `room_pricing_histories`

    where
      `accommodation_room_id` = 3
      and `from_date` <= "2019-06-01 09:00:00"
      and `to_date` >= "2019-06-01 09:00:00"

so any idea on how to optimize this query ??

Body:
Well, as a rule of thumb - don't run a query inside a loop.

You can use whereIn() for the querying multiple IDs

$roomIds = $hasroom // assume this has array of ids

$roomprice = RoomPricingHistory::
        whereIn('accommodation_room_id', $roomIds)
        ->where('from_date', '<=', $fromDate)
        ->where('to_date', '>=', $toDate)
        ->get()->sortBy('created_at');


问:
Passing data to a javascript file after loading fails
I have the following in my html

```<code><html>
<body>
<script type="text/javascript">
 var hccid=98964571;
 function add_chatinline(){
    var nt=document.createElement("script");
    nt.async=true;
    nt.src="http://localhost/ll.js";
    var ct=document.getElementsByTagName("script")[0];
    ct.parentNode.insertBefore(nt,ct);
    console.log("state is ", SORCHAT)//SORCHAT is not defined
 }
 add_chatinline();
 </script>
</body>
</html>
</code>```

On the ll.js i have

```<code>var SORCHAT = SORCHAT || (function () {
return {
    init: function (Args) {
        console.log("hash is ", Args)
    },
};
}());
</code>```

But now am getting an error of SORCHAT is not defined.

By adding window.onload that is

```<code> <script>
  window.onload = function(){
    SORCHAT.init(12736474676); //this works
 }
 </script>
</code>```

But whenever i include another javascript file with window.onload function the SORCHAT.init is not executed.

What am i missing.

答:
You are probably overwriting the window.onload when using it multiple times. You can prevent that with the help of the addEventListener-function.

window.onload = function () {
  console.log('onload #1');
}
window.onload = function () { // This replaces the first onload (#1)
  console.log('onload #2');
}

window.addEventListener('load', function () {
  console.log('onload #A');
});

window.addEventListener('load', function () {
  console.log('onload #B');
});```

Body:
I have the following in my html

On the ll.js i have

var SORCHAT = SORCHAT || (function () {
return {
    init: function (Args) {
        console.log("hash is ", Args)
    },
};
}());

But now am getting an error of SORCHAT is not defined.

By adding window.onload that is

But whenever i include another javascript file with window.onload function the SORCHAT.init is not executed.

What am i missing.