问:
python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>
I'm trying to make a script that gets data out from an sqlite3 database, but I have run in to a problem.

The field in the database is of type text and the contains a html formated text. see the text below

```<code><html>
<head>
<title>Yahoo!</title>
</head>
<body>
<style type="text/css">
html {}
.yshortcuts {border-bottom:none !important;}
.ReadMsgBody {width:100%;}
.ExternalClass{width:100%;}
</style>
<table cellpadding="0" cellspacing="0" bgcolor="#ffffff">
<tr>
<td width="550" valign="top" align="left">

    <table cellpadding="0" cellspacing="0" width="500">
        <tr>
            <td colspan="3"><img        src="http://mail.yimg.com/nq/assets/sharedmessages/v1/us/logo.gif" width="292" height="51" style="display:block;" border="0" alt="Yahoo! Mail"></td>
        </tr>
        <tr>
            <td rowspan="3" width="1" bgcolor="#c7c4ca"></td>
            <td width="498" height="1" bgcolor="#c7c4ca"></td>
            <td rowspan="3" width="1" bgcolor="#c7c4ca"></td>
        </tr>
        <tr>
            <td width="498" valign="top" align="left">
            <table cellpadding="0" cellspacing="0">
                <tr>
                    <td width="498" bgcolor="#61399d" align="left" valign="top">
                    <table cellspacing="0" cellpadding="0"><tr><td height="24"></td></tr></table>
                    <div style="font-family:Arial, Helvetica, sans-serif;font-size:23px;line-height:27px;margin-bottom:10px;color:#ffffff;margin-left:15px;"><span style="color:#ffffff;text-decoration:none;font-weight:bold;line-height:27px;">Välkommen till Yahoo! Mail.</span></div>
                    <div style="font-family:Arial, Helvetica, sans-serif;font-size:22px;line-height:26px;margin-bottom:1px;color:#ffffff;margin-left:15px;margin-bottom:7px;margin-right:15px;">Ansluta och dela går snabbt och enkelt och är tillgängligt överallt.</div>
                    </td>
                </tr>
                <tr>
                    <td><img src="http://mail.yimg.com/nq/assets/sharedmessages/v1/all/b1.gif" width="498" height="18" style="display:block;" border="0"></td>
                </tr>
            </table>
            <table cellpadding="0" cellspacing="0" width="498">
                <tr>
                    <td width="292" valign="top">
                    <table cellpadding="0" cellspacing="0">
                        <tr>
                            <td><img src="http://mail.yimg.com/nq/assets/sharedmessages/v1/all/grad.gif" width="292" height="9" style="display:block;"></td>
                        </tr>
                        <tr>
                            <td width="292" bgcolor="#ffffff" align="left" valign="top">
                            <table cellspacing="0" cellpadding="0"><tr><td height="11"></td></tr></table>
                            <div style="margin-left:15px;">
                                <div style="font-family:Arial, Helvetica, sans-serif;font-size:14px;line-height:18px;color:#333333;margin-bottom:11px;font-weight:bold;">Det är lätt som en plätt att komma igång.</div>
                                <table cellpadding="0" cellspacing="0" width="267">
                                    <tr>
                                        <td width="16" align="left" valign="top"><div style="font-family:Arial, Helvetica, sans-serif;font-size:14px;line-height:16px;color:#61399d;margin-bottom:9px;font-weight:bold;">1. </div></td>
                                        <td align="left" valign="top"><div style="font-family:Arial, Helvetica, sans-serif;font-size:13px;line-height:16px;color:#61399d;margin-bottom:9px;"><a rel="nofollow" target="_blank" href="http://us-mg999.mail.yahoo.com/neo/launch?action=contacts" style="text-decoration:underline;color:#61399d;"><span>Lägg till alla dina kontakter på en plats</span></a>.</div></td>
                                    </tr>
                                    <tr>
                                        <td align="left" valign="top"><div style="font-family:Arial, Helvetica, sans-serif;font-size:14px;line-height:16px;color:#61399d;margin-bottom:9px;font-weight:bold;">2. </div></td>
                                        <td align="left" valign="top"><div style="font-family:Arial, Helvetica, sans-serif;font-size:13px;line-height:16px;color:#61399d;margin-bottom:9px;"><a rel="nofollow" target="_blank" href="http://mrd.mail.yahoo.com/themes" style="text-decoration:underline;color:#61399d;"><span>Anpassa din nya inkorg</span></a>.</div></td>
                                    </tr>
                                    <tr>
                                        <td align="left" valign="top"><div style="font-family:Arial, Helvetica, sans-serif;font-size:14px;line-height:16px;color:#61399d;margin-bottom:9px;font-weight:bold;">3. </div></td>
                                        <td align="left" valign="top"><div style="font-family:Arial, Helvetica, sans-serif;font-size:13px;line-height:16px;color:#61399d;"><a rel="nofollow" target="_blank" href="http://se.overview.mail.yahoo.com/mobile" style="text-decoration:underline;color:#61399d;"><span>Anslut överallt på dina mobila enheter</span></a>.</div></td>
                                    </tr>
                                </table>

                            </div>
                            </td>
                        </tr>
                        <tr><td height="13"></td></tr>
                    </table>
                    </td>
                    <td width="196" valign="top">
                    <table cellpadding="0" cellspacing="0">
                        <tr>
                            <td width="1" bgcolor="#fbfbfd" valign="top"><img src="http://mail.yimg.com/nq/assets/sharedmessages/v1/all/g1.gif" width="1" height="21" style="display:block;"></td>
                            <td width="1" bgcolor="#f5f6fa" valign="top"><img src="http://mail.yimg.com/nq/assets/sharedmessages/v1/all/g2.gif" width="1" height="21" style="display:block;"></td>
                            <td width="1" bgcolor="#e8eaf1" valign="top"><img src="http://mail.yimg.com/nq/assets/sharedmessages/v1/all/g3.gif" width="1" height="21" style="display:block;"></td>
                            <td width="1" bgcolor="#d4d4d4"></td>
                            <td width="186" bgcolor="#f0f0f0" align="left" valign="top">
                            <table cellspacing="0" cellpadding="0"><tr><td height="3">   </td></tr></table>
                            <div style="margin-left:11px;">
                            <div style="font-family:Arial, Helvetica, sans-serif;font-size:13px;line-height:16px;color:#333333;margin-bottom:9px;"><b>Info för dig:</b></div>
                            <div style="font-family:Arial, Helvetica, sans-serif;font-size:12px;color:#43494e;line-height:18px;margin-bottom:10px;">
                            Yahoo!-ID och e-postadress:<br />
                            <div style="font-family:Arial, Helvetica, sans-serif;font-size:12px;color:#43494e;line-height:18px;">
                            Håll ditt konto och inställningar aktuella. <br><a rel="nofollow" target="_blank" href="https://edit.yahoo.com/config/eval_profile" style="text-decoration:underline;color:#61399d;"><span>Mitt konto</span></a>
                            </div>
                            </div>
                            <table cellspacing="0" cellpadding="0"><tr><td height="20"></td></tr></table>
                            </td>
                            <td width="1" bgcolor="#dbdbdb"></td>
                            <td width="1" bgcolor="#ced2de"></td>
                            <td width="1" bgcolor="#dbdfed"></td>
                            <td width="1" bgcolor="#e8ebf3"></td>
                            <td width="1" bgcolor="#f3f4f9"></td>
                            <td width="1" bgcolor="#fafbfc"></td>
                        </tr>
                        <tr>
                            <td colspan="11"><img src="http://mail.yimg.com/nq/assets/sharedmessages/v1/all/b2.gif" width="196" height="8" style="display:block;" border="0"></td>
                        </tr>
                        <tr><td height="13"></td></tr>
                    </table>
                    </td>
                    <td width="10"></td>
                </tr>
            </table>
            </td>
        </tr>
        <tr>
            <td width="498" height="1" bgcolor="#c7c4ca"></td>
        </tr>
    </table>
    <table cellpadding="0" cellspacing="0" width="500">
        <tr>
            <td align="center" valign="top">
            <table cellspacing="0" cellpadding="0"><tr><td height="10"></td></tr></table>
                <div style="font-family:Arial, Helvetica, sans-serif;font-size:11px;line-height:18px;margin-bottom:10px;">
                <a rel="nofollow" target="_blank" href="http://info.yahoo.com/legal/se/yahoo/utos.html" style="text-decoration:underline;color:#61399d;">Yahoo! Villkor för användning</a>   |   <a rel="nofollow" target="_blank" href="http://info.yahoo.com/legal/se/yahoo/mail/atos.html" style="text-decoration:underline;color:#61399d;">Yahoo! Mail –Villkor för användning</a>   |   <a rel="nofollow" target="_blank" href="http://info.yahoo.com/privacy/se/yahoo/details.html" style="text-decoration:underline;color:#61399d;">Yahoo! Sekretesspolicy</a>
                </div>
            </td>
        </tr>
        <tr>
            <td align="left" valign="top">
                <div style="font-family:Arial, Helvetica, sans-serif;font-size:11px;line-height:14px;color:#545454;margin-left:16px;margin-right:14px;">Var god svara inte på detta meddelande. Detta är ett servicemeddelande som rör din användning av Yahoo! Mail. Om du vill veta mer om Yahoo!s användning av personlig information, inklusive användning av webb-beacons i HTML-baserad e-post, kan du läsa vår Yahoo! Sekretesspolicy. Yahoo!s adress är 701 First Avenue, Sunnyvale, CA 94089, USA.<br /><br />RefID: lp-1037111</div>
            </td>
        </tr>
    </table>

    </td>
</tr>
</table>
<img width="1" height="1" src="http://pclick.internal.yahoo.com/p/s=2143684696">
</body>
</html>`
</code>```

and the python code that try to extract the data is as follows.

```<code>>>> import sqlite3
>>> conn = sqlite3.connect('C:/temp/Mobils/export/com.yahoo.mobile.client.android.mail/databases/mail.db')
>>> c = conn.cursor()
>>> conn.row_factory=sqlite3.Row
>>> c.execute('select body from messages_1 where _id=7')
<sqlite3.Cursor object at 0x0000000001FB78F0>
>>> r = c.fetchone()
>>> r.keys()
['body']
>>> print(r['body'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python32\lib\encodings\cp850.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>
>>>
</code>```

Does anybody have any idea of how to print/write this to a file. Yes I know that this is printed to stdout, but I get the same UnicodeEncodeError when I try to write to a file. I tried both write method of a file object and print(r['body'], file=f).

答: for me  using export PYTHONIOENCODING=UTF-8 before executing python command worked .

Body:
I'm trying to make a script that gets data out from an sqlite3 database, but I have run in to a problem.

The field in the database is of type text and the contains a html formated text. see the text below

<title>Yahoo!</title>

Välkommen till Yahoo! Mail.

Ansluta och dela går snabbt och enkelt och är tillgängligt överallt.

Det är lätt som en plätt att komma igång.

1.

Lägg till alla dina kontakter på en plats.

2.

Anpassa din nya inkorg.

3.

Anslut överallt på dina mobila enheter.

Info för dig:

                            Yahoo!-ID och e-postadress:

                            Håll ditt konto och inställningar aktuella.
Mitt konto

                Yahoo! Villkor för användning   |   Yahoo! Mail –Villkor för användning   |   Yahoo! Sekretesspolicy

Var god svara inte på detta meddelande. Detta är ett servicemeddelande som rör din användning av Yahoo! Mail. Om du vill veta mer om Yahoo!s användning av personlig information, inklusive användning av webb-beacons i HTML-baserad e-post, kan du läsa vår Yahoo! Sekretesspolicy. Yahoo!s adress är 701 First Avenue, Sunnyvale, CA 94089, USA.

RefID: lp-1037111

`

and the python code that try to extract the data is as follows.

>>> import sqlite3
>>> conn = sqlite3.connect('C:/temp/Mobils/export/com.yahoo.mobile.client.android.mail/databases/mail.db')
>>> c = conn.cursor()
>>> conn.row_factory=sqlite3.Row
>>> c.execute('select body from messages_1 where _id=7')
<sqlite3.Cursor object at 0x0000000001FB78F0>
>>> r = c.fetchone()
>>> r.keys()
['body']
>>> print(r['body'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python32\lib\encodings\cp850.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>
>>>

Does anybody have any idea of how to print/write this to a file. Yes I know that this is printed to stdout, but I get the same UnicodeEncodeError when I try to write to a file. I tried both write method of a file object and print(r['body'], file=f).


来源: stackexchange

问:
how to check password contain username on word or special characters in PHP
i have username and password, i need to check if password are specific on username or not

My Code is

```<code>$username = "paul.gilbert";
$password = "Paul@2019";
if (stripos($password,$username) !== false) {
    echo "password contains username";
}else{
    echo "good password";
}
</code>```

how to check if i have username and password like this?

答:
```<code><?php
/***************************************
Change the special character with blank.
explode username by blank
$username [0] - First name
$username [1] - Last name

Make it  case insensitive use  strtolower function
*****************************************/

$username = explode(' ', (preg_replace('/[^A-Za-z0-9 -]+/', ' ', 'paul.gilbert')));

$Firstname = strtolower($username[0]);
$lastname = strtolower($username[1]);

$password = strtolower(preg_replace('/[^A-Za-z0-9 -]+/', ' ', 'Paul@2019'));

//check if password contains first name or last name of username
if (stripos($password,$Firstname) !== false || stripos($password,$lastname) !== false) {
    echo "password contains username";
}else{
    //If not contains make it good password
    echo "good password";
}

?>
</code>```

Solution 2- if you want 3 words like "pau" or "aul". Use preg_match

```<code>//check if password contains first name or last name of username
if(preg_match("/\b{$Firstname}\b/i", $password) || preg_match("/\b{$lastname}\b/i", $password)) {
    echo "password contains username";
}else{
    //If not contains make it good password
    echo "good password";
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
i have username and password, i need to check if password are specific on username or not

My Code is

$username = "paul.gilbert";
$password = "Paul@2019";
if (stripos($password,$username) !== false) {
    echo "password contains username";
}else{
    echo "good password";
}

how to check if i have username and password like this?

Body:
<?php
/***************************************
Change the special character with blank.
explode username by blank
$username [0] - First name
$username [1] - Last name

Make it  case insensitive use  strtolower function
*****************************************/

$username = explode(' ', (preg_replace('/[^A-Za-z0-9 -]+/', ' ', 'paul.gilbert')));

$Firstname = strtolower($username[0]);
$lastname = strtolower($username[1]);

$password = strtolower(preg_replace('/[^A-Za-z0-9 -]+/', ' ', 'Paul@2019'));

//check if password contains first name or last name of username
if (stripos($password,$Firstname) !== false || stripos($password,$lastname) !== false) {
    echo "password contains username";
}else{
    //If not contains make it good password
    echo "good password";
}

?>

Solution 2- if you want 3 words like "pau" or "aul". Use preg_match

//check if password contains first name or last name of username
if(preg_match("/\b{$Firstname}\b/i", $password) || preg_match("/\b{$lastname}\b/i", $password)) {
    echo "password contains username";
}else{
    //If not contains make it good password
    echo "good password";
}


问:
How to disable wi-fi on Android device in Appium?
In our test case: I need to disable Wi-Fi at some specific point/action.

I have verified:

```<code>driver[deviceIndex].setConnection(Connection.NONE);
assertEquals(Connection.ALL, driver[deviceIndex].getConnection());
</code>```

But it's not doing anything.

My expectation is "turning OFF wi-fi" and keeping Mobile Data ON.

Current code is doing no action.

答:
In appium you can only toggle the wifi network using driver.toggleWifi() method. That means it will change wifi to off state if it is in on state and vice versa.
To use toggleWifi() method you must use androidDriver. If you are using AppiumDriver you can typecast it to AndroidDriver like following.

```<code>((AndroidDriver) driver).toggleWifi();
</code>```

You can also use setNetworkConnection() method but it also has certain limitaions. The limitations are:

Body:
In our test case: I need to disable Wi-Fi at some specific point/action.

I have verified:

driver[deviceIndex].setConnection(Connection.NONE);
assertEquals(Connection.ALL, driver[deviceIndex].getConnection());

But it's not doing anything.

My expectation is "turning OFF wi-fi" and keeping Mobile Data ON.

Current code is doing no action.

Body:
In appium you can only toggle the wifi network using driver.toggleWifi() method. That means it will change wifi to off state if it is in on state and vice versa.
To use toggleWifi() method you must use androidDriver. If you are using AppiumDriver you can typecast it to AndroidDriver like following.

((AndroidDriver) driver).toggleWifi();

You can also use setNetworkConnection() method but it also has certain limitaions. The limitations are:


问:
Postgres Exception ERROR: syntax error at or near ":" Position: 46
I'm getting SQL exception while executing the below query.

```<code>@Query(value="SELECT * FROM lat_long WHERE ST_DWithin(geom :: geography,ST_SetSRID(ST_MakePoint(:lat, :lang),4326) :: geography,1000);",nativeQuery=true)

List<LatLong>find(@Param("lat")Double lat,@Param("lang")Double lang);
</code>```

Hibernate:

```<code>SELECT
    *
FROM
    lat_long
WHERE
    ST_DWithin(geom : geography,ST_SetSRID(ST_MakePoint(?, ?),4326) : geography,1000);
</code>```

2019-05-28 10:39:55.861  WARN 7374 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 0, SQLState: 42601
2019-05-28 10:39:55.861 ERROR 7374 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : ERROR: syntax error at or near ":"
  Position: 46
2019-05-28 10:39:55.885 ERROR 7374 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause

org.postgresql.util.PSQLException: ERROR: syntax error at or near ":"
  Position: 46
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440) ~[postgresql-42.2.5.jar:42.2.5]
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2183) ~[postgresql-42.2.5.jar:42.2.5]
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:308) ~[postgresql-42.2.5.jar:42.2.5]
    at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:441) ~[postgresql-42.2.5.jar:42.2.5]
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:365) ~[postgresql-42.2.5.jar:42.2.5]
    at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:143) ~[postgresql-42.2.5.jar:42.2.5]
    at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:106) ~[postgresql
```

答:
Hibernate treats the :as a parameter placeholder, messing up your cast.

The easiest way is to use a cast() operator instead:

```<code>SELECT *
FROM lat_long
WHERE ST_DWithin(cast(geom as geography), cast(ST_SetSRID(ST_MakePoint(:lat, :lang),4326) as  geography),1000)
</code>```

Body:
I'm getting SQL exception while executing the below query.

@Query(value="SELECT * FROM lat_long WHERE ST_DWithin(geom :: geography,ST_SetSRID(ST_MakePoint(:lat, :lang),4326) :: geography,1000);",nativeQuery=true)

List<LatLong>find(@Param("lat")Double lat,@Param("lang")Double lang);

Hibernate:

SELECT
    *
FROM
    lat_long
WHERE
    ST_DWithin(geom : geography,ST_SetSRID(ST_MakePoint(?, ?),4326) : geography,1000);

2019-05-28 10:39:55.861  WARN 7374 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 0, SQLState: 42601
2019-05-28 10:39:55.861 ERROR 7374 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : ERROR: syntax error at or near ":"
  Position: 46
2019-05-28 10:39:55.885 ERROR 7374 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause

org.postgresql.util.PSQLException: ERROR: syntax error at or near ":"
  Position: 46
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440) ~[postgresql-42.2.5.jar:42.2.5]
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2183) ~[postgresql-42.2.5.jar:42.2.5]
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:308) ~[postgresql-42.2.5.jar:42.2.5]
    at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:441) ~[postgresql-42.2.5.jar:42.2.5]
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:365) ~[postgresql-42.2.5.jar:42.2.5]
    at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:143) ~[postgresql-42.2.5.jar:42.2.5]
    at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:106) ~[postgresql

Body:
Hibernate treats the :as a parameter placeholder, messing up your cast.

The easiest way is to use a cast() operator instead:

SELECT *
FROM lat_long
WHERE ST_DWithin(cast(geom as geography), cast(ST_SetSRID(ST_MakePoint(:lat, :lang),4326) as  geography),1000)


问:
How can i display a particular product?
I am trying to display a particular product by clicking on it from the list

```<code><ul>
    <% products.each do |product| %>
    <tr>

        <a href="<%= products_path(@product) %>"><%= product.title %> .   </a>
        <br/>

    </tr>
    <% end %>
</ul>
</code>```

Expected results should be products/1 but the result is products.1 and should displays a list of products

答:
Instead of this

```<code> <a href="<%= products_path(@product) %>"><%= product.title %> .   </a>
</code>```

Use rails standard way

```<code><%= link_to product.title, product_path(product)  %>
</code>```

Title: How can i display a particular product?

Body:
I am trying to display a particular product by clicking on it from the list

    <% products.each do |product| %>

        <a href="<%= products_path(@product) %>"><%= product.title %> .

    <% end %>

Expected results should be products/1 but the result is products.1 and should displays a list of products

Body:
Instead of this

 <a href="<%= products_path(@product) %>"><%= product.title %> .   </a>

Use rails standard way

<%= link_to product.title, product_path(product)  %>


问:
Why doesn't my MSBuild project build incrementally?
I have a project which generates a class from its XSD definition, then builds it. My problem is that, even though I specify the inputs and outputs of my Xsd target, it still gets executed every time I build the Visual Studio solution. What could be the problem here?</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="3.5" InitialTargets="Xsd" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <!-- snip -->
  <ItemGroup>
    <Compile Include="Properties\AssemblyInfo.cs" />
    <Compile Include="request.cs">
      <DependentUpon>request.xsd</DependentUpon>
    </Compile>
  </ItemGroup>
  <ItemGroup>
    <None Include="key.snk" />
  </ItemGroup>
  <ItemGroup>
    <Xsd Include="request.xsd" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <Target Name="Xsd" Inputs="@(Xsd)" Outputs="request.cs">
    <Exec Command='"C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\xsd.exe" "@(Xsd)" /c /o:..\.. /n:Order.Messaging' />
  </Target>
</Project>
</code>```

答:
Remove Xsd target from InitialTargets

Initial targets are typically used for error checking.

and add dependency to BeforeBuild Target:

```<code><Target Name="BeforeBuild" DependsOnTargets="Xsd" />
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a project which generates a class from its XSD definition, then builds it. My problem is that, even though I specify the inputs and outputs of my Xsd target, it still gets executed every time I build the Visual Studio solution. What could be the problem here?

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="3.5" InitialTargets="Xsd" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

  <ItemGroup>
    <Compile Include="Properties\AssemblyInfo.cs" />
    <Compile Include="request.cs">
      <DependentUpon>request.xsd</DependentUpon>
    </Compile>
  </ItemGroup>
  <ItemGroup>
    <None Include="key.snk" />
  </ItemGroup>
  <ItemGroup>
    <Xsd Include="request.xsd" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <Target Name="Xsd" Inputs="@(Xsd)" Outputs="request.cs">
    <Exec Command='"C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\xsd.exe" "@(Xsd)" /c /o:..\.. /n:Order.Messaging' />
  </Target>
</Project>

Body:
Remove Xsd target from InitialTargets

Initial targets are typically used for error checking.

and add dependency to BeforeBuild Target:

<Target Name="BeforeBuild" DependsOnTargets="Xsd" />


问:
How to find the unique list entries in a python dataframe?
I have a dataset which has the movie title along with the different genres that it falls under. Each movie has more than one genre. Hence, for the entire dataset I want to find the total number of unique genres that are present.

I am not able to use df.unique() as it is a list in each column of the DataFrame itself.

```<code>movieId title   genres
0   1   Toy Story (1995)    Adventure|Animation|Children|Comedy|Fantasy
1   2   Jumanji (1995)  Adventure|Children|Fantasy
2   3   Grumpier Old Men (1995) Comedy|Romance
3   4   Waiting to Exhale (1995)    Comedy|Drama|Romance
4   5   Father of the Bride Part II (1995)  Comedy
5   6   Heat (1995) Action|Crime|Thriller
6   7   Sabrina (1995)  Comedy|Romance
7   8   Tom and Huck (1995) Adventure|Children
8   9   Sudden Death (1995) Action
9   10  GoldenEye (1995)    Action|Adventure|Thriller
10  11  American President, The (1995)  Comedy|Drama|Romance
11  12  Dracula: Dead and Loving It (1995)  Comedy|Horror
12  13  Balto (1995)    Adventure|Animation|Children
13  14  Nixon (1995)    Drama
14  15  Cutthroat Island (1995) Action|Adventure|Romance
15  16  Casino (1995)   Crime|Drama
16  17  Sense and Sensibility (1995)    Drama|Romance
17  18  Four Rooms (1995)   Comedy
18  19  Ace Ventura: When Nature Calls (1995)   Comedy
19  20  Money Train (1995)  Action|Comedy|Crime|Drama|Thriller
20  21  Get Shorty (1995)   Comedy|Crime|Thriller
21  22  Copycat (1995)  Crime|Drama|Horror|Mystery|Thriller
22  23  Assassins (1995)    Action|Crime|Thriller
23  24  Powder (1995)   Drama|Sci-Fi
24  25  Leaving Las Vegas (1995)    Drama|Romance
25  26  Othello (1995)  Drama
26  27  Now and Then (1995) Children|Drama
27  28  Persuasion (1995)   Drama|Romance
28  29  City of Lost Children, The (Cité des enfants p...
</code>```

This is the dataset for movies.

Under the genres column I want to split Action|Comedy|Crime|Drama|Thriller into Action, Comedy, Crime, Drama, Thriller.

Also for the entire dataset which is as a DataFrame now, I want to find the unique genres.

答:
Try using this approach:</p>

```<code>temp = df.genres.str.split("|").tolist() # this will return a list of lists for all the genres
import functools
import operator

unique_genres = set(functools.reduce(operator.concat, temp)) #this will flatten the list of lists and ultimately call the set to get the unique genres. Use len to get the number of unique genres afterwards
</code>```

Body:
I have a dataset which has the movie title along with the different genres that it falls under. Each movie has more than one genre. Hence, for the entire dataset I want to find the total number of unique genres that are present.

I am not able to use df.unique() as it is a list in each column of the DataFrame itself.

movieId title   genres
0   1   Toy Story (1995)    Adventure|Animation|Children|Comedy|Fantasy
1   2   Jumanji (1995)  Adventure|Children|Fantasy
2   3   Grumpier Old Men (1995) Comedy|Romance
3   4   Waiting to Exhale (1995)    Comedy|Drama|Romance
4   5   Father of the Bride Part II (1995)  Comedy
5   6   Heat (1995) Action|Crime|Thriller
6   7   Sabrina (1995)  Comedy|Romance
7   8   Tom and Huck (1995) Adventure|Children
8   9   Sudden Death (1995) Action
9   10  GoldenEye (1995)    Action|Adventure|Thriller
10  11  American President, The (1995)  Comedy|Drama|Romance
11  12  Dracula: Dead and Loving It (1995)  Comedy|Horror
12  13  Balto (1995)    Adventure|Animation|Children
13  14  Nixon (1995)    Drama
14  15  Cutthroat Island (1995) Action|Adventure|Romance
15  16  Casino (1995)   Crime|Drama
16  17  Sense and Sensibility (1995)    Drama|Romance
17  18  Four Rooms (1995)   Comedy
18  19  Ace Ventura: When Nature Calls (1995)   Comedy
19  20  Money Train (1995)  Action|Comedy|Crime|Drama|Thriller
20  21  Get Shorty (1995)   Comedy|Crime|Thriller
21  22  Copycat (1995)  Crime|Drama|Horror|Mystery|Thriller
22  23  Assassins (1995)    Action|Crime|Thriller
23  24  Powder (1995)   Drama|Sci-Fi
24  25  Leaving Las Vegas (1995)    Drama|Romance
25  26  Othello (1995)  Drama
26  27  Now and Then (1995) Children|Drama
27  28  Persuasion (1995)   Drama|Romance
28  29  City of Lost Children, The (Cité des enfants p...

This is the dataset for movies.

Under the genres column I want to split Action|Comedy|Crime|Drama|Thriller into Action, Comedy, Crime, Drama, Thriller.

Also for the entire dataset which is as a DataFrame now, I want to find the unique genres.

Body:
Try using this approach:

temp = df.genres.str.split("|").tolist() # this will return a list of lists for all the genres
import functools
import operator

unique_genres = set(functools.reduce(operator.concat, temp)) #this will flatten the list of lists and ultimately call the set to get the unique genres. Use len to get the number of unique genres afterwards


问:
Using firebase realtime database my entries are around 300 items. now not getting response from firebase in datasnapshot
I am using Firebase realtime database in my android app. My entries in table is around 300. I'm not able to get the data from the Firebase in Datasnapshot. Sometimes it works after loading 20 minutes. How can I access my data & response fast. It's working well & very fast in iOS with same database & same queries.

```<code>private void checkBookingInfo() throws Exception {

    mDatabaseReference.child(FireBaseConstants.BOOKING_INFO_TABLE).limitToFirst(10).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            if (dataSnapshot != null) {
                countArrival = 0;
                countDeparture = 0;

                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    //check  arrivals date matches with today's date then increment counter
                    if (snapshot.hasChild(FireBaseConstants.ARRIVAL_DATE)) {
                        String currentDate = Utils.getCurrentDate();
                        String arrivalDate = snapshot.child(FireBaseConstants.ARRIVAL_DATE).getValue().toString();
                        String status = snapshot.child(FireBaseConstants.STATUS).getValue().toString();

                        if (currentDate.equalsIgnoreCase(arrivalDate) && !status.equalsIgnoreCase("Cancel")) {
                            countArrival++;
                        }
                    }
                    //check  departure date matches with today's date then increment counter
                    if (snapshot.hasChild(FireBaseConstants.DEPARTURE_DATE)) {
                        String currentDate = Utils.getCurrentDate();
                        String departureDate = snapshot.child(FireBaseConstants.DEPARTURE_DATE).getValue().toString();
                        String status = snapshot.child(FireBaseConstants.STATUS).getValue().toString();
                        if (currentDate.equalsIgnoreCase(departureDate) && !status.equalsIgnoreCase("Cancel")) {
                            countDeparture++;
                        }
                    }
                }
                setValueInEditText();
            } else {

            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.e("notme", "");
        }
    });
}
</code>```

答:
To improve performance of the Firebase query you can add index on the field by which you are ordering Your query. Like

```<code>  {
   "rules": {
      "YOUR_NODE": {
         ".indexOn": ["FIELD1", "FIELD2"]
     }
   }
  }
</code>```

You can find the helping link here

Firebase also says here

Important: The onDataChange() method is called every time data is
  changed at the specified database reference, including changes to
  children. To limit the size of your snapshots, attach only at the
  highest level needed for watching changes. For example, attaching a
  listener to the root of your database is not recommended.

But even if the index is not applied still 20 minutes is much time, you need to check your source code there could be some other issue in the UI, may be data is coming but not populating in the UI.

Body:
I am using Firebase realtime database in my android app. My entries in table is around 300. I'm not able to get the data from the Firebase in Datasnapshot. Sometimes it works after loading 20 minutes. How can I access my data & response fast. It's working well & very fast in iOS with same database & same queries.

private void checkBookingInfo() throws Exception {

    mDatabaseReference.child(FireBaseConstants.BOOKING_INFO_TABLE).limitToFirst(10).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            if (dataSnapshot != null) {
                countArrival = 0;
                countDeparture = 0;

                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    //check  arrivals date matches with today's date then increment counter
                    if (snapshot.hasChild(FireBaseConstants.ARRIVAL_DATE)) {
                        String currentDate = Utils.getCurrentDate();
                        String arrivalDate = snapshot.child(FireBaseConstants.ARRIVAL_DATE).getValue().toString();
                        String status = snapshot.child(FireBaseConstants.STATUS).getValue().toString();

                        if (currentDate.equalsIgnoreCase(arrivalDate) && !status.equalsIgnoreCase("Cancel")) {
                            countArrival++;
                        }
                    }
                    //check  departure date matches with today's date then increment counter
                    if (snapshot.hasChild(FireBaseConstants.DEPARTURE_DATE)) {
                        String currentDate = Utils.getCurrentDate();
                        String departureDate = snapshot.child(FireBaseConstants.DEPARTURE_DATE).getValue().toString();
                        String status = snapshot.child(FireBaseConstants.STATUS).getValue().toString();
                        if (currentDate.equalsIgnoreCase(departureDate) && !status.equalsIgnoreCase("Cancel")) {
                            countDeparture++;
                        }
                    }
                }
                setValueInEditText();
            } else {

            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.e("notme", "");
        }
    });
}

Body:
To improve performance of the Firebase query you can add index on the field by which you are ordering Your query. Like

  {
   "rules": {
      "YOUR_NODE": {
         ".indexOn": ["FIELD1", "FIELD2"]
     }
   }
  }

You can find the helping link here

Firebase also says here

Important: The onDataChange() method is called every time data is
  changed at the specified database reference, including changes to
  children. To limit the size of your snapshots, attach only at the
  highest level needed for watching changes. For example, attaching a
  listener to the root of your database is not recommended.

But even if the index is not applied still 20 minutes is much time, you need to check your source code there could be some other issue in the UI, may be data is coming but not populating in the UI.


问:
Application Crashing due to API issue
I am coding for an android application code is exactly right. I have set min sdk version 21 but when I try to install application in android set having sdk version 21 application crashes but it works good in other android mobile phones having sdk greater then 21. Please help to resolve the issue.</p>

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.fyp"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
</code>```

答: Change your target sdk version to 21 and min sdk version to 20 and try</p>

Title: Application Crashing due to API issue

Body:
I am coding for an android application code is exactly right. I have set min sdk version 21 but when I try to install application in android set having sdk version 21 application crashes but it works good in other android mobile phones having sdk greater then 21. Please help to resolve the issue.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.fyp"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}


问:
how to avoid spaces in *ngFor loops in angular?
Im creating a Star-Rating Component in Angular using fontawesome fa fa-star  and far fa-star.

This is the HTML Output, I want inside my component.

```<code><div style="font-size: 80%">
    <i class="fa fa-star"></i>
    <i class="fa fa-star"></i>
    <i class="fa fa-star"></i>
    <i class="fa fa-star"></i>
    <i class="far fa-star"></i>
</div>
</code>```

If I do this with a Loop, I'm somehow getting spaces between the stars

```<code><div style="font-size: 80%">
    <ng-container *ngFor="let i of [1,2,3,4,5]">
        <i class="{{i <= 4 ? 'fa' : 'far'}} fa-star"></i>
    </ng-container>
</div>
</code>```

But it is fixed by making the loop a oneliner. So either deleting newlines in the code or switching the *ngFor... part to the  Tag and deleting the <ng-container> will fix the issue.

```<code><div style="font-size: 80%">
    <ng-container *ngFor="let i of [1,2,3,4,5]"><i class="{{i <= 4 ? 'fa' : 'far'}} fa-star"></i></ng-container>
</div>

<!-- Both work -->

<div style="font-size: 80%">
    <i *ngFor="let i of [1,2,3,4,5]" class="{{i <= 4 ? 'fa' : 'far'}} fa-star"></i>
</div>
</code>```

So how do I achieve this without making sure that the ngFor loop is only on one line?

How to prevent the space when the iteration body has a newline?

答:
This is a result of  tags being inline, so HTML treats whitespace between them as space.

One workaround would be to set the font-size to zero and un-zero it on the child elements:

```<code><div style="font-size: 0">
    <ng-container *ngFor="let i of [1,2,3,4,5]">
        <i style="font-size: 80%" class="{{i <= 4 ? 'fa' : 'far'}} fa-star"></i>
    </ng-container>
</div>
</code>```

You can read more about the problem and this and other solutions in this article.

Body:
Im creating a Star-Rating Component in Angular using fontawesome fa fa-star  and far fa-star.

This is the HTML Output, I want inside my component.

If I do this with a Loop, I'm somehow getting spaces between the stars

    <ng-container *ngFor="let i of [1,2,3,4,5]">
        <i class="{{i <= 4 ? 'fa' : 'far'}} fa-star">
    </ng-container>

But it is fixed by making the loop a oneliner. So either deleting newlines in the code or switching the *ngFor... part to the  Tag and deleting the <ng-container> will fix the issue.

    <ng-container *ngFor="let i of [1,2,3,4,5]"><i class="{{i <= 4 ? 'fa' : 'far'}} fa-star"></ng-container>

    <i *ngFor="let i of [1,2,3,4,5]" class="{{i <= 4 ? 'fa' : 'far'}} fa-star">

So how do I achieve this without making sure that the ngFor loop is only on one line?

How to prevent the space when the iteration body has a newline?

Body:
This is a result of <i> tags being inline, so HTML treats whitespace between them as space.

One workaround would be to set the font-size to zero and un-zero it on the child elements:

<div style="font-size: 0">
    <ng-container *ngFor="let i of [1,2,3,4,5]">
        <i style="font-size: 80%" class="{{i <= 4 ? 'fa' : 'far'}} fa-star"></i>
    </ng-container>
</div>

You can read more about the problem and this and other solutions in this article.


问:
How to Highlight the `Selected row` in a `Listview` using Fragments
I created a listview that is acting as a menu. When the user chooses a specific menu, another fragment will show up on the right portion.

Please see this image:

The problem is, the icon and the title are only highlighted and not the whole selected row. How can I highlight the selected row instead of the icon and title only?

This is my code:

fragment_inventory_list.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".InventoryListFragment"
    android:layout_marginTop="@dimen/padding_50"
    android:orientation="vertical"
    android:background="?android:attr/activatedBackgroundIndicator">

   <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:orientation="vertical">

       <ListView
           android:id="@+id/inventorylist_listview"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:choiceMode="singleChoice"
           android:listSelector="@color/light_gray"/>

   </LinearLayout>

</LinearLayout>
</code>```

InventoryListFragment.java

```<code>package com.example.devcash;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.devcash.CustomAdapters.InventoryListAdapter;
import com.example.devcash.Fragments.CategoriesFragment;
import com.example.devcash.Fragments.DiscountsFragment;
import com.example.devcash.Fragments.ProductsFragment;
import com.example.devcash.Fragments.ServicesFragment;
import com.example.devcash.Lists.InventoryList;

import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 */
public class InventoryListFragment extends Fragment implements AdapterView.OnItemClickListener {

    ListView lvinventory;
    ArrayList<InventoryList> list = new ArrayList<InventoryList>();
    InventoryListAdapter adapter;

    public InventoryListFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_inventory_list, container, false);

        lvinventory = (ListView) view.findViewById(R.id.inventorylist_listview);
        adapter = new InventoryListAdapter(getActivity(),list);

        list.add(new InventoryList(R.drawable.ic_product,"Products"));
        list.add(new InventoryList(R.drawable.ic_services,"Services"));
        list.add(new InventoryList(R.drawable.ic_category, "Categories"));
        list.add(new InventoryList(R.drawable.ic_local_offer,"Discounts"));

        lvinventory.setAdapter(adapter);
        lvinventory.setOnItemClickListener(this);

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        InventoryList selectedList = this.list.get(position);

        int icon = selectedList.getIcon();
        String title = selectedList.getInventory_title();

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        switch (position){
            case 0:
                ProductsFragment productsFragment = new ProductsFragment();
                fragmentTransaction.add(R.id.inventorylist_fragmentcontainer, productsFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
            case 1:
                ServicesFragment servicesFragment = new ServicesFragment();
                fragmentTransaction.add(R.id.inventorylist_fragmentcontainer, servicesFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
            case  2:
                CategoriesFragment categoriesFragment = new CategoriesFragment();
                fragmentTransaction.add(R.id.inventorylist_fragmentcontainer, categoriesFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
            case 3:
                DiscountsFragment discountsFragment = new DiscountsFragment();
                fragmentTransaction.add(R.id.inventorylist_fragmentcontainer, discountsFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
        }
    }
}
</code>```

答:
I would recommend to use recyclerview over listview , like @Ferran already answered for listview

RecyclerView vs. ListView

i would like to answer the same for recyclerview

```<code>public class AdapterClass extends RecyclerView.Adapter<AdapterClass.ViewHolder> {
        private int selected_position = -1;

        @Override
        public void onBindViewHolder(PlacesLocationAdapter.ViewHolder holder, final int position) {
            if (selected_position == position) {
                // do your stuff here like
                //Change selected item background color and Show sub item views

            } else {
                  // do your stuff here like
                  //Change  unselected item background color and Hide sub item views
            }
  // rest of the code here

    holder.linelayout.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {
              if(selected_position==position){
                        selected_position=-1;
                        notifyDataSetChanged();
                        return;
                    }
                    selected_position = position;
                    notifyDataSetChanged();

            }
        });

    //rest of the code here

     }

}
</code>```

Body:
I created a listview that is acting as a menu. When the user chooses a specific menu, another fragment will show up on the right portion.

Please see this image:

The problem is, the icon and the title are only highlighted and not the whole selected row. How can I highlight the selected row instead of the icon and title only?

This is my code:

fragment_inventory_list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".InventoryListFragment"
    android:layout_marginTop="@dimen/padding_50"
    android:orientation="vertical"
    android:background="?android:attr/activatedBackgroundIndicator">

   <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:orientation="vertical">

       <ListView
           android:id="@+id/inventorylist_listview"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:choiceMode="singleChoice"
           android:listSelector="@color/light_gray"/>

   </LinearLayout>

</LinearLayout>

InventoryListFragment.java

package com.example.devcash;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.devcash.CustomAdapters.InventoryListAdapter;
import com.example.devcash.Fragments.CategoriesFragment;
import com.example.devcash.Fragments.DiscountsFragment;
import com.example.devcash.Fragments.ProductsFragment;
import com.example.devcash.Fragments.ServicesFragment;
import com.example.devcash.Lists.InventoryList;

import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 */
public class InventoryListFragment extends Fragment implements AdapterView.OnItemClickListener {

    ListView lvinventory;
    ArrayList<InventoryList> list = new ArrayList<InventoryList>();
    InventoryListAdapter adapter;

    public InventoryListFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_inventory_list, container, false);

        lvinventory = (ListView) view.findViewById(R.id.inventorylist_listview);
        adapter = new InventoryListAdapter(getActivity(),list);

        list.add(new InventoryList(R.drawable.ic_product,"Products"));
        list.add(new InventoryList(R.drawable.ic_services,"Services"));
        list.add(new InventoryList(R.drawable.ic_category, "Categories"));
        list.add(new InventoryList(R.drawable.ic_local_offer,"Discounts"));

        lvinventory.setAdapter(adapter);
        lvinventory.setOnItemClickListener(this);

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        InventoryList selectedList = this.list.get(position);

        int icon = selectedList.getIcon();
        String title = selectedList.getInventory_title();

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        switch (position){
            case 0:
                ProductsFragment productsFragment = new ProductsFragment();
                fragmentTransaction.add(R.id.inventorylist_fragmentcontainer, productsFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
            case 1:
                ServicesFragment servicesFragment = new ServicesFragment();
                fragmentTransaction.add(R.id.inventorylist_fragmentcontainer, servicesFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
            case  2:
                CategoriesFragment categoriesFragment = new CategoriesFragment();
                fragmentTransaction.add(R.id.inventorylist_fragmentcontainer, categoriesFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
            case 3:
                DiscountsFragment discountsFragment = new DiscountsFragment();
                fragmentTransaction.add(R.id.inventorylist_fragmentcontainer, discountsFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
        }
    }
}

Body:
I would recommend to use recyclerview over listview , like @Ferran already answered for listview

RecyclerView vs. ListView

i would like to answer the same for recyclerview

public class AdapterClass extends RecyclerView.Adapter<AdapterClass.ViewHolder> {
        private int selected_position = -1;

        @Override
        public void onBindViewHolder(PlacesLocationAdapter.ViewHolder holder, final int position) {
            if (selected_position == position) {
                // do your stuff here like
                //Change selected item background color and Show sub item views

            } else {
                  // do your stuff here like
                  //Change  unselected item background color and Hide sub item views
            }
  // rest of the code here

    holder.linelayout.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {
              if(selected_position==position){
                        selected_position=-1;
                        notifyDataSetChanged();
                        return;
                    }
                    selected_position = position;
                    notifyDataSetChanged();

            }
        });

    //rest of the code here

     }

}


问:
Finding out which Linux process was executing when system locked up by evaluating CPU registers
I need to find out what is executing when my Linux (Debian) system hangs (x86 platform). I managed to extract the following information just before the system locked up:

```<code>es: 0x7B
cs: 0x73
ss: 0x7B
ds: 0x7B
fs: 0x0
gs: 0x33
ldtbase: 0x0
tr: 0x80
dr7: 0x400
dr6: 0xFFFF0FF0
eax: 0xBFBDE820
ecx: 0xA908F9A0
edx: 0xB708A000
ebx: 0xB71B5278
esp: 0xBFBDE730
ebp: 0xBFBDE838
esi: 0x9D36B58
edi: 0x9D50BB8
eip: 0xB71B13E8
eflags: 0x203206
cr3: 0x1E9DE000
cr0: 0x80050033
</code>```

From the values of the segment registers, I know that when Linux hangs, it's on user-space mode. What I would like to find out is which process/library is causing the crash, and ideally which exact part of it.

By looking at CR3 and EIP, I should be able to get this information but I am getting confused. As far as I know, the virtual address 0xB71B13E8 is relative to the page table used (0x1E9DE000).
Now, the instruction pointer points to a physical address, right? I think I should convert this (EIP value) to a virtual address which would be the offset of the page table pointed by CR3.

Could anyone please help me a bit on that?

答:
Where did you extract the information from?

If this is a usermode crash/lockup, presumably this information is from a core dump (you can dump cores on the fly without necessarily killing the subject)

In that case, use gdb /usr/bin/myprogrambinary corefile

And navigate using gdb commands bt, info threads, info shared, thread apply all bt full etc

The usefulness of all this will greatly improve with debugging symbols for the various libraries installed on your system (depending on your distro, install the relevant *-dbg packages)

Body:
I need to find out what is executing when my Linux (Debian) system hangs (x86 platform). I managed to extract the following information just before the system locked up:

es: 0x7B
cs: 0x73
ss: 0x7B
ds: 0x7B
fs: 0x0
gs: 0x33
ldtbase: 0x0
tr: 0x80
dr7: 0x400
dr6: 0xFFFF0FF0
eax: 0xBFBDE820
ecx: 0xA908F9A0
edx: 0xB708A000
ebx: 0xB71B5278
esp: 0xBFBDE730
ebp: 0xBFBDE838
esi: 0x9D36B58
edi: 0x9D50BB8
eip: 0xB71B13E8
eflags: 0x203206
cr3: 0x1E9DE000
cr0: 0x80050033

From the values of the segment registers, I know that when Linux hangs, it's on user-space mode. What I would like to find out is which process/library is causing the crash, and ideally which exact part of it.

By looking at CR3 and EIP, I should be able to get this information but I am getting confused. As far as I know, the virtual address 0xB71B13E8 is relative to the page table used (0x1E9DE000).
Now, the instruction pointer points to a physical address, right? I think I should convert this (EIP value) to a virtual address which would be the offset of the page table pointed by CR3.

Could anyone please help me a bit on that?


问:
How to aggregate two messages in single route?
I have one route that collects headers and sends a request to another queue from which I wait for an answer (I only need the response body). The problem is that both the headers and the answer I want to receive in one message in one route, but now I get two messages in one route (I need to aggregate the response body and headers).
how to do it?

```<code>from("jms:queue:aaa")
    .log("incoming message")
    .process(exchange -> {
        exchange.getIn().setHeader("c", c);
        exchange.getIn().setHeader("d", d);
        exchange.getIn().setHeader("a", a);
        exchange.getIn().setHeader("b", b);
        exchange.getIn().setBody("2+3");
    })
    .removeHeaders("*", "a", "b", "c", "d")
    .setHeader("JMSReplyTo", simple("bbb"))
        //send request
    .to(ExchangePattern.InOnly, "jms:ccc?preserveMessageQos=true&includeSentJMSMessageID=true")
        //trying to send headers from this route to bbb
    .to(ExchangePattern.InOut, "jms:bbb")
.end();
from("jms:bbb")
    .log("${headers}\n${}body")
.end();
</code>```

from("jms:bbb")
this is the route in which I want to combine the results from .

.to(ExchangePattern.InOnly, "jms:ccc?preserveMessageQos=true& includeSentJMSMessageID=true") .

and .

.to (ExchangePattern.InOut, "jms: bbb")

UPD:

```<code>public class AggregationStrategyImpl implements AggregationStrategy {

    private static final Logger log = LoggerFactory.getLogger(AggregationStrategyImpl.class);

    @Override
    public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
        if(newExchange == null)
            newExchange = oldExchange;
        String a = oldExchange.getIn().getHeader("a", String.class);
        String b = oldExchange.getIn().getHeader("b", String.class);
        String c = oldExchange.getIn().getHeader("c", String.class);
        String d = oldExchange.getIn().getHeader("d", String.class);
        newExchange.getIn().setHeader("a", a);
        newExchange.getIn().setHeader("b", b);
        newExchange.getIn().setHeader("c", c);
        newExchange.getIn().setHeader("d", d);

        return newExchange;
    }
}

</code>```

```<code> .setHeader("JMSReplyTo", simple("bbb"))
                    .multicast(aggregationStrategy)
                    .to(ExchangePattern.InOnly, "jms:ccc?preserveMessageQos=true&includeSentJMSMessageID=true")
                    .to(ExchangePattern.OutOnly, "jms:bbb")
</code>```

答:
See here.
It looks like your first if statement doesn't work:

```<code>if(newExchange == null)
  newExchange = oldExchange;
</code>```

This way the newly incoming exchange object will always stay null.
Instead, it should be the other way, because you want to keep oldExchange, when a newExchange comes in:

```<code>if (oldExchange == null) {
    //...
    return newExchange;
} else {
    //...
    return oldExchange;
}
</code>```

The problem seems to be that you are waiting for newExchange to be null, but there always is a newExchange, if aggregate is called. The very first exchange object to come is a newExchange, too. Instead the first call of aggregate does not have an oldExchange!

Body:
I have one route that collects headers and sends a request to another queue from which I wait for an answer (I only need the response body). The problem is that both the headers and the answer I want to receive in one message in one route, but now I get two messages in one route (I need to aggregate the response body and headers).
how to do it?

from("jms:queue:aaa")
    .log("incoming message")
    .process(exchange -> {
        exchange.getIn().setHeader("c", c);
        exchange.getIn().setHeader("d", d);
        exchange.getIn().setHeader("a", a);
        exchange.getIn().setHeader("b", b);
        exchange.getIn().setBody("2+3");
    })
    .removeHeaders("*", "a", "b", "c", "d")
    .setHeader("JMSReplyTo", simple("bbb"))
        //send request
    .to(ExchangePattern.InOnly, "jms:ccc?preserveMessageQos=true&includeSentJMSMessageID=true")
        //trying to send headers from this route to bbb
    .to(ExchangePattern.InOut, "jms:bbb")
.end();
from("jms:bbb")
    .log("${headers}\n${}body")
.end();

from("jms:bbb")
this is the route in which I want to combine the results from .

.to(ExchangePattern.InOnly, "jms:ccc?preserveMessageQos=true& includeSentJMSMessageID=true") .

and .

.to (ExchangePattern.InOut, "jms: bbb")

UPD:

public class AggregationStrategyImpl implements AggregationStrategy {

    private static final Logger log = LoggerFactory.getLogger(AggregationStrategyImpl.class);

    @Override
    public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
        if(newExchange == null)
            newExchange = oldExchange;
        String a = oldExchange.getIn().getHeader("a", String.class);
        String b = oldExchange.getIn().getHeader("b", String.class);
        String c = oldExchange.getIn().getHeader("c", String.class);
        String d = oldExchange.getIn().getHeader("d", String.class);
        newExchange.getIn().setHeader("a", a);
        newExchange.getIn().setHeader("b", b);
        newExchange.getIn().setHeader("c", c);
        newExchange.getIn().setHeader("d", d);

        return newExchange;
    }
}

 .setHeader("JMSReplyTo", simple("bbb"))
                    .multicast(aggregationStrategy)
                    .to(ExchangePattern.InOnly, "jms:ccc?preserveMessageQos=true&includeSentJMSMessageID=true")
                    .to(ExchangePattern.OutOnly, "jms:bbb")

Body:
See here.
It looks like your first if statement doesn't work:

if(newExchange == null)
  newExchange = oldExchange;

This way the newly incoming exchange object will always stay null.
Instead, it should be the other way, because you want to keep oldExchange, when a newExchange comes in:

if (oldExchange == null) {
    //...
    return newExchange;
} else {
    //...
    return oldExchange;
}

The problem seems to be that you are waiting for newExchange to be null, but there always is a newExchange, if aggregate is called. The very first exchange object to come is a newExchange, too. Instead the first call of aggregate does not have an oldExchange!


问:
Copying files from a series of directories based off a list in a text file
I am attempting to use either rsync or cp in a for loop to copy files matching a list of 200 of names stored on new lines in a .txt file that match filenames with the .pdbqt extension that are in a series of subdirectories with one parent folder. The .txt file looks as follows:

```<code>file01
file02
file08
file75
file45
...
</code>```

I have attempted to use rsync with the following command:

```<code>rsync -a /home/ubuntu/Project/files/pdbqt/*/*.pdbqt \
--files-from=/home/ubuntu/Project/working/output.txt \
/home/ubuntu/Project/files/top/
</code>```

When I run the rsync command I receive:

```<code>rsync error: syntax or usage error (code 1) at options.c(2346) [client=3.1.2]
</code>```

I have written a bash script as follows in an attempt to get that to work:

```<code>#!/bin/bash
for i in "$(cat /home/ubuntu/Project/working/output.txt | tr '\n' '')"; do
    cp /home/ubuntu/Project/files/pdbqt/*/"$i".pdbqt /home/ubuntu/Project/files/top/;
done
</code>```

I understand cat isn't a great command to use but I could not figure out an alternate solution to it, as I am still new to using bash. Running that I get the following error:

```<code>tr: when not truncating set1, string2 must be non-empty
cp: cannot stat '/home/ubuntu/Project/files/pdbqt/*/.pdbqt': No such file or directory
</code>```

I assume that the cp error is thrown as a result of the tr error but I am not sure how else to get rid of the \n that is read from the new line separated list.

The expected results are that from the subdirectories in /pdbqt/ with the 12000 .pdbqt files the 200 files from the output.txt list would be copied from those subdirectories into the /top/ directory.

答:
Your are thinking correctly to think rsync. rsync provides the option --files-from="yourfile" that will rsync all the files in your textfile (relative to the base directory you specify next) to the destination (either host:/dest/path or locally with /dest/path alone)

You will want to specify the --no-R to tell rsync not to use relative filenames since --files-from= takes the base path as the next argument. For example, to transfer all files in your text file to some remote host where the location of the files specified are in the current directory, you could use:

```<code>rsync -uai --no-R --files-from="textfile" ./ host:/dest/path
</code>```

Where the command essentially specifies you read the names to transfer from textfile where the files will be found under ./ (the current directory) and you will transfer the files to host:/dest/path on the host you specify. You can see man 1 rsync for full details.

Body:
I am attempting to use either rsync or cp in a for loop to copy files matching a list of 200 of names stored on new lines in a .txt file that match filenames with the .pdbqt extension that are in a series of subdirectories with one parent folder. The .txt file looks as follows:

file01
file02
file08
file75
file45
...

I have attempted to use rsync with the following command:

rsync -a /home/ubuntu/Project/files/pdbqt/*/*.pdbqt \
--files-from=/home/ubuntu/Project/working/output.txt \
/home/ubuntu/Project/files/top/

When I run the rsync command I receive:

rsync error: syntax or usage error (code 1) at options.c(2346) [client=3.1.2]

I have written a bash script as follows in an attempt to get that to work:

#!/bin/bash
for i in "$(cat /home/ubuntu/Project/working/output.txt | tr '\n' '')"; do
    cp /home/ubuntu/Project/files/pdbqt/*/"$i".pdbqt /home/ubuntu/Project/files/top/;
done

I understand cat isn't a great command to use but I could not figure out an alternate solution to it, as I am still new to using bash. Running that I get the following error:

tr: when not truncating set1, string2 must be non-empty
cp: cannot stat '/home/ubuntu/Project/files/pdbqt/*/.pdbqt': No such file or directory

I assume that the cp error is thrown as a result of the tr error but I am not sure how else to get rid of the \n that is read from the new line separated list.

The expected results are that from the subdirectories in /pdbqt/ with the 12000 .pdbqt files the 200 files from the output.txt list would be copied from those subdirectories into the /top/ directory.

Body:
Your are thinking correctly to think rsync. rsync provides the option --files-from="yourfile" that will rsync all the files in your textfile (relative to the base directory you specify next) to the destination (either host:/dest/path or locally with /dest/path alone)

You will want to specify the --no-R to tell rsync not to use relative filenames since --files-from= takes the base path as the next argument. For example, to transfer all files in your text file to some remote host where the location of the files specified are in the current directory, you could use:

rsync -uai --no-R --files-from="textfile" ./ host:/dest/path

Where the command essentially specifies you read the names to transfer from textfile where the files will be found under ./ (the current directory) and you will transfer the files to host:/dest/path on the host you specify. You can see man 1 rsync for full details.


问:
ASP.NET Core 2 Unable to resolve service for type Microsoft EntityFrameworkCore DbContext
When I run my asp.net core 2 projects I get the following error message:

InvalidOperationException: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContext' while attempting to activate 'ContosoUniversity.Service.Class.StudentService'.

Here is my project structure:

```<code>-- solution 'ContosoUniversity'
----- ContosoUniversity
----- ContosoUniversity.Model
----- ContosoUniversity.Service
</code>```

IEntityService (related code) :

```<code>public interface IEntityService<T> : IService
 where T : BaseEntity
{
    Task<List<T>> GetAllAsync();
}
</code>```

IEntityService (related code) :

```<code>public abstract class EntityService<T> : IEntityService<T> where T : BaseEntity
{
    protected DbContext _context;
    protected DbSet<T> _dbset;

    public EntityService(DbContext context)
    {
        _context = context;
        _dbset = _context.Set<T>();
    }

    public async virtual Task<List<T>> GetAllAsync()
    {
        return await _dbset.ToListAsync<T>();
    }
}
</code>```

Entity :

```<code>public abstract class BaseEntity {

}

public abstract class Entity<T> : BaseEntity, IEntity<T>
{
    public virtual T Id { get; set; }
}
</code>```

IStudentService :

```<code>public interface IStudentService : IEntityService<Student>
{
    Task<Student> GetById(int Id);
}
</code>```

StudentService :

```<code>public class StudentService : EntityService<Student>, IStudentService
{
    DbContext _context;

    public StudentService(DbContext context)
        : base(context)
    {
        _context = context;
        _dbset = _context.Set<Student>();
    }

    public async Task<Student> GetById(int Id)
    {
        return await _dbset.FirstOrDefaultAsync(x => x.Id == Id);
    }
}
</code>```

SchoolContext :

```<code>public class SchoolContext : DbContext
{
    public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
    {
    }

    public DbSet<Course> Courses { get; set; }
    public DbSet<Enrollment> Enrollments { get; set; }
    public DbSet<Student> Students { get; set; }
}
</code>```

And finally here is my Startup.cs class :

```<code>public class Startup
{
    public Startup(IConfiguration configuration, IHostingEnvironment env, IServiceProvider serviceProvider)
    {
        Configuration = configuration;

        var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

        Configuration = builder.Build();

    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<SchoolContext>(option =>
            option.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddScoped<IStudentService, StudentService>();

        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}
</code>```

What should I do to resolve this problem?

答:
I encountered a similar error i.e.

An unhandled exception occurred while processing the request.
InvalidOperationException: Unable to resolve service for type 'MyProjectName.Models.myDatabaseContext' while attempting to activate 'MyProjectName.Controllers.MyUsersController'.

Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)

What I later figured out was... I was missing the following line i.e. adding my database context to services:

```<code>services.AddDbContext<yourDbContext>(option => option.UseSqlServer("Server=Your-Server-Name\\SQLExpress;Database=yourDatabaseName;Trusted_Connection=True;"));
</code>```

Here goes my ConfigureServices method defined in Startup class:

```<code> public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential
                //cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddDbContext<yourDbContext>(option =>
            option.UseSqlServer("Server=Your-Server-Name\\SQLExpress;Database=yourDatabaseName;Trusted_Connection=True;"));

                }
        ...
        ...
    }
</code>```

Basically, when you generated model classes from database, all your database tables were mapped into respective Model classes by creating the "New Scaffolded Item" and choosing the appropriate database context during the scaffolding procedure.
Now, you need to manually register your database context as a service to the services parameter of ConfigureServices method.

Btw, rather than hard coding your connection string, you'll ideally pick it up from the configuration data. I have attempted to keep things simple here.

Body:
When I run my asp.net core 2 projects I get the following error message:

InvalidOperationException: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContext' while attempting to activate 'ContosoUniversity.Service.Class.StudentService'.

Here is my project structure:

-- solution 'ContosoUniversity'
----- ContosoUniversity
----- ContosoUniversity.Model
----- ContosoUniversity.Service

IEntityService (related code) :

public interface IEntityService<T> : IService
 where T : BaseEntity
{
    Task<List<T>> GetAllAsync();
}

IEntityService (related code) :

public abstract class EntityService<T> : IEntityService<T> where T : BaseEntity
{
    protected DbContext _context;
    protected DbSet<T> _dbset;

    public EntityService(DbContext context)
    {
        _context = context;
        _dbset = _context.Set<T>();
    }

    public async virtual Task<List<T>> GetAllAsync()
    {
        return await _dbset.ToListAsync<T>();
    }
}

Entity :

public abstract class BaseEntity {

}

public abstract class Entity<T> : BaseEntity, IEntity<T>
{
    public virtual T Id { get; set; }
}

IStudentService :

public interface IStudentService : IEntityService<Student>
{
    Task<Student> GetById(int Id);
}

StudentService :

public class StudentService : EntityService<Student>, IStudentService
{
    DbContext _context;

    public StudentService(DbContext context)
        : base(context)
    {
        _context = context;
        _dbset = _context.Set<Student>();
    }

    public async Task<Student> GetById(int Id)
    {
        return await _dbset.FirstOrDefaultAsync(x => x.Id == Id);
    }
}

SchoolContext :

public class SchoolContext : DbContext
{
    public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
    {
    }

    public DbSet<Course> Courses { get; set; }
    public DbSet<Enrollment> Enrollments { get; set; }
    public DbSet<Student> Students { get; set; }
}

And finally here is my Startup.cs class :

public class Startup
{
    public Startup(IConfiguration configuration, IHostingEnvironment env, IServiceProvider serviceProvider)
    {
        Configuration = configuration;

        var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

        Configuration = builder.Build();

    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<SchoolContext>(option =>
            option.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddScoped<IStudentService, StudentService>();

        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

What should I do to resolve this problem?

Body:
I encountered a similar error i.e.

An unhandled exception occurred while processing the request.
InvalidOperationException: Unable to resolve service for type 'MyProjectName.Models.myDatabaseContext' while attempting to activate 'MyProjectName.Controllers.MyUsersController'.

Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)

What I later figured out was... I was missing the following line i.e. adding my database context to services:

services.AddDbContext<yourDbContext>(option => option.UseSqlServer("Server=Your-Server-Name\\SQLExpress;Database=yourDatabaseName;Trusted_Connection=True;"));

Here goes my ConfigureServices method defined in Startup class:

 public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential
                //cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddDbContext<yourDbContext>(option =>
            option.UseSqlServer("Server=Your-Server-Name\\SQLExpress;Database=yourDatabaseName;Trusted_Connection=True;"));

                }
        ...
        ...
    }

Basically, when you generated model classes from database, all your database tables were mapped into respective Model classes by creating the "New Scaffolded Item" and choosing the appropriate database context during the scaffolding procedure.
Now, you need to manually register your database context as a service to the services parameter of ConfigureServices method.

Btw, rather than hard coding your connection string, you'll ideally pick it up from the configuration data. I have attempted to keep things simple here.


问:
can we set tabindex for textbox and other controls in javascript
can we set tabindex for input and other html controls using javascript. I've seen this in .net. can we do the same in javascript?

Thanks

答:
You can set tabindex for input all html-elements, in javascript:

```<code>[someElement].tabIndex = [number]
</code>```

Body:
You can set tabindex for input all html-elements, in javascript:

[someElement].tabIndex = [number]


问:
Localization for input field with double value in Razor Pages
In my ViewModel I have a property like this:

```<code>[DisplayFormat(DataFormatString = "{0:0.00}", ApplyFormatInEditMode = true)]
public double SomeDoubleProperty { get; set; }
</code>```

Markup:

```<code><div class="form-group row">
    <label asp-for="ViewModel.SomeDoubleProperty" class="col-sm-3 col-form-label">
        @Localizer[nameof(Model.ViewModel.SomeDoubleProperty)]
    </label>
    <div class="col-sm-9">
        <div class="input-group">
            <div class="input-group-prepend">
                <span class="input-group-text">%</span>
            </div>
            <input asp-for="ViewModel.SomeDoubleProperty"
                   class="form-control">
        </div>
        <span asp-validation-for="ViewModel.SomeDoubleProperty" class="text-danger"></span>
    </div>
</div>
</code>```

After loading the page (with the default value 0) it is shown like this in the input field:

(The current culture and current ui culture of the thread is "de", so the decimal separator "," is the expected one).

But when I now leave the input field, the following validation error is shown:

The field SomeDoubleProperty must be a number.

When replacing the "," with a ".", the validator accepts the value.
How can I achieve that the "," is accepted, too, if the current ui culture is "de"?

答:
Thanks to @Laz Ziya I found a combination that does the trick:

ViewModel:

```<code>    [DisplayFormat(DataFormatString = "{0:0.00}", ApplyFormatInEditMode = true)]
    [Range(0, 100, ErrorMessage = "RangeAttribute_ValidationError")]
    public double SomeDoubleProperty { get; set; }
</code>```

Markup:

```<code>    <div class="form-group row">
        <label asp-for="ViewModel.SomeDoubleProperty" class="col-sm-3 col-form-label">
            @Localizer[nameof(Model.ViewModel.SomeDoubleProperty)]
        </label>
        <div class="col-sm-9">
            <div class="input-group">
                <div class="input-group-prepend">
                    <span class="input-group-text">%</span>
                </div>
                <input asp-for="ViewModel.SomeDoubleProperty"
                       class="form-control"
                       id="some-double-input" digit-count="2">
            </div>
            <span asp-validation-for="ViewModel.SomeDoubleProperty" class="text-danger"></span>
        </div>
    </div>
<partial name="_NumberInputPartial" />
</code>```

NumberInputPartial:

```<code> @using System.Threading;

@*To use this partial add the following attribute to the input element: digit-count="{enter requested digit count here}"*@

<script asp-location="Footer">
    function toLocalizedNumberString(numberAsString, digitCount) {
        var decimalSeparator = '@(Thread.CurrentThread.CurrentUICulture.NumberFormat.NumberDecimalSeparator)';
        var groupSeparator = '@(Thread.CurrentThread.CurrentUICulture.NumberFormat.NumberGroupSeparator)';
          var num = parseFloat(numberAsString.replace(decimalSeparator, '.'));
          return ( num
            .toFixed(digitCount)
            .replace('.', decimalSeparator)
            .replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' + groupSeparator)
            )
    }
    $("input[digit-count]").on("focusin", function () {
        $(this).val($(this).val().replace(@("/[" + Thread.CurrentThread.CurrentUICulture.NumberFormat.NumberGroupSeparator + "]/g"), ""));
    });
    $("input[digit-count]").on("focusout", function () {
        $(this).val(toLocalizedNumberString($(this).val(), $(this).attr("digit-count")));
    });
</script>

<partial name="_ValidationScriptsPartial" />
<localization-validation-scripts></localization-validation-scripts>
</code>```

Body:
In my ViewModel I have a property like this:

[DisplayFormat(DataFormatString = "{0:0.00}", ApplyFormatInEditMode = true)]
public double SomeDoubleProperty { get; set; }

Markup:

        @Localizer[nameof(Model.ViewModel.SomeDoubleProperty)]

                %

            <input asp-for="ViewModel.SomeDoubleProperty"
                   class="form-control">

After loading the page (with the default value 0) it is shown like this in the input field:

(The current culture and current ui culture of the thread is "de", so the decimal separator "," is the expected one).

But when I now leave the input field, the following validation error is shown:

The field SomeDoubleProperty must be a number.

When replacing the "," with a ".", the validator accepts the value.
How can I achieve that the "," is accepted, too, if the current ui culture is "de"?

Body:
Thanks to @Laz Ziya I found a combination that does the trick:

ViewModel:

    [DisplayFormat(DataFormatString = "{0:0.00}", ApplyFormatInEditMode = true)]
    [Range(0, 100, ErrorMessage = "RangeAttribute_ValidationError")]
    public double SomeDoubleProperty { get; set; }

Markup:

    <div class="form-group row">
        <label asp-for="ViewModel.SomeDoubleProperty" class="col-sm-3 col-form-label">
            @Localizer[nameof(Model.ViewModel.SomeDoubleProperty)]
        </label>
        <div class="col-sm-9">
            <div class="input-group">
                <div class="input-group-prepend">
                    <span class="input-group-text">%</span>
                </div>
                <input asp-for="ViewModel.SomeDoubleProperty"
                       class="form-control"
                       id="some-double-input" digit-count="2">
            </div>
            <span asp-validation-for="ViewModel.SomeDoubleProperty" class="text-danger"></span>
        </div>
    </div>
<partial name="_NumberInputPartial" />

NumberInputPartial:

 @using System.Threading;

@*To use this partial add the following attribute to the input element: digit-count="{enter requested digit count here}"*@

<script asp-location="Footer">
    function toLocalizedNumberString(numberAsString, digitCount) {
        var decimalSeparator = '@(Thread.CurrentThread.CurrentUICulture.NumberFormat.NumberDecimalSeparator)';
        var groupSeparator = '@(Thread.CurrentThread.CurrentUICulture.NumberFormat.NumberGroupSeparator)';
          var num = parseFloat(numberAsString.replace(decimalSeparator, '.'));
          return ( num
            .toFixed(digitCount)
            .replace('.', decimalSeparator)
            .replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' + groupSeparator)
            )
    }
    $("input[digit-count]").on("focusin", function () {
        $(this).val($(this).val().replace(@("/[" + Thread.CurrentThread.CurrentUICulture.NumberFormat.NumberGroupSeparator + "]/g"), ""));
    });
    $("input[digit-count]").on("focusout", function () {
        $(this).val(toLocalizedNumberString($(this).val(), $(this).attr("digit-count")));
    });
</script>

<partial name="_ValidationScriptsPartial" />
<localization-validation-scripts></localization-validation-scripts>


问:
How to skip initializing a Git Repository during creation of angular 6 project
Is there any command to skip initializing a Git Repository during angular 6 project creation

I am using ng new [name] command to create angular 6 project. by default it is adding git repository.

ng new [name]

答:
To list the available options

```<code>ng new  --help
</code>```

To skip Git. This is the command

```<code>ng new my-app --skip-git
</code>```

Body:
To list the available options

ng new  --help

To skip Git. This is the command

ng new my-app --skip-git


问:
How to pre-authorize URL to use microphone in Electron (or Chrome)?
I need to pre-authorize a URL to use microphone. It's an internal system accessed via Electron (v4.1.3).

Pre-authorization is required as users use it in some sort of Linux thin client. That is, each day the system bootstrap from an image and then profiles,etc are created. Therefore users would have to click Yes on the access prompt every single day, and if hitting NO just causing headaches to provide them steps to fix as the system requires mic/audio.

I've checked Google Chrome, and apparently it writes the permission on {chrome_profile_dir}\Default\Preferences file.

But on Electron, could not see same behavior on AppData\Roaming\{app.name}\Preferences file. So, to be honest I don't even know where Electron is storing the permission. I deleted the aforementioned folder, but it doesn't ask permission anymore.

Is there a way, like writing to a preference file, I could pre-authorize this? If yes, would write that to the image file.

答:
You could use permission request handlers in electron.
https://electronjs.org/docs/api/session#sessetpermissionrequesthandlerhandler</p>