问:
How to create Generic Response handler for error and validate response using retrofit,rxjava and dagger
I'm trying to create generic architecture to consume complex json structure as follows:

Json Format

```<code>{
"type": "success",
"code": "s-groups-0006",
"description": "Index List successfully",
"result": {
    "asOnDate": 1505457095278,
    "indexList": [
        {
            "change": "22.35",
            "changePercent": "0.27",
            "isDefault": true,
            "isEditable": false
        }
    ]
}
</code>```

}

Dagger Format

```<code>@Singleton
fun provideGson(): Gson =
        GsonBuilder()
                .setLenient()
             //   .registerTypeAdapter(BaseResponse::class.java, RestDeserializer<BaseResponse<T>>())
                .create()
</code>```

Rest Deseralizers

```<code> class RestDeserializer<T> : JsonDeserializer<T> {
@Throws(JsonParseException::class)
override fun deserialize(je: JsonElement, type: Type, jdc: JsonDeserializationContext): T? {
    val content = je.asJsonObject

    // Deserialize it. You use a new instance of Gson to avoid infinite recursion
    // to this deserializer
    return Gson().fromJson<T>(content, type)

}
</code>```

}

Error callback

```<code>abstract class ErrorCallBack<T : BaseResponse<T>> : DisposableObserver<T>() {

protected abstract fun onSuccess(t: T)

override fun onNext(t: T) {
    //You can return StatusCodes of different cases from your API and handle it here. I usually include these cases on BaseResponse and iherit it from every Response
    onSuccess(t)
}

override fun onError(e: Throwable) {

    when (e) {
        is HttpException -> {
            val responseBody = (e).response().errorBody()
            responseBody?.let {
                L.e("Error in call htttp exception")
            }
        }
        is SocketTimeoutException -> {
            // todo
            L.e("Error in Socket time out")
        }
        is IOException -> {
            // todo
            L.e("Error in IO Exception")
        }
        else -> {
            e.message?.let {
                // todo
            }
        }
    }
}

override fun onComplete() {

}

private fun getErrorMessage(responseBody: ResponseBody): String {
    return try {
        val jsonObject = JSONObject(responseBody.string())
        jsonObject.getString("message")
    } catch (e: Exception) {
        e.message!!
    }

}
</code>```

}

Repository

```<code>    override fun getValidateUser(validateUser: ValidateUser): LiveData<ValidateUserResponse> {

    val mutableLiveData = MutableLiveData<ValidateUserResponse>()
    remoteServices.requestValidateUser(validateUser)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(object : ErrorCallBack<BaseResponse<ValidateUserResponse>>() {
                override fun onSuccess(t: BaseResponse<ValidateUserResponse>) {
                    if (t.type == CommonContents.SUCCESS) {
                        L.d("Success in validate user")
                        mutableLiveData.value = transform(t)
                    } else {
                        L.e("Validate User Error")
                    }
                }
            })
    return mutableLiveData
}
</code>```

Data Class

```<code>data class BaseResponse<out T>(
    @SerializedName(CommonContents.TYPE) val type: String,
    @SerializedName(CommonContents.CODE) val Code: String,
    @SerializedName(CommonContents.DESCRIPTION) val Description: String,
    @SerializedName(CommonContents.RESULT)val result: T? = null)
</code>```

These are my structures and I try to make a generic structure but am facing an issue when invoking the Error callback.

Please guide me how to achieve this. Can i call generic method inside generic Response?

```<code>  .subscribeWith(object : ErrorCallBack<BaseResponse<ValidateUserResponse>>() {
</code>```

答:
Guide To Achieving Working Code

This is my guide to making some code work. It is based on the principles of Test Driven Development.

Set up your unit test environment in your IDE. Personally, I have been using JUnit 4 with Eclipse, but you may prefer JUnit 5 with JetBrains' IDE.

Write a unit test for your ErrorCallback class constructor. Make it pass. Next, write unit tests for each of the methods, to see that it behaves the way that you expect.

Write unit tests where your test fixture is a PublishSubject<BaseResponse<Integer>> for some number of different cases: normal data, sequence of normal data, normal data followed by error, normal data followed by completion.

From there, add some more tests so that you can test the entire observable chain.

Body:
I'm trying to create generic architecture to consume complex json structure as follows:

Json Format

{
"type": "success",
"code": "s-groups-0006",
"description": "Index List successfully",
"result": {
    "asOnDate": 1505457095278,
    "indexList": [
        {
            "change": "22.35",
            "changePercent": "0.27",
            "isDefault": true,
            "isEditable": false
        }
    ]
}

}

Dagger Format

@Singleton
fun provideGson(): Gson =
        GsonBuilder()
                .setLenient()
             //   .registerTypeAdapter(BaseResponse::class.java, RestDeserializer<BaseResponse<T>>())
                .create()

Rest Deseralizers

 class RestDeserializer<T> : JsonDeserializer<T> {
@Throws(JsonParseException::class)
override fun deserialize(je: JsonElement, type: Type, jdc: JsonDeserializationContext): T? {
    val content = je.asJsonObject

    // Deserialize it. You use a new instance of Gson to avoid infinite recursion
    // to this deserializer
    return Gson().fromJson<T>(content, type)

}

}

Error callback

abstract class ErrorCallBack<T : BaseResponse<T>> : DisposableObserver<T>() {

protected abstract fun onSuccess(t: T)

override fun onNext(t: T) {
    //You can return StatusCodes of different cases from your API and handle it here. I usually include these cases on BaseResponse and iherit it from every Response
    onSuccess(t)
}

override fun onError(e: Throwable) {

    when (e) {
        is HttpException -> {
            val responseBody = (e).response().errorBody()
            responseBody?.let {
                L.e("Error in call htttp exception")
            }
        }
        is SocketTimeoutException -> {
            // todo
            L.e("Error in Socket time out")
        }
        is IOException -> {
            // todo
            L.e("Error in IO Exception")
        }
        else -> {
            e.message?.let {
                // todo
            }
        }
    }
}

override fun onComplete() {

}

private fun getErrorMessage(responseBody: ResponseBody): String {
    return try {
        val jsonObject = JSONObject(responseBody.string())
        jsonObject.getString("message")
    } catch (e: Exception) {
        e.message!!
    }

}

}

Repository

    override fun getValidateUser(validateUser: ValidateUser): LiveData<ValidateUserResponse> {

    val mutableLiveData = MutableLiveData<ValidateUserResponse>()
    remoteServices.requestValidateUser(validateUser)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(object : ErrorCallBack<BaseResponse<ValidateUserResponse>>() {
                override fun onSuccess(t: BaseResponse<ValidateUserResponse>) {
                    if (t.type == CommonContents.SUCCESS) {
                        L.d("Success in validate user")
                        mutableLiveData.value = transform(t)
                    } else {
                        L.e("Validate User Error")
                    }
                }
            })
    return mutableLiveData
}

Data Class

data class BaseResponse<out T>(
    @SerializedName(CommonContents.TYPE) val type: String,
    @SerializedName(CommonContents.CODE) val Code: String,
    @SerializedName(CommonContents.DESCRIPTION) val Description: String,
    @SerializedName(CommonContents.RESULT)val result: T? = null)

These are my structures and I try to make a generic structure but am facing an issue when invoking the Error callback.

Please guide me how to achieve this. Can i call generic method inside generic Response?

  .subscribeWith(object : ErrorCallBack<BaseResponse<ValidateUserResponse>>() {


来源: stackexchange

问:
How to get two table value using Linq
I have two table one is Administrator table and another is Teacher table .
I want to display these both tables values in single Gridview .
I have make id as a primary key in Administrator table and make this tech_id as foreign key in Teacher table .
Now how to get these table values together in single gridview as shown in pic

Now please any body help me how to get these two value together using Linq .
I have try but  I can't make any more

```<code>   private void loadgri()
    {
        StudentDatabaseEntities empl = new StudentDatabaseEntities();

      var query=from g in empl.Teachers
                join m in empl.Administrators on g.id equals m.id
                where m.username=="cs"
                select new{
   Name = g.username,

        };
       }
</code>```

答:
You don't need a join if you have already a navigation-property:

```<code>var query= from t in empl.Teachers
           where t.Administrator.username == "cs"
           select new { Teacher = t.username, Administrator = t.Administrator.username };
</code>```

This is just an example, but you see that you can access all properties of both entities.

Don’t use Linq’s Join. Navigate!

ContentLicense: CC BY-SA 3.0

Title: How to get two table value using Linq

Body:
I have two table one is Administrator table and another is Teacher table .
I want to display these both tables values in single Gridview .
I have make id as a primary key in Administrator table and make this tech_id as foreign key in Teacher table .
Now how to get these table values together in single gridview as shown in pic

Now please any body help me how to get these two value together using Linq .
I have try but  I can't make any more

   private void loadgri()
    {
        StudentDatabaseEntities empl = new StudentDatabaseEntities();

      var query=from g in empl.Teachers
                join m in empl.Administrators on g.id equals m.id
                where m.username=="cs"
                select new{
   Name = g.username,

        };
       }

Body:
You don't need a join if you have already a navigation-property:

var query= from t in empl.Teachers
           where t.Administrator.username == "cs"
           select new { Teacher = t.username, Administrator = t.Administrator.username };

This is just an example, but you see that you can access all properties of both entities.

Don’t use Linq’s Join. Navigate!


问:
SQL Count Status For Each Day

Fairly new to SQL, but I am looking for help with organizing some data. Have several status broken out into different columns with date/time and want to be able to pivot them to give a breakdown of the different status on each day.

For instance the following data:

```<code> Status4            Status5             Status6             Status7
 12/1/17 5:46       NULL                NULL                NULL
 11/30/17 14:53     11/30/17 14:53      11/30/17 14:53      11/30/17 14:54
 11/18/17 4:50      11/18/17 4:48       11/18/17 4:48       NULL
</code>```

Would return a table such as the one below with the bounds of highest and lowest date present in Status4.

```<code>               Status4      Status5     Status6     Status7
 11/18/17          1           1           1        0
 11/30/17          2           2           2        1
 12/1/1            3           2           2        1
</code>```

Thanks!

答:
If you are looking at getting counts against each date, try this code.

Please note you have to write a dynamic query, if number of status columns is dynamic / unknown.

```<code>DECLARE @TempDates As Table (DateValues Date)

/*Table1 is the table having your status columns */
Insert into @TempDates
    Select Convert(Date,Status1) from Table1
    Union
    Select Convert(Date,Status2) from Table1
    Union
    Select Convert(Date,Status3) from Table1
    Union
    Select Convert(Date,Status4) from Table1

    SELECT * FROM
             (
                 SELECT COL, VAL, DateValues FROM Table1
                 CROSS APPLY (VALUES (Convert(Date,Status1),'Status1'),
                                      (Convert(Date,Status2),'Status2'),
                                      (Convert(Date,Status3),'Status3'),
                                      (Convert(Date,Status4),'Status4')) CS (COL,VAL)
                RIGHT JOIN @TempDates tp ON tp.DateValues = CS.COL
            )T
            PIVOT
            (
                    COUNT(COL)
                    FOR VAL in ([Status1],[Status2],[Status3],[Status4])
            ) P
            WHERE Datevalues IS NOT NULL
</code>```

Title: SQL Count Status For Each Day

Body:
Fairly new to SQL, but I am looking for help with organizing some data. Have several status broken out into different columns with date/time and want to be able to pivot them to give a breakdown of the different status on each day.

For instance the following data:

 Status4            Status5             Status6             Status7
 12/1/17 5:46       NULL                NULL                NULL
 11/30/17 14:53     11/30/17 14:53      11/30/17 14:53      11/30/17 14:54
 11/18/17 4:50      11/18/17 4:48       11/18/17 4:48       NULL

Would return a table such as the one below with the bounds of highest and lowest date present in Status4.

               Status4      Status5     Status6     Status7
 11/18/17          1           1           1        0
 11/30/17          2           2           2        1
 12/1/1            3           2           2        1

Thanks!

Body:
If you are looking at getting counts against each date, try this code.

Please note you have to write a dynamic query, if number of status columns is dynamic / unknown.

DECLARE @TempDates As Table (DateValues Date)

/*Table1 is the table having your status columns */
Insert into @TempDates
    Select Convert(Date,Status1) from Table1
    Union
    Select Convert(Date,Status2) from Table1
    Union
    Select Convert(Date,Status3) from Table1
    Union
    Select Convert(Date,Status4) from Table1

    SELECT * FROM
             (
                 SELECT COL, VAL, DateValues FROM Table1
                 CROSS APPLY (VALUES (Convert(Date,Status1),'Status1'),
                                      (Convert(Date,Status2),'Status2'),
                                      (Convert(Date,Status3),'Status3'),
                                      (Convert(Date,Status4),'Status4')) CS (COL,VAL)
                RIGHT JOIN @TempDates tp ON tp.DateValues = CS.COL
            )T
            PIVOT
            (
                    COUNT(COL)
                    FOR VAL in ([Status1],[Status2],[Status3],[Status4])
            ) P
            WHERE Datevalues IS NOT NULL


问:
IKImageBrowserItem imageRepresentationType error
Just started leaning Cocoa and its dev env, libs, etc.

The error I'm getting:

```<code>"_IKImageBrowserNSImageRepresentationType", referenced from:
-[ImageBrowserItem imageRepresentationType] in ImageBrowserItem.o
ld: symbol(s) not found
</code>```

Any ideas on how to fix this error? This method (imageRepresentationType) is required per the IKImageBrowserItem protocol.

The files (.h and .m) that use it are defined thusly:

ImageBrowserItem.h:

```<code>#import <Cocoa/Cocoa.h>
#import <Quartz/Quartz.h>

@interface ImageBrowserItem : NSObject
{
    NSImage *_image;
    NSString *_imageID;
}

@property (readwrite, copy) NSImage *_image;
@property (readwrite, copy) NSString *_imageID;

- (id) imageRepresentation;
- (NSString *) imageUID;
- (NSString *) imageRepresentationType;

@end
</code>```

ImageBrowserItem.m:

```<code>#import "ImageBrowserItem.h"

@implementation ImageBrowserItem

@synthesize _image;
@synthesize _imageID;

- (id)  imageRepresentation
{
    return _image;
}

- (NSString *) imageUID
{
    return _imageID;
}

// This method is causing the error.
/*
  IKImageBrowserNSImageRepresentationType is a constant
  defined in Apple's IKImageBrowserView.h.
*/
- (NSString *) imageRepresentationType
{
    return IKImageBrowserNSImageRepresentationType;
}

- (void) dealloc
{
    [_image release];
    [_imageID release];
    [super dealloc];
}
@end
</code>```

答: Solved: To fix this, if you have this problem, add the Quartz framework as described here: http://developer.apple.com/library/mac/#DOCUMENTATION/GraphicsImaging/Conceptual/ImageKitProgrammingGuide/ImageKitComponents/ImageKitComponents.html#//apple_ref/doc/uid/TP40004907-CH3-SW4</p>

ContentLicense: CC BY-SA 2.5

Body:
Just started leaning Cocoa and its dev env, libs, etc.

The error I'm getting:

"_IKImageBrowserNSImageRepresentationType", referenced from:
-[ImageBrowserItem imageRepresentationType] in ImageBrowserItem.o
ld: symbol(s) not found

Any ideas on how to fix this error? This method (imageRepresentationType) is required per the IKImageBrowserItem protocol.

The files (.h and .m) that use it are defined thusly:

ImageBrowserItem.h:

#import <Cocoa/Cocoa.h>
#import <Quartz/Quartz.h>

@interface ImageBrowserItem : NSObject
{
    NSImage *_image;
    NSString *_imageID;
}

@property (readwrite, copy) NSImage *_image;
@property (readwrite, copy) NSString *_imageID;

- (id) imageRepresentation;
- (NSString *) imageUID;
- (NSString *) imageRepresentationType;

@end

ImageBrowserItem.m:

#import "ImageBrowserItem.h"

@implementation ImageBrowserItem

@synthesize _image;
@synthesize _imageID;

- (id)  imageRepresentation
{
    return _image;
}

- (NSString *) imageUID
{
    return _imageID;
}

// This method is causing the error.
/*
  IKImageBrowserNSImageRepresentationType is a constant
  defined in Apple's IKImageBrowserView.h.
*/
- (NSString *) imageRepresentationType
{
    return IKImageBrowserNSImageRepresentationType;
}

- (void) dealloc
{
    [_image release];
    [_imageID release];
    [super dealloc];
}
@end


问:
Hide and show text by click on div
I have a question concerning an event onclick. I found this code during my research. My question is : even before the click the text already appears, is it possible to hide the text until we click on the actual button. And is it possible to have numerous onclick event working seperately that is o say only open the text above it? Thank you

  <title>Show and hide div with JavaScript</title>

This div will be show and hide on button click

  <button id="button" onclick="showhide()">Click Me</button>

```

答:
Yes. In your stylesheet, have the #newpost div display: none and also add a modifier class, .visible with display: block. Lastly in your function you could toggle the .visible class via classList.toggle and you should be good to go:

var div = document.getElementById('newpost');

document.getElementById('button').addEventListener('click', showhide);

function showhide() {
  div.classList.toggle('visible');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#newpost {
  display: none;
}

#newpost.visible {
  display: block;
}</code>```

<button id="button">Click Me</button>

This div will be show and hide on button click

```

Title: Hide and show text by click on div

Body:
Yes. In your stylesheet, have the #newpost div display: none and also add a modifier class, .visible with display: block. Lastly in your function you could toggle the .visible class via classList.toggle and you should be good to go:

var div = document.getElementById('newpost');

document.getElementById('button').addEventListener('click', showhide);

function showhide() {
  div.classList.toggle('visible');
}

#newpost {
  display: none;
}

#newpost.visible {
  display: block;
}

<button id="button">Click Me</button>

<div id="newpost">
  <p>This div will be show and hide on button click</p>
</div>


问:
Trouble with String + RandBetween() VBA
```<code>For i = i To nr_commercial
    Cells(i, 1) = commercial & RandBetween(1, 6)
Next i
</code>```

Hi All - I have the above but I am not able to solve it. It returns a compiler error every time. I'm having issues putting a string plus a formula together.

commercial is defined as a string

I have even tried

```<code>Cells(i, 1) = commercial & = Randbetween(1,6)
</code>```

and it returns error saying expecting expression. Is there something not right with the randbetween functionality?

I need to have output in cells such like:

```<code>commercial-1
commercial-5
commercial-3
</code>```

答: I think your issue is that you are using For i = i To nr_commercial which means every iteration it is changing "For 1 = 1 to nr_commercial" and then "2 = 2 to nr_commercial" which doesn't make sense. It should be For i = 1 to nr_commercial or whatever cell you want to start at, probably not in the first cell, as you are likely to have headers.

Title: Trouble with String + RandBetween() VBA

Body:
For i = i To nr_commercial
    Cells(i, 1) = commercial & RandBetween(1, 6)
Next i

Hi All - I have the above but I am not able to solve it. It returns a compiler error every time. I'm having issues putting a string plus a formula together.

commercial is defined as a string

I have even tried

Cells(i, 1) = commercial & = Randbetween(1,6)

and it returns error saying expecting expression. Is there something not right with the randbetween functionality?

I need to have output in cells such like:

commercial-1
commercial-5
commercial-3


问:
How to Retrieve JTable Data as an Array
I've populated a JTable through a DefaultTableModel with the (Object[][] data, String[] headers) constructor. Users can edit the table, and I want to be able to load the new data back into an array (Object[][]). Note that I'd rather not just update the array bit by bit, but be able to just completely load a new array from the table. How can this be done?

答:
Not with the existing default table model. As a rule of thumb, you should ever use the default table model. You should implement your own table model (MyTableModel). You can either implement TableModel or extend AbstractTableModel. I suggest the latter as it provides some nice utility methods. There are 2 ways to achieve what you are doing

populate your new data into a new instance of MyTableModel and call JTable.setModel().

A second way is to create a method in MyTableModel call eg, replaceData(T[][] data). Hold a reference to the model that the table is current displaying. Whenever you want to replace the data, call replaceData(). Assuming you are extending AbstractTableModel, then call fireTableChanged() to notify the table.

Title: How to Retrieve JTable Data as an Array


问:
Sonar-CSharp doesn't analyze .cs files
I'm running the sonar qube runner with teamcity. It completes the step without any errors but it doesn't find any issues.

The project structure like:

root

-sources

--projectA

---projectA.csproj

--projectB

---projectB.csproj

-tests

--projectAtests

---projectAtests.csproj

--projectBtests

---projectBtests.csproj

-solution.sln

The configured parameters are:
working directory:

source location: "sources"

tests location: "tests"

Additional parameters: "-Dsonar.resharper.cs.reportPath=%system.teamcity.build.tempDir%\inspectReport.xml

-Dsonar.resharper.solutionFile=%solutionproject%

-X"

The log looks looks like this:

```<code>    Starting SQS from C:\BuildAgent\tools\sonar-qube-scanner.3.0.3.778-scanner
-classpath
C:\BuildAgent\tools\sonar-qube-scanner.3.0.3.778-scanner\lib\sonar-scanner-cli-3.0.3.778.jar
org.sonarsource.scanner.cli.Main
"-Dproject.home=."
"-Dsonar.host.url=http://teamcity:9000"
"-Dsonar.projectKey=MyProj"
"-Dsonar.projectName=MyProj"
"-Dsonar.projectVersion=84"
"-Dsonar.sources=Sources"
"-Dsonar.tests=Tests"
"-Dsonar.password=*******"
"-Dsonar.login=*******"
-Dscanner.home=C:\BuildAgent\tools\sonar-qube-scanner.3.0.3.778-scanner
-Dsonar.resharper.cs.reportPath=C:\BuildAgent\temp\buildTmp\inspectReport.xml
-Dsonar.resharper.solutionFile=MyProj
-X
Starting: "C:\Program Files\Java\jdk1.8.0_144\bin\java.exe" -classpath C:\BuildAgent\tools\sonar-qube-scanner.3.0.3.778-scanner\lib\sonar-scanner-cli-3.0.3.778.jar org.sonarsource.scanner.cli.Main "-Dproject.home=." "-Dsonar.host.url=http://teamcity:9000" "-Dsonar.projectKey=MyProj" "-Dsonar.projectName=MyProj" "-Dsonar.projectVersion=84" "-Dsonar.sources=Sources" "-Dsonar.tests=Tests" "-Dsonar.password=*******" "-Dsonar.login=*******" -Dscanner.home=C:\BuildAgent\tools\sonar-qube-scanner.3.0.3.778-scanner -Dsonar.resharper.cs.reportPath=C:\BuildAgent\temp\buildTmp\inspectReport.xml -Dsonar.resharper.solutionFile=MyProj -X
in directory: C:\BuildAgent\work\a5fc21edc9db6866
14:05:27.272 INFO: Scanner configuration file: C:\BuildAgent\tools\sonar-qube-scanner.3.0.3.778-scanner\conf\sonar-scanner.properties
14:05:27.279 INFO: Project root configuration file: NONE
14:05:27.307 INFO: SonarQube Scanner 3.0.3.778
14:05:27.307 INFO: Java 1.8.0_144 Oracle Corporation (64-bit)
14:05:27.307 INFO: Windows 10 10.0 amd64
14:05:27.581 DEBUG: keyStore is :
14:05:27.581 DEBUG: keyStore type is : jks
14:05:27.581 DEBUG: keyStore provider is :
14:05:27.581 DEBUG: init keystore
14:05:27.582 DEBUG: init keymanager of type SunX509
14:05:27.799 INFO: User cache: C:\Users\support\.sonar\cache
14:05:27.800 DEBUG: Extract sonar-scanner-api-batch in temp...
14:05:27.876 DEBUG: Get bootstrap index...
14:05:27.877 DEBUG: Download: http://teamcity:9000/batch/index
14:05:27.951 DEBUG: Get bootstrap completed
14:05:27.953 DEBUG: Create isolated classloader...
14:05:27.967 DEBUG: Start temp cleaning...
14:05:27.978 DEBUG: Temp cleaning done
14:05:27.978 DEBUG: Execution getVersion
14:05:27.984 DEBUG: Execution start
14:05:28.276 INFO: Publish mode
14:05:28.431 INFO: Load global settings
14:05:28.515 DEBUG: GET 200 http://teamcity:9000/api/settings/values.protobuf | time=54ms
14:05:28.537 INFO: Load global settings (done) | time=106ms
14:05:28.547 INFO: Server id: AWANnH2mQgX7CJzKVokm
14:05:28.557 INFO: User cache: C:\Users\support\.sonar\cache
14:05:28.823 INFO: Load plugins index
14:05:28.835 DEBUG: GET 200 http://teamcity:9000/api/plugins/installed | time=12ms
14:05:28.877 INFO: Load plugins index (done) | time=54ms
14:05:28.878 DEBUG: Load plugins
14:05:28.899 DEBUG: Load plugins (done) | time=21ms
14:05:28.921 DEBUG: API compatibility mode is enabled on plugin Git [scmgit] (built with API lower than 5.2)
14:05:28.926 DEBUG: API compatibility mode is enabled on plugin SVN [scmsvn] (built with API lower than 5.2)
14:05:29.070 DEBUG: Plugins:
14:05:29.070 DEBUG:   * SonarC# 6.7.0.4267 (csharp)
14:05:29.070 DEBUG:   * SonarPython 1.8.0.1496 (python)
14:05:29.071 DEBUG:   * SonarJava 4.15.0.12310 (java)
14:05:29.072 DEBUG:   * Flex 2.3 (flex)
14:05:29.072 DEBUG:   * Git 1.2 (scmgit)
14:05:29.072 DEBUG:   * SonarXML 1.4.3.1027 (xml)
14:05:29.072 DEBUG:   * SoftVis3D Sonar plugin 1.0 (softvis3d)
14:05:29.072 DEBUG:   * SonarPHP 2.11.0.2485 (php)
14:05:29.072 DEBUG:   * SonarTS 1.1.0.1079 (typescript)
14:05:29.072 DEBUG:   * SVN 1.5.0.715 (scmsvn)
14:05:29.072 DEBUG:   * SonarJS 3.3.0.5702 (javascript)
14:05:29.101 DEBUG: Execution getVersion
14:05:29.101 INFO: SonarQube server 6.7.0
14:05:29.101 INFO: Default locale: "de_DE", source code encoding: "windows-1252" (analysis is platform dependent)
14:05:29.102 DEBUG: Work directory: C:\BuildAgent\work\a5fc21edc9db6866\.scannerwork
14:05:29.102 DEBUG: Execution getVersion
14:05:29.103 DEBUG: Execution execute
14:05:29.997 INFO: Process project properties
14:05:30.004 DEBUG: Process project properties (done) | time=6ms
14:05:30.050 INFO: Load project repositories
14:05:30.056 DEBUG: GET 404 http://teamcity:9000/batch/project.protobuf?key=MyProj | time=5ms
14:05:30.060 DEBUG: Project repository not available - continuing without it
14:05:30.064 INFO: Load project repositories (done) | time=14ms
14:05:30.147 DEBUG: Available languages:
14:05:30.147 DEBUG:   * C# => "cs"
14:05:30.148 DEBUG:   * Python => "py"
14:05:30.148 DEBUG:   * Java => "java"
14:05:30.148 DEBUG:   * Flex => "flex"
14:05:30.148 DEBUG:   * XML => "xml"
14:05:30.148 DEBUG:   * PHP => "php"
14:05:30.150 DEBUG:   * TypeScript => "ts"
14:05:30.151 DEBUG:   * JavaScript => "js"
14:05:30.187 INFO: Load quality profiles
14:05:30.218 DEBUG: GET 200 http://teamcity:9000/api/qualityprofiles/search.protobuf?defaults=true | time=29ms
14:05:30.227 INFO: Load quality profiles (done) | time=40ms
14:05:30.237 INFO: Load active rules
14:05:30.439 DEBUG: GET 200 http://teamcity:9000/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives,createdAt&activation=true&qprofile=AWAmibuEbXZi-9wv_dLM&p=1&ps=500 | time=202ms
14:05:30.988 DEBUG: GET 200 http://teamcity:9000/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives,createdAt&activation=true&qprofile=AWANnNk3QgX7CJzKVpGk&p=1&ps=500 | time=427ms
14:05:31.094 DEBUG: GET 200 http://teamcity:9000/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives,createdAt&activation=true&qprofile=AWANnNr-QgX7CJzKVpMK&p=1&ps=500 | time=46ms
14:05:31.129 DEBUG: GET 200 http://teamcity:9000/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives,createdAt&activation=true&qprofile=AWANnNqpQgX7CJzKVpLL&p=1&ps=500 | time=21ms
14:05:31.254 DEBUG: GET 200 http://teamcity:9000/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives,createdAt&activation=true&qprofile=AWANnNybQgX7CJzKVpR5&p=1&ps=500 | time=124ms
14:05:31.365 DEBUG: GET 200 http://teamcity:9000/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives,createdAt&activation=true&qprofile=AWANnN1iQgX7CJzKVpT7&p=1&ps=500 | time=83ms
14:05:31.432 DEBUG: GET 200 http://teamcity:9000/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives,createdAt&activation=true&qprofile=AWANnN8kQgX7CJzKVpWs&p=1&ps=500 | time=66ms
14:05:31.471 DEBUG: GET 200 http://teamcity:9000/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives,createdAt&activation=true&qprofile=AWANnN_hQgX7CJzKVpXw&p=1&ps=500 | time=33ms
14:05:31.489 INFO: Load active rules (done) | time=1252ms
14:05:31.492 INFO: Load metrics repository
14:05:31.551 DEBUG: GET 200 http://teamcity:9000/api/metrics/search?f=name,description,direction,qualitative,custom&ps=500&p=1 | time=58ms
14:05:31.610 INFO: Load metrics repository (done) | time=118ms
14:05:31.690 INFO: Project key: MyProj
14:05:31.691 DEBUG: Start recursive analysis of project modules
14:05:31.691 INFO: -------------  Scan MyProj
14:05:32.849 INFO: Load server rules
14:05:32.977 DEBUG: GET 200 http://teamcity:9000/api/rules/list.protobuf | time=124ms
14:05:33.017 INFO: Load server rules (done) | time=168ms
14:05:33.083 INFO: Base dir: C:\BuildAgent\work\a5fc21edc9db6866
14:05:33.083 INFO: Working dir: C:\BuildAgent\work\a5fc21edc9db6866\.scannerwork
14:05:33.095 INFO: Source paths: Sources
14:05:33.095 INFO: Test paths: Tests
14:05:33.096 INFO: Source encoding: windows-1252, default locale: de_DE
14:05:33.213 DEBUG: Declared extensions of language C# were converted to sonar.lang.patterns.cs : **/*.cs
14:05:33.214 DEBUG: Declared extensions of language Python were converted to sonar.lang.patterns.py : **/*.py
14:05:33.214 DEBUG: Declared extensions of language Java were converted to sonar.lang.patterns.java : **/*.java,**/*.jav
14:05:33.216 DEBUG: Declared extensions of language Flex were converted to sonar.lang.patterns.flex : **/*.as
14:05:33.216 DEBUG: Declared extensions of language XML were converted to sonar.lang.patterns.xml : **/*.xml,**/*.xsd,**/*.xsl
14:05:33.216 DEBUG: Declared extensions of language PHP were converted to sonar.lang.patterns.php : **/*.php,**/*.php3,**/*.php4,**/*.php5,**/*.phtml,**/*.inc
14:05:33.218 DEBUG: Declared extensions of language TypeScript were converted to sonar.lang.patterns.ts : **/*.ts,**/*.tsx
14:05:33.218 DEBUG: Declared extensions of language JavaScript were converted to sonar.lang.patterns.js : **/*.js,**/*.jsx,**/*.vue
14:05:33.223 DEBUG: Initializers :
14:05:33.225 INFO: Index files
14:05:33.310 DEBUG: 'Sources\DevExpress.Xpf.Themes.MyTheme\AddResourcesToPackage.nuspec' indexed with language 'null'
...
...
...
14:05:35.027 DEBUG: 'Tests\TestFramework.Tests\TestAutomationTests.cs' indexed as test with language 'cs'
14:05:35.027 INFO: 1213 files indexed
14:05:35.029 INFO: Quality profile for cs: My way
14:05:35.029 INFO: Quality profile for xml: Sonar way
14:05:37.347 DEBUG: 'Generic Coverage Report' skipped because one of the required properties is missing
14:05:37.347 DEBUG: 'Generic Test Executions Report' skipped because one of the required properties is missing
14:05:37.386 DEBUG: 'C# Tests Coverage Report Import' skipped because one of the required properties is missing
14:05:37.390 DEBUG: '[Deprecated] C# Integration Tests Coverage Report Import' skipped because one of the required properties is missing
14:05:37.393 DEBUG: 'C# Unit Test Results Import' skipped because one of the required properties is missing
14:05:37.395 DEBUG: 'Python Squid Sensor' skipped because there is no related file in current project
14:05:37.395 DEBUG: 'SurefireSensor' skipped because there is no related file in current project
14:05:37.404 DEBUG: 'JaCoCoSensor' skipped because there is no related file in current project
14:05:37.404 DEBUG: 'JavaSquidSensor' skipped because there is no related file in current project
14:05:37.404 DEBUG: 'Flex' skipped because there is no related file in current project
14:05:37.404 DEBUG: 'Flex Cobertura' skipped because there is no related file in current project
14:05:37.408 DEBUG: 'PHP sensor' skipped because there is no related file in current project
14:05:37.408 DEBUG: 'TypeScript Sensor' skipped because there is no related file in current project
14:05:37.408 DEBUG: 'TypeScript LCOV Coverage Sensor' skipped because there is no related file in current project
14:05:37.408 DEBUG: 'JavaScript Squid Sensor' skipped because there is no related file in current project
14:05:37.462 DEBUG: 'Generic Coverage Report' skipped because one of the required properties is missing
14:05:37.462 DEBUG: 'Generic Test Executions Report' skipped because one of the required properties is missing
14:05:37.463 DEBUG: 'C# Tests Coverage Report Import' skipped because one of the required properties is missing
14:05:37.463 DEBUG: '[Deprecated] C# Integration Tests Coverage Report Import' skipped because one of the required properties is missing
14:05:37.468 DEBUG: 'C# Unit Test Results Import' skipped because one of the required properties is missing
14:05:37.468 DEBUG: 'Python Squid Sensor' skipped because there is no related file in current project
14:05:37.471 DEBUG: 'SurefireSensor' skipped because there is no related file in current project
14:05:37.471 DEBUG: 'JaCoCoSensor' skipped because there is no related file in current project
14:05:37.471 DEBUG: 'JavaSquidSensor' skipped because there is no related file in current project
14:05:37.471 DEBUG: 'Flex' skipped because there is no related file in current project
14:05:37.475 DEBUG: 'Flex Cobertura' skipped because there is no related file in current project
14:05:37.477 DEBUG: 'PHP sensor' skipped because there is no related file in current project
14:05:37.477 DEBUG: 'TypeScript Sensor' skipped because there is no related file in current project
14:05:37.477 DEBUG: 'TypeScript LCOV Coverage Sensor' skipped because there is no related file in current project
14:05:37.477 DEBUG: 'JavaScript Squid Sensor' skipped because there is no related file in current project
14:05:37.482 DEBUG: Sensors : C# Properties -> SonarJavaXmlFileSensor -> XML Sensor -> Analyzer for "php.ini" files -> C# -> Zero Coverage Sensor -> CPD Block Indexer
14:05:37.482 INFO: Sensor C# Properties [csharp]
14:05:37.482 WARN: Property missing: 'sonar.cs.analyzer.projectOutPaths'. No protobuf files will be loaded for this project.
14:05:37.484 WARN: No roslyn issues report not found for this project.
14:05:37.484 INFO: Sensor C# Properties [csharp] (done) | time=2ms
14:05:37.484 INFO: Sensor SonarJavaXmlFileSensor [java]
14:05:37.564 INFO: Sensor SonarJavaXmlFileSensor [java] (done) | time=80ms
14:05:37.564 INFO: Sensor XML Sensor [xml]
14:05:37.581 DEBUG: 'Sources/Core.Authority.UI/Connected Services/LicenseServiceWCF/LicenseService.xsd' generated metadata  with charset 'windows-1252'
14:05:37.585 DEBUG: Count lines in C:/BuildAgent/work/a5fc21edc9db6866/Sources/Core.Authority.UI/Connected Services/LicenseServiceWCF/LicenseService.xsd
14:05:37.782 DEBUG: 'Sources/Core.Authority.UI/Connected Services/LicenseServiceWCF/LicenseService1.xsd' generated metadata  with charset 'windows-1252'
14:05:37.782 DEBUG: Count lines in C:/BuildAgent/work/a5fc21edc9db6866/Sources/Core.Authority.UI/Connected Services/LicenseServiceWCF/LicenseService1.xsd
14:05:37.873 DEBUG: 'Sources/Core.Authority.UI/Connected Services/LicenseServiceWCF/LicenseService2.xsd' generated metadata  with charset 'windows-1252'
14:05:37.873 DEBUG: Count lines in C:/BuildAgent/work/a5fc21edc9db6866/Sources/Core.Authority.UI/Connected Services/LicenseServiceWCF/LicenseService2.xsd
14:05:37.937 INFO: Sensor XML Sensor [xml] (done) | time=373ms
14:05:37.937 INFO: Sensor Analyzer for "php.ini" files [php]
14:05:37.969 INFO: Sensor Analyzer for "php.ini" files [php] (done) | time=32ms
14:05:37.969 INFO: Sensor C# [csharp]
14:05:37.969 INFO: Sensor C# [csharp] (done) | time=0ms
14:05:37.969 INFO: Sensor Zero Coverage Sensor
14:05:38.187 INFO: Sensor Zero Coverage Sensor (done) | time=218ms
14:05:38.187 INFO: Sensor CPD Block Indexer
14:05:38.187 DEBUG: org.sonar.scanner.cpd.deprecated.DefaultCpdBlockIndexer is used for cs
14:05:38.189 DEBUG: No CpdMapping for language cs
14:05:38.189 DEBUG: org.sonar.scanner.cpd.deprecated.DefaultCpdBlockIndexer is used for xml
14:05:38.189 DEBUG: No CpdMapping for language xml
14:05:38.189 INFO: Sensor CPD Block Indexer (done) | time=2ms
14:05:38.193 DEBUG: 'Sources/DevExpress.Xpf.Themes.MyTheme/Properties/AssemblyInfo.cs' generated metadata  with charset 'windows-1252'
14:05:38.198 DEBUG: 'Sources/DevExpress.Xpf.Themes.MyTheme/Properties/Resources.Designer.cs' generated metadata  with charset 'UTF-8'
14:05:38.726 INFO: SCM provider for this project is: git
14:05:38.728 INFO: 467 files to be analyzed
14:05:38.779 DEBUG: readpipe [git, --version],C:\Program Files (x86)\Git\cmd
14:05:38.852 DEBUG: readpipe may return 'git version 2.10.1.windows.1'
14:05:38.852 DEBUG: remaining output:

14:05:38.857 DEBUG: readpipe [git, config, --system, --edit],C:\Program Files (x86)\Git\cmd
14:05:39.112 DEBUG: readpipe may return 'C:/Program Files (x86)/Git/mingw32/etc/gitconfig'
14:05:39.112 DEBUG: remaining output:

14:09:26.696 DEBUG: Blame file Tests/TestFramework.Tests/TestAutomationTests.cs
...
...
...
14:09:26.995 INFO: 467/467 files analyzed
14:09:26.997 INFO: Calculating CPD for 0 files
14:09:26.999 INFO: CPD calculation finished
14:09:34.501 INFO: Analysis report generated in 7353ms, dir size=1 MB
14:09:35.289 INFO: Analysis reports compressed in 787ms, zip size=658 KB
14:09:35.289 INFO: Analysis report generated in C:\BuildAgent\work\a5fc21edc9db6866\.scannerwork\scanner-report
14:09:35.292 DEBUG: Upload report
14:09:35.898 DEBUG: POST 200 http://teamcity:9000/api/ce/submit?projectKey=MyProj&projectName=MyProj | time=604ms
14:09:35.900 INFO: Analysis report uploaded in 608ms
Publishing artifacts
[Publishing artifacts] Collecting files to publish: [C:\BuildAgent\temp\buildTmp\sonar_server.txt=>.teamcity/sonar/]
[Publishing artifacts] Publishing 1 file using [ArtifactsCachePublisher]: C:/BuildAgent/temp/buildTmp/sonar_server.txt => .teamcity/sonar
[Publishing artifacts] Publishing 1 file using [WebPublisher]: C:/BuildAgent/temp/buildTmp/sonar_server.txt => .teamcity/sonar
14:09:35.909 INFO: ANALYSIS SUCCESSFUL, you can browse http://teamcity:9000/dashboard/index/MyProj
14:09:35.910 INFO: Note that you will be able to access the updated dashboard once the server has processed the submitted analysis report
14:09:35.910 INFO: More about the report processing at http://teamcity:9000/api/ce/task?id=AWAmzHhyF2rjhrlmqekU
14:09:35.910 DEBUG: Report metadata written to C:\BuildAgent\work\a5fc21edc9db6866\.scannerwork\report-task.txt
14:09:35.931 DEBUG: Post-jobs :
14:09:35.935 INFO: Task total time: 4:06.820 s
14:09:35.935 INFO: ------------------------------------------------------------------------
14:09:35.935 INFO: EXECUTION SUCCESS
14:09:35.935 INFO: ------------------------------------------------------------------------
14:09:35.935 INFO: Total time: 4:08.728s
14:09:36.013 INFO: Final Memory: 48M/115M
14:09:36.013 INFO: ------------------------------------------------------------------------
14:09:36.013 DEBUG: Execution getVersion
14:09:36.015 DEBUG: Execution stop
Process exited with code 0
</code>```

The runner seems to process all files but doesn't analyze them.
MsBuild 14 and 15 are installed on the build agent.

I tried this with several versions of the sonar-csharp-plugin. Every version since 6.0 has this problem. (Older versions produce exceptions)

What can I do to repair the system?

答:
As far as I can see, the TeamCity plugin for SonarQube does not support .NET analysis (see comment from Domingos Silva):
https://confluence.jetbrains.com/display/TW/SonarQube+Integration

Unfortunately this plugin was not developed by SonarSource and we cannot update it.

What you could try to do is to use generic script steps and execute the Begin and End commands of Scanner for MSBuild according our documentation:
https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner+for+MSBuild

I hope this helps.

Title: Sonar-CSharp doesn't analyze .cs files

Body:
I'm running the sonar qube runner with teamcity. It completes the step without any errors but it doesn't find any issues.

The project structure like:

root

-sources

--projectA

---projectA.csproj

--projectB

---projectB.csproj

-tests

--projectAtests

---projectAtests.csproj

--projectBtests

---projectBtests.csproj

-solution.sln

The configured parameters are:
working directory:

source location: "sources"

tests location: "tests"

Additional parameters: "-Dsonar.resharper.cs.reportPath=%system.teamcity.build.tempDir%\inspectReport.xml

-Dsonar.resharper.solutionFile=%solutionproject%

-X"

The log looks looks like this:

    Starting SQS from C:\BuildAgent\tools\sonar-qube-scanner.3.0.3.778-scanner
-classpath
C:\BuildAgent\tools\sonar-qube-scanner.3.0.3.778-scanner\lib\sonar-scanner-cli-3.0.3.778.jar
org.sonarsource.scanner.cli.Main
"-Dproject.home=."
"-Dsonar.host.url=http://teamcity:9000"
"-Dsonar.projectKey=MyProj"
"-Dsonar.projectName=MyProj"
"-Dsonar.projectVersion=84"
"-Dsonar.sources=Sources"
"-Dsonar.tests=Tests"
"-Dsonar.password=*******"
"-Dsonar.login=*******"
-Dscanner.home=C:\BuildAgent\tools\sonar-qube-scanner.3.0.3.778-scanner
-Dsonar.resharper.cs.reportPath=C:\BuildAgent\temp\buildTmp\inspectReport.xml
-Dsonar.resharper.solutionFile=MyProj
-X
Starting: "C:\Program Files\Java\jdk1.8.0_144\bin\java.exe" -classpath C:\BuildAgent\tools\sonar-qube-scanner.3.0.3.778-scanner\lib\sonar-scanner-cli-3.0.3.778.jar org.sonarsource.scanner.cli.Main "-Dproject.home=." "-Dsonar.host.url=http://teamcity:9000" "-Dsonar.projectKey=MyProj" "-Dsonar.projectName=MyProj" "-Dsonar.projectVersion=84" "-Dsonar.sources=Sources" "-Dsonar.tests=Tests" "-Dsonar.password=*******" "-Dsonar.login=*******" -Dscanner.home=C:\BuildAgent\tools\sonar-qube-scanner.3.0.3.778-scanner -Dsonar.resharper.cs.reportPath=C:\BuildAgent\temp\buildTmp\inspectReport.xml -Dsonar.resharper.solutionFile=MyProj -X
in directory: C:\BuildAgent\work\a5fc21edc9db6866
14:05:27.272 INFO: Scanner configuration file: C:\BuildAgent\tools\sonar-qube-scanner.3.0.3.778-scanner\conf\sonar-scanner.properties
14:05:27.279 INFO: Project root configuration file: NONE
14:05:27.307 INFO: SonarQube Scanner 3.0.3.778
14:05:27.307 INFO: Java 1.8.0_144 Oracle Corporation (64-bit)
14:05:27.307 INFO: Windows 10 10.0 amd64
14:05:27.581 DEBUG: keyStore is :
14:05:27.581 DEBUG: keyStore type is : jks
14:05:27.581 DEBUG: keyStore provider is :
14:05:27.581 DEBUG: init keystore
14:05:27.582 DEBUG: init keymanager of type SunX509
14:05:27.799 INFO: User cache: C:\Users\support\.sonar\cache
14:05:27.800 DEBUG: Extract sonar-scanner-api-batch in temp...
14:05:27.876 DEBUG: Get bootstrap index...
14:05:27.877 DEBUG: Download: http://teamcity:9000/batch/index
14:05:27.951 DEBUG: Get bootstrap completed
14:05:27.953 DEBUG: Create isolated classloader...
14:05:27.967 DEBUG: Start temp cleaning...
14:05:27.978 DEBUG: Temp cleaning done
14:05:27.978 DEBUG: Execution getVersion
14:05:27.984 DEBUG: Execution start
14:05:28.276 INFO: Publish mode
14:05:28.431 INFO: Load global settings
14:05:28.515 DEBUG: GET 200 http://teamcity:9000/api/settings/values.protobuf | time=54ms
14:05:28.537 INFO: Load global settings (done) | time=106ms
14:05:28.547 INFO: Server id: AWANnH2mQgX7CJzKVokm
14:05:28.557 INFO: User cache: C:\Users\support\.sonar\cache
14:05:28.823 INFO: Load plugins index
14:05:28.835 DEBUG: GET 200 http://teamcity:9000/api/plugins/installed | time=12ms
14:05:28.877 INFO: Load plugins index (done) | time=54ms
14:05:28.878 DEBUG: Load plugins
14:05:28.899 DEBUG: Load plugins (done) | time=21ms
14:05:28.921 DEBUG: API compatibility mode is enabled on plugin Git [scmgit] (built with API lower than 5.2)
14:05:28.926 DEBUG: API compatibility mode is enabled on plugin SVN [scmsvn] (built with API lower than 5.2)
14:05:29.070 DEBUG: Plugins:
14:05:29.070 DEBUG:   * SonarC# 6.7.0.4267 (csharp)
14:05:29.070 DEBUG:   * SonarPython 1.8.0.1496 (python)
14:05:29.071 DEBUG:   * SonarJava 4.15.0.12310 (java)
14:05:29.072 DEBUG:   * Flex 2.3 (flex)
14:05:29.072 DEBUG:   * Git 1.2 (scmgit)
14:05:29.072 DEBUG:   * SonarXML 1.4.3.1027 (xml)
14:05:29.072 DEBUG:   * SoftVis3D Sonar plugin 1.0 (softvis3d)
14:05:29.072 DEBUG:   * SonarPHP 2.11.0.2485 (php)
14:05:29.072 DEBUG:   * SonarTS 1.1.0.1079 (typescript)
14:05:29.072 DEBUG:   * SVN 1.5.0.715 (scmsvn)
14:05:29.072 DEBUG:   * SonarJS 3.3.0.5702 (javascript)
14:05:29.101 DEBUG: Execution getVersion
14:05:29.101 INFO: SonarQube server 6.7.0
14:05:29.101 INFO: Default locale: "de_DE", source code encoding: "windows-1252" (analysis is platform dependent)
14:05:29.102 DEBUG: Work directory: C:\BuildAgent\work\a5fc21edc9db6866\.scannerwork
14:05:29.102 DEBUG: Execution getVersion
14:05:29.103 DEBUG: Execution execute
14:05:29.997 INFO: Process project properties
14:05:30.004 DEBUG: Process project properties (done) | time=6ms
14:05:30.050 INFO: Load project repositories
14:05:30.056 DEBUG: GET 404 http://teamcity:9000/batch/project.protobuf?key=MyProj | time=5ms
14:05:30.060 DEBUG: Project repository not available - continuing without it
14:05:30.064 INFO: Load project repositories (done) | time=14ms
14:05:30.147 DEBUG: Available languages:
14:05:30.147 DEBUG:   * C# => "cs"
14:05:30.148 DEBUG:   * Python => "py"
14:05:30.148 DEBUG:   * Java => "java"
14:05:30.148 DEBUG:   * Flex => "flex"
14:05:30.148 DEBUG:   * XML => "xml"
14:05:30.148 DEBUG:   * PHP => "php"
14:05:30.150 DEBUG:   * TypeScript => "ts"
14:05:30.151 DEBUG:   * JavaScript => "js"
14:05:30.187 INFO: Load quality profiles
14:05:30.218 DEBUG: GET 200 http://teamcity:9000/api/qualityprofiles/search.protobuf?defaults=true | time=29ms
14:05:30.227 INFO: Load quality profiles (done) | time=40ms
14:05:30.237 INFO: Load active rules
14:05:30.439 DEBUG: GET 200 http://teamcity:9000/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives,createdAt&activation=true&qprofile=AWAmibuEbXZi-9wv_dLM&p=1&ps=500 | time=202ms
14:05:30.988 DEBUG: GET 200 http://teamcity:9000/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives,createdAt&activation=true&qprofile=AWANnNk3QgX7CJzKVpGk&p=1&ps=500 | time=427ms
14:05:31.094 DEBUG: GET 200 http://teamcity:9000/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives,createdAt&activation=true&qprofile=AWANnNr-QgX7CJzKVpMK&p=1&ps=500 | time=46ms
14:05:31.129 DEBUG: GET 200 http://teamcity:9000/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives,createdAt&activation=true&qprofile=AWANnNqpQgX7CJzKVpLL&p=1&ps=500 | time=21ms
14:05:31.254 DEBUG: GET 200 http://teamcity:9000/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives,createdAt&activation=true&qprofile=AWANnNybQgX7CJzKVpR5&p=1&ps=500 | time=124ms
14:05:31.365 DEBUG: GET 200 http://teamcity:9000/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives,createdAt&activation=true&qprofile=AWANnN1iQgX7CJzKVpT7&p=1&ps=500 | time=83ms
14:05:31.432 DEBUG: GET 200 http://teamcity:9000/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives,createdAt&activation=true&qprofile=AWANnN8kQgX7CJzKVpWs&p=1&ps=500 | time=66ms
14:05:31.471 DEBUG: GET 200 http://teamcity:9000/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives,createdAt&activation=true&qprofile=AWANnN_hQgX7CJzKVpXw&p=1&ps=500 | time=33ms
14:05:31.489 INFO: Load active rules (done) | time=1252ms
14:05:31.492 INFO: Load metrics repository
14:05:31.551 DEBUG: GET 200 http://teamcity:9000/api/metrics/search?f=name,description,direction,qualitative,custom&ps=500&p=1 | time=58ms
14:05:31.610 INFO: Load metrics repository (done) | time=118ms
14:05:31.690 INFO: Project key: MyProj
14:05:31.691 DEBUG: Start recursive analysis of project modules
14:05:31.691 INFO: -------------  Scan MyProj
14:05:32.849 INFO: Load server rules
14:05:32.977 DEBUG: GET 200 http://teamcity:9000/api/rules/list.protobuf | time=124ms
14:05:33.017 INFO: Load server rules (done) | time=168ms
14:05:33.083 INFO: Base dir: C:\BuildAgent\work\a5fc21edc9db6866
14:05:33.083 INFO: Working dir: C:\BuildAgent\work\a5fc21edc9db6866\.scannerwork
14:05:33.095 INFO: Source paths: Sources
14:05:33.095 INFO: Test paths: Tests
14:05:33.096 INFO: Source encoding: windows-1252, default locale: de_DE
14:05:33.213 DEBUG: Declared extensions of language C# were converted to sonar.lang.patterns.cs : **/*.cs
14:05:33.214 DEBUG: Declared extensions of language Python were converted to sonar.lang.patterns.py : **/*.py
14:05:33.214 DEBUG: Declared extensions of language Java were converted to sonar.lang.patterns.java : **/*.java,**/*.jav
14:05:33.216 DEBUG: Declared extensions of language Flex were converted to sonar.lang.patterns.flex : **/*.as
14:05:33.216 DEBUG: Declared extensions of language XML were converted to sonar.lang.patterns.xml : **/*.xml,**/*.xsd,**/*.xsl
14:05:33.216 DEBUG: Declared extensions of language PHP were converted to sonar.lang.patterns.php : **/*.php,**/*.php3,**/*.php4,**/*.php5,**/*.phtml,**/*.inc
14:05:33.218 DEBUG: Declared extensions of language TypeScript were converted to sonar.lang.patterns.ts : **/*.ts,**/*.tsx
14:05:33.218 DEBUG: Declared extensions of language JavaScript were converted to sonar.lang.patterns.js : **/*.js,**/*.jsx,**/*.vue
14:05:33.223 DEBUG: Initializers :
14:05:33.225 INFO: Index files
14:05:33.310 DEBUG: 'Sources\DevExpress.Xpf.Themes.MyTheme\AddResourcesToPackage.nuspec' indexed with language 'null'
...
...
...
14:05:35.027 DEBUG: 'Tests\TestFramework.Tests\TestAutomationTests.cs' indexed as test with language 'cs'
14:05:35.027 INFO: 1213 files indexed
14:05:35.029 INFO: Quality profile for cs: My way
14:05:35.029 INFO: Quality profile for xml: Sonar way
14:05:37.347 DEBUG: 'Generic Coverage Report' skipped because one of the required properties is missing
14:05:37.347 DEBUG: 'Generic Test Executions Report' skipped because one of the required properties is missing
14:05:37.386 DEBUG: 'C# Tests Coverage Report Import' skipped because one of the required properties is missing
14:05:37.390 DEBUG: '[Deprecated] C# Integration Tests Coverage Report Import' skipped because one of the required properties is missing
14:05:37.393 DEBUG: 'C# Unit Test Results Import' skipped because one of the required properties is missing
14:05:37.395 DEBUG: 'Python Squid Sensor' skipped because there is no related file in current project
14:05:37.395 DEBUG: 'SurefireSensor' skipped because there is no related file in current project
14:05:37.404 DEBUG: 'JaCoCoSensor' skipped because there is no related file in current project
14:05:37.404 DEBUG: 'JavaSquidSensor' skipped because there is no related file in current project
14:05:37.404 DEBUG: 'Flex' skipped because there is no related file in current project
14:05:37.404 DEBUG: 'Flex Cobertura' skipped because there is no related file in current project
14:05:37.408 DEBUG: 'PHP sensor' skipped because there is no related file in current project
14:05:37.408 DEBUG: 'TypeScript Sensor' skipped because there is no related file in current project
14:05:37.408 DEBUG: 'TypeScript LCOV Coverage Sensor' skipped because there is no related file in current project
14:05:37.408 DEBUG: 'JavaScript Squid Sensor' skipped because there is no related file in current project
14:05:37.462 DEBUG: 'Generic Coverage Report' skipped because one of the required properties is missing
14:05:37.462 DEBUG: 'Generic Test Executions Report' skipped because one of the required properties is missing
14:05:37.463 DEBUG: 'C# Tests Coverage Report Import' skipped because one of the required properties is missing
14:05:37.463 DEBUG: '[Deprecated] C# Integration Tests Coverage Report Import' skipped because one of the required properties is missing
14:05:37.468 DEBUG: 'C# Unit Test Results Import' skipped because one of the required properties is missing
14:05:37.468 DEBUG: 'Python Squid Sensor' skipped because there is no related file in current project
14:05:37.471 DEBUG: 'SurefireSensor' skipped because there is no related file in current project
14:05:37.471 DEBUG: 'JaCoCoSensor' skipped because there is no related file in current project
14:05:37.471 DEBUG: 'JavaSquidSensor' skipped because there is no related file in current project
14:05:37.471 DEBUG: 'Flex' skipped because there is no related file in current project
14:05:37.475 DEBUG: 'Flex Cobertura' skipped because there is no related file in current project
14:05:37.477 DEBUG: 'PHP sensor' skipped because there is no related file in current project
14:05:37.477 DEBUG: 'TypeScript Sensor' skipped because there is no related file in current project
14:05:37.477 DEBUG: 'TypeScript LCOV Coverage Sensor' skipped because there is no related file in current project
14:05:37.477 DEBUG: 'JavaScript Squid Sensor' skipped because there is no related file in current project
14:05:37.482 DEBUG: Sensors : C# Properties -> SonarJavaXmlFileSensor -> XML Sensor -> Analyzer for "php.ini" files -> C# -> Zero Coverage Sensor -> CPD Block Indexer
14:05:37.482 INFO: Sensor C# Properties [csharp]
14:05:37.482 WARN: Property missing: 'sonar.cs.analyzer.projectOutPaths'. No protobuf files will be loaded for this project.
14:05:37.484 WARN: No roslyn issues report not found for this project.
14:05:37.484 INFO: Sensor C# Properties [csharp] (done) | time=2ms
14:05:37.484 INFO: Sensor SonarJavaXmlFileSensor [java]
14:05:37.564 INFO: Sensor SonarJavaXmlFileSensor [java] (done) | time=80ms
14:05:37.564 INFO: Sensor XML Sensor [xml]
14:05:37.581 DEBUG: 'Sources/Core.Authority.UI/Connected Services/LicenseServiceWCF/LicenseService.xsd' generated metadata  with charset 'windows-1252'
14:05:37.585 DEBUG: Count lines in C:/BuildAgent/work/a5fc21edc9db6866/Sources/Core.Authority.UI/Connected Services/LicenseServiceWCF/LicenseService.xsd
14:05:37.782 DEBUG: 'Sources/Core.Authority.UI/Connected Services/LicenseServiceWCF/LicenseService1.xsd' generated metadata  with charset 'windows-1252'
14:05:37.782 DEBUG: Count lines in C:/BuildAgent/work/a5fc21edc9db6866/Sources/Core.Authority.UI/Connected Services/LicenseServiceWCF/LicenseService1.xsd
14:05:37.873 DEBUG: 'Sources/Core.Authority.UI/Connected Services/LicenseServiceWCF/LicenseService2.xsd' generated metadata  with charset 'windows-1252'
14:05:37.873 DEBUG: Count lines in C:/BuildAgent/work/a5fc21edc9db6866/Sources/Core.Authority.UI/Connected Services/LicenseServiceWCF/LicenseService2.xsd
14:05:37.937 INFO: Sensor XML Sensor [xml] (done) | time=373ms
14:05:37.937 INFO: Sensor Analyzer for "php.ini" files [php]
14:05:37.969 INFO: Sensor Analyzer for "php.ini" files [php] (done) | time=32ms
14:05:37.969 INFO: Sensor C# [csharp]
14:05:37.969 INFO: Sensor C# [csharp] (done) | time=0ms
14:05:37.969 INFO: Sensor Zero Coverage Sensor
14:05:38.187 INFO: Sensor Zero Coverage Sensor (done) | time=218ms
14:05:38.187 INFO: Sensor CPD Block Indexer
14:05:38.187 DEBUG: org.sonar.scanner.cpd.deprecated.DefaultCpdBlockIndexer is used for cs
14:05:38.189 DEBUG: No CpdMapping for language cs
14:05:38.189 DEBUG: org.sonar.scanner.cpd.deprecated.DefaultCpdBlockIndexer is used for xml
14:05:38.189 DEBUG: No CpdMapping for language xml
14:05:38.189 INFO: Sensor CPD Block Indexer (done) | time=2ms
14:05:38.193 DEBUG: 'Sources/DevExpress.Xpf.Themes.MyTheme/Properties/AssemblyInfo.cs' generated metadata  with charset 'windows-1252'
14:05:38.198 DEBUG: 'Sources/DevExpress.Xpf.Themes.MyTheme/Properties/Resources.Designer.cs' generated metadata  with charset 'UTF-8'
14:05:38.726 INFO: SCM provider for this project is: git
14:05:38.728 INFO: 467 files to be analyzed
14:05:38.779 DEBUG: readpipe [git, --version],C:\Program Files (x86)\Git\cmd
14:05:38.852 DEBUG: readpipe may return 'git version 2.10.1.windows.1'
14:05:38.852 DEBUG: remaining output:

14:05:38.857 DEBUG: readpipe [git, config, --system, --edit],C:\Program Files (x86)\Git\cmd
14:05:39.112 DEBUG: readpipe may return 'C:/Program Files (x86)/Git/mingw32/etc/gitconfig'
14:05:39.112 DEBUG: remaining output:

14:09:26.696 DEBUG: Blame file Tests/TestFramework.Tests/TestAutomationTests.cs
...
...
...
14:09:26.995 INFO: 467/467 files analyzed
14:09:26.997 INFO: Calculating CPD for 0 files
14:09:26.999 INFO: CPD calculation finished
14:09:34.501 INFO: Analysis report generated in 7353ms, dir size=1 MB
14:09:35.289 INFO: Analysis reports compressed in 787ms, zip size=658 KB
14:09:35.289 INFO: Analysis report generated in C:\BuildAgent\work\a5fc21edc9db6866\.scannerwork\scanner-report
14:09:35.292 DEBUG: Upload report
14:09:35.898 DEBUG: POST 200 http://teamcity:9000/api/ce/submit?projectKey=MyProj&projectName=MyProj | time=604ms
14:09:35.900 INFO: Analysis report uploaded in 608ms
Publishing artifacts
[Publishing artifacts] Collecting files to publish: [C:\BuildAgent\temp\buildTmp\sonar_server.txt=>.teamcity/sonar/]
[Publishing artifacts] Publishing 1 file using [ArtifactsCachePublisher]: C:/BuildAgent/temp/buildTmp/sonar_server.txt => .teamcity/sonar
[Publishing artifacts] Publishing 1 file using [WebPublisher]: C:/BuildAgent/temp/buildTmp/sonar_server.txt => .teamcity/sonar
14:09:35.909 INFO: ANALYSIS SUCCESSFUL, you can browse http://teamcity:9000/dashboard/index/MyProj
14:09:35.910 INFO: Note that you will be able to access the updated dashboard once the server has processed the submitted analysis report
14:09:35.910 INFO: More about the report processing at http://teamcity:9000/api/ce/task?id=AWAmzHhyF2rjhrlmqekU
14:09:35.910 DEBUG: Report metadata written to C:\BuildAgent\work\a5fc21edc9db6866\.scannerwork\report-task.txt
14:09:35.931 DEBUG: Post-jobs :
14:09:35.935 INFO: Task total time: 4:06.820 s
14:09:35.935 INFO: ------------------------------------------------------------------------
14:09:35.935 INFO: EXECUTION SUCCESS
14:09:35.935 INFO: ------------------------------------------------------------------------
14:09:35.935 INFO: Total time: 4:08.728s
14:09:36.013 INFO: Final Memory: 48M/115M
14:09:36.013 INFO: ------------------------------------------------------------------------
14:09:36.013 DEBUG: Execution getVersion
14:09:36.015 DEBUG: Execution stop
Process exited with code 0

The runner seems to process all files but doesn't analyze them.
MsBuild 14 and 15 are installed on the build agent.

I tried this with several versions of the sonar-csharp-plugin. Every version since 6.0 has this problem. (Older versions produce exceptions)

What can I do to repair the system?


答:
To show all the teachers and their administrator, you don't have to use "join", you could just use the navigation property:</p>

```<code>var query = from g in empl.Teachers
            where g.Administrator.username=="cs"
            select new {
                Teacher_Id = g.Id,
                Teacher_Name = g.username,
                Administrator_Id = g.Id,
                Administrator_Name = g.Administrator.username,
                //etc...
            };
</code>```

Title: How to get two table value using Linq

Body:
To show all the teachers and their administrator, you don't have to use "join", you could just use the navigation property:

var query = from g in empl.Teachers
            where g.Administrator.username=="cs"
            select new {
                Teacher_Id = g.Id,
                Teacher_Name = g.username,
                Administrator_Id = g.Id,
                Administrator_Name = g.Administrator.username,
                //etc...
            };


问:
Use Update_all with conditions
I'm trying to update all the elements of an Array, but I've this error

undefined method `update_all' for ...

```<code>@group.questions.where(user_id: current_user.id).last(@post.question_counter).update_all(post_id: @post.id)
</code>```

While when I try to update_all without condition like :

```<code>@group.questions.update_all(post_id: @post.id)
</code>```

The method is working. Do you have a solution to run this method ? I could do something like this to solve it, but i think is not really elegant & performant

```<code>@questions = @group.questions.where(user_id: current_user.id).last(@post.question_counter)
@questions.each do |question|
  question.update(post_id: @post.id)
end
</code>```

答:
Try something like</p>

```<code>@group.questions.where(user_id: current_user.id).
    order('questions.id DESC').limit(@post.question_counter).
    update_all(post_id: @post.id)
</code>```

Title: Use Update_all with conditions

Body:
I'm trying to update all the elements of an Array, but I've this error

undefined method `update_all' for ...

@group.questions.where(user_id: current_user.id).last(@post.question_counter).update_all(post_id: @post.id)

While when I try to update_all without condition like :

@group.questions.update_all(post_id: @post.id)

The method is working. Do you have a solution to run this method ? I could do something like this to solve it, but i think is not really elegant & performant

@questions = @group.questions.where(user_id: current_user.id).last(@post.question_counter)
@questions.each do |question|
  question.update(post_id: @post.id)
end

Body:
Try something like

@group.questions.where(user_id: current_user.id).
    order('questions.id DESC').limit(@post.question_counter).
    update_all(post_id: @post.id)


问:
Firefox Developer Edition - unable to view JavaScript file in debugger

I am having trouble getting the new Firefox Developer Edition (Developer Tools) to show loaded source files in the debugger.

I am running a Spring MVC Web app running on Tomcat locally and am able to view the source fine when explicitly putting the path in the browsers address bar. However when trying to debug through javascript files I get a "Loading..." indicator and the file never loads:

Chrome Developer tools seems to be working for debugging and will load the files fine with the same setup.

I am at a loss at what I am doing wrong. Any help is appreciated.

答: This is obviously a bug in the DevTools. Check if the issue is still present in Firefox Nightly. If it is not present there, it likely already got fixed. Otherwise you should file a bug report and try to include a minimal test case. You may also include any related errors logged to the Browser Console (can be opened via Ctrl+Shift+J or main menu > Web Developer > Browser Console) when trying to open the source.


问:
Setting an enum by int value
I have an enum with an int value for storage in a DB:

```<code>public enum DayType {
    REGULAR(1), VACATION(2), SICK(3);

    private final int value;
    private DayType(int value)
    {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}
</code>```

And here is a setter for this enum:

```<code>private DayType dayType

public void setDayType(int dayType) {

     switch(dayType) {
        case 1:
            this.dayType = DayType.REGULAR;
            break;

        case 2:
            this.dayType = DayType.VACATION;
            break;

        case 3:
            this.dayType = DayType.SICK;
            break;

        default :
            this.dayType = DayType.REGULAR;
            break;
    }
</code>```

Everything works just fine. But there has to be a more "pretty" way to write the setter if there is a int value for each enum value. Without using switch case...

答:
The usual way is to add a static method in the enum

```<code>public enum DayType {
    REGULAR(1), VACATION(2), SICK(3);

    private final int value;
    private DayType(int value)
    {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public static DayType byValue(int value) {
        Arrays.stream(DayType.values())
            .filter(dt -> dt.value == value)
            .findFirst()
            .orElse(DayType.REGULAR);
    }
}
</code>```

Usage

```<code>private DayType dayType

public void setDayType(int dayType) {
    this.dayType = DayType.byValue(dayType);
}
</code>```

Title: Setting an enum by int value

Body:
I have an enum with an int value for storage in a DB:

public enum DayType {
    REGULAR(1), VACATION(2), SICK(3);

    private final int value;
    private DayType(int value)
    {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

And here is a setter for this enum:

private DayType dayType

public void setDayType(int dayType) {

     switch(dayType) {
        case 1:
            this.dayType = DayType.REGULAR;
            break;

        case 2:
            this.dayType = DayType.VACATION;
            break;

        case 3:
            this.dayType = DayType.SICK;
            break;

        default :
            this.dayType = DayType.REGULAR;
            break;
    }

Everything works just fine. But there has to be a more "pretty" way to write the setter if there is a int value for each enum value. Without using switch case...

Body:
The usual way is to add a static method in the enum

public enum DayType {
    REGULAR(1), VACATION(2), SICK(3);

    private final int value;
    private DayType(int value)
    {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public static DayType byValue(int value) {
        Arrays.stream(DayType.values())
            .filter(dt -> dt.value == value)
            .findFirst()
            .orElse(DayType.REGULAR);
    }
}

Usage

private DayType dayType

public void setDayType(int dayType) {
    this.dayType = DayType.byValue(dayType);
}


答:
In this particular case you don't need to explicitly specify int value for each element, but just treat its constants as array:</p>

```<code>private DayType dayType = DayType.REGULAR;
public void setDayType(int dayType) {
   if (dayType <= DayType.values().length) this.dayType = DayType.values()[dayType - 1];
}
</code>```

Title: Setting an enum by int value

Body:
In this particular case you don't need to explicitly specify int value for each element, but just treat its constants as array:

private DayType dayType = DayType.REGULAR;
public void setDayType(int dayType) {
   if (dayType <= DayType.values().length) this.dayType = DayType.values()[dayType - 1];
}


问:
Facebook logout programmatically in Xamarin ios in Visual Studio
I have an application in IOS in which there is a Facebook Login Button.
when ever user clicks this Facebook login button My app redirects the user to the Facebook App installed in my device. So I want to logout the user from the application as soon as he leaves the facebook app and comes to my app.
i redirect the user to the facebook app using </p>

```<code>NSUrl url = NSUrl.FromString("fb://profile/<id>");
UIApplication.SharedApplication.OpenUrl(url);
</code>```

答:
Are you using the Xamarin Facebook SDK? If yes you can do this to log out:</p>
```<code>new LoginManager().LogOut();
</code>```

Body:
I have an application in IOS in which there is a Facebook Login Button.
when ever user clicks this Facebook login button My app redirects the user to the Facebook App installed in my device. So I want to logout the user from the application as soon as he leaves the facebook app and comes to my app.
i redirect the user to the facebook app using

NSUrl url = NSUrl.FromString("fb://profile/<id>");
UIApplication.SharedApplication.OpenUrl(url);

Body:
Are you using the Xamarin Facebook SDK? If yes you can do this to log out:

new LoginManager().LogOut();

ContentLicense: CC BY-SA 4.0


问:
Why Image goes beyond Grid?
I'm making a program for viewing images and I met with a problem that wide pictures go beyond the window.

I set the property "stretch" to "uniform" but it doesn't work with wide pictures. What can I do?

An example of this problem:

And if I expand window it will be this

This is XAML of image:

<Grid Grid.Row="1">
    <Grid.ColumnDefinitions>
        <ColumnDefinition MinWidth="300" Width="0.1*"/>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition MinWidth="300" Width="*"/>
    </Grid.ColumnDefinitions>
    <TreeView Style="{StaticResource BorderStyle}" ScrollViewer.VerticalScrollBarVisibility="Auto" Name="folders" Grid.Row="0"  Grid.Column="0" TreeViewItem.Expanded="treeView_Expanded">
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate ItemsSource="{Binding Nodes}">
                <StackPanel>

                </StackPanel>
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>
    <GridSplitter Margin="-5 5 -5 5" Cursor="SizeWE" Grid.Row="0" Grid.Column="1" VerticalAlignment="Stretch" ShowsPreview="False" Width="5" HorizontalAlignment="Center" Background="Transparent"/>
    <Border Style="{StaticResource BorderStyle}" Grid.Row="0" Grid.Column="2">
        <Image Name="ImageViewer"/>
    </Border>
  </Grid>
```

答:
The image is sizing itself to its parent, but the MinWidth="300" in your first and third grid column definitions is forcing the parent to be wider than the window. MinWidth overrides Width if the two disagree.

If you change to these values, it won't do that any more except when the window is too narrow to be much use anyway:

```<code>    <Grid.ColumnDefinitions>
        <ColumnDefinition MinWidth="30" Width="*"/>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition MinWidth="30" Width="4*"/>
    </Grid.ColumnDefinitions>
</code>```

I'm not sure what you were getting at with what you had: The number/* Width values (the System.Windows.GridLength structure, whose documentation meets the usual regrettable standard of WPF documentation) work in a not immediately obvious way. The following creates three columns. The middle one is sized to its content. The first one uses one eleventh of the remaining space; the last one uses ten elevenths of the remaining space. "*" means "1*". We add all the numeric values and pro-rate the available space accordingly.

```<code>    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="0.1*"/>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
</code>```

That's exactly equivalent to this:

```<code>    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="1*"/>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="10*"/>
    </Grid.ColumnDefinitions>
</code>```

It's proportional.

So your MinWidth values seem wrong to me, unless you have a truly enviable monitor setup. What I've given you will make the image area four times the width of the left sidebar, which is a rough guess at what you seem to be looking for. I like those proportions.

Title: Why Image goes beyond Grid?

Body:
The image is sizing itself to its parent, but the MinWidth="300" in your first and third grid column definitions is forcing the parent to be wider than the window. MinWidth overrides Width if the two disagree.

If you change to these values, it won't do that any more except when the window is too narrow to be much use anyway:

    <Grid.ColumnDefinitions>
        <ColumnDefinition MinWidth="30" Width="*"/>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition MinWidth="30" Width="4*"/>
    </Grid.ColumnDefinitions>

I'm not sure what you were getting at with what you had: The number/* Width values (the System.Windows.GridLength structure, whose documentation meets the usual regrettable standard of WPF documentation) work in a not immediately obvious way. The following creates three columns. The middle one is sized to its content. The first one uses one eleventh of the remaining space; the last one uses ten elevenths of the remaining space. "*" means "1*". We add all the numeric values and pro-rate the available space accordingly.

    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="0.1*"/>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>

That's exactly equivalent to this:

    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="1*"/>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="10*"/>
    </Grid.ColumnDefinitions>

It's proportional.

So your MinWidth values seem wrong to me, unless you have a truly enviable monitor setup. What I've given you will make the image area four times the width of the left sidebar, which is a rough guess at what you seem to be looking for. I like those proportions.


答:
happy coding :)

function showhide() {
  var div = document.getElementById("newpost");
  div.classList.toggle('hidden');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden{
display : none;
}</code>```

  <title>Show and hide div with JavaScript</title>

This div will be show and hide on button click

  <button id="button" onclick="showhide()">Click Me</button>

```

Title: Hide and show text by click on div

Body:
I have a question concerning an event onclick. I found this code during my research. My question is : even before the click the text already appears, is it possible to hide the text until we click on the actual button. And is it possible to have numerous onclick event working seperately that is o say only open the text above it? Thank you

  <title>Show and hide div with JavaScript</title>

This div will be show and hide on button click

  <button id="button" onclick="showhide()">Click Me</button>

Body:
happy coding :)

function showhide() {
  var div = document.getElementById("newpost");
  div.classList.toggle('hidden');
}

.hidden{
display : none;
}

<html>
 <head>
  <title>Show and hide div with JavaScript</title>

 </head>
 <body>
 <!--if you want  by default hidden then add class .hidden in new post -->
  <div id="newpost"  class="hidden">
    <p>This div will be show and hide on button click</p>
  </div>
  <button id="button" onclick="showhide()">Click Me</button>
</body>
</html>


问:
java - cannot find file in jersey project
I am trying to load Properties from a file in a resource class of a jersey webapp. This is the resource and I followed the advice here

```<code>import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("persons")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class PersonResource {

public PersonResource()
{
     Properties props = new Properties();
     InputStream is = PersonResource.class.getClass().getClassLoader().getResourceAsStream("WEB-INF/test.txt");
     if(is == null) { System.out.println("Inputstream is null");}
     else
     {
         try
         {
             props.load(is);
             System.out.println(props.propertyNames());
         }
         catch (IOException e) { e.printStackTrace(); }
     }

}

@GET
public List<Person> getAllPersons()
{
    List<Person> res = new ArrayList<>();
    res.add(new Person("peter", "sullivan"));
    res.add(new Person("claire", "wood"));
    return res;
}

@GET
@Path("/{fn}")
public Person getPerson(@PathParam("fn") String fn)
{
    return new Person("peter", "sullivan");
}
</code>```

}

This is my folder structure

where the test.txt is located in WebContent/WEB-INF/. The file is just a single line "key=value". I added the WebContent folder as a source folder.

When I run the app on tomcat 7, I get

```<code>java.lang.NullPointerException
demo.rest.jersey.resource.PersonResource.<init>(PersonResource.java:25)
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
java.lang.reflect.Constructor.newInstance(Constructor.java:423)
org.glassfish.hk2.utilities.reflection.ReflectionHelper.makeMe(ReflectionHelper.java:1375)
org.jvnet.hk2.internal.ClazzCreator.createMe(ClazzCreator.java:272)
org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:366)
org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:487)
org.glassfish.jersey.process.internal.RequestScope.findOrCreate(RequestScope.java:162)
org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2022)
</code>```

Line 25 where the error occurs is InputStream is = PersonResource.class.getClass().getClassLoader().getResourceAsStream("WebContent/WEB-INF/test.txt");

Thanks for the help!

答:
if you are using eclipse, do the right click on the test.txt file,  and press on the properties.

It opens a dialogue bow, there you will find the path of that file.  Copy that path and run it.

Body:
I am trying to load Properties from a file in a resource class of a jersey webapp. This is the resource and I followed the advice here

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("persons")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class PersonResource {

public PersonResource()
{
     Properties props = new Properties();
     InputStream is = PersonResource.class.getClass().getClassLoader().getResourceAsStream("WEB-INF/test.txt");
     if(is == null) { System.out.println("Inputstream is null");}
     else
     {
         try
         {
             props.load(is);
             System.out.println(props.propertyNames());
         }
         catch (IOException e) { e.printStackTrace(); }
     }

}

@GET
public List<Person> getAllPersons()
{
    List<Person> res = new ArrayList<>();
    res.add(new Person("peter", "sullivan"));
    res.add(new Person("claire", "wood"));
    return res;
}

@GET
@Path("/{fn}")
public Person getPerson(@PathParam("fn") String fn)
{
    return new Person("peter", "sullivan");
}

}

This is my folder structure

where the test.txt is located in WebContent/WEB-INF/. The file is just a single line "key=value". I added the WebContent folder as a source folder.

When I run the app on tomcat 7, I get

java.lang.NullPointerException
demo.rest.jersey.resource.PersonResource.<init>(PersonResource.java:25)
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
java.lang.reflect.Constructor.newInstance(Constructor.java:423)
org.glassfish.hk2.utilities.reflection.ReflectionHelper.makeMe(ReflectionHelper.java:1375)
org.jvnet.hk2.internal.ClazzCreator.createMe(ClazzCreator.java:272)
org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:366)
org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:487)
org.glassfish.jersey.process.internal.RequestScope.findOrCreate(RequestScope.java:162)
org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2022)

Line 25 where the error occurs is InputStream is = PersonResource.class.getClass().getClassLoader().getResourceAsStream("WebContent/WEB-INF/test.txt");

Thanks for the help!


问:
Net Beans "Must set src.dir" error when generating jforms
I have developed a problem, I cannot resolve.

I am running Net Bean 8.2 Build: 201609300101.
I am running it on a Windows 7 platform.

Yesterday Net Bean worked fine and would generate the jforms for me. Last night something happened and I can no-longer build, compile and run jforms classes.

I can generate and run simple Java programs. I wrote a simple program that just prints "Hello" and that worked.

When I generate a jform, everything looks good in the IDE but it will not build or run.

I get the following error:
c:users\Admin\Documents\Netbeans\KensPanel\nbproject\build-impl.xml:899 Must set src.dir.

None of the NetBeans examples work either and they did yesterday.

In reviewing the posts on the NetBeans forum concerning the problem, I found several that suggested looking in "nbproject directory for a project.properties file. in the file there should be a "build.dir = build" statement. It is there.

I have completely deleted the project and rebuilt the program and that did not work.

I uninstalled the NetBeans program, the JDK and the JRE programs and reinstalled them (JDK & JRE first) and that did not fix the problem.

I put a simple print statement "(System.out.println("Hello");" in the "Public Static void Main(String[] args)" function at the bottom of the KensPanel.java file and the program will compile and print out "Hello" but will not bring up the GUI.

I get the feeling the problem is somehow related to the "ANT" process but anything having anything to do with that is way over my head.

As I stated earlier, the program worked yesterday afternoon. Last night, the IDE decided that it did not want to play any more and I have not been able to find the problem. I am at a loss.

I am real new to the program and for that matter, Java in general. I really need help.

Ken

答:
I think I found my own answer.  At least, I got around the problem.

In the New Java application screen, I had left the "create Main Class" box checked.  I found in the NetBeans tutorial, the tutorial stated that I needed to "un-check" the box. When I did that, at least my application works.  I haven't tried the examples yet.

Moving on to the next learning task.

Ken


答:
You can use the values of .ordinal() and values[index] to acess the values.

Instead of having the value field in the enum, store its DayType.REGULAR.ordinal()  value.

So to load:

```<code>this.dayTipe = DayType.values[dayType];
</code>```

The only downside here is to update the Enum, you need to add all new ones after the last one, so its indexes never conflicts.

Title: Setting an enum by int value

Body:
You can use the values of .ordinal() and values[index] to acess the values.

Instead of having the value field in the enum, store its DayType.REGULAR.ordinal()  value.

So to load:

this.dayTipe = DayType.values[dayType];

The only downside here is to update the Enum, you need to add all new ones after the last one, so its indexes never conflicts.


答:
The answer is here. This works now:</p>

```<code>@Path("persons")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class PersonResource implements ServletContextListener
{

@GET
public List<Person> getAllPersons()
{
    List<Person> res = new ArrayList<>();
    res.add(new Person("peter", "sullivan"));
    res.add(new Person("claire", "wood"));
    return res;
}

@GET
@Path("/{fn}")
public Person getPerson(@PathParam("fn") String fn)
{
    return new Person("peter", "sullivan");
}

@Override
public void contextDestroyed(ServletContextEvent ctxt) {
    System.out.println("Destroying context");
}

@Override
public void contextInitialized(ServletContextEvent ctxt) {
    System.out.println("PersonResource initialized!");

    Properties props = new Properties();
    try(InputStream is = ctxt.getServletContext().getResourceAsStream("/WEB-INF/test.txt"))
    {
        props.load(is);
        System.out.println("key= " + props.getProperty("key"));
    }
    catch(Exception e)
    {
        System.out.println("Cannot load test.txt");
    }
}
}
</code>```

Title: java - cannot find file in jersey project

Body:
The answer is here. This works now:

@Path("persons")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class PersonResource implements ServletContextListener
{

@GET
public List<Person> getAllPersons()
{
    List<Person> res = new ArrayList<>();
    res.add(new Person("peter", "sullivan"));
    res.add(new Person("claire", "wood"));
    return res;
}

@GET
@Path("/{fn}")
public Person getPerson(@PathParam("fn") String fn)
{
    return new Person("peter", "sullivan");
}

@Override
public void contextDestroyed(ServletContextEvent ctxt) {
    System.out.println("Destroying context");
}

@Override
public void contextInitialized(ServletContextEvent ctxt) {
    System.out.println("PersonResource initialized!");

    Properties props = new Properties();
    try(InputStream is = ctxt.getServletContext().getResourceAsStream("/WEB-INF/test.txt"))
    {
        props.load(is);
        System.out.println("key= " + props.getProperty("key"));
    }
    catch(Exception e)
    {
        System.out.println("Cannot load test.txt");
    }
}
}


问:
creating complex dictionary from string with multiple keys in python
I'm getting output string in format like this:

```<code>w = "name: some name|age: 23|street: some address|favorite meal: meal|name: some other name|age: 15|street: some other address|pet: dog|name: <and so on..>"
</code>```

The issue is that this string is not fully predictable, the info after "name" until another "name" belongs to the given person and the "keys" for that info could be more than one word ( although I think I can estimate/predict all the "key words")

Is there a way to arrange this into python dictionary ? ( I guess this would require dictionary with another dictionary as its value... but how would I extract all the info from the string and keep the relevant data together ( the string is much longer around 10 people in one )

答:
You can try this:

```<code>import re
w = "name: some name|age: 23|street: some address|favorite meal: meal|name: some other name|age: 15|street: some other address|pet: dog|"
new_w = re.split('(?<=\|)name:\s|(?<=^)name:\s', w)
new_data = {i.split('|')[0]:{b[:b.index(':')]:b[b.index(':')+2:] for b in filter(lambda x:x, i.split('|')[1:])} for i in filter(lambda x:x, new_w)}
</code>```

Output:

```<code>{'some name': {'favorite meal': 'meal', 'age': '23', 'street': 'some address'}, 'some other name': {'pet': 'dog', 'age': '15', 'street': 'some other address'}}
</code>```

Body:
I'm getting output string in format like this:

w = "name: some name|age: 23|street: some address|favorite meal: meal|name: some other name|age: 15|street: some other address|pet: dog|name: <and so on..>"

The issue is that this string is not fully predictable, the info after "name" until another "name" belongs to the given person and the "keys" for that info could be more than one word ( although I think I can estimate/predict all the "key words")

Is there a way to arrange this into python dictionary ? ( I guess this would require dictionary with another dictionary as its value... but how would I extract all the info from the string and keep the relevant data together ( the string is much longer around 10 people in one )

Body:
You can try this:

import re
w = "name: some name|age: 23|street: some address|favorite meal: meal|name: some other name|age: 15|street: some other address|pet: dog|"
new_w = re.split('(?<=\|)name:\s|(?<=^)name:\s', w)
new_data = {i.split('|')[0]:{b[:b.index(':')]:b[b.index(':')+2:] for b in filter(lambda x:x, i.split('|')[1:])} for i in filter(lambda x:x, new_w)}

Output:

{'some name': {'favorite meal': 'meal', 'age': '23', 'street': 'some address'}, 'some other name': {'pet': 'dog', 'age': '15', 'street': 'some other address'}}


问:
TextView is not showing in an Activity
I have an Activity that has some elements such as ImageViews, TextViews, EditTexts and Buttons. Everything is showing OK but two TextViews are not visible when I run the app. The preview is OK but when I open the app in my phone it doesn't show.

This is my XML code:

```<code><RelativeLayout 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"
              android:orientation="vertical"
              tools:context="com.construct.v2.activities.auth.PasswordChangeActivity">
  <!--<include android:id="@+id/toolbar" layout="@layout/toolbar_simple" />-->
  <ProgressBar
    android:id="@+id/progressBar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/mm_margin"
    android:layout_gravity="center"
    android:visibility="gone"/>

  <RelativeLayout
      android:id="@+id/contentLayout"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical"
      android:paddingLeft="24dp"
      android:paddingRight="24dp"
      android:paddingTop="80dp">
    <ImageView
        android:id="@+id/change_lock"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/change_pass"
        android:layout_centerHorizontal="true"/>

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:fontFamily="sans-serif-medium"
        android:textStyle="normal"
        android:textColor="#00596f"
        android:lineSpacingExtra="2sp"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/change_lock"
        tools:text="@string/change_password"
        />

    <TextView
        android:id="@+id/subtitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:fontFamily="sans-serif"
        android:textStyle="normal"
        android:textColor="#555555"
        android:lineSpacingExtra="4sp"
        android:layout_below="@+id/title"
        android:layout_centerHorizontal="true"
        android:paddingTop="15dp"
        tools:text="@string/new_password_text"
        />

    <TextView
        android:id="@+id/fill_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/subtitle"
        android:textColor="@color/construct_red"
        android:paddingTop="15dp"
        />

    <EditText
          android:id="@+id/password"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:hint="@string/password"
          android:textSize="16dp"
          android:textColorHint="#b1b1b1"
          android:layout_below="@+id/fill_password"
          android:backgroundTint="#00596f"
          android:textColor="#00596f"
          android:textCursorDrawable="@drawable/color_cursor"
          android:inputType="textPassword"
          />
    <Button
        android:id="@+id/saveButton"
        android:layout_width="220dp"
        android:layout_height="40dp"
        android:text="@string/save"
        android:textSize="14dp"
        android:gravity="center"
        android:layout_centerHorizontal="true"
        android:textColor="#b1b1b1"
        android:background="#e3e3e3"
        android:paddingLeft="56dp"
        android:paddingRight="56dp"
        android:layout_below="@+id/password"
        android:layout_marginTop="32dp"/>
  </RelativeLayout>
</RelativeLayout>
</code>```

This is the preview from Android Studio:

And this is the app running in my phone:

答:
You are setting text with tools

```<code>tools:text="@string/new_password_text"
</code>```

change to:

```<code>android:text="@string/new_password_text"
</code>```

Title: TextView is not showing in an Activity

Body:
I have an Activity that has some elements such as ImageViews, TextViews, EditTexts and Buttons. Everything is showing OK but two TextViews are not visible when I run the app. The preview is OK but when I open the app in my phone it doesn't show.

This is my XML code:

<RelativeLayout 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"
              android:orientation="vertical"
              tools:context="com.construct.v2.activities.auth.PasswordChangeActivity">

  <ProgressBar
    android:id="@+id/progressBar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/mm_margin"
    android:layout_gravity="center"
    android:visibility="gone"/>

  <RelativeLayout
      android:id="@+id/contentLayout"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical"
      android:paddingLeft="24dp"
      android:paddingRight="24dp"
      android:paddingTop="80dp">
    <ImageView
        android:id="@+id/change_lock"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/change_pass"
        android:layout_centerHorizontal="true"/>

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:fontFamily="sans-serif-medium"
        android:textStyle="normal"
        android:textColor="#00596f"
        android:lineSpacingExtra="2sp"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/change_lock"
        tools:text="@string/change_password"
        />

    <TextView
        android:id="@+id/subtitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:fontFamily="sans-serif"
        android:textStyle="normal"
        android:textColor="#555555"
        android:lineSpacingExtra="4sp"
        android:layout_below="@+id/title"
        android:layout_centerHorizontal="true"
        android:paddingTop="15dp"
        tools:text="@string/new_password_text"
        />

    <TextView
        android:id="@+id/fill_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/subtitle"
        android:textColor="@color/construct_red"
        android:paddingTop="15dp"
        />

    <EditText
          android:id="@+id/password"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:hint="@string/password"
          android:textSize="16dp"
          android:textColorHint="#b1b1b1"
          android:layout_below="@+id/fill_password"
          android:backgroundTint="#00596f"
          android:textColor="#00596f"
          android:textCursorDrawable="@drawable/color_cursor"
          android:inputType="textPassword"
          />
    <Button
        android:id="@+id/saveButton"
        android:layout_width="220dp"
        android:layout_height="40dp"
        android:text="@string/save"
        android:textSize="14dp"
        android:gravity="center"
        android:layout_centerHorizontal="true"
        android:textColor="#b1b1b1"
        android:background="#e3e3e3"
        android:paddingLeft="56dp"
        android:paddingRight="56dp"
        android:layout_below="@+id/password"
        android:layout_marginTop="32dp"/>
  </RelativeLayout>
</RelativeLayout>

This is the preview from Android Studio:

And this is the app running in my phone:

Body:
You are setting text with tools

tools:text="@string/new_password_text"

change to:

android:text="@string/new_password_text"