问:
How to plot values of pandas dataframe with reference to a list (problems with indexing)?
I am looking for a clever way to produce a plot styled like this rather childish example:

with source data like this:

```<code>days = ['Monday','Tuesday','Wednesday','Thursday','Friday']

   Feature                   Values                             observed on
0        1  [5.5, 14.3, 12.0, 11.8]  [Tuesday, Wednesday, Thursday, Friday]
1        2        [6.1, 14.6, 12.7]            [Monday, Tuesday, Wednesday]
2        3             [15.2, 13.3]                       [Tuesday, Friday]
3        4       [14.9, 14.3, 17.0]              [Monday, Thursday, Friday]
4        5  [13.0, 13.1, 13.5, 10.3]     [Monday, Tuesday, Thursday, Friday]
5        6              [12.5, 7.0]                     [Wednesday, Friday]
</code>```

In other words, for each line of this dataframe, I want to plot/connect the values for the "days" on which they were acquired. (Please note the days are here just to illustrate my problem, using datetime is not a solution.)
But I got lost in indexing.

This is how I prepared the figure (i.e. having vertical black lines for each day)

```<code>for count, log in enumerate(days):
    plt.plot(np.ones(len(allvalues))*count,np.array(allvalues),'k',linestyle='-',linewidth=1.)
    plt.xticks(np.arange(0,5,1),['M','T','W','T','F'])
</code>```

and this works, I get my vertical lines and the labels. (later I may want to plot other datasets instead of those vertical lines, but for now, the vertical lines are more illustrative)
But now, how can I plot the values for each day?

```<code>for index, group in observations.iterrows():
    whichdays= group['observed on']
    values = group['Values']
    for d in whichdays:
        plt.plot(days[np.where(days==d)],values)
</code>```

but this produces TypeError: list indices must be integers, not tuple

答:
One possible solution is flatenning values from lists, pivot and then plot:

```<code>from  itertools import chain

df2 = pd.DataFrame({
        "Feature": np.repeat(df.Feature.values, df.Values.str.len()),
        "Values": list(chain.from_iterable(df.Values)),
        "observed on": list(chain.from_iterable(df['observed on']))})
print (df2)
    Feature  Values observed on
0         1     5.5     Tuesday
1         1    14.3   Wednesday
2         1    12.0    Thursday
3         1    11.8      Friday
4         2     6.1      Monday
5         2    14.6     Tuesday
6         2    12.7   Wednesday
7         3    15.2     Tuesday
8         3    13.3      Friday
9         4    14.9      Monday
10        4    14.3    Thursday
11        4    17.0      Friday
12        5    13.0      Monday
13        5    13.1     Tuesday
14        5    13.5    Thursday
15        5    10.3      Friday
16        6    12.5   Wednesday
17        6     7.0      Friday
</code>```

```<code>df = df2.pivot(index='observed on', columns='Feature', values='Values')
df.index.name = None
df.columns.name = None
print (df)
              1     2     3     4     5     6
Friday     11.8   NaN  13.3  17.0  10.3   7.0
Monday      NaN   6.1   NaN  14.9  13.0   NaN
Thursday   12.0   NaN   NaN  14.3  13.5   NaN
Tuesday     5.5  14.6  15.2   NaN  13.1   NaN
Wednesday  14.3  12.7   NaN   NaN   NaN  12.5

df.plot(linestyle='-',linewidth=1.)
</code>```

Body:
I am looking for a clever way to produce a plot styled like this rather childish example:

with source data like this:

days = ['Monday','Tuesday','Wednesday','Thursday','Friday']

   Feature                   Values                             observed on
0        1  [5.5, 14.3, 12.0, 11.8]  [Tuesday, Wednesday, Thursday, Friday]
1        2        [6.1, 14.6, 12.7]            [Monday, Tuesday, Wednesday]
2        3             [15.2, 13.3]                       [Tuesday, Friday]
3        4       [14.9, 14.3, 17.0]              [Monday, Thursday, Friday]
4        5  [13.0, 13.1, 13.5, 10.3]     [Monday, Tuesday, Thursday, Friday]
5        6              [12.5, 7.0]                     [Wednesday, Friday]

In other words, for each line of this dataframe, I want to plot/connect the values for the "days" on which they were acquired. (Please note the days are here just to illustrate my problem, using datetime is not a solution.)
But I got lost in indexing.

This is how I prepared the figure (i.e. having vertical black lines for each day)

for count, log in enumerate(days):
    plt.plot(np.ones(len(allvalues))*count,np.array(allvalues),'k',linestyle='-',linewidth=1.)
    plt.xticks(np.arange(0,5,1),['M','T','W','T','F'])

and this works, I get my vertical lines and the labels. (later I may want to plot other datasets instead of those vertical lines, but for now, the vertical lines are more illustrative)
But now, how can I plot the values for each day?

for index, group in observations.iterrows():
    whichdays= group['observed on']
    values = group['Values']
    for d in whichdays:
        plt.plot(days[np.where(days==d)],values)

but this produces TypeError: list indices must be integers, not tuple

Body:
One possible solution is flatenning values from lists, pivot and then plot:

from  itertools import chain

df2 = pd.DataFrame({
        "Feature": np.repeat(df.Feature.values, df.Values.str.len()),
        "Values": list(chain.from_iterable(df.Values)),
        "observed on": list(chain.from_iterable(df['observed on']))})
print (df2)
    Feature  Values observed on
0         1     5.5     Tuesday
1         1    14.3   Wednesday
2         1    12.0    Thursday
3         1    11.8      Friday
4         2     6.1      Monday
5         2    14.6     Tuesday
6         2    12.7   Wednesday
7         3    15.2     Tuesday
8         3    13.3      Friday
9         4    14.9      Monday
10        4    14.3    Thursday
11        4    17.0      Friday
12        5    13.0      Monday
13        5    13.1     Tuesday
14        5    13.5    Thursday
15        5    10.3      Friday
16        6    12.5   Wednesday
17        6     7.0      Friday

df = df2.pivot(index='observed on', columns='Feature', values='Values')
df.index.name = None
df.columns.name = None
print (df)
              1     2     3     4     5     6
Friday     11.8   NaN  13.3  17.0  10.3   7.0
Monday      NaN   6.1   NaN  14.9  13.0   NaN
Thursday   12.0   NaN   NaN  14.3  13.5   NaN
Tuesday     5.5  14.6  15.2   NaN  13.1   NaN
Wednesday  14.3  12.7   NaN   NaN   NaN  12.5

df.plot(linestyle='-',linewidth=1.)


来源: stackexchange

问:
Is it ok to still use tables?

Possible Duplicate:

  Why not use tables for layout in HTML?

Just wondering, I thought I have read before that it is bad to use tables, so my question is, is it still acceptable to use tables in development?

答:
Yes. Tables are very good (even preferred) for tabular data.

For layout alone, there are newer and better options such as CSS Grid.

ContentLicense: CC BY-SA 2.5

Title: Is it ok to still use tables?

ContentLicense: CC BY-SA 4.0


问:
Preventing Brute Force Attack on MVC
I am trying to figure out how to fight a brute force attack on my website.  Based on all the research I have done the top answers were Account Lockout & Captcha.

If I lock out a user then I am denying them service for x amount of time.  This means that if an attacker were to attack 10 different accounts he will lock them all.  Then when time is up he will lock them again.  Basically he can keep at it and keep the users locked out indefinitely.  The users can contact me but that is now 10 tickets I would have to deal with and I'd rather avoid that work if its possible.  So what I am failing to understand exactly is how is this then useful?  The attacker might not get into account but they will cause me and users a lot of grief.

How do I combat this?  Ip banning seems pointless as it can be changed fairly easy.

答:
You can add an incremental delay that doubles after each failed login attempt, after a handful of login attempts the delay gets too long for brute force to work (e.g. after 20 attempts the delay is 6 days).

```<code>[HttpPost]
public async Task<ActionResult> Login(LoginViewModel viewModel, string returnUrl)
{
    // incremental delay to prevent brute force attacks
    int incrementalDelay;
    if (HttpContext.Application[Request.UserHostAddress] != null)
    {
        // wait for delay if there is one
        incrementalDelay = (int)HttpContext.Application[Request.UserHostAddress];
        await Task.Delay(incrementalDelay * 1000);
    }

    if (!ModelState.IsValid)
        return View();

    // authenticate user
    var user = _userService.Authenticate(viewModel.Username, viewModel.Password);

    if (user == null)
    {
        // login failed

        // increment the delay on failed login attempts
        if (HttpContext.Application[Request.UserHostAddress] == null)
        {
            incrementalDelay = 1;
        }
        else
        {
            incrementalDelay = (int)HttpContext.Application[Request.UserHostAddress] * 2;
        }
        HttpContext.Application[Request.UserHostAddress] = incrementalDelay;

        // return view with error
        ModelState.AddModelError("", "The user name or password provided is incorrect.");
        return View();
    }

    // login success

    // reset incremental delay on successful login
    if (HttpContext.Application[Request.UserHostAddress] != null)
    {
        HttpContext.Application.Remove(Request.UserHostAddress);
    }

    // set authentication cookie
    _formsAuthenticationService.SetAuthCookie(
        user.Username,
        viewModel.KeepMeLoggedIn,
        null);

    // redirect to returnUrl
    return Redirect(returnUrl);
}
</code>```

There's more details at this post

ContentLicense: CC BY-SA 3.0

Title: Preventing Brute Force Attack on MVC

Body:
You can add an incremental delay that doubles after each failed login attempt, after a handful of login attempts the delay gets too long for brute force to work (e.g. after 20 attempts the delay is 6 days).

[HttpPost]
public async Task<ActionResult> Login(LoginViewModel viewModel, string returnUrl)
{
    // incremental delay to prevent brute force attacks
    int incrementalDelay;
    if (HttpContext.Application[Request.UserHostAddress] != null)
    {
        // wait for delay if there is one
        incrementalDelay = (int)HttpContext.Application[Request.UserHostAddress];
        await Task.Delay(incrementalDelay * 1000);
    }

    if (!ModelState.IsValid)
        return View();

    // authenticate user
    var user = _userService.Authenticate(viewModel.Username, viewModel.Password);

    if (user == null)
    {
        // login failed

        // increment the delay on failed login attempts
        if (HttpContext.Application[Request.UserHostAddress] == null)
        {
            incrementalDelay = 1;
        }
        else
        {
            incrementalDelay = (int)HttpContext.Application[Request.UserHostAddress] * 2;
        }
        HttpContext.Application[Request.UserHostAddress] = incrementalDelay;

        // return view with error
        ModelState.AddModelError("", "The user name or password provided is incorrect.");
        return View();
    }

    // login success

    // reset incremental delay on successful login
    if (HttpContext.Application[Request.UserHostAddress] != null)
    {
        HttpContext.Application.Remove(Request.UserHostAddress);
    }

    // set authentication cookie
    _formsAuthenticationService.SetAuthCookie(
        user.Username,
        viewModel.KeepMeLoggedIn,
        null);

    // redirect to returnUrl
    return Redirect(returnUrl);
}

There's more details at this post


问:
Batch script for loop won't set variable correctly
I have following code but I see variables inside for loop are not set correctly. I tried using ! mark too still that doesn't work.

```<code>set dev_root=.\
set prod_root=..\prod\
setlocal disableDelayedExpansion

for /f "tokens=1* delims=\" %%A in ('forfiles /s /m *.txt /c "cmd /c echo @relpath"') do for %%F in (^"%%B) do (
    set "file=%%~F"
    set dev_filepath="%dev_root%%file%"
    set prod_filepath="%prod_root%%file%"

    if exist %prod_filepath% (
            fc /b %dev_filepath% %prod_filepath% > nul
        if errorlevel 1 (
            sd edit %prod_filepath%
            echo f | xcopy /f /y %dev_filepath% %prod_filepath%
        )
    ) else (
        echo f | xcopy /f /y %dev_filepath% %prod_filepath%
            sd add %prod_filepath%
    )
)

endlocal
</code>```

答:
Try like this (though I have no idea what is sd):

```<code>set dev_root=.\
set prod_root=..\prod\
setlocal enableDelayedExpansion

for /f "tokens=1* delims=\" %%A in ('forfiles /s /m *.txt /c "cmd /c echo @relpath"') do for %%F in (^"%%B) do (
    set "file=%%~F"
    set "dev_filepath=%dev_root%%%~F"
    set "prod_filepath=%prod_root%%%~F"

    if exist "!prod_filepath!" (
            fc /b "!dev_filepath!" "!prod_filepath!" > nul 2>nul || (
                sd edit "!prod_filepath!"
                copy /Y "!dev_filepath!" "!prod_filepath!"

            )

    ) else (
        copy /Y "!dev_filepath!" "!prod_filepath!"
        sd add "!prod_filepath!"
    )
)
</code>```

Body:
I have following code but I see variables inside for loop are not set correctly. I tried using ! mark too still that doesn't work.

set dev_root=.\
set prod_root=..\prod\
setlocal disableDelayedExpansion

for /f "tokens=1* delims=\" %%A in ('forfiles /s /m *.txt /c "cmd /c echo @relpath"') do for %%F in (^"%%B) do (
    set "file=%%~F"
    set dev_filepath="%dev_root%%file%"
    set prod_filepath="%prod_root%%file%"

    if exist %prod_filepath% (
            fc /b %dev_filepath% %prod_filepath% > nul
        if errorlevel 1 (
            sd edit %prod_filepath%
            echo f | xcopy /f /y %dev_filepath% %prod_filepath%
        )
    ) else (
        echo f | xcopy /f /y %dev_filepath% %prod_filepath%
            sd add %prod_filepath%
    )
)

endlocal

Body:
Try like this (though I have no idea what is sd):

set dev_root=.\
set prod_root=..\prod\
setlocal enableDelayedExpansion

for /f "tokens=1* delims=\" %%A in ('forfiles /s /m *.txt /c "cmd /c echo @relpath"') do for %%F in (^"%%B) do (
    set "file=%%~F"
    set "dev_filepath=%dev_root%%%~F"
    set "prod_filepath=%prod_root%%%~F"

    if exist "!prod_filepath!" (
            fc /b "!dev_filepath!" "!prod_filepath!" > nul 2>nul || (
                sd edit "!prod_filepath!"
                copy /Y "!dev_filepath!" "!prod_filepath!"

            )

    ) else (
        copy /Y "!dev_filepath!" "!prod_filepath!"
        sd add "!prod_filepath!"
    )
)


问:
Kendo UI Notifications and MVC
Does anyone tried Kendo UI notifications from MVC server side, like MvcFlashMessages?

I want to show "succeed or error" notification after form submit(In my scenario, after form submit Controller action redirects to view with items list and i want to show succeed notification).

Or maybe more different scenario like after grid item create/delete/edit notification show but notification must rise from server side if some errors occurs not only from JS.

Thanks for attention.

答:
First of all you can check this website. http://demos.telerik.com/kendo-ui/notification/templates

I gave you an example about it.

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

    var addUserUrl = "<%=Url.Action("AddUser", "ControlAccount")%>";

    $("#addUser").click(function addUserFunc() {

        var userName= 'exampleUser';
        var password = 'examplePassword';

        $.post(addUserUrl, { userName: userName, password: password}, function (data, result) {

            var d = new Date();
            staticNotification.show(kendo.toString(d, 'HH:MM:ss.') + kendo.toString(d.getMilliseconds(), "000"), text);
            var container = $(staticNotification.options.appendTo);
            container.scrollTop(container[0].scrollHeight);

        });
    });
</code>```

In the server side ;

```<code>    [HttpPost]
    public ActionResult AddUser(string kullaniciAdi, string password)
    {
        var result = "";
      //// Do it your jobs
        return Json(result, JsonRequestBehavior.AllowGet);
    }
</code>```

Title: Kendo UI Notifications and MVC

Body:
First of all you can check this website. http://demos.telerik.com/kendo-ui/notification/templates

I gave you an example about it.

    $(document).ready(function () {

    var addUserUrl = "<%=Url.Action("AddUser", "ControlAccount")%>";

    $("#addUser").click(function addUserFunc() {

        var userName= 'exampleUser';
        var password = 'examplePassword';

        $.post(addUserUrl, { userName: userName, password: password}, function (data, result) {

            var d = new Date();
            staticNotification.show(kendo.toString(d, 'HH:MM:ss.') + kendo.toString(d.getMilliseconds(), "000"), text);
            var container = $(staticNotification.options.appendTo);
            container.scrollTop(container[0].scrollHeight);

        });
    });

In the server side ;

    [HttpPost]
    public ActionResult AddUser(string kullaniciAdi, string password)
    {
        var result = "";
      //// Do it your jobs
        return Json(result, JsonRequestBehavior.AllowGet);
    }


问:
is it possible to assign base class's struct to dervied class's struct
I have class A which has struct as member and another class B which inherit class A and class B's struct inherit class A's struct.

```<code>class A
{
public:
    struct st
    {
        int x;
        int y;
    };
};

class B : public A
{
public:
    struct st : A::st
    {
        int z;
    };
};
</code>```

following code give me error: what is the way to do this thing

```<code>B::st* obj = NULL;

obj = new A::st [10];
</code>```

答:
What you are trying is wrong since B::st is sub-type of A::st. Hence, a pointer to A::st cannot be automatically converted to a pointer of type B::st.

For the same reason, you can't use:

```<code>B* bPtr = new A;
</code>```

You can do the other way around.

```<code>A::st* obj = NULL;
obj = new B::st;  // Don't use the array new. That is going to be problematic.
</code>```

Body:
I have class A which has struct as member and another class B which inherit class A and class B's struct inherit class A's struct.

class A
{
public:
    struct st
    {
        int x;
        int y;
    };
};

class B : public A
{
public:
    struct st : A::st
    {
        int z;
    };
};

following code give me error: what is the way to do this thing

B::st* obj = NULL;

obj = new A::st [10];

Body:
What you are trying is wrong since B::st is sub-type of A::st. Hence, a pointer to A::st cannot be automatically converted to a pointer of type B::st.

For the same reason, you can't use:

B* bPtr = new A;

You can do the other way around.

A::st* obj = NULL;
obj = new B::st;  // Don't use the array new. That is going to be problematic.


问:
How to hide menu element with only CSS
I have these menu elements I am trying to hide but I cannot seem to only select the middle option called 'Contact'. I cannot edit the html directly so am using CSS to override the style.

Essentially I just want to hide the item called 'Contact' from appearing. How do I select it using CSS? I have put what I thought might work in the  section, but it's not really working. Any help would be greatly appreciated. Thanks in advance. (Here it is as well: https://jsfiddle.net/amhzv0Lw/4/)

Here's the menu code:

```<code>    <!DOCTYPE html>
    <html>
    <head>
    <style>
    .nav a[title:contact] {
        display: none;
    }
    </style>
    </head>
    <body>

    <ul class="nav navbar-nav navbar-left">
<li><a href="/www.example.com/" title="Home">Home</a></li>
<li><a href="/www.example.com/storepage.aspx" title="Contact">Contact</a></li>
<li><a href="https://www.example.com/login" title="Login">Login</a></li>

    </ul>

    </body>
    </html>
</code>```

答:
You only have to replace : with =, because that's how css selectors work (reference here)

Your code should look like this

```<code><style>
    .nav a[title=Contact] {
        display: none;
    }
</style>
</code>```

Title: How to hide menu element with only CSS

Body:
I have these menu elements I am trying to hide but I cannot seem to only select the middle option called 'Contact'. I cannot edit the html directly so am using CSS to override the style.

Essentially I just want to hide the item called 'Contact' from appearing. How do I select it using CSS? I have put what I thought might work in the  section, but it's not really working. Any help would be greatly appreciated. Thanks in advance. (Here it is as well: https://jsfiddle.net/amhzv0Lw/4/)

Here's the menu code:

    <!DOCTYPE html>

Home

Contact

Login

Body:
You only have to replace : with =, because that's how css selectors work (reference here)

Your code should look like this

<style>
    .nav a[title=Contact] {
        display: none;
    }
</style>


问:
visual studio header
I'm a newbie to visual studio. I am following a tutorial to learn C++ and they have provided some headers for the course. So when i work with projects i include the headers in the header folder of the solution explorer on the left. But when i run the program, i get errors that the headers are no where to be found. pls help. </p>

<p>Thanks in advance :) </p>

答: Use menu Tools, Options, Projects and Solutions, VC++ Directories to set the path where VS will seach the headers.</p>

Title: visual studio header

Body:
I'm a newbie to visual studio. I am following a tutorial to learn C++ and they have provided some headers for the course. So when i work with projects i include the headers in the header folder of the solution explorer on the left. But when i run the program, i get errors that the headers are no where to be found. pls help.

Thanks in advance :)


问:
Youtube data api return dailyLimitExceededUnreg reach
We are using the YouTube Data API to get the YouTube channel information, it was working before two days now it is giving me below error:

```<code>{
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "dailyLimitExceededUnreg",
"message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.",
"extendedHelp": "https://code.google.com/apis/console"
}
],
"code": 403,
"message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
}
}
</code>```

Is there any new update on YouTube Data API?
Can anyone help me to resolve this issue?

答:
In order to access any Google API you need to identify your application.   This rule has not been enforced on all Google APIs.  If you say your request has worked in the past I suspect that they have begun to enforce this now with the YouTube API.

The problem is that you have either not authenticate your application using Oauth2 or you are not sending an API key along with this request.

You need a Google Account to access the Google Developers Console, request an API key, and register your application.

Create a project in the Google Developers Console and obtain authorization credentials so your application can submit API requests.

After creating your project, make sure the YouTube Data API is one of the services that your application is registered to use:

a. Go to the Developers Console and select the project that you just registered.
b. Open the API Library in the Google Developers Console. If prompted, select a project or create a new one. In the list of APIs, make sure the status is ON for the YouTube Data API v3.

If your application will use any API methods that require user authorization, read the authentication guide to learn how to implement OAuth 2.0 authorization.

see Getting started

Body:
We are using the YouTube Data API to get the YouTube channel information, it was working before two days now it is giving me below error:

{
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "dailyLimitExceededUnreg",
"message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.",
"extendedHelp": "https://code.google.com/apis/console"
}
],
"code": 403,
"message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
}
}

Is there any new update on YouTube Data API?
Can anyone help me to resolve this issue?


问:
SELECT and JOIN column not in Group by function
I have to join two different table to get my result.
The table 'Resource' it is simple, while the table 'Dimension.[Code]' contains, among the others, a column with different values (i.e :

Code
 SILO
 GRADE
 OTHER 1
 OTHER2

This is the reason why a join twice that column to get two different columns called GRADE and SILO.

Now, I have a query that selects the maximum value of a grade within the group as follows:

```<code>`SELECT
R.[ID] -- If I inserted that here, it is not working obviously.
       -- This cannot But this is the additional column I need (see later)
 DD_SILO.[Value] DIR ,
 max(R.[GRADE]) GRADE_DIR
 FROM [Resource] R
LEFT JOIN
Dimension DD_SILO ON  R.[ID] = DD_SILO.[ID] AND DD_SILO.[Code] = 'SILO'
   group by DD_SILO.[Value]'
</code>```

What I need is basically to have, beside GRADE AND SILO, also the ID name, which is contained into the [Resource] table.
Please notice that [Resource].ID = [Dimension].ID

I would have solved the problem with ROW_NUMBER () to select the highest within the group, avoiding then then 'group by', but as the query has to be inserted in a bigger one, that would take too much time to run. I am using Microsoft SQL Server 2016.

答:
Could you use a virtual table something like: -

```<code>`
select
     a.max_grade_silo,
     a.max_grade_value,
     (select max(r.id)
        from [resource] r,
             [dimension] d
        where r.[ID] = d.[ID] and
              d.[CODE]= 'SILO' and
              r.[GRADE] = a.[max_grade_value]
     ),
     max_grade_silo a
from
(SELECT
     DD_SILO.[Value] DIR ,
     max(R.[GRADE]) GRADE_DIR
     FROM [Resource] R
    LEFT JOIN
    Dimension DD_SILO ON  R.[ID] = DD_SILO.[ID] AND DD_SILO.[Code] = 'SILO'
       group by DD_SILO.[Value]
) temp_result (max_grade_silo, max_grade_value)
'
</code>```

Probably better to look at normalizing the tables?

Body:
I have to join two different table to get my result.
The table 'Resource' it is simple, while the table 'Dimension.[Code]' contains, among the others, a column with different values (i.e :

Code
 SILO
 GRADE
 OTHER 1
 OTHER2

This is the reason why a join twice that column to get two different columns called GRADE and SILO.

Now, I have a query that selects the maximum value of a grade within the group as follows:

`SELECT
R.[ID] -- If I inserted that here, it is not working obviously.
       -- This cannot But this is the additional column I need (see later)
 DD_SILO.[Value] DIR ,
 max(R.[GRADE]) GRADE_DIR
 FROM [Resource] R
LEFT JOIN
Dimension DD_SILO ON  R.[ID] = DD_SILO.[ID] AND DD_SILO.[Code] = 'SILO'
   group by DD_SILO.[Value]'

What I need is basically to have, beside GRADE AND SILO, also the ID name, which is contained into the [Resource] table.
Please notice that [Resource].ID = [Dimension].ID

I would have solved the problem with ROW_NUMBER () to select the highest within the group, avoiding then then 'group by', but as the query has to be inserted in a bigger one, that would take too much time to run. I am using Microsoft SQL Server 2016.

Body:
Could you use a virtual table something like: -

`
select
     a.max_grade_silo,
     a.max_grade_value,
     (select max(r.id)
        from [resource] r,
             [dimension] d
        where r.[ID] = d.[ID] and
              d.[CODE]= 'SILO' and
              r.[GRADE] = a.[max_grade_value]
     ),
     max_grade_silo a
from
(SELECT
     DD_SILO.[Value] DIR ,
     max(R.[GRADE]) GRADE_DIR
     FROM [Resource] R
    LEFT JOIN
    Dimension DD_SILO ON  R.[ID] = DD_SILO.[ID] AND DD_SILO.[Code] = 'SILO'
       group by DD_SILO.[Value]
) temp_result (max_grade_silo, max_grade_value)
'

Probably better to look at normalizing the tables?


问:
Adding a table row in jQuery
I'm using jQuery to add an additional row to a table as the last row.

I have done it this way:

```<code>$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');
</code>```

Are there limitations to what you can add to a table like this (such as inputs, selects, number of rows)? Is there a different way to do it?

答:
This could also be done :</p>

```<code>$("#myTable > tbody").html($("#myTable > tbody").html()+"<tr><td>my data</td><td>more data</td></tr>")
</code>```

OwnerDisplayName: Darryl Hein

Title: Adding a table row in jQuery

Body:
I'm using jQuery to add an additional row to a table as the last row.

I have done it this way:

$('#myTable').append('
my data	more data
');

Are there limitations to what you can add to a table like this (such as inputs, selects, number of rows)? Is there a different way to do it?

LastEditorDisplayName: Darryl Hein

Body:
This could also be done :

$("#myTable > tbody").html($("#myTable > tbody").html()+"<tr><td>my data</td><td>more data</td></tr>")


问:
Steps to develop a multilingual web application
What are the steps to develop a multilingual web application?

Should i store the languages texts and resources in database or should i use property files or resource files?

I understand that I need to use CurrentCulture with C# alone with CultureFormat etc.

I wanted to know you opinions on steps to build a multilingual web application.

Doesn't have to be language specific. I'm just looking for steps to build this.

答:
The specific mechanisms are different depending on the platform you are developing on.

As a cursory set of work items:

Separation of code from content. Generally, resources are compiled into assemblies with the help of resource files (in dot net) or stored in property files (in java, though there are other options), or some other location, and referred to by ID. If you want localization costs to be reasonable, you need to avoid changes to the IDs between releases, as most localization tools will treat new IDs as new content.

Identification of areas in the application which make assumptions about the locale of the user, especially date/time, currency, number formatting or input.

Create some mechanism for locale-specific CSS content; not all fonts work for all languages, and not all font-sizes are sane for all languages. Don't paint yourself into a corner of forcing Thai text to be displayed in 8 pt. Also, text directionality is going to be right-to-left for at least two languages.

Design your page content to reflow or resize reasonably when more or less content than you expect is present. Many languages expand 50-80% from English for short strings, and 30-40% for longer pieces of content (that's a rough rule of thumb, not a law).

Identify cultural presumptions made by your UI designers, and try to make them more neutral, or, if you've got money and sanity to burn, localizable. Mailboxes don't look the same everywhere, hand gestures aren't universal, and something that's cute or clever or relies on a visual pun won't necessarily travel well.

Choose appropriate encodings for your supported languages. It's now reasonable to use UTF-8 for all content that's sent to web browsers, regardless of language.

Choose appropriate collation for your databases, or enable alternate collations, if you are dealing with content in multiple languages in your databases. Case-insensitivity works differently in many languages than it does in English, and accent insensitivity is acceptable in some languages and generally inappropriate in others.

Don't assume words are delimited by spaces or that sentences are delimited by punctuation, if you're trying to support search.

Avoid:

Storing localized content in databases, unless there's a really, really, good reason. And then, think again. If you have content that is somewhat dynamic and representatives of each region need to customize it, it may be reasonable to store certain categories of content with an associated locale ID.

Trying to be clever with string concatenation. Also, try not to assume rules about pluralization or counting work the same for every culture. Make sure, at least, that the order of strings (and controls) can be specified with format strings that are typical your platform, or well documented in your localization kit if you elect to roll your own for some reason.

Presuming that it's ok for code bugs to be fixed by localizers. That's generally not reasonable, at least if you want to deliver your product within a reasonable time at a reasonable cost; it's sometimes not even possible.


问:
Delphi + FireDAC Get database errors on ApplyUpdates
I'm facing difficulty to find a correct way to get errors on ApplyUpdates method, using FireDAC in memory (CachedUpdates).

Here is my scenario, a master-detail relationship, compounded by:

1 TFDConnection

2 TFDQuery

2 TDataSource

1 TFDSchemaAdapter

Both queries are setted as CachedUpdates and are linked to FDSchemaAdapter.
The FDQuery2 (detail) is linked with the master by MasterSource property. MasterFields and IndexFieldNames are setted as "idMaster". The property FetchOptions.DetailCascade is also checked.

I also have a button to perform the apply:

```<code>  try
    FDConnection1.StartTransaction;

    FDSchemaAdapter1.ApplyUpdates(0);

    FDQuery1.CommitUpdates;
    FDQuery2.CommitUpdates;

    FDConnection1.Commit;
  except on E: Exception do
    begin
      FDConnection1.Rollback;
      raise Exception.CreateFmt('Something went wrong. Error: %s', [E.Message]);
    end;
  end;
</code>```

Everything is working fine so far.

The problem occurs when my database throw an exception, such a constraint violation. The exception is not raising. Consequently, my transaction is not 'rollbacked'.

ps: I'm using Delphi XE7 and Firebird 2.5

答:
As the documentation states:

ApplyUpdates returns the number of errors it encountered. Based on
this return value and the setting of AMaxErrors successfully, applied
updates are removed from the centralized change log. If the update
process is aborted before all updates are applied, any unapplied
updates remain in the change log.

ApplyUpdates does not raise an
exception. Instead, the application should review erroneous records
using Reconcile and the OnReconcileRow event handler or the
FilterChanges and RowError properties for each dataset. For more
details, read "Reviewing errors" at Caching Updates.

So... you should not be expecting an exception but you should be checking the value returned by ApplyUpdates to decide if you can commit or handle errors.

Body:
I'm facing difficulty to find a correct way to get errors on ApplyUpdates method, using FireDAC in memory (CachedUpdates).

Here is my scenario, a master-detail relationship, compounded by:

1 TFDConnection

2 TFDQuery

2 TDataSource

1 TFDSchemaAdapter

Both queries are setted as CachedUpdates and are linked to FDSchemaAdapter.
The FDQuery2 (detail) is linked with the master by MasterSource property. MasterFields and IndexFieldNames are setted as "idMaster". The property FetchOptions.DetailCascade is also checked.

I also have a button to perform the apply:

  try
    FDConnection1.StartTransaction;

    FDSchemaAdapter1.ApplyUpdates(0);

    FDQuery1.CommitUpdates;
    FDQuery2.CommitUpdates;

    FDConnection1.Commit;
  except on E: Exception do
    begin
      FDConnection1.Rollback;
      raise Exception.CreateFmt('Something went wrong. Error: %s', [E.Message]);
    end;
  end;

Everything is working fine so far.

The problem occurs when my database throw an exception, such a constraint violation. The exception is not raising. Consequently, my transaction is not 'rollbacked'.

ps: I'm using Delphi XE7 and Firebird 2.5


答:
Here, it works : See this fiddle</p>

```<code>.nav a[title=Contact] {
        display: none;
    }
</code>```

Title: How to hide menu element with only CSS

Body:
Here, it works : See this fiddle

.nav a[title=Contact] {
        display: none;
    }


问:
Advance on salary request in odoo
I want to create a advance salary module in Odoo v9.
I don't think that there is a module available in odoo for the same.
Functionality goes like this.
An employee request's for advance salary. The request then goes to Team lead and other senior officer like Manager for approve or refuse.
Can anyone suggest me a way that how can I achieve this task.</p>

答:
There is a module for that:

https://www.odoo.com/apps/modules/9.0/employee_advance_salary/

...with a cost.

Maybe you can work on a free version, at lease you have soomething to base on.

Title: Advance on salary request in odoo


问:
Manually creating interactive PDFs
For reasons tedious to explain, I need to create simple PDFs from a C# application without using any third-party libraries. The PDFs in question need to include text and line drawings, and if possible should include images, radio buttons, and text fields. I've been reading Adobe's documentation, which is for the most part straightforward, but so far have been unable to figure out how to make interactive fields actually appear on the document.

For example, consider the partial test PDF document described below:

```<code>1 0 obj
  << /Type /Catalog
     /Pages 2 0 R
     /AcroForm 6 0 R
  >>
endobj

...

6 0 obj
  << /Fields [ 7 0 R ]
     /DR 5 0 R
  >>
endobj

7 0 obj
  << /FT /Btn
     /Ff 65536
     /Kids [ 8 0 R 9 0 R ]
  >>
endobj

8 0 obj
  << /Parent 7 0 R
     /AS /FieldA
     /AP 10 0 R
  >>
endobj

9 0 obj
  << /Parent 8 0 R
     /AS /FieldB
     /AP 10 0 R
  >>
endobj

10 0 obj
  << /N
    << /FieldA 11 0 R
       /FieldB 12 0 R
       /Off 13 0 R
    >>
  >>
endobj

11 0 obj
  << /Length  59 >>
stream
  BT
    /F1 12 Tf
    0 0 Td
    (Field A) Tj
  ET
endstream
endobj

...
</code>```

Where 5 0 R references a resource dictionary containing the font /F1 and 12 0 R and 13 0 R reference streams similar to 11 0 R with the string replaced by Field B and Off respectively.

What changes do I need to make to the document to cause the fields thus defined to actually appear on a page?

Edit: Since mkl asked, here's the whole pdf (extra line breaks removed to save space)

```<code>%PDF-1.7
%¥±ë

1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 200] >> endobj
3 0 obj << /Type /Page /Parent 2 0 R /Resources 5 0 R /Contents 4 0 R >> endobj

4 0 obj << /Length 39 >>
stream
BT /F1 12 Tf 0 0 Td (Hello World) Tj ET
endstream
endobj

5 0 obj << /Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >> >> endobj
6 0 obj << /Fields [ 7 0 R ] /DR 5 0 R >> endobj
7 0 obj << /FT /Btn /Ff 65536 /Kids [ 8 0 R 9 0 R ] >> endobj
8 0 obj << /Parent 7 0 R /AS /FieldA /AP 10 0 R >> endobj
9 0 obj << /Parent 7 0 R /AS /FieldB /AP 10 0 R >> endobj
10 0 obj << /N << /FieldA 11 0 R /FieldB 12 0 R /Off 13 0 R >> >> endobj

11 0 obj << /Length 59 >>
stream
BT /F1 12 Tf 0 0 Td (Field A) Tj ET
endstream
endobj

12 0 obj << /Length 39 >>
stream
BT /F1 12 Tf 0 0 Td (Field B) Tj ET
endstream
endobj

13 0 obj << /Length 39 >>
stream
BT /F1 12 Tf 0 0 Td (Off... ) Tj ET 94
endstream
endobj

xref
0 14
0000000000 65535 f
0000000018 00000 n
0000000068 00000 n
0000000150 00000 n
0000000233 00000 n
0000000327 00000 n
0000000420 00000 n
0000000470 00000 n
0000000533 00000 n
0000000592 00000 n
0000000651 00000 n
0000000727 00000 n
0000000821 00000 n
0000000917 00000 n
trailer << /Root 1 0 R /Size 5 >>
startxref
1013
%%EOF
</code>```

答:
Based on the full file you posted I see several issues (there might be more):

The document catalog does not include an /AcroForm entry

The page does not include an /Annots entry with links to field widgets

Field definitions 8 and 9 are incomplete, they do not include the widget annotation entries. These entries specify the field location on the page

Your field is a pushbutton, it does not have different appearance states, the /N appearance should be a reference to an appearance stream (11, 12 or 13)

Field appearances 11, 12, 13 are invalid, entries such as /Type, /Subtype, /BBox, /Resources are missing

Update: below you can find a minimum file structure for a radio button.

```<code>1 0 obj
<< /Type /Catalog /Version /1.4 /Pages 8 0 R /AcroForm <</Fields [2 0 R ]>> >>
endobj
2 0 obj
<< /FT /Btn /T (Radio) /V /Off /Kids [5 0 R 3 0 R ] /Ff 32768 >>
endobj
3 0 obj
<< /Type /Annot /F 4 /Rect [250  667  270  687  ] /Subtype /Widget /AS /Off /AP << /N << /Two 7 0 R /Off 6 0 R >> >> /Parent 2 0 R /P 4 0 R >>
endobj
4 0 obj
<< /Type /Page /Contents null /MediaBox [0  0  612  792  ] /Parent 8 0 R /Annots [5 0 R 3 0 R ] >>
endobj
5 0 obj
<< /Type /Annot /F 4 /Rect [150  667  170  687  ] /Subtype /Widget /AS /Off /AP << /N << /One 7 0 R /Off 6 0 R >> >> /Parent 2 0 R /P 4 0 R >>
endobj
6 0 obj
<< /Type /XObject /Subtype /Form /BBox [0  0  20  20  ] /Length 74 >>
stream
/DeviceRGB CS 0 0 0 SC 1 w 0.5 0.5 m 19.5 0.5 l 19.5 19.5 l 0.5 19.5 l h S
endstream
endobj
7 0 obj
<< /Type /XObject /Subtype /Form /BBox [0  0  20  20  ] /Length 55 >>
stream
/DeviceRGB cs 0 0 0 sc 0 0 m 20 0 l 20 20 l 0 20 l h f
endstream
endobj
8 0 obj
<< /Type /Pages /Count 1 /Kids [4 0 R ] >>
endobj
</code>```

You can download minimum radio button sample and a more detailed radio button sample.

Using our XFINIUM.PDF Inspector you can visualize the PDF file structure.

Title: Manually creating interactive PDFs

Body:
For reasons tedious to explain, I need to create simple PDFs from a C# application without using any third-party libraries. The PDFs in question need to include text and line drawings, and if possible should include images, radio buttons, and text fields. I've been reading Adobe's documentation, which is for the most part straightforward, but so far have been unable to figure out how to make interactive fields actually appear on the document.

For example, consider the partial test PDF document described below:

1 0 obj
  << /Type /Catalog
     /Pages 2 0 R
     /AcroForm 6 0 R
  >>
endobj

...

6 0 obj
  << /Fields [ 7 0 R ]
     /DR 5 0 R
  >>
endobj

7 0 obj
  << /FT /Btn
     /Ff 65536
     /Kids [ 8 0 R 9 0 R ]
  >>
endobj

8 0 obj
  << /Parent 7 0 R
     /AS /FieldA
     /AP 10 0 R
  >>
endobj

9 0 obj
  << /Parent 8 0 R
     /AS /FieldB
     /AP 10 0 R
  >>
endobj

10 0 obj
  << /N
    << /FieldA 11 0 R
       /FieldB 12 0 R
       /Off 13 0 R
    >>
  >>
endobj

11 0 obj
  << /Length  59 >>
stream
  BT
    /F1 12 Tf
    0 0 Td
    (Field A) Tj
  ET
endstream
endobj

...

Where 5 0 R references a resource dictionary containing the font /F1 and 12 0 R and 13 0 R reference streams similar to 11 0 R with the string replaced by Field B and Off respectively.

What changes do I need to make to the document to cause the fields thus defined to actually appear on a page?

Edit: Since mkl asked, here's the whole pdf (extra line breaks removed to save space)

%PDF-1.7
%¥±ë

1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 200] >> endobj
3 0 obj << /Type /Page /Parent 2 0 R /Resources 5 0 R /Contents 4 0 R >> endobj

4 0 obj << /Length 39 >>
stream
BT /F1 12 Tf 0 0 Td (Hello World) Tj ET
endstream
endobj

5 0 obj << /Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >> >> endobj
6 0 obj << /Fields [ 7 0 R ] /DR 5 0 R >> endobj
7 0 obj << /FT /Btn /Ff 65536 /Kids [ 8 0 R 9 0 R ] >> endobj
8 0 obj << /Parent 7 0 R /AS /FieldA /AP 10 0 R >> endobj
9 0 obj << /Parent 7 0 R /AS /FieldB /AP 10 0 R >> endobj
10 0 obj << /N << /FieldA 11 0 R /FieldB 12 0 R /Off 13 0 R >> >> endobj

11 0 obj << /Length 59 >>
stream
BT /F1 12 Tf 0 0 Td (Field A) Tj ET
endstream
endobj

12 0 obj << /Length 39 >>
stream
BT /F1 12 Tf 0 0 Td (Field B) Tj ET
endstream
endobj

13 0 obj << /Length 39 >>
stream
BT /F1 12 Tf 0 0 Td (Off... ) Tj ET 94
endstream
endobj

xref
0 14
0000000000 65535 f
0000000018 00000 n
0000000068 00000 n
0000000150 00000 n
0000000233 00000 n
0000000327 00000 n
0000000420 00000 n
0000000470 00000 n
0000000533 00000 n
0000000592 00000 n
0000000651 00000 n
0000000727 00000 n
0000000821 00000 n
0000000917 00000 n
trailer << /Root 1 0 R /Size 5 >>
startxref
1013
%%EOF

Body:
Based on the full file you posted I see several issues (there might be more):

The document catalog does not include an /AcroForm entry

The page does not include an /Annots entry with links to field widgets

Field definitions 8 and 9 are incomplete, they do not include the widget annotation entries. These entries specify the field location on the page

Your field is a pushbutton, it does not have different appearance states, the /N appearance should be a reference to an appearance stream (11, 12 or 13)

Field appearances 11, 12, 13 are invalid, entries such as /Type, /Subtype, /BBox, /Resources are missing

Update: below you can find a minimum file structure for a radio button.

1 0 obj
<< /Type /Catalog /Version /1.4 /Pages 8 0 R /AcroForm <</Fields [2 0 R ]>> >>
endobj
2 0 obj
<< /FT /Btn /T (Radio) /V /Off /Kids [5 0 R 3 0 R ] /Ff 32768 >>
endobj
3 0 obj
<< /Type /Annot /F 4 /Rect [250  667  270  687  ] /Subtype /Widget /AS /Off /AP << /N << /Two 7 0 R /Off 6 0 R >> >> /Parent 2 0 R /P 4 0 R >>
endobj
4 0 obj
<< /Type /Page /Contents null /MediaBox [0  0  612  792  ] /Parent 8 0 R /Annots [5 0 R 3 0 R ] >>
endobj
5 0 obj
<< /Type /Annot /F 4 /Rect [150  667  170  687  ] /Subtype /Widget /AS /Off /AP << /N << /One 7 0 R /Off 6 0 R >> >> /Parent 2 0 R /P 4 0 R >>
endobj
6 0 obj
<< /Type /XObject /Subtype /Form /BBox [0  0  20  20  ] /Length 74 >>
stream
/DeviceRGB CS 0 0 0 SC 1 w 0.5 0.5 m 19.5 0.5 l 19.5 19.5 l 0.5 19.5 l h S
endstream
endobj
7 0 obj
<< /Type /XObject /Subtype /Form /BBox [0  0  20  20  ] /Length 55 >>
stream
/DeviceRGB cs 0 0 0 sc 0 0 m 20 0 l 20 20 l 0 20 l h f
endstream
endobj
8 0 obj
<< /Type /Pages /Count 1 /Kids [4 0 R ] >>
endobj

You can download minimum radio button sample and a more detailed radio button sample.

Using our XFINIUM.PDF Inspector you can visualize the PDF file structure.


问:
How to reverse vaadin Grid?
I'm trying to build a simple java application using Spring Boot and Vaadin.
I need to add a table on UI like this: https://www.screencast.com/t/1c4xkr4IE

It could be extended by periods.

Looks like Vaadin Grid element perfectly fits my requirements, but it adds my rows as columns. Is it possible to reverse grid or maybe there is another way to build needed table?

UPDATE

Here are my code:

```<code>@SpringComponent
@UIScope
public class MyDataEditor extends VerticalLayout {
private final MyDataRepository repository;
private MyData myData;

TextField month = new TextField("Period");
TextField numberOfWorkers = new TextField(" Number of workers");
TextField numberOfNewcomers = new TextField("Number of newcomers");
TextField numberOfDismissals = new TextField("Number of dismissals");

Button save = new Button("Save");
Button cancel = new Button("Cancel");
Button delete = new Button("Delete");
CssLayout actions = new CssLayout(save, cancel, delete);

Binder<MyData> binder = new Binder<>(MyData.class);

@Autowired
public MyDataEditor(MyDataRepository repository) {
    this.repository = repository;
    addComponents(month, numberOfWorkers, numberOfNewcomers, numberOfDismissals, actions);
    binder.bindInstanceFields(this);
    setSpacing(true);
    actions.setStyleName(ValoTheme.LAYOUT_COMPONENT_GROUP);
    save.setStyleName(ValoTheme.BUTTON_PRIMARY);
    save.setClickShortcut(ShortcutAction.KeyCode.ENTER);

    save.addClickListener(e -> repository.save(myData));
    delete.addClickListener(e -> repository.delete(myData));
    cancel.addClickListener(e -> editInputData(myData));
    setVisible(false);
}

public interface ChangeHandler {
    void onChange();
}

public final void editMyData(MyData c) {
    if (c == null) {
        setVisible(false);
        return;
    }
    final boolean persisted = c.getMonth() != null;
    if (persisted) {
        myData = repository.findOne(c.getMonth());
    } else {
        myData = c;
    }
    cancel.setVisible(persisted);
    binder.setBean(myData);
    save.focus();
    periodId.selectAll();
}

public void setChangeHandler(ChangeHandler h) {
    save.addClickListener(e -> h.onChange());
    delete.addClickListener(e -> h.onChange());
}

}

@SpringUI
@Theme("valo")
public class VaadinUI extends UI {
private final MyDataRepository repo;
private final MyDataEditor editor;
final Grid<MyData> grid;
private final Button addNewBtn;

@Autowired
public VaadinUI(MyDataRepository repo, MyDataEditor editor) {
    this.repo = repo;
    this.editor = editor;
    this.grid = new Grid<>(MyData.class);
    this.addNewBtn = new Button("Add new month");
}

@Override
protected void init(VaadinRequest request) {

    grid.setHeight(300, Unit.PIXELS);
    grid.setColumns("month", "numberOfWorkers", "numberOfNewcomers", "numberOfDismissals");
    grid.asSingleSelect().addValueChangeListener(e -> {
        editor.editMyData(e.getValue());
    });
    addNewBtn.addClickListener(e -> editor.editMyData(new MyData()));
    editor.setChangeHandler(() -> {
        editor.setVisible(false);
        grid.setItems(repo.findAll());
    });
}
}
</code>```

So what I mean by this question is that I set

```<code>grid.setColumns("month", "numberOfWorkers", "numberOfNewcomers", "numberOfDismissals");
</code>```

and do not find out method like setRows, so my table looks like: https://www.screencast.com/t/ndDY6tXp, but should be like on first picture.

答:
I do believe there is no way to solve it elegantly without CSS or extending the client grid component.

What you could do though is add your data using

```<code>List<MyData> data = repo.findAll();
for(int i = 0; i < data.size(); i++)
    grid.addColumn(i)

//String[] months = data.map(x -> x.month).collect(Collectors.toArray)
//String[] nrWork = data.map(x -> x.nrWork).collect(Collectors.toArray)
grid.addRow(months)
grid.addRow(nrWork)
</code>```

Title: How to reverse vaadin Grid?

Body:
I'm trying to build a simple java application using Spring Boot and Vaadin.
I need to add a table on UI like this: https://www.screencast.com/t/1c4xkr4IE

It could be extended by periods.

Looks like Vaadin Grid element perfectly fits my requirements, but it adds my rows as columns. Is it possible to reverse grid or maybe there is another way to build needed table?

UPDATE

Here are my code:

@SpringComponent
@UIScope
public class MyDataEditor extends VerticalLayout {
private final MyDataRepository repository;
private MyData myData;

TextField month = new TextField("Period");
TextField numberOfWorkers = new TextField(" Number of workers");
TextField numberOfNewcomers = new TextField("Number of newcomers");
TextField numberOfDismissals = new TextField("Number of dismissals");

Button save = new Button("Save");
Button cancel = new Button("Cancel");
Button delete = new Button("Delete");
CssLayout actions = new CssLayout(save, cancel, delete);

Binder<MyData> binder = new Binder<>(MyData.class);

@Autowired
public MyDataEditor(MyDataRepository repository) {
    this.repository = repository;
    addComponents(month, numberOfWorkers, numberOfNewcomers, numberOfDismissals, actions);
    binder.bindInstanceFields(this);
    setSpacing(true);
    actions.setStyleName(ValoTheme.LAYOUT_COMPONENT_GROUP);
    save.setStyleName(ValoTheme.BUTTON_PRIMARY);
    save.setClickShortcut(ShortcutAction.KeyCode.ENTER);

    save.addClickListener(e -> repository.save(myData));
    delete.addClickListener(e -> repository.delete(myData));
    cancel.addClickListener(e -> editInputData(myData));
    setVisible(false);
}

public interface ChangeHandler {
    void onChange();
}

public final void editMyData(MyData c) {
    if (c == null) {
        setVisible(false);
        return;
    }
    final boolean persisted = c.getMonth() != null;
    if (persisted) {
        myData = repository.findOne(c.getMonth());
    } else {
        myData = c;
    }
    cancel.setVisible(persisted);
    binder.setBean(myData);
    save.focus();
    periodId.selectAll();
}

public void setChangeHandler(ChangeHandler h) {
    save.addClickListener(e -> h.onChange());
    delete.addClickListener(e -> h.onChange());
}

}

@SpringUI
@Theme("valo")
public class VaadinUI extends UI {
private final MyDataRepository repo;
private final MyDataEditor editor;
final Grid<MyData> grid;
private final Button addNewBtn;

@Autowired
public VaadinUI(MyDataRepository repo, MyDataEditor editor) {
    this.repo = repo;
    this.editor = editor;
    this.grid = new Grid<>(MyData.class);
    this.addNewBtn = new Button("Add new month");
}

@Override
protected void init(VaadinRequest request) {

    grid.setHeight(300, Unit.PIXELS);
    grid.setColumns("month", "numberOfWorkers", "numberOfNewcomers", "numberOfDismissals");
    grid.asSingleSelect().addValueChangeListener(e -> {
        editor.editMyData(e.getValue());
    });
    addNewBtn.addClickListener(e -> editor.editMyData(new MyData()));
    editor.setChangeHandler(() -> {
        editor.setVisible(false);
        grid.setItems(repo.findAll());
    });
}
}

So what I mean by this question is that I set

grid.setColumns("month", "numberOfWorkers", "numberOfNewcomers", "numberOfDismissals");

and do not find out method like setRows, so my table looks like: https://www.screencast.com/t/ndDY6tXp, but should be like on first picture.

Body:
I do believe there is no way to solve it elegantly without CSS or extending the client grid component.

What you could do though is add your data using

List<MyData> data = repo.findAll();
for(int i = 0; i < data.size(); i++)
    grid.addColumn(i)

//String[] months = data.map(x -> x.month).collect(Collectors.toArray)
//String[] nrWork = data.map(x -> x.nrWork).collect(Collectors.toArray)
grid.addRow(months)
grid.addRow(nrWork)


问:
Retrieve value TR in javascript
Goal:

Retrieve the value "2TR" from "MARSSTANDGATA132TR" in javascript.

Need to retrieve the index number of number 2.

Problem:

Just don't know what is the right syntax to do it?

Info:

*The value "TR" is always in the end of the word.

*The number "2" of "TR" is always changing. it is only a single number, no two or 3 numbers.

*The address and address number is always changing.

*When you execute the regex code and it cannot find the TR in the end of the word, then you cannot retrieve the requested result.

function myFunction() {
    var str = "MARSSTANDGATA132TR";
    var n = str.search("TR");
    document.getElementById("demo").innerHTML = n;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="myFunction()">Test</button>

<p id="demo"></p></code>```

Thank you!

答:
Since TR is always at the end of sting, than you do not need to use regex here.

Take last two symbols, check if it's TR, if yes - take third symbol from the end of string - else - do error processing:

var str = "MARSSTANDGATA132TR";

if (str.slice(-2) == 'TR') {
  console.log(''+str.slice(-3, -2) + ' and index is ' + (str.length - 3));
} else {
  console.log('no TR');
}```

Title: Retrieve value TR in javascript

Body:
Goal:

Retrieve the value "2TR" from "MARSSTANDGATA132TR" in javascript.

Need to retrieve the index number of number 2.

Problem:

Just don't know what is the right syntax to do it?

Info:

*The value "TR" is always in the end of the word.

*The number "2" of "TR" is always changing. it is only a single number, no two or 3 numbers.

*The address and address number is always changing.

*When you execute the regex code and it cannot find the TR in the end of the word, then you cannot retrieve the requested result.

function myFunction() {
    var str = "MARSSTANDGATA132TR";
    var n = str.search("TR");
    document.getElementById("demo").innerHTML = n;
}

<button onclick="myFunction()">Test</button>

Thank you!


问:
How can we predict using RandomForestClassifier obtained from pyspark.ml
I am doing a text classification and I have built a model using the pipeline method. I have created the RF classifier object and have set the features column and the label column that I obtained in my previous steps (steps not shown).

I am fitting my training data which I have created using a dataframe and it has the columns "labels" and "sentences". The labels are different question types. The DF looks like,

```<code>training = sqlContext.createDataFrame([
("DESC:manner", "How did serfdom develop in and then leave Russia ?"),
("DESC:def", "What does '' extended definition '' mean and how would one a paper on it ? "),
("HUM:ind", " Who was The Pride of the Yankees ?")
], ["label", "sentence"])
</code>```

The code for the pipeline is,

```<code>rf = RandomForestClassifier().setFeaturesCol("features").setLabelCol("idxlabel")
pipeline = Pipeline(stages=[pos, tokenizer, hashingTF, idf, indexer,rf])
model = pipeline.fit(training)
</code>```

So now I can get the predictions by using the following code,

```<code>prediction = model.transform(test)
selected = prediction.select("sentence","prediction")
</code>```

I can do the select() operation to get the predicted labels.

But for my use case, there is a stream of data that is coming from Kinesis and it will be only sentences (plain strings). For each sentence, I have to predict the label. But now I am not finding any predict() function when I do dir(model). How come there is no predict() method for the RandomForestClassifier obtained from pyspark.ml? If not, how can I perform my use case successfully? I need the predict() method to satisfy the requirement. What ML algorithm should I use if not RF? Am I doing anything wrong? Can anyone please suggest something? Any help is appreciated. My environment is Spark 1.6 and Python 2.7.

答:
So I figured it out that there is no predict() method that can be used. So instead, we need to use the transform() method to make predictions. Just remove the label column and create a new dataframe. For example, in my case, I did,

```<code>pred = sqlContext.createDataFrame([("What are liver enzymes ?" ,)], ["sentence"])

prediction = model.transform(pred)
</code>```

And then we can find the prediction using the select() method. Atleast for now, this solution worked successfully for me. Please do let me know if there is any correction or a better approach than this.

Body:
I am doing a text classification and I have built a model using the pipeline method. I have created the RF classifier object and have set the features column and the label column that I obtained in my previous steps (steps not shown).

I am fitting my training data which I have created using a dataframe and it has the columns "labels" and "sentences". The labels are different question types. The DF looks like,

training = sqlContext.createDataFrame([
("DESC:manner", "How did serfdom develop in and then leave Russia ?"),
("DESC:def", "What does '' extended definition '' mean and how would one a paper on it ? "),
("HUM:ind", " Who was The Pride of the Yankees ?")
], ["label", "sentence"])

The code for the pipeline is,

rf = RandomForestClassifier().setFeaturesCol("features").setLabelCol("idxlabel")
pipeline = Pipeline(stages=[pos, tokenizer, hashingTF, idf, indexer,rf])
model = pipeline.fit(training)

So now I can get the predictions by using the following code,

prediction = model.transform(test)
selected = prediction.select("sentence","prediction")

I can do the select() operation to get the predicted labels.

But for my use case, there is a stream of data that is coming from Kinesis and it will be only sentences (plain strings). For each sentence, I have to predict the label. But now I am not finding any predict() function when I do dir(model). How come there is no predict() method for the RandomForestClassifier obtained from pyspark.ml? If not, how can I perform my use case successfully? I need the predict() method to satisfy the requirement. What ML algorithm should I use if not RF? Am I doing anything wrong? Can anyone please suggest something? Any help is appreciated. My environment is Spark 1.6 and Python 2.7.

Body:
So I figured it out that there is no predict() method that can be used. So instead, we need to use the transform() method to make predictions. Just remove the label column and create a new dataframe. For example, in my case, I did,

pred = sqlContext.createDataFrame([("What are liver enzymes ?" ,)], ["sentence"])

prediction = model.transform(pred)

And then we can find the prediction using the select() method. Atleast for now, this solution worked successfully for me. Please do let me know if there is any correction or a better approach than this.


问:
Undefined global variable but showing in view of Angular 2
I am confused with my codes in Angular 2. In my ts file I have:

```<code>    import { Test } from '../../../../models/test';
    import { TestService } from '../../../../services/test.service';
    import { Job} from '../../../../models/job';
    import { JobService } from '../../../../services/job.service';

    export class TestTakeMcComponent implements OnInit {
          company_name: string;
          test: Test;
          job: Job;

          constructor(
            private testService: TestService,
            private jobService: JobService
          ) { }
          ngOnInit() {
            this.getTest();
            this.getJob(this.test.id);
          }
          getTest(){
            this.testService.getById(40).subscribe(
              test => {
               if(test.data.data.length != 0){
                 this.test = test.data.data[0];
               }
              }
            );
          }
         getJob(id: number){
           this.jobService.getJobByTestId(id).subscribe();
         }
    }
</code>```

And in my HTML file I have:

```<code><h3 class="box-title">{{ test?.title }} </h3>
</code>```

Surely, the data binding {{ test?.title }} is working and showing the data. But during the call of another function getJob(this.test.id) on my ts file, it says an undefined parameter.
How this became undefined when it is showing perfectly in the view? I wanted to use the data inside this.test variable to other functions but I cannot since it is undefined.
Please someone has the same issue with me and how did you fix this problem. Thank you.

答:
Replace you code with this :

```<code>import { Test } from '../../../../models/test';
    import { TestService } from '../../../../services/test.service';

    export class TestTakeMcComponent implements OnInit {
          company_name: string;
          test: Test;

          constructor(
            private testService: TestService
          ) { }
          ngOnInit() {
            this.getTest();
            // console.log(this.test);
          }
          getTest(){
            this.testService.getById(40).subscribe(
              test => {
               if(test.data.data.length != 0){
                 this.test = test.data.data[0];
                 console.log(this.test);
                 this.getJob();
               }
              }
            );
          }

          getJob(){
              this.jobService.getJobByTestId(this.test.id).subscribe();
         }
    }
</code>```

You have just put the console.log() at wrong place.

As this.testService.getById(40).subscribe is async part , so

```<code>ngOnInit() {
    this.getTest();
    // at this time we'll not have this.test ;
    // console.log(this.test);
}
</code>```

Body:
I am confused with my codes in Angular 2. In my ts file I have:

    import { Test } from '../../../../models/test';
    import { TestService } from '../../../../services/test.service';
    import { Job} from '../../../../models/job';
    import { JobService } from '../../../../services/job.service';

    export class TestTakeMcComponent implements OnInit {
          company_name: string;
          test: Test;
          job: Job;

          constructor(
            private testService: TestService,
            private jobService: JobService
          ) { }
          ngOnInit() {
            this.getTest();
            this.getJob(this.test.id);
          }
          getTest(){
            this.testService.getById(40).subscribe(
              test => {
               if(test.data.data.length != 0){
                 this.test = test.data.data[0];
               }
              }
            );
          }
         getJob(id: number){
           this.jobService.getJobByTestId(id).subscribe();
         }
    }

And in my HTML file I have:

{{ test?.title }}

Surely, the data binding {{ test?.title }} is working and showing the data. But during the call of another function getJob(this.test.id) on my ts file, it says an undefined parameter.
How this became undefined when it is showing perfectly in the view? I wanted to use the data inside this.test variable to other functions but I cannot since it is undefined.
Please someone has the same issue with me and how did you fix this problem. Thank you.

Body:
Replace you code with this :

import { Test } from '../../../../models/test';
    import { TestService } from '../../../../services/test.service';

    export class TestTakeMcComponent implements OnInit {
          company_name: string;
          test: Test;

          constructor(
            private testService: TestService
          ) { }
          ngOnInit() {
            this.getTest();
            // console.log(this.test);
          }
          getTest(){
            this.testService.getById(40).subscribe(
              test => {
               if(test.data.data.length != 0){
                 this.test = test.data.data[0];
                 console.log(this.test);
                 this.getJob();
               }
              }
            );
          }

          getJob(){
              this.jobService.getJobByTestId(this.test.id).subscribe();
         }
    }

You have just put the console.log() at wrong place.

As this.testService.getById(40).subscribe is async part , so

ngOnInit() {
    this.getTest();
    // at this time we'll not have this.test ;
    // console.log(this.test);
}


问:
python matplotlib make everything bold
Well , I am making some plots and wants to make everything in bold font. I can can use weight="bold" to make bold font of label to ticks. Can also use the prop={'weight':'bold'} to make the legends lines bold, but I can't make the legend title bold. So, 1st question is there a way to make the legend title bold?

2nd,I tried to used matplotlib latex support to make the title bold, that did it but if I use rc('text', usetex=True) I cant use weight=bold and have to use \textbf{} everytime, also how do I make the ticks bold in this way.

3rd , If I use latex support then the font changes that I don't like. How do use the normal matplotlib font with using latex?

答:
Making everything bold is rather easy. Just add

```<code>plt.rcParams["font.weight"] = "bold"
plt.rcParams["axes.labelweight"] = "bold"
</code>```

at the top of the script.

```<code>import matplotlib.pyplot as plt
plt.rcParams["font.weight"] = "bold"
plt.rcParams["axes.labelweight"] = "bold"

plt.plot([2,3,1], label="foo")
plt.plot([3,1,3], label="bar")

plt.legend(title="Legend Title")
plt.xlabel("xLabel")

plt.show()
</code>```

Title: python matplotlib make everything bold

Body:
Making everything bold is rather easy. Just add

plt.rcParams["font.weight"] = "bold"
plt.rcParams["axes.labelweight"] = "bold"

at the top of the script.

import matplotlib.pyplot as plt
plt.rcParams["font.weight"] = "bold"
plt.rcParams["axes.labelweight"] = "bold"

plt.plot([2,3,1], label="foo")
plt.plot([3,1,3], label="bar")

plt.legend(title="Legend Title")
plt.xlabel("xLabel")

plt.show()


问:
Reading a text file of values 0-1 in R: data gets corrupted when converted to numeric
I am trying to read the simplest of csv files but there seems to be a problem when trying to convert the data to numerical. This is the minimal code and output:

```<code>initialsoltext=read.csv('initialsol.txt', header = FALSE, sep = "")
initialsoltext

output:  V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1 [1  0  0  0  0  1  0  0  1  0]
as.numeric(initialsoltext)
output:  [1] 1 0 0 0 0 1 0 0 1 1
</code>```

The csv file is not the issue since the text is read properly - what can possibly happen during the conversion of the last 0?
I tried replacing the "[" and "]" thinking that maybe the last bracket was read as a 1 but it doesn't make a difference.
Thanks to anyone who can help,

答:
You can use lapply to apply a function to all columns of a data.frame. To read the file using read.csv and then apply the gsub function Andrew Gustar wrote to all columns, try:

```<code>initialsoltext <- read.csv('initialsol.txt', header = FALSE, sep = "",
  stringsAsFactors = FALSE)
initialsoltext[] <- lapply(initialsoltext, function(x) {
  as.numeric(gsub(pattern = "[\\[\\]]", replacement = "", x, perl = TRUE))})

> initialsoltext
  V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1  1  0  0  0  0  1  0  0  1   0
</code>```

Body:
I am trying to read the simplest of csv files but there seems to be a problem when trying to convert the data to numerical. This is the minimal code and output:

initialsoltext=read.csv('initialsol.txt', header = FALSE, sep = "")
initialsoltext

output:  V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1 [1  0  0  0  0  1  0  0  1  0]
as.numeric(initialsoltext)
output:  [1] 1 0 0 0 0 1 0 0 1 1

The csv file is not the issue since the text is read properly - what can possibly happen during the conversion of the last 0?
I tried replacing the "[" and "]" thinking that maybe the last bracket was read as a 1 but it doesn't make a difference.
Thanks to anyone who can help,

Body:
You can use lapply to apply a function to all columns of a data.frame. To read the file using read.csv and then apply the gsub function Andrew Gustar wrote to all columns, try:

initialsoltext <- read.csv('initialsol.txt', header = FALSE, sep = "",
  stringsAsFactors = FALSE)
initialsoltext[] <- lapply(initialsoltext, function(x) {
  as.numeric(gsub(pattern = "[\\[\\]]", replacement = "", x, perl = TRUE))})

> initialsoltext
  V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1  1  0  0  0  0  1  0  0  1   0


问:
Items obtained using retrofit2 when selected, is not shown in the spinner
Items are not displayed on the spinner initially too.When one clicks on the spinner we can see that it is populated and the data obtained from the web api(json array) using retrofit2 is shown.The selected item is neither shown on the spinner nor gets set to the edittext.

Code:

```<code>public class BranchsActivity extends AppCompatActivity {
Button br_add;
String brName,brShortName;
EditText et_BrName,et_BrShName;
Spinner spinner_Branch;
List<BranchResponse> branch;
Integer brId;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_branchs);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    br_add = (Button)findViewById(R.id.bt_bradd);
    et_BrName = (EditText)findViewById(R.id.editTextBrName);
    et_BrShName = (EditText)findViewById(R.id.editTextBrShName);
    spinner_Branch = (Spinner)findViewById(R.id.spinner_br);
    final ArrayList<String> brList = new ArrayList<>();

            Callback <List<BranchResponse>> callback = new Callback<List<BranchResponse>>() {
                @Override
                public void onResponse(Response<List<BranchResponse>> response, Retrofit retrofit) {
                    if (response.isSuccess()) {
                         branch = response.body();
                        brList.clear();
                        for(int i=0;i<branch.size();i++){
                            brName= branch.get(i).getBrName();
                            brShortName = branch.get(i).getBrShortName();
                            brId = branch.get(i).getBranchId();
                            brList.add(brName);

                        }
                        brList.add(0,"Select a Branch");
                        Toast.makeText(getApplicationContext(), "Successful!", Toast.LENGTH_SHORT).show();

                    }else
                        Toast.makeText(getApplicationContext(), response.raw().message().toString(), Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(Throwable t) {
                    Toast.makeText(getApplicationContext(), "failure!", Toast.LENGTH_SHORT).show();

                }
            };
            ApiManager.getApi().getService().getBranch().enqueue(callback);

    spinner_Branch.setAdapter(new ArrayAdapter<String>(BranchsActivity.this,android.R.layout.simple_spinner_dropdown_item, brList));
    spinner_Branch.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
    @Override
    public void onItemSelected(AdapterView<?>parent,View view,int position,long id){
 //This toast is also not shown when the item is selected
        Toast.makeText(getApplicationContext(), "item selected!", Toast.LENGTH_SHORT).show();
        et_BrName.setText(branch.get(position).getBrName());
        et_BrShName.setText(branch.get(position).getBrShortName());
        Toast.makeText(parent.getContext(),
                "On Item Select : \n" + parent.getItemAtPosition(position-1).toString(),
                Toast.LENGTH_LONG).show();
 }
        @Override
        public void onNothingSelected(AdapterView<?>arg0){

        }
    });

}
</code>```

I have gone through almost all of the posts dealing with spinner issues and tried all of the suggested answers but none of them solved this problem.

答:
```<code>ArrayAdapter<String> mAdapter;
mAdapter = new ArrayAdapter<String>(BranchsActivity.this,android.R.layout.simple_spinner_dropdown_item, brList);
spinner_Branch.setAdapter(mAdapter);

Callback <List<BranchResponse>> callback = new Callback<List<BranchResponse>>() {
            @Override
            public void onResponse(Response<List<BranchResponse>> response, Retrofit retrofit) {
                if (response.isSuccess()) {
                     branch = response.body();
                    brList.clear();
                    for(int i=0;i<branch.size();i++){
                        brName= branch.get(i).getBrName();
                        brShortName = branch.get(i).getBrShortName();
                        brId = branch.get(i).getBranchId();
                        brList.add(brName);

                    }

                    brList.add(0,"Select a Branch");
                    mAdapter.notifydatasetchanged();
                    Toast.makeText(getApplicationContext(), "Successful!", Toast.LENGTH_SHORT).show();

                }else
                    Toast.makeText(getApplicationContext(), response.raw().message().toString(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(Throwable t) {
                Toast.makeText(getApplicationContext(), "failure!", Toast.LENGTH_SHORT).show();

            }
        };
        ApiManager.getApi().getService().getBranch().enqueue(callback);
</code>```

Body:
Items are not displayed on the spinner initially too.When one clicks on the spinner we can see that it is populated and the data obtained from the web api(json array) using retrofit2 is shown.The selected item is neither shown on the spinner nor gets set to the edittext.

Code:

public class BranchsActivity extends AppCompatActivity {
Button br_add;
String brName,brShortName;
EditText et_BrName,et_BrShName;
Spinner spinner_Branch;
List<BranchResponse> branch;
Integer brId;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_branchs);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    br_add = (Button)findViewById(R.id.bt_bradd);
    et_BrName = (EditText)findViewById(R.id.editTextBrName);
    et_BrShName = (EditText)findViewById(R.id.editTextBrShName);
    spinner_Branch = (Spinner)findViewById(R.id.spinner_br);
    final ArrayList<String> brList = new ArrayList<>();

            Callback <List<BranchResponse>> callback = new Callback<List<BranchResponse>>() {
                @Override
                public void onResponse(Response<List<BranchResponse>> response, Retrofit retrofit) {
                    if (response.isSuccess()) {
                         branch = response.body();
                        brList.clear();
                        for(int i=0;i<branch.size();i++){
                            brName= branch.get(i).getBrName();
                            brShortName = branch.get(i).getBrShortName();
                            brId = branch.get(i).getBranchId();
                            brList.add(brName);

                        }
                        brList.add(0,"Select a Branch");
                        Toast.makeText(getApplicationContext(), "Successful!", Toast.LENGTH_SHORT).show();

                    }else
                        Toast.makeText(getApplicationContext(), response.raw().message().toString(), Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(Throwable t) {
                    Toast.makeText(getApplicationContext(), "failure!", Toast.LENGTH_SHORT).show();

                }
            };
            ApiManager.getApi().getService().getBranch().enqueue(callback);

    spinner_Branch.setAdapter(new ArrayAdapter<String>(BranchsActivity.this,android.R.layout.simple_spinner_dropdown_item, brList));
    spinner_Branch.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
    @Override
    public void onItemSelected(AdapterView<?>parent,View view,int position,long id){
 //This toast is also not shown when the item is selected
        Toast.makeText(getApplicationContext(), "item selected!", Toast.LENGTH_SHORT).show();
        et_BrName.setText(branch.get(position).getBrName());
        et_BrShName.setText(branch.get(position).getBrShortName());
        Toast.makeText(parent.getContext(),
                "On Item Select : \n" + parent.getItemAtPosition(position-1).toString(),
                Toast.LENGTH_LONG).show();
 }
        @Override
        public void onNothingSelected(AdapterView<?>arg0){

        }
    });

}

I have gone through almost all of the posts dealing with spinner issues and tried all of the suggested answers but none of them solved this problem.


问:
Android: Incoming call listener without permission
I know that we can listen phone state by broadcast receiver with filter

action android:name="android.intent.action.PHONE_STATE"

but this way requires permission

uses-permission android:name="android.permission.READ_PHONE_STATE"

How to determine the incoming GSM call whithout this permission?

P.S.

I'm sure that this is possibly because Whatsapp doing it.

 When I'm talking on the Whatsapp audio calls and then got incoming gsm call - whatsapp checking it and set self call to pause. How do they understand that need set pause?

Whatsapp has READ_PHONE_STATE permission in Manifest file, but I check calls on Android 6 and not granted this permission. This permission was disabled.

When this permission is disabled my Receiver doesn't receive action  android.intent.action.PHONE_STATE and PhoneStateListener is not working.

答:
I found solution without this permission.

First of all (when our sip call start) we need request audio focus with lisener

```<code> mAudioManager.requestAudioFocus(afChangeListener, AudioManager.STREAM_VOICE_CALL, AudioManager.AUDIOFOCUS_GAIN);
</code>```

The afChangeListener can tell us then someboby changed audio focus and then we can check current audio channel. If current mode is AudioManager.MODE_IN_CALL or AudioManager.MODE_RINGTONE then we know that gsm call started.

```<code>AudioManager.OnAudioFocusChangeListener afChangeListener =
        new AudioManager.OnAudioFocusChangeListener() {
            public void onAudioFocusChange(int focusChange) {

                if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
                    // Permanent loss of audio focus
                    // Pause playback immediately
                } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
                    ScheduledExecutorService scheduler = App.getInstance().obtainScheduler();
                    scheduler.schedule(() -> {
                         Logging.i(TAG, "onAudioFocusChange defer mode = " + mAudioManager.getMode());
                         switch (mAudioManager.getMode()) {
                             case AudioManager.MODE_RINGTONE:
                             case AudioManager.MODE_IN_CALL:
                                 //**there we can start standby mode**
                                 break;
                         }
                    }, 100, TimeUnit.MILLISECONDS);

                } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
                    Logging.i(TAG, "onAudioFocusChange AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK");
                    // Lower the volume, keep playing
                } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                    // Your app has been granted audio focus again
                    //**there we can stop standby mode**
                }

            }
        };
</code>```

Body:
I found solution without this permission.

First of all (when our sip call start) we need request audio focus with lisener

 mAudioManager.requestAudioFocus(afChangeListener, AudioManager.STREAM_VOICE_CALL, AudioManager.AUDIOFOCUS_GAIN);

The afChangeListener can tell us then someboby changed audio focus and then we can check current audio channel. If current mode is AudioManager.MODE_IN_CALL or AudioManager.MODE_RINGTONE then we know that gsm call started.

AudioManager.OnAudioFocusChangeListener afChangeListener =
        new AudioManager.OnAudioFocusChangeListener() {
            public void onAudioFocusChange(int focusChange) {

                if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
                    // Permanent loss of audio focus
                    // Pause playback immediately
                } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
                    ScheduledExecutorService scheduler = App.getInstance().obtainScheduler();
                    scheduler.schedule(() -> {
                         Logging.i(TAG, "onAudioFocusChange defer mode = " + mAudioManager.getMode());
                         switch (mAudioManager.getMode()) {
                             case AudioManager.MODE_RINGTONE:
                             case AudioManager.MODE_IN_CALL:
                                 //**there we can start standby mode**
                                 break;
                         }
                    }, 100, TimeUnit.MILLISECONDS);

                } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
                    Logging.i(TAG, "onAudioFocusChange AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK");
                    // Lower the volume, keep playing
                } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                    // Your app has been granted audio focus again
                    //**there we can stop standby mode**
                }

            }
        };


问:
Tcl Expect: How can you expect 2 matches in 1 line
How can you expect 2 matches in 1 line</p>

```<code>expect "New password*" | "Retype"
send "something\r
</code>```

答:
You can use -re flag to enable the regular expression support.

```<code> expect -re "New password*|Retype"
 send "something\r"
</code>```

Body:
How can you expect 2 matches in 1 line

expect "New password*" | "Retype"
send "something\r

Body:
You can use -re flag to enable the regular expression support.

 expect -re "New password*|Retype"
 send "something\r"


问:
Ada: How to read variable length strings from command line
I am doing a multi-stack program with opcodes that look like the following:

```<code>I2 Sam
I3 Bobby
I1 Steve
D3
I3 Jonathan
</code>```

"I" means insert and the number is which stack, "D" means to delete and number is which stack. My question is, how do I read each of these from the command line and determine which operation to perform? The names are of variable length, and I cannot use heap memory. The one thing I can do is, since the list of possible names is known, is make the names into an enumeration type. Thanks!

答:
If you are reading the values from standard input and are using at least Ada 2005, this method will work:</p>

```<code>with Ada.Text_IO;

procedure Foo is
   use Ada.Text_IO;
begin
   while not End_Of_File loop
      declare
         Cur_Line : constant String := Get_Line;
      begin
         -- process the line here
      end;
   end loop;
end Foo;
</code>```

Body:
I am doing a multi-stack program with opcodes that look like the following:

I2 Sam
I3 Bobby
I1 Steve
D3
I3 Jonathan

"I" means insert and the number is which stack, "D" means to delete and number is which stack. My question is, how do I read each of these from the command line and determine which operation to perform? The names are of variable length, and I cannot use heap memory. The one thing I can do is, since the list of possible names is known, is make the names into an enumeration type. Thanks!

Body:
If you are reading the values from standard input and are using at least Ada 2005, this method will work:

with Ada.Text_IO;

procedure Foo is
   use Ada.Text_IO;
begin
   while not End_Of_File loop
      declare
         Cur_Line : constant String := Get_Line;
      begin
         -- process the line here
      end;
   end loop;
end Foo;


问:
Incorrect syntax near '.'. Sql Server 2008
I'm trying to do a SQL query Join with Function it gives me error this error:

```<code>SELECT *
  FROM Tbl a
  CROSS APPLY V_TBL_STR(a.Number)
</code>```

What can be the error?
Thanks

答:
```<code>Use below query :

SELECT * FROM Tbl AS a
CROSS APPLY (SELECT [DBO].[V_TBL_STR](a.Number) [Number]) AS T
</code>```

Body:
I'm trying to do a SQL query Join with Function it gives me error this error:

SELECT *
  FROM Tbl a
  CROSS APPLY V_TBL_STR(a.Number)

What can be the error?
Thanks


问:
How to hide menu element with only CSS
I have these menu elements I am trying to hide but I cannot seem to only select the middle option called 'Contact'. I cannot edit the html directly so am using CSS to override the style.

Essentially I just want to hide the item called 'Contact' from appearing. How do I select it using CSS? I have put what I thought might work in the  section, but it's not really working. Any help would be greatly appreciated. Thanks in advance. (Here it is as well: https://jsfiddle.net/amhzv0Lw/4/)

Here's the menu code:

```<code>    <!DOCTYPE html>
    <html>
    <head>
    <style>
    .nav a[title:contact] {
        display: none;
    }
    </style>
    </head>
    <body>

    <ul class="nav navbar-nav navbar-left">
<li><a href="/www.example.com/" title="Home">Home</a></li>
<li><a href="/www.example.com/storepage.aspx" title="Contact">Contact</a></li>
<li><a href="https://www.example.com/login" title="Login">Login</a></li>

    </ul>

    </body>
    </html>
</code>```

答:
Try this :

```<code>.nav>li:nth-child(2){
   display:none;
}
</code>```

please check out the fiddle : https://jsfiddle.net/amhzv0Lw/9/

Title: How to hide menu element with only CSS

Body:
I have these menu elements I am trying to hide but I cannot seem to only select the middle option called 'Contact'. I cannot edit the html directly so am using CSS to override the style.

Essentially I just want to hide the item called 'Contact' from appearing. How do I select it using CSS? I have put what I thought might work in the  section, but it's not really working. Any help would be greatly appreciated. Thanks in advance. (Here it is as well: https://jsfiddle.net/amhzv0Lw/4/)

Here's the menu code:

    <!DOCTYPE html>

Home

Contact

Login

Body:
Try this :

.nav>li:nth-child(2){
   display:none;
}

please check out the fiddle : https://jsfiddle.net/amhzv0Lw/9/


问:
how to pass ID in a link using jquery
I have a book now button, when a user clicks on book now he should be redirected to a order confirmation page. I want to pass type and id in a url using jquery.
want to pass this kind of url - http://localhost/company/order-confirmation?type=course&id=35

How can I do that in jquery.

html:

```<code> <a href="" class="book_now" batch-id="">Book Now</a>
</code>```

Jquery:

```<code>  $('.book_now',template).attr('batch-id', val['batch_id']);
</code>```

答:
You should use the attribute data* (see this link) because the attribute "batch-id" is no valid html.

In regular jQuery, if the link is provided like this:

```<code><a href="http://localhost/company/order-confirmation?type=course" class="book_now" data-batch-id="123">Book Now</a>
</code>```

i would do it like this:

$(document).on('click', '[data-batch-id]', function(e) {
       // Disable link behavior
       e.preventDefault();

       // Save information
       var batchID = $(this).data().batchId,
           href    = $(this).attr('href');

       // Check if any ID is aviable
       if (batchID) {
          // Save the url and perform a page load
          var link = href + '&id=' + batchID;
          window.open(link, '_blank');

       } else {
          // Error handling
          alert('Can\'t find course, no ID provided')
       }

    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Book Now</code>```

Title: how to pass ID in a link using jquery

Body:
I have a book now button, when a user clicks on book now he should be redirected to a order confirmation page. I want to pass type and id in a url using jquery.
want to pass this kind of url - http://localhost/company/order-confirmation?type=course&id=35

How can I do that in jquery.

html:

 Book Now

Jquery:

  $('.book_now',template).attr('batch-id', val['batch_id']);

Body:
You should use the attribute data* (see this link) because the attribute "batch-id" is no valid html.

In regular jQuery, if the link is provided like this:

<a href="http://localhost/company/order-confirmation?type=course" class="book_now" data-batch-id="123">Book Now</a>

i would do it like this:

$(document).on('click', '[data-batch-id]', function(e) {
       // Disable link behavior
       e.preventDefault();

       // Save information
       var batchID = $(this).data().batchId,
           href    = $(this).attr('href');

       // Check if any ID is aviable
       if (batchID) {
          // Save the url and perform a page load
          var link = href + '&id=' + batchID;
          window.open(link, '_blank');

       } else {
          // Error handling
          alert('Can\'t find course, no ID provided')
       }

    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="http://localhost/company/order-confirmation?type=course" class="book_now" data-batch-id="123">Book Now</a>


问:
How to prevent default route to redirect to "#/"?
When I visit http://localhost/ it redirects me to http://localhost/#/. Is it possible to prevent this and stay at http://localhost/ and load a default component when you request root? I need to use HashLocationStrategy because I'm also using ASP.NET Core MVC and its routes in the same project.

```<code>export const HomeRoutes = [
    { path: '', component: HomeComponent },
    { path: 'Home', component: HomeComponent },
];

const MyRoutes: Routes = [
    ...HomeRoutes
];

export const MyRouting = RouterModule.forRoot(MyRoutes, { useHash: true });
</code>```

答:
You are using hash strategy change your export statement with this line</p>

```<code>export const MyRouting = RouterModule.forRoot(MyRoutes, { useHash: false });
</code>```

Body:
When I visit http://localhost/ it redirects me to http://localhost/#/. Is it possible to prevent this and stay at http://localhost/ and load a default component when you request root? I need to use HashLocationStrategy because I'm also using ASP.NET Core MVC and its routes in the same project.

export const HomeRoutes = [
    { path: '', component: HomeComponent },
    { path: 'Home', component: HomeComponent },
];

const MyRoutes: Routes = [
    ...HomeRoutes
];

export const MyRouting = RouterModule.forRoot(MyRoutes, { useHash: true });

Body:
You are using hash strategy change your export statement with this line

export const MyRouting = RouterModule.forRoot(MyRoutes, { useHash: false });


问:
Angular - Add component B inside component A
I have the following structure in my project,

```<code>src
- component-a
-- component-a.component.ts
-- component-a.html
-- component-a.scss
-- component-a.component.spec.ts

- component-b
-- component-b.component.ts
-- component-b.html
-- component-b.scss
-- component-b.component.spec.ts

- app.component.ts
- app.module.ts
- app.html
</code>```

I'm using component-a inside my app.component.ts, so I have included it in declarations in the app.module.ts.

```<code>declarations: [
        App, ComponentA,
    ],
</code>```

And in the app.html: <component-a></component-a>

Now I want to add component-b inside my component-a.
So whatever I tried, when I use <component-b></component-b> inside component-a.html I get this error:

```<code>Unhandled Promise rejection: Template parse errors:
'component-b' is not a known element:
1. If 'component-b' is an Angular component, then verify that it is part of this module.
2. If 'component-b' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("
      [ERROR ->]<component-b></component-b>
"): ng:///AppModule/ComponentA.html@7:6 ; Zone: <root> ; Task: Promise.then ; Value:
</code>```

How do use component-b in component-a.html?

I tried importing component-b in component-a.component.ts

I tried importing and adding component-b in the app.module.ts
declarations.

答:
As we've discussed in the comment section. You can provide ComponentB inside your app.module to import it throughout your app.

```<code>import {NgModule} from '@angular/core';

@NgModule({
  ...
  declarations: [
    AComponent, BComponent
  ]
})
export class AppModule {}
</code>```

http://plnkr.co/edit/H929znCRMcqlwuI4ySvp?p=preview

Body:
I have the following structure in my project,

src
- component-a
-- component-a.component.ts
-- component-a.html
-- component-a.scss
-- component-a.component.spec.ts

- component-b
-- component-b.component.ts
-- component-b.html
-- component-b.scss
-- component-b.component.spec.ts

- app.component.ts
- app.module.ts
- app.html

I'm using component-a inside my app.component.ts, so I have included it in declarations in the app.module.ts.

declarations: [
        App, ComponentA,
    ],

And in the app.html: <component-a></component-a>

Now I want to add component-b inside my component-a.
So whatever I tried, when I use <component-b></component-b> inside component-a.html I get this error:

Unhandled Promise rejection: Template parse errors:
'component-b' is not a known element:
1. If 'component-b' is an Angular component, then verify that it is part of this module.
2. If 'component-b' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("
      [ERROR ->]<component-b></component-b>
"): ng:///AppModule/ComponentA.html@7:6 ; Zone: <root> ; Task: Promise.then ; Value:

How do use component-b in component-a.html?

I tried importing component-b in component-a.component.ts

I tried importing and adding component-b in the app.module.ts
declarations.

Body:
As we've discussed in the comment section. You can provide ComponentB inside your app.module to import it throughout your app.

import {NgModule} from '@angular/core';

@NgModule({
  ...
  declarations: [
    AComponent, BComponent
  ]
})
export class AppModule {}

http://plnkr.co/edit/H929znCRMcqlwuI4ySvp?p=preview