问:
C# Change specific lines in file
I have a text file containing some information that I want to edit. The file looks something like this:

```<code>id: 31
name: Anna
profession: Doctor
</code>```

I can read that entry with a StreamReader, and present it in my application. I then want the user to be able to change the name and profession of an entry, so I'd like to edit these specific rows to the new values, while keeping id intact (in my real code, there's not just a few rows, but a lot of rows where only some should be changed). So, for example, I want the file, at the end of my operation, to look like this.

```<code>id: 31
name: Emma
profession: Programmer
</code>```

However, I also have to take into account that sometimes the rows don't exist beforehand. For example, before editing Anna to Emma, it's not certain that she had a profession, the file could have looked like this:

```<code>id: 31
name: Anna
</code>```

And in that case, I want to add the line profession: Programmerto the end there.

I tried using a FileStreamwith ReadWrite access, that I give to a StreamReader and a StreamWriter, but then I found no way of changing or replacing a line of text, only reading it and writing a new identical line while keeping the old.

```<code>using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite))
using (StreamReader reader = new StreamReader(fileStream))
using (StreamWriter writer = new StreamWriter(fileStream))
{
    bool idExists = false;
    bool nameExists = false;
    bool tagsExist = false;

    string line;
    while((line = reader.ReadLine()) != null)
    {
        if (line.StartsWith("id:"))
            idExists = true;
        else if (line.StartsWith("name:"))
        {
            nameExists = true;
            line = $"name: {entryToSave.Name}";
            writer.WriteLine(line); // Will write an additional line and not replace
        }
        else if (line.StartsWith("profession:"))
        {
            professionExists = true;
            line = $"profession: {entryToSave.Profession}";
            writer.WriteLine(line); // Will write an additional line and not replace
        }
    }

    if (!idExists)
        writer.WriteLine($"id: {generatedId}");
    if (!nameExists)
        writer.WriteLine($"name: {entryToSave.Name}");
    if (!professionExists)
        writer.WriteLine($"profession: {entryToSave.Profession}");
}
</code>```

I also tried using File.ReadAllLines, loop through the lines, and then write back all the lines to the file, only modifying the lines that were to be modified. However, I don't have access to the file through File.WriteAllLines for some reason that I don't understand, as a StreamWriter has access. Code:

```<code>var previousData = File.ReadAllLines(filePath);
var newData = new List<string>();
bool idExists = false;
bool nameExists = false;
bool professionExists = false;

for (int i = 0; i < previousData.Length; i++)
{
    var line = previousData[i];

    if (line.StartsWith("id:")
        idExists = true;
    else if (line.StartsWith("name:")
    {
        nameExists = true;
        line = $"name: {entryToSave.Name}";
    }
    else if (line.StartsWith("profession:"))
    {
        professionExists = true;
        line = $"profession: {entryToSave.Profession}";
    }

    newData.Add(line);
}

if (!idExists)
    newData.Add($"id: {generatedId}");
if (!nameExists)
    newData.Add($"name: {entryToSave.Name}");
if (!professionExists)
    newData.Add($"profession: {entryToSave.Profession}");

File.WriteAllLines(filePath, newData.ToArray()); // Access denied
</code>```

How is this most easily achieved, without file streams interfering with each other?

答:
If you've already presented the data to the user in entries, enabling the user to edit name and profession, you could just read the file, get the ID and fill the remainder of the file with the value of the entries. The following is an example console application.

```<code>static void Main(string[] args)
{
    var filePath = "test.txt";

    // Simulated input from user
    // these should come from entries in the application?
    var name = "Foo";
    var profession = "Bar";

    var personData = new PersonData(); // class declared below

    using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite))
    using (StreamReader reader = new StreamReader(fileStream))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            if (line.StartsWith("id:"))
                personData.ID = line;
        }
    } // Now reader and filestream is closed, file is available again.

    // You don't specify what you would like to happen if personData.ID is null,
    // so I make an assumption the generatedId is what you'd like to use.
    if (string.IsNullOrWhiteSpace(personData.ID)
        personData.ID = $"id: {generatedId}";

    // Add the data from the entries
    personData.Name = $"name: {name}";
    personData.Profession = $"profession: {profession}";

    File.Delete(filePath); // remove the file

    using (FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
    using (StreamWriter writer = new StreamWriter(fileStream))
    {
        writer.WriteLine(personData.ID);
        writer.WriteLine(personData.Name);
        writer.WriteLine(personData.Profession);
    }
}
private class PersonData
{
    public string ID { get; set; }
    public string Name { get; set; }
    public string Profession { get; set; }
}
</code>```

Now you just have to find out how to get access to the file if you're having permission problems.

Title: C# Change specific lines in file

Body:
I have a text file containing some information that I want to edit. The file looks something like this:

id: 31
name: Anna
profession: Doctor

I can read that entry with a StreamReader, and present it in my application. I then want the user to be able to change the name and profession of an entry, so I'd like to edit these specific rows to the new values, while keeping id intact (in my real code, there's not just a few rows, but a lot of rows where only some should be changed). So, for example, I want the file, at the end of my operation, to look like this.

id: 31
name: Emma
profession: Programmer

However, I also have to take into account that sometimes the rows don't exist beforehand. For example, before editing Anna to Emma, it's not certain that she had a profession, the file could have looked like this:

id: 31
name: Anna

And in that case, I want to add the line profession: Programmerto the end there.

I tried using a FileStreamwith ReadWrite access, that I give to a StreamReader and a StreamWriter, but then I found no way of changing or replacing a line of text, only reading it and writing a new identical line while keeping the old.

using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite))
using (StreamReader reader = new StreamReader(fileStream))
using (StreamWriter writer = new StreamWriter(fileStream))
{
    bool idExists = false;
    bool nameExists = false;
    bool tagsExist = false;

    string line;
    while((line = reader.ReadLine()) != null)
    {
        if (line.StartsWith("id:"))
            idExists = true;
        else if (line.StartsWith("name:"))
        {
            nameExists = true;
            line = $"name: {entryToSave.Name}";
            writer.WriteLine(line); // Will write an additional line and not replace
        }
        else if (line.StartsWith("profession:"))
        {
            professionExists = true;
            line = $"profession: {entryToSave.Profession}";
            writer.WriteLine(line); // Will write an additional line and not replace
        }
    }

    if (!idExists)
        writer.WriteLine($"id: {generatedId}");
    if (!nameExists)
        writer.WriteLine($"name: {entryToSave.Name}");
    if (!professionExists)
        writer.WriteLine($"profession: {entryToSave.Profession}");
}

I also tried using File.ReadAllLines, loop through the lines, and then write back all the lines to the file, only modifying the lines that were to be modified. However, I don't have access to the file through File.WriteAllLines for some reason that I don't understand, as a StreamWriter has access. Code:

var previousData = File.ReadAllLines(filePath);
var newData = new List<string>();
bool idExists = false;
bool nameExists = false;
bool professionExists = false;

for (int i = 0; i < previousData.Length; i++)
{
    var line = previousData[i];

    if (line.StartsWith("id:")
        idExists = true;
    else if (line.StartsWith("name:")
    {
        nameExists = true;
        line = $"name: {entryToSave.Name}";
    }
    else if (line.StartsWith("profession:"))
    {
        professionExists = true;
        line = $"profession: {entryToSave.Profession}";
    }

    newData.Add(line);
}

if (!idExists)
    newData.Add($"id: {generatedId}");
if (!nameExists)
    newData.Add($"name: {entryToSave.Name}");
if (!professionExists)
    newData.Add($"profession: {entryToSave.Profession}");

File.WriteAllLines(filePath, newData.ToArray()); // Access denied

How is this most easily achieved, without file streams interfering with each other?

Body:
If you've already presented the data to the user in entries, enabling the user to edit name and profession, you could just read the file, get the ID and fill the remainder of the file with the value of the entries. The following is an example console application.

static void Main(string[] args)
{
    var filePath = "test.txt";

    // Simulated input from user
    // these should come from entries in the application?
    var name = "Foo";
    var profession = "Bar";

    var personData = new PersonData(); // class declared below

    using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite))
    using (StreamReader reader = new StreamReader(fileStream))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            if (line.StartsWith("id:"))
                personData.ID = line;
        }
    } // Now reader and filestream is closed, file is available again.

    // You don't specify what you would like to happen if personData.ID is null,
    // so I make an assumption the generatedId is what you'd like to use.
    if (string.IsNullOrWhiteSpace(personData.ID)
        personData.ID = $"id: {generatedId}";

    // Add the data from the entries
    personData.Name = $"name: {name}";
    personData.Profession = $"profession: {profession}";

    File.Delete(filePath); // remove the file

    using (FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
    using (StreamWriter writer = new StreamWriter(fileStream))
    {
        writer.WriteLine(personData.ID);
        writer.WriteLine(personData.Name);
        writer.WriteLine(personData.Profession);
    }
}
private class PersonData
{
    public string ID { get; set; }
    public string Name { get; set; }
    public string Profession { get; set; }
}

Now you just have to find out how to get access to the file if you're having permission problems.


来源: stackexchange

问:
log4j not writing into file but its writing into console
i am aritinga small application in Linux based system where i am using slf4j libraries for logger

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

i could see the logs are visible in console but not appending to log files.

```<code><appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
    <param name="threshold" value="INFO" />
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="[%d{ABSOLUTE}][%-5p][%-10t]%m%n" />
    </layout>
</appender>

<!-- EXAMPLE logging setup NOTES: 1. files are written to "./logs/<filename>".
    You must setup the environment so that ./logs is a symlink to the correct
    location according to the EXAMPLE log standard. For example, "/opt/logs/".
    If that's not possible, change the File setting in each appender appropriately. -->

<appender name="EXAMPLE_AUDIT" class="org.apache.log4j.RollingFileAppender">
    <param name="threshold" value="INFO" />
    <param name="File" value="./logs/audit.log" />
    <param name="MaxFileSize" value="128MB" />
    <param name="MaxBackupIndex" value="20" />
    <layout class="com.rsg.ova.logging.log4j.EXAMPLELayout">
        <param name="ConversionPattern" value="EXAMPLE_AUDIT" />
    </layout>
</appender>

<appender name="EXAMPLE_METRIC" class="org.apache.log4j.RollingFileAppender">
    <param name="threshold" value="DEBUG" />
    <param name="File" value="./logs/metric.log" />
    <param name="MaxFileSize" value="128MB" />
    <param name="MaxBackupIndex" value="10" />
    <layout class="com.rsg.ova.logging.log4j.EXAMPLELayout">
        <param name="ConversionPattern" value="EXAMPLE_METRIC" />
    </layout>
</appender>

<appender name="EXAMPLE_ERROR" class="org.apache.log4j.RollingFileAppender">
    <param name="threshold" value="ERROR" />    <!-- only WARN and ERROR are allowed in this log -->
    <param name="File" value="./logs/error.log" />
    <param name="MaxFileSize" value="128MB" />
    <param name="MaxBackupIndex" value="10" />
    <layout class="com.rsg.ova.logging.log4j.EXAMPLELayout">
        <param name="ConversionPattern" value="EXAMPLE_ERROR" />
    </layout>
</appender>

<appender name="EXAMPLE_DEBUG" class="org.apache.log4j.RollingFileAppender">
    <param name="threshold" value="DEBUG" />
    <param name="File" value="./logs/debug.log" />
    <param name="MaxFileSize" value="128MB" />
    <param name="MaxBackupIndex" value="20" />
    <layout class="com.rsg.ova.logging.log4j.EXAMPLELayout">
        <param name="ConversionPattern" value="EXAMPLE_DEBUG" />
    </layout>
</appender>

<logger name="com.rsg.EXAMPLE.audit" additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_AUDIT" />
</logger>

<logger name="com.rsg.EXAMPLE.metrics" additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_METRIC" />
</logger>

<logger name="com.rsg.EXAMPLE.error" additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_ERROR" />
</logger>

<logger name="com.rsg.EXAMPLE.debug" additivity="false">
    <level value="info" />
    <appender-ref ref="CONSOLE" />
    <appender-ref ref="EXAMPLE_DEBUG" />
</logger>

<root>
    <level value="DEBUG" />
    <appender-ref ref="EXAMPLE_DEBUG" />
    <appender-ref ref="CONSOLE" />

</root>

<logger name="org.openEXAMPLE.agcp.commonFunction.input"
    additivity="false">
    <level value="INFO" />
    <appender-ref ref="CONSOLE" />
</logger>

<logger name="org.openEXAMPLE.agcp.commonFunction.output"
    additivity="false">
    <level value="INFO" />
    <appender-ref ref="CONSOLE" />

</logger>

<logger name="org.openEXAMPLE.agcp.commonFunction.error"
    additivity="false">
    <level value="DEBUG" />
    <appender-ref ref="CONSOLE" />
    <appender-ref ref="EXAMPLE_ERROR" />
</logger>

<!-- The EXAMPLE logging standard has four specific classes of logging that
    are unrelated to subsystem logger names. If you want them activated, uncomment
    this block. -->
<logger name="com.rsg.EXAMPLE.audit" additivity="false">
    <level value="info" />
    <appender-ref ref="CONSOLE" />
    <appender-ref ref="EXAMPLE_AUDIT" />
</logger>

<logger name="com.rsg.EXAMPLE.metrics" additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_METRIC" />
</logger>

<logger name="com.rsg.EXAMPLE.error" additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_ERROR" />
</logger>

<logger name="com.rsg.EXAMPLE.debug" additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_DEBUG" />
</logger>

<logger name="com.rsg.ova.apiClient.http.HttpClient" additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_ERROR" />
    <appender-ref ref="CONSOLE" />
</logger>

<logger name="com.rsg.ova.roman.client.impl.romanSimplerBatchPublisher"
    additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_ERROR" />
    <appender-ref ref="CONSOLE" />
</logger>
</code>```

答:
It seems you missed root tag in your xml file. Please find the below code to write the logs in a file.</p>

```<code><appender name="file" class="org.apache.log4j.RollingFileAppender">
    <param name="append" value="false" />
    <param name="maxFileSize" value="128MB" />
    <param name="maxBackupIndex" value="20" />
    <param name="file" value="./logs/audit.log" />
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
    </layout>
</appender>

<root>
    <level value="INFO" />
    <appender-ref ref="file" />
</root>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i am aritinga small application in Linux based system where i am using slf4j libraries for logger

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

i could see the logs are visible in console but not appending to log files.

<appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
    <param name="threshold" value="INFO" />
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="[%d{ABSOLUTE}][%-5p][%-10t]%m%n" />
    </layout>
</appender>

<appender name="EXAMPLE_AUDIT" class="org.apache.log4j.RollingFileAppender">
    <param name="threshold" value="INFO" />
    <param name="File" value="./logs/audit.log" />
    <param name="MaxFileSize" value="128MB" />
    <param name="MaxBackupIndex" value="20" />
    <layout class="com.rsg.ova.logging.log4j.EXAMPLELayout">
        <param name="ConversionPattern" value="EXAMPLE_AUDIT" />
    </layout>
</appender>

<appender name="EXAMPLE_METRIC" class="org.apache.log4j.RollingFileAppender">
    <param name="threshold" value="DEBUG" />
    <param name="File" value="./logs/metric.log" />
    <param name="MaxFileSize" value="128MB" />
    <param name="MaxBackupIndex" value="10" />
    <layout class="com.rsg.ova.logging.log4j.EXAMPLELayout">
        <param name="ConversionPattern" value="EXAMPLE_METRIC" />
    </layout>
</appender>

<appender name="EXAMPLE_ERROR" class="org.apache.log4j.RollingFileAppender">
    <param name="threshold" value="ERROR" />
    <param name="File" value="./logs/error.log" />
    <param name="MaxFileSize" value="128MB" />
    <param name="MaxBackupIndex" value="10" />
    <layout class="com.rsg.ova.logging.log4j.EXAMPLELayout">
        <param name="ConversionPattern" value="EXAMPLE_ERROR" />
    </layout>
</appender>

<appender name="EXAMPLE_DEBUG" class="org.apache.log4j.RollingFileAppender">
    <param name="threshold" value="DEBUG" />
    <param name="File" value="./logs/debug.log" />
    <param name="MaxFileSize" value="128MB" />
    <param name="MaxBackupIndex" value="20" />
    <layout class="com.rsg.ova.logging.log4j.EXAMPLELayout">
        <param name="ConversionPattern" value="EXAMPLE_DEBUG" />
    </layout>
</appender>

<logger name="com.rsg.EXAMPLE.audit" additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_AUDIT" />
</logger>

<logger name="com.rsg.EXAMPLE.metrics" additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_METRIC" />
</logger>

<logger name="com.rsg.EXAMPLE.error" additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_ERROR" />
</logger>

<logger name="com.rsg.EXAMPLE.debug" additivity="false">
    <level value="info" />
    <appender-ref ref="CONSOLE" />
    <appender-ref ref="EXAMPLE_DEBUG" />
</logger>

<root>
    <level value="DEBUG" />
    <appender-ref ref="EXAMPLE_DEBUG" />
    <appender-ref ref="CONSOLE" />

</root>

<logger name="org.openEXAMPLE.agcp.commonFunction.input"
    additivity="false">
    <level value="INFO" />
    <appender-ref ref="CONSOLE" />
</logger>

<logger name="org.openEXAMPLE.agcp.commonFunction.output"
    additivity="false">
    <level value="INFO" />
    <appender-ref ref="CONSOLE" />

</logger>

<logger name="org.openEXAMPLE.agcp.commonFunction.error"
    additivity="false">
    <level value="DEBUG" />
    <appender-ref ref="CONSOLE" />
    <appender-ref ref="EXAMPLE_ERROR" />
</logger>

<logger name="com.rsg.EXAMPLE.audit" additivity="false">
    <level value="info" />
    <appender-ref ref="CONSOLE" />
    <appender-ref ref="EXAMPLE_AUDIT" />
</logger>

<logger name="com.rsg.EXAMPLE.metrics" additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_METRIC" />
</logger>

<logger name="com.rsg.EXAMPLE.error" additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_ERROR" />
</logger>

<logger name="com.rsg.EXAMPLE.debug" additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_DEBUG" />
</logger>

<logger name="com.rsg.ova.apiClient.http.HttpClient" additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_ERROR" />
    <appender-ref ref="CONSOLE" />
</logger>

<logger name="com.rsg.ova.roman.client.impl.romanSimplerBatchPublisher"
    additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_ERROR" />
    <appender-ref ref="CONSOLE" />
</logger>

Body:
It seems you missed root tag in your xml file. Please find the below code to write the logs in a file.

<appender name="file" class="org.apache.log4j.RollingFileAppender">
    <param name="append" value="false" />
    <param name="maxFileSize" value="128MB" />
    <param name="maxBackupIndex" value="20" />
    <param name="file" value="./logs/audit.log" />
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
    </layout>
</appender>

<root>
    <level value="INFO" />
    <appender-ref ref="file" />
</root>


问:
Calculating timespan with t-sql
Given two date/times:

```<code>@start_date = '2009-04-15 10:24:00.000'
@end_date = '2009-04-16 19:43:01.000'
</code>```

Is it possible to calculate the time elapsed between the two dates in the following format

1d 9h 19m

答:
```<code>DECLARE @FirstDate DATETIME, @SecondDate DATETIME, @result VARCHAR(MAX)
SELECT @FirstDate = '2017-03-01 09:54:00.637', @SecondDate = GETDATE()

DECLARE @Day INT,@Month INT,@Hour INT, @Minute INT,@TotalSeconds INT,@Year INT
SELECT @TotalSeconds = ABS(DATEDIFF(SECOND,@FirstDate,@SecondDate))

-- Standard values in seconds
DECLARE @YearSeconds INT, @MonthSeconds INT, @DaySeconds INT, @HourSeconds INT, @MinuteSeconds INT

SELECT  @MinuteSeconds = 60
SELECT  @HourSeconds = 60 * @MinuteSeconds
SELECT  @DaySeconds = 24 * @HourSeconds
SELECT  @MonthSeconds = 30 * @DaySeconds
SELECT  @YearSeconds = 12 * @MonthSeconds

--SELECT @MinuteSeconds AS [Minutes], @HourSeconds AS [Hours], @DaySeconds AS [Day],@MonthSeconds AS [Month],@YearSeconds AS [Year]

IF @TotalSeconds < @MinuteSeconds
BEGIN
    SELECT @result = CAST(@TotalSeconds AS NVARCHAR(20)) + ' seconds ago'
END
ELSE IF @TotalSeconds < @HourSeconds
BEGIN
    SELECT @result = CAST(ABS(DATEDIFF(MINUTE,@FirstDate,@SecondDate)) AS NVARCHAR(20)) + ' minutes ago'
END
ELSE IF @TotalSeconds < @DaySeconds
BEGIN
    SELECT @result = CAST(ABS(DATEDIFF(HOUR,@FirstDate,@SecondDate)) AS     NVARCHAR(20)) + ' hours ago'
END
ELSE IF @TotalSeconds < @MonthSeconds
BEGIN
    SELECT @result = CAST(ABS(DATEDIFF(DAY,@FirstDate,@SecondDate)) AS NVARCHAR(20)) + ' days ago'
END
ELSE IF @TotalSeconds < @YearSeconds
BEGIN
    SELECT @result = CAST(ABS(DATEDIFF(MONTH,@FirstDate,@SecondDate)) AS NVARCHAR(20)) + ' months ago'
END
ELSE IF @TotalSeconds > @YearSeconds
BEGIN
    SELECT @result = CAST(ABS(DATEDIFF(YEAR,@FirstDate,@SecondDate)) AS NVARCHAR(20)) + ' year ago'
END

SELECT @result
</code>```

ContentLicense: CC BY-SA 2.5

Title: Calculating timespan with t-sql

Body:
Given two date/times:

@start_date = '2009-04-15 10:24:00.000'
@end_date = '2009-04-16 19:43:01.000'

Is it possible to calculate the time elapsed between the two dates in the following format

1d 9h 19m


问:
Showing font from string ascii value in java
I need to show a font from an ascii value. The following code is working fine:

```<code>String font = Character.toString((char) 0x0627);
</code>```

In my case, 0x0627 value is stored in a string variable like String strValue = "0x0627";

Now how can i use this strValue in my above code?

答:
You can use this :

```<code>String strValue = "0x0627";
String font = Character.toString((char) Integer.decode(strValue).intValue());
//-------------------------------------^-Convert String to Hex-^
</code>```

It is the equivalent of :

```<code>String font = Character.toString((char) 0x0627);
</code>```

Body:
I need to show a font from an ascii value. The following code is working fine:

String font = Character.toString((char) 0x0627);

In my case, 0x0627 value is stored in a string variable like String strValue = "0x0627";

Now how can i use this strValue in my above code?

Body:
You can use this :

String strValue = "0x0627";
String font = Character.toString((char) Integer.decode(strValue).intValue());
//-------------------------------------^-Convert String to Hex-^

It is the equivalent of :

String font = Character.toString((char) 0x0627);


问:
SettingwithCopy when creating new column and when dropping NaN rows
I've been searching around reading the pandas docs here and trying different lines of code from questions posted around here and here and I can't seem to get away from the setting with copy warning. I'd prefer to learn to code it the "right" way as opposed to just ignoring the warnings.

The following lines of code are inside a for loop and I don't want to generate this warning a lot of times because it could slow things down.

I'm trying to make a new column with name: 'E'+vs where vs is a string in a list in the for loop

But for each one of them, I still get the following warning, even with the last 3 lines:

```<code>SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
</code>```

Here are the troublesome lines I've tried so far:

```<code>#based on research, the first two seem to be the "wrong" way

df_out['E'+vs] = df_out[kvs].rolling(v).mean().copy()
df_out['E'+vs] = df_out[kvs].rolling(v).mean()

df_out.loc[:,'E'+vs] = df_out[kvs].rolling(v).mean().copy()
df_out.loc[:,'E'+vs] = df_out[kvs].rolling(v).mean()
df_out.loc[:,'E'+vs] = df_out.loc[:,kvs].rolling(v).mean()
</code>```

The other one that gives a SettingWithCopyWarning is this:

```<code>df_out.dropna(inplace=True,axis=0)
</code>```

This one also gave a warning (but I figured this one would)

```<code>df_out = df_out.dropna(inplace=True,axis=0)
</code>```

How do I do both of these operations correctly?

EDIT: Here is the code that produced the original df_out

```<code>df_out= pd.concat([vol.Date[1:-1], ret.Return_Time[:-2], vol.Freq_Time[:-2],
               vol.Freq_Time[:-1].shift(-1), vol.Freq_Time[:].shift(-2)],
               axis=1).dropna().set_index('Date')
</code>```

答:
This is a confusing topic.  It's not the code you've posted that is the problem.  It's the code you haven't posted.  It's the code that generated the df_out

Consider this example and note the last line that generates the warning.

```<code>df_other = pd.DataFrame(dict(A=[1], B=[2]))
df_out = df_other[:]

df_out['E'] = 5
</code>```

```<code>//anaconda/envs/3.5/lib/python3.5/site-packages/ipykernel/__main__.py:4: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
</code>```

Now we'll try an equivalent thing that won't produce the warning

```<code>df_other = pd.DataFrame(dict(A=[1], B=[2]))
df_out = df_other.loc[:]

df_out['E'] = 5
</code>```

Then

```<code>print `df_out`

   A  B  E
0  1  2  5
</code>```

It boils down to pandas deciding to attach an is_copy attribute to a dataframe when it's constructed  based on lots of criteria.

Notice the

```<code>df_other[:].is_copy

<weakref at 0x103323458; to 'DataFrame' at 0x116a684e0>
</code>```

When

```<code>df_other.loc[:].is_copy
</code>```

Returns None

So what types of construction trigger the copy?  I still don't know everything, and not even the things I know all make sense to me.

Like why does this not trigger it?

```<code>df_other[['A', 'B', 'E']].is_copy
</code>```

Body:
I've been searching around reading the pandas docs here and trying different lines of code from questions posted around here and here and I can't seem to get away from the setting with copy warning. I'd prefer to learn to code it the "right" way as opposed to just ignoring the warnings.

The following lines of code are inside a for loop and I don't want to generate this warning a lot of times because it could slow things down.

I'm trying to make a new column with name: 'E'+vs where vs is a string in a list in the for loop

But for each one of them, I still get the following warning, even with the last 3 lines:

SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

Here are the troublesome lines I've tried so far:

#based on research, the first two seem to be the "wrong" way

df_out['E'+vs] = df_out[kvs].rolling(v).mean().copy()
df_out['E'+vs] = df_out[kvs].rolling(v).mean()

df_out.loc[:,'E'+vs] = df_out[kvs].rolling(v).mean().copy()
df_out.loc[:,'E'+vs] = df_out[kvs].rolling(v).mean()
df_out.loc[:,'E'+vs] = df_out.loc[:,kvs].rolling(v).mean()

The other one that gives a SettingWithCopyWarning is this:

df_out.dropna(inplace=True,axis=0)

This one also gave a warning (but I figured this one would)

df_out = df_out.dropna(inplace=True,axis=0)

How do I do both of these operations correctly?

EDIT: Here is the code that produced the original df_out

df_out= pd.concat([vol.Date[1:-1], ret.Return_Time[:-2], vol.Freq_Time[:-2],
               vol.Freq_Time[:-1].shift(-1), vol.Freq_Time[:].shift(-2)],
               axis=1).dropna().set_index('Date')

Body:
This is a confusing topic.  It's not the code you've posted that is the problem.  It's the code you haven't posted.  It's the code that generated the df_out

Consider this example and note the last line that generates the warning.

df_other = pd.DataFrame(dict(A=[1], B=[2]))
df_out = df_other[:]

df_out['E'] = 5

//anaconda/envs/3.5/lib/python3.5/site-packages/ipykernel/__main__.py:4: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

Now we'll try an equivalent thing that won't produce the warning

df_other = pd.DataFrame(dict(A=[1], B=[2]))
df_out = df_other.loc[:]

df_out['E'] = 5

Then

print `df_out`

   A  B  E
0  1  2  5

It boils down to pandas deciding to attach an is_copy attribute to a dataframe when it's constructed  based on lots of criteria.

Notice the

df_other[:].is_copy

<weakref at 0x103323458; to 'DataFrame' at 0x116a684e0>

When

df_other.loc[:].is_copy

Returns None

So what types of construction trigger the copy?  I still don't know everything, and not even the things I know all make sense to me.

Like why does this not trigger it?

df_other[['A', 'B', 'E']].is_copy


问:
Problem working with the NetworkInterface.Name
I am using following code to detect the name of the Network Interface Card on my PC. I am using a USB Modem.

```<code>public class DetectNIC
{
    public string ReturnNIC()
    {
        List<NetworkInterface> Interfaces = new List<NetworkInterface>();
        foreach (var nic in NetworkInterface.GetAllNetworkInterfaces())
        {
            if (nic.OperationalStatus == OperationalStatus.Up)
            {
                Interfaces.Add(nic);
            }
        }

        NetworkInterface result = null;
        foreach (NetworkInterface nic in Interfaces)
        {
            if (result == null)
            {
                result = nic;
            }
            else
            {
                if (nic.GetIPProperties().GetIPv4Properties() != null)
                {
                    if (nic.GetIPProperties().GetIPv4Properties().Index < result.GetIPProperties().GetIPv4Properties().Index)
                        result = nic;
                }
            }
        }
        return result.Name.ToString();
    }
}
</code>```

I am passing the result to the below given class to calculate the bytes consumption during internet traffic:

```<code>public class ByteCounter
{
    public double GetNetworkUtilization(string networkCard)
    {
        const int numberOfIterations = 10;

        PerformanceCounter bandwidthCounter =
            new PerformanceCounter("Network Interface", "Current Bandwidth", networkCard);

        float bandwidth = bandwidthCounter.NextValue();

        PerformanceCounter dataSentCounter =
            new PerformanceCounter("Network Interface", "Bytes Sent/sec", networkCard);

        PerformanceCounter dataReceivedCounter =
            new PerformanceCounter("Network Interface", "Bytes Received/sec", networkCard);

        float sendSum = 0;
        float receiveSum = 0;

        for (int index = 0; index < numberOfIterations; index++)
        {
            sendSum += dataSentCounter.NextValue();
            receiveSum += dataReceivedCounter.NextValue();
        }

        float dataSent = sendSum;
        float dataReceived = receiveSum;

        double utilization = (8 * (dataSent + dataReceived)) / (bandwidth * numberOfIterations) * 100;
        return utilization;
    }
}
</code>```

The first code works fine. It detects my modem as "MBlaze USB Modem", but when the control reaches to the second code with following line:

```<code>float bandwidth = bandwidthCounter.NextValue();
</code>```

it displays error:

```<code>System.InvalidOperationException was unhandled
  Message="Instance 'MBlaze USB Modem' does not exist in the specified Category."
  Source="System"
  StackTrace:
       at System.Diagnostics.CounterDefinitionSample.GetInstanceValue(String instanceName)
       at System.Diagnostics.PerformanceCounter.NextSample()
       at System.Diagnostics.PerformanceCounter.NextValue()
       at LogTraffic.ByteCounter.GetNetworkUtilization(String networkCard) in F:\Projects\LogTraffic\bytecounter.cs:line 15
       at LogTraffic.MainForm.MainForm_Load(Object sender, EventArgs e) in F:\Projects\LogTraffic\MainForm.cs:line 24
       at System.Windows.Forms.Form.OnLoad(EventArgs e)
       at System.Windows.Forms.Form.OnCreateControl()
       at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
       at System.Windows.Forms.Control.CreateControl()
       at System.Windows.Forms.Control.WmShowWindow(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       at System.Windows.Forms.ContainerControl.WndProc(Message& m)
       at System.Windows.Forms.Form.WmShowWindow(Message& m)
       at System.Windows.Forms.Form.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.SafeNativeMethods.ShowWindow(HandleRef hWnd, Int32 nCmdShow)
       at System.Windows.Forms.Control.SetVisibleCore(Boolean value)
       at System.Windows.Forms.Form.SetVisibleCore(Boolean value)
       at System.Windows.Forms.Control.set_Visible(Boolean value)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at LogTraffic.Program.Main() in F:\Projects\LogTraffic\Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:
</code>```

What is the problem?

I won't forget to give the credit to the authors of both the code.

First code credit: Keyvan Nayyeri

Second code credit: entens for his answer here.

答:
I modified my NIC finding code to return result.Description instead of result.Name. This should give the full interface name used as the InstanceName.

Windows will replace special characters however, so you should be aware of that. Which may be found at the MSDN page for the PerformanceCounter.InstanceName property.

I also made some modifications to the code from Keyvan Nayyeri to condition the input string to match expected instance names. Also, I incorporated Aliostad's code for searching the category for a matching name, but I only throw an exception if the InstanceName does not exist.

```<code>    public double GetNetworkUtilization(string networkCard)
{
    const int numberOfIterations = 10;

    // Condition networkCard;
    networkCard = networkCard.Replace("\\", "_");
    networkCard = networkCard.Replace("/", "_");
    networkCard = networkCard.Replace("(", "[");
    networkCard = networkCard.Replace(")", "]");
    networkCard = networkCard.Replace("#", "_");

    PerformanceCounterCategory NetworkInterfaceCatagory =
        PerformanceCounterCategory.GetCategories().Where(c => c.CategoryName.Equals("Network Interface")).FirstOrDefault();

    //// DEBUG: Check this array to see if the network card exists
    //foreach(string instance in NetworkInterfaceCatagory.GetInstanceNames())
    //{
    //    System.Diagnostics.Debug.Print(instance);
    //}

    if (string.IsNullOrEmpty(NetworkInterfaceCatagory.GetInstanceNames().Where(i => i.Equals(networkCard)).FirstOrDefault()))
        throw new ApplicationException("NIC does not exist in existing performance counters");

    string instanceName = networkCard;

    PerformanceCounter bandwidthCounter =
        new PerformanceCounter("Network Interface", "Current Bandwidth", instanceName);

    PerformanceCounter dataSentCounter =
        new PerformanceCounter("Network Interface", "Bytes Sent/sec", instanceName);

    PerformanceCounter dataReceivedCounter =
        new PerformanceCounter("Network Interface", "Bytes Received/sec", instanceName);

    float bandwidth = bandwidthCounter.NextValue();
    float sendSum = 0;
    float receiveSum = 0;

    for (int index = 0; index < numberOfIterations; index++)
    {
        sendSum += dataSentCounter.NextValue();
        receiveSum += dataReceivedCounter.NextValue();
    }

    float dataSent = sendSum;
    float dataReceived = receiveSum;

    double utilization = (8 * (dataSent + dataReceived)) / (bandwidth * numberOfIterations) * 100;
    return utilization;
}
</code>```

Body:
I am using following code to detect the name of the Network Interface Card on my PC. I am using a USB Modem.

public class DetectNIC
{
    public string ReturnNIC()
    {
        List<NetworkInterface> Interfaces = new List<NetworkInterface>();
        foreach (var nic in NetworkInterface.GetAllNetworkInterfaces())
        {
            if (nic.OperationalStatus == OperationalStatus.Up)
            {
                Interfaces.Add(nic);
            }
        }

        NetworkInterface result = null;
        foreach (NetworkInterface nic in Interfaces)
        {
            if (result == null)
            {
                result = nic;
            }
            else
            {
                if (nic.GetIPProperties().GetIPv4Properties() != null)
                {
                    if (nic.GetIPProperties().GetIPv4Properties().Index < result.GetIPProperties().GetIPv4Properties().Index)
                        result = nic;
                }
            }
        }
        return result.Name.ToString();
    }
}

I am passing the result to the below given class to calculate the bytes consumption during internet traffic:

public class ByteCounter
{
    public double GetNetworkUtilization(string networkCard)
    {
        const int numberOfIterations = 10;

        PerformanceCounter bandwidthCounter =
            new PerformanceCounter("Network Interface", "Current Bandwidth", networkCard);

        float bandwidth = bandwidthCounter.NextValue();

        PerformanceCounter dataSentCounter =
            new PerformanceCounter("Network Interface", "Bytes Sent/sec", networkCard);

        PerformanceCounter dataReceivedCounter =
            new PerformanceCounter("Network Interface", "Bytes Received/sec", networkCard);

        float sendSum = 0;
        float receiveSum = 0;

        for (int index = 0; index < numberOfIterations; index++)
        {
            sendSum += dataSentCounter.NextValue();
            receiveSum += dataReceivedCounter.NextValue();
        }

        float dataSent = sendSum;
        float dataReceived = receiveSum;

        double utilization = (8 * (dataSent + dataReceived)) / (bandwidth * numberOfIterations) * 100;
        return utilization;
    }
}

The first code works fine. It detects my modem as "MBlaze USB Modem", but when the control reaches to the second code with following line:

float bandwidth = bandwidthCounter.NextValue();

it displays error:

System.InvalidOperationException was unhandled
  Message="Instance 'MBlaze USB Modem' does not exist in the specified Category."
  Source="System"
  StackTrace:
       at System.Diagnostics.CounterDefinitionSample.GetInstanceValue(String instanceName)
       at System.Diagnostics.PerformanceCounter.NextSample()
       at System.Diagnostics.PerformanceCounter.NextValue()
       at LogTraffic.ByteCounter.GetNetworkUtilization(String networkCard) in F:\Projects\LogTraffic\bytecounter.cs:line 15
       at LogTraffic.MainForm.MainForm_Load(Object sender, EventArgs e) in F:\Projects\LogTraffic\MainForm.cs:line 24
       at System.Windows.Forms.Form.OnLoad(EventArgs e)
       at System.Windows.Forms.Form.OnCreateControl()
       at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
       at System.Windows.Forms.Control.CreateControl()
       at System.Windows.Forms.Control.WmShowWindow(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       at System.Windows.Forms.ContainerControl.WndProc(Message& m)
       at System.Windows.Forms.Form.WmShowWindow(Message& m)
       at System.Windows.Forms.Form.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.SafeNativeMethods.ShowWindow(HandleRef hWnd, Int32 nCmdShow)
       at System.Windows.Forms.Control.SetVisibleCore(Boolean value)
       at System.Windows.Forms.Form.SetVisibleCore(Boolean value)
       at System.Windows.Forms.Control.set_Visible(Boolean value)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at LogTraffic.Program.Main() in F:\Projects\LogTraffic\Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:

What is the problem?

I won't forget to give the credit to the authors of both the code.

First code credit: Keyvan Nayyeri

Second code credit: entens for his answer here.

Body:
I modified my NIC finding code to return result.Description instead of result.Name. This should give the full interface name used as the InstanceName.

Windows will replace special characters however, so you should be aware of that. Which may be found at the MSDN page for the PerformanceCounter.InstanceName property.

I also made some modifications to the code from Keyvan Nayyeri to condition the input string to match expected instance names. Also, I incorporated Aliostad's code for searching the category for a matching name, but I only throw an exception if the InstanceName does not exist.

    public double GetNetworkUtilization(string networkCard)
{
    const int numberOfIterations = 10;

    // Condition networkCard;
    networkCard = networkCard.Replace("\\", "_");
    networkCard = networkCard.Replace("/", "_");
    networkCard = networkCard.Replace("(", "[");
    networkCard = networkCard.Replace(")", "]");
    networkCard = networkCard.Replace("#", "_");

    PerformanceCounterCategory NetworkInterfaceCatagory =
        PerformanceCounterCategory.GetCategories().Where(c => c.CategoryName.Equals("Network Interface")).FirstOrDefault();

    //// DEBUG: Check this array to see if the network card exists
    //foreach(string instance in NetworkInterfaceCatagory.GetInstanceNames())
    //{
    //    System.Diagnostics.Debug.Print(instance);
    //}

    if (string.IsNullOrEmpty(NetworkInterfaceCatagory.GetInstanceNames().Where(i => i.Equals(networkCard)).FirstOrDefault()))
        throw new ApplicationException("NIC does not exist in existing performance counters");

    string instanceName = networkCard;

    PerformanceCounter bandwidthCounter =
        new PerformanceCounter("Network Interface", "Current Bandwidth", instanceName);

    PerformanceCounter dataSentCounter =
        new PerformanceCounter("Network Interface", "Bytes Sent/sec", instanceName);

    PerformanceCounter dataReceivedCounter =
        new PerformanceCounter("Network Interface", "Bytes Received/sec", instanceName);

    float bandwidth = bandwidthCounter.NextValue();
    float sendSum = 0;
    float receiveSum = 0;

    for (int index = 0; index < numberOfIterations; index++)
    {
        sendSum += dataSentCounter.NextValue();
        receiveSum += dataReceivedCounter.NextValue();
    }

    float dataSent = sendSum;
    float dataReceived = receiveSum;

    double utilization = (8 * (dataSent + dataReceived)) / (bandwidth * numberOfIterations) * 100;
    return utilization;
}


问:
Opening A File With Code
I have a string of the file path and I want to open the file. Not in the way that it shows bytes in the console for example, but to open the original file with the program that suits him.

For example if my path shows a .docs file I want it to be opened with Word.

Any suggestions?

Title: Opening A File With Code

Body: System.Diagnostics.Process.Start("CMD.exe",filePath);


问:
Java - cast not producing expected output
```<code>public class Test {

public static void main(String[] args) {

int test = 1;

System.out.println((double)(Math.pow(test/++test, 2)));

}
</code>```

0.0 is printed to the screen. Why? Why is the cast not working as expected?

If test is declared this way...

```<code>double test = 1;
</code>```

I get what I expect to print... 0.25.

Why?

I am new to programming and I'm playing around. Reading some of the documentation at this level is next to useless.

答:
You are doing integer division. SO change the line to

```<code>System.out.println((Math.pow(test/(double)++test, 2)));
</code>```

to do double division

Body:
public class Test {

public static void main(String[] args) {

int test = 1;

System.out.println((double)(Math.pow(test/++test, 2)));

}

0.0 is printed to the screen. Why? Why is the cast not working as expected?

If test is declared this way...

double test = 1;

I get what I expect to print... 0.25.

Why?

I am new to programming and I'm playing around. Reading some of the documentation at this level is next to useless.

Body:
You are doing integer division. SO change the line to

System.out.println((Math.pow(test/(double)++test, 2)));

to do double division


问:
Android logcat error: "E/CliptrayUtils: hideClipTrayIfNeeded() TextView is focused!! hideClipTray()"
I am new und unexperienced to Android, trying to develop apps in Ubuntu 14.04 with Android Studio 1.4. I use two activities, and none of these activities, layout or the like uses a 'ClipTray'. However, in logcat I see the following entry:

```<code>E/CliptrayUtils: hideClipTrayIfNeeded() TextView is focused!! hideClipTray()
</code>```

and google does not really help here (no luck to find anything even for just the phrase hideClipTrayIfNeeded().

Although this is listed as an error, the app seems to work without problems! But I do not like to have unfixed errors!

I also see those lines randomly in my log file:

```<code>D/CliptrayUtils: setInputTypeforClipTray(): 0
</code>```

Any suggestions are welcome.

Addition: I just realized that this error probably only occurs when the app is running on the actual phone and I switch off the display. Could that be the cause of this error? Then it has nothing to do with the actual app and I will be happy...

答:
Ok, it's an old post but due to the fact that as I tested my application and I had exactly the same question, I would like to add that this issue is shown only in LG devices.
Testing the same app on a Nexus device this issue is not shown at all.
So I think, it is not an issue.</p>

Body:
I am new und unexperienced to Android, trying to develop apps in Ubuntu 14.04 with Android Studio 1.4. I use two activities, and none of these activities, layout or the like uses a 'ClipTray'. However, in logcat I see the following entry:

E/CliptrayUtils: hideClipTrayIfNeeded() TextView is focused!! hideClipTray()

and google does not really help here (no luck to find anything even for just the phrase hideClipTrayIfNeeded().

Although this is listed as an error, the app seems to work without problems! But I do not like to have unfixed errors!

I also see those lines randomly in my log file:

D/CliptrayUtils: setInputTypeforClipTray(): 0

Any suggestions are welcome.

Addition: I just realized that this error probably only occurs when the app is running on the actual phone and I switch off the display. Could that be the cause of this error? Then it has nothing to do with the actual app and I will be happy...


问:
linebreak from text_area missing in the database
I use a text_area in my test rails app

```<code>= form_for @post do |f|
  = f.text_field :title, size: '40'
  = f.text_area :description, size: "80x20"
</code>```

and render markdown using RedCarpet

```<code>.post-description
  = markdown(post.description)
</code>```

When I insert a list into the text_area, markdown is not rendered correctly due to missing line breaks in the description field.

The result is something like this

```<code>=markdown("1. test 2. test")
</code>```

I guess linebreaks from the form need to be saved in the database. A simple string with a linebreak

```<code>=markdown("1. test /n 2. test")
</code>```

worked as expected.

Can anyone give me a hint?

答:
normally the textarea field have newline saved as \r\n, and it can be parse by the redcarpet. you need to check the post.description output, check if there exist some jquery plugin for the description edit, if there are callback which modify the description.Find the reason why description field it didn't have newline.

try

```<code>require 'redcarpet'

markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML.new)

p markdown.render("1. test 2. test")
p markdown.render("1. eee\r\n2. 113")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I use a text_area in my test rails app

= form_for @post do |f|
  = f.text_field :title, size: '40'
  = f.text_area :description, size: "80x20"

and render markdown using RedCarpet

.post-description
  = markdown(post.description)

When I insert a list into the text_area, markdown is not rendered correctly due to missing line breaks in the description field.

The result is something like this

=markdown("1. test 2. test")

I guess linebreaks from the form need to be saved in the database. A simple string with a linebreak

=markdown("1. test /n 2. test")

worked as expected.

Can anyone give me a hint?

Body:
normally the textarea field have newline saved as \r\n, and it can be parse by the redcarpet. you need to check the post.description output, check if there exist some jquery plugin for the description edit, if there are callback which modify the description.Find the reason why description field it didn't have newline.

try

require 'redcarpet'

markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML.new)

p markdown.render("1. test 2. test")
p markdown.render("1. eee\r\n2. 113")


问:
A regex to remove id, style, class attributes from HTML tags in JS
I got a html String in javascript and using regex I want to remove id, style and class attributes in html tags, for example I have:

```<code>New York City.<div style="padding:20px" id="upp" class="upper"><div style="background:#F2F2F2; color:black; font-size:90%; padding:10px 10px; width:500px;">This message is.</div></div>
</code>```

I want this String to become:

```<code>New York City.<div><div>This message is.</div></div>
</code>```

答:
I don't know about RegEx, but I sure as hell know about jQuery.

Convert the given HTML string into a DOM element, parse it, and return its contents.

```<code>function cleanStyles(html){
    var temp = $(document.createElement('div'));
        temp.html(html);

        temp.find('*').removeAttr('style');
        return temp.html();
}
</code>```

Body:
I got a html String in javascript and using regex I want to remove id, style and class attributes in html tags, for example I have:

New York City.

This message is.

I want this String to become:

New York City.

This message is.

Body:
I don't know about RegEx, but I sure as hell know about jQuery.

Convert the given HTML string into a DOM element, parse it, and return its contents.

function cleanStyles(html){
    var temp = $(document.createElement('div'));
        temp.html(html);

        temp.find('*').removeAttr('style');
        return temp.html();
}


问:
Solving equations involving ceilings
I would like to solve the equations of the following type in Python. Please let me know if there are any relevant libraries or methods to solve it. ceil(x) denotes the ceiling function.

ceil(x/7)+3*ceil(x/12) = x

This is just a random example, not sure if there is a solution to this.

I tried looking into Sympy library of Python but I can't find a way to use it for my case.

Any help is appreciated. Thanks!

答:
I tried

```<code>from sympy import ceiling
from sympy.solvers import solve
from sympy import Symbol
x = Symbol('x')

print(solve(ceiling(x/7) + 3*ceiling(x/12) - x, x))
</code>```

which ended up in

```<code>No algorithms are implemented to solve equation -x + 3*ceiling(x/12) + ceiling(x/7)
</code>```

The only thing I can think of right now is a graphical solution.

Title: Solving equations involving ceilings

Body:
I tried

from sympy import ceiling
from sympy.solvers import solve
from sympy import Symbol
x = Symbol('x')

print(solve(ceiling(x/7) + 3*ceiling(x/12) - x, x))

which ended up in

No algorithms are implemented to solve equation -x + 3*ceiling(x/12) + ceiling(x/7)

The only thing I can think of right now is a graphical solution.


问:
DataSerializable - serialize and deserialize two dimensional arrays
There are methods like writeDoubleArray and so on in ObjectDataOutput interface. Of course arrays can be of any dimension and in my case there are some 2D double arrays. How to serialize and then deserialize those? Or maybe because of the way Java handles 2D arrays (not really contiguous blocks in memory) I need to represent a 2D array as 1D one? I mean because of the performance I shouldn't really serialize 2D arrays. Just wrap it into utility object and store like this...?

答:
You have to put the other dimensions yourself first, like the following snippet:

```<code>public static class Foo implements DataSerializable {

    private double[][] multiDimArray;

    @Override
    public void writeData(ObjectDataOutput out)
            throws IOException {

        int firstDim = multiDimArray.length;
        out.writeInt(firstDim);
        for (int i = 0; i < firstDim; i++) {
            out.writeDoubleArray(multiDimArray[i]);
        }
    }

    @Override
    public void readData(ObjectDataInput in)
            throws IOException {

        int firstDim = in.readInt();
        multiDimArray = new double[firstDim][];
        for (int i = 0; i < firstDim; i++) {
            multiDimArray[i] = in.readDoubleArray();
        }
    }
}
</code>```

That way it is possible two write any depth of array into a stream. You might be able to abstract that a bit away into two methods (read/write) for easier / more convenient use.

Body:
You have to put the other dimensions yourself first, like the following snippet:

public static class Foo implements DataSerializable {

    private double[][] multiDimArray;

    @Override
    public void writeData(ObjectDataOutput out)
            throws IOException {

        int firstDim = multiDimArray.length;
        out.writeInt(firstDim);
        for (int i = 0; i < firstDim; i++) {
            out.writeDoubleArray(multiDimArray[i]);
        }
    }

    @Override
    public void readData(ObjectDataInput in)
            throws IOException {

        int firstDim = in.readInt();
        multiDimArray = new double[firstDim][];
        for (int i = 0; i < firstDim; i++) {
            multiDimArray[i] = in.readDoubleArray();
        }
    }
}

That way it is possible two write any depth of array into a stream. You might be able to abstract that a bit away into two methods (read/write) for easier / more convenient use.


问:
How to check if last element in array matches a condition, mongodb
I have a collection of samples which is like this :

```<code>{
    "_id" : ObjectId("58d6cbc14124691cd8154d72"),
    "correlativeCode" : "CSLLPA53E20M017W",
    "registrationMethod" : "taken",
    "originPlace" : "INSPI",
    "temperature" : 16,
    "sampleStatus" : [
        {
            "nameStatus" : "status1",
            "place" : "place1",
            "rejectionReason" : "Nothing",
            "user" : "user1",
            "_id" : ObjectId("58d6cbc14124691cd8154d73")
        },
        {
            "nameStatus" : "status2",
            "place" : "place2",
            "rejectionReason" : "Nothing",
            "user" : "user4",
            "_id" : ObjectId("58d6cbc14124691cd8154d73")
        },
        {
            "nameStatus" : "status3",
            "place" : "place3",
            "rejectionReason" : "Nothing",
            "user" : "user3",
            "_id" : ObjectId("58d6cbc14124691cd8154d73")
        },
        {
            "nameStatus" : "status4",
            "place" : "place4",
            "rejectionReason" : "Nothing",
            "user" : "user1",
            "_id" : ObjectId("58d6cbc14124691cd8154d73")
        },
        {
            "nameStatus" : "status5",
            "place" : "place5",
            "rejectionReason" : "Nothing",
            "user" : "user5",
            "_id" : ObjectId("58d6cbc14124691cd8154d73")
        }
    ]
}
</code>```

First, I want to find a Sample by correlativeCode (it is very easy) but.. then
I need to get the last element of sampleStatus and check if the user field of the sampleStatus array, is equal to an expression (another user).

The length of the sampleStatus array is variable.

I have tried $slice command but it doesn't work fine.

For example,

If I find a Sample with correlativeCode "CSLLPA53E20M017W" where the last sampleStatus.user is user1, it should fetch 0 records.

But if I find a Sample with correlativeCode "CSLLPA53E20M017W" where the last sampleStatus.user is user5, it should fetch 1 record.

Please help me, I'm stuck.

答:
You can do this with the aggregation framework</p>

```<code>db.collection.aggregate([
    { "$match": { "correlativeCode": "CSLLPA53E20M017W" } },
    { "$redact": {
        "$cond": [
            { "$eq": [
                { "$let": {
                    "vars": {
                        "item": { "$arrayElemAt": [ "$sampleStatus", -1 ] }
                    },
                    "in": "$$item.user"
                } },
                "user5"
            ] },
            "$$KEEP",
            "$$PRUNE"
        ]
    }}
])
</code>```

Body:
I have a collection of samples which is like this :

{
    "_id" : ObjectId("58d6cbc14124691cd8154d72"),
    "correlativeCode" : "CSLLPA53E20M017W",
    "registrationMethod" : "taken",
    "originPlace" : "INSPI",
    "temperature" : 16,
    "sampleStatus" : [
        {
            "nameStatus" : "status1",
            "place" : "place1",
            "rejectionReason" : "Nothing",
            "user" : "user1",
            "_id" : ObjectId("58d6cbc14124691cd8154d73")
        },
        {
            "nameStatus" : "status2",
            "place" : "place2",
            "rejectionReason" : "Nothing",
            "user" : "user4",
            "_id" : ObjectId("58d6cbc14124691cd8154d73")
        },
        {
            "nameStatus" : "status3",
            "place" : "place3",
            "rejectionReason" : "Nothing",
            "user" : "user3",
            "_id" : ObjectId("58d6cbc14124691cd8154d73")
        },
        {
            "nameStatus" : "status4",
            "place" : "place4",
            "rejectionReason" : "Nothing",
            "user" : "user1",
            "_id" : ObjectId("58d6cbc14124691cd8154d73")
        },
        {
            "nameStatus" : "status5",
            "place" : "place5",
            "rejectionReason" : "Nothing",
            "user" : "user5",
            "_id" : ObjectId("58d6cbc14124691cd8154d73")
        }
    ]
}

First, I want to find a Sample by correlativeCode (it is very easy) but.. then
I need to get the last element of sampleStatus and check if the user field of the sampleStatus array, is equal to an expression (another user).

The length of the sampleStatus array is variable.

I have tried $slice command but it doesn't work fine.

For example,

If I find a Sample with correlativeCode "CSLLPA53E20M017W" where the last sampleStatus.user is user1, it should fetch 0 records.

But if I find a Sample with correlativeCode "CSLLPA53E20M017W" where the last sampleStatus.user is user5, it should fetch 1 record.

Please help me, I'm stuck.

Body:
You can do this with the aggregation framework

db.collection.aggregate([
    { "$match": { "correlativeCode": "CSLLPA53E20M017W" } },
    { "$redact": {
        "$cond": [
            { "$eq": [
                { "$let": {
                    "vars": {
                        "item": { "$arrayElemAt": [ "$sampleStatus", -1 ] }
                    },
                    "in": "$$item.user"
                } },
                "user5"
            ] },
            "$$KEEP",
            "$$PRUNE"
        ]
    }}
])


问:
Combine 2 lists in python such that elements at the corresponding index are together
I have two lists like:

```<code>listone = [1, 2, 3]
listtwo = [4, 5, 6]
</code>```

I would like to combine them to get:

```<code>l = [1, 4, 2, 5, 3, 6]
</code>```

How can I do this without using loops?

答:
You may use list slicing feature of the list as:

```<code>>>> new_list = listone + listtwo  # create initial list of `len` equal
                                  # to `listone + listtwo`
>>> new_list[::2] = listone
>>> new_list[1::2] = listtwo
>>> new_list
[1, 4, 2, 5, 3, 6]
</code>```

Another very simple way to achieve this is via using zip() with nested list comprehension expression as:

```<code>>>> listone = [1, 2, 3]
>>> listtwo = [4, 5, 6]

>>> [b for a in zip(listone, listtwo) for b in a]
[1, 4, 2, 5, 3, 6]
</code>```

Body:
I have two lists like:

listone = [1, 2, 3]
listtwo = [4, 5, 6]

I would like to combine them to get:

l = [1, 4, 2, 5, 3, 6]

How can I do this without using loops?

Body:
You may use list slicing feature of the list as:

>>> new_list = listone + listtwo  # create initial list of `len` equal
                                  # to `listone + listtwo`
>>> new_list[::2] = listone
>>> new_list[1::2] = listtwo
>>> new_list
[1, 4, 2, 5, 3, 6]

Another very simple way to achieve this is via using zip() with nested list comprehension expression as:

>>> listone = [1, 2, 3]
>>> listtwo = [4, 5, 6]

>>> [b for a in zip(listone, listtwo) for b in a]
[1, 4, 2, 5, 3, 6]


问:
Android Studio - XML Editor autocomplete not working with support libraries
I just started using the new android.support.design library. When using any of the widgets inside the XML editor I stop getting the XML autocomplete suggestions!

For example,

```<code><android.support.design.widget.CoordinatorLayout
    android:id="@+id/header_root"
    android:layout_width="match_parent"
    android:layout_height="200dp">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/primary_dark" />

    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|right"
        android:src="@drawable/ic_action_add"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="56dp"
        app:fabSize="normal"
        app:layout_anchor="@id/header_root"
        app:layout_anchorGravity="bottom|right|end" />

</android.support.design.widget.CoordinatorLayout>
</code>```

None of the tags will show the autocomplete popup, like when I start typing "android:i" no popup appears, the only suggestion I get is shown in the following picture.

I have tried cleaning my project, restarting the pc, restarting Android Studio.. nothing is working!

答:
In my case Code Completion suggestions were not appearing because Gradle dependency was missing in my application's module.

I was using android.support.design.widget.TabLayout in my XML layout, but I have not added Design Support Library compile 'com.android.support:design:25.3.1' Gradle dependency in my application module.

Body:
I just started using the new android.support.design library. When using any of the widgets inside the XML editor I stop getting the XML autocomplete suggestions!

For example,

<android.support.design.widget.CoordinatorLayout
    android:id="@+id/header_root"
    android:layout_width="match_parent"
    android:layout_height="200dp">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/primary_dark" />

    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|right"
        android:src="@drawable/ic_action_add"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="56dp"
        app:fabSize="normal"
        app:layout_anchor="@id/header_root"
        app:layout_anchorGravity="bottom|right|end" />

</android.support.design.widget.CoordinatorLayout>

None of the tags will show the autocomplete popup, like when I start typing "android:i" no popup appears, the only suggestion I get is shown in the following picture.

I have tried cleaning my project, restarting the pc, restarting Android Studio.. nothing is working!


问:
jsonp loop through the data
I have a webservice returning jsonp format. here's the code:

```<code>$(document).ready(function(){
       $.getJSON("http://api.tubeupdates.com/?method=get.status&lines=central,victoria&return=name&jsonp=?",
             function (result){
                  $.each(result.items, function(item){
                     $('body').append(item.response.lines[0].name);

             });
        }
     );

});
</code>```

It works fine if I remove the loop but fails with the $.each loop.
Any idea of what am I doing wrong?

Thanks

Mauro

答:
The response doesn't have an array on an items property, it looks like this:

```<code>{"response":{"lines":[{"name":"Central"},{"name":"Victoria"}]}}
</code>```

It looks like you want to iterate the response.lines array, in which case you need to do this:

```<code>$.each(result.response.lines, function(i, item){
   $('body').append(item.name);
});
</code>```

You can test it out here.

Title: jsonp loop through the data

Body:
I have a webservice returning jsonp format. here's the code:

$(document).ready(function(){
       $.getJSON("http://api.tubeupdates.com/?method=get.status&lines=central,victoria&return=name&jsonp=?",
             function (result){
                  $.each(result.items, function(item){
                     $('body').append(item.response.lines[0].name);

             });
        }
     );

});

It works fine if I remove the loop but fails with the $.each loop.
Any idea of what am I doing wrong?

Thanks

Mauro

Body:
The response doesn't have an array on an items property, it looks like this:

{"response":{"lines":[{"name":"Central"},{"name":"Victoria"}]}}

It looks like you want to iterate the response.lines array, in which case you need to do this:

$.each(result.response.lines, function(i, item){
   $('body').append(item.name);
});

You can test it out here.


问:
Why rails devise gem throws 'invalid current password' error if only password confirmation is blank?
I'm dealing with the renewal password screen errors on my rails app which has three inputs: current password, new password and password confirmation.

There is one case when current password is correct but new password and password confirmation are blank but devise still throws 2 errors:

Current password is invalid. (wrong)

New password can't be blank. (correct)

Have anyone experienced this behaviour?

Thanks

答:
I guess your current_password is not correct. Any typos?

Let's update your password and test again!

```<code>user.password = new_password
user.password_confirmation = new_password
user.save
</code>```

Body:
I guess your current_password is not correct. Any typos?

Let's update your password and test again!

user.password = new_password
user.password_confirmation = new_password
user.save


问:
Maven set dependency mediation strategy to newest rather than nearest
Can I configure Maven to choose the "newest" dependency on a conflict, rather than the "nearest"?

The "newest" is the default in Ivy and other sensible dependency managers, see http://ant.apache.org/ivy/history/2.2.0/settings/conflict-managers.html

I find the "nearest" strategy is rarely what I want.

I'm using Maven 3.3.3, but I can switch versions if necessary.

I know how to override Maven's choice on individual conflicts, but I'd prefer to change the default so that I don't have to detect and fix each conflict one at a time.

(See the Maven docs on "Dependency mediation")

答:
Can I configure Maven to automatically use the "newest" version of a dependency instead of the "nearest" when resolving version conflicts?

No, you cannot configure Maven's dependency mediation strategy to anything other than nearest.

Adding configurable dependency mediation strategies has been proposed before, but was ultimately abandoned because the proposal involved changing the POM XSD, which has not happened in years.

Why does Maven use the nearest strategy as a default?

The strategy of nearest is favored by Maven for two reasons:

Easy overriding of individual conflicts: For any particular conflicting
dependency, you can specify its version within your own POM, and that version becomes the nearest.

Reproducible builds:  Version ranges anywhere in your dependency graph can cause builds to not be reproducible.  A mediation strategy of "newest" would magnify the negative impact of version ranges on build reproducibility.

But I really want a different dependency mediation strategy.  What can I do?

These are your best options:

Make a Maven extension: Usage of the "nearest" strategy is specified by NearestVersionSelector in MavenRepositorySystemUtils.  You could create your own Maven extension that defines your own VersionSelector that implements the strategy of your choice, then in the afterSessionStart method of your extension, replace the session's DependencyGraphTransformer with one that uses your custom VersionSelector.

Migrate to another build tool: Obviously.


问:
Toast crash during main thread execution
I've got a method test() that runs every 3 seconds in main thread using the following Runnable and Handler decleration:

```<code>private Runnable _checker = new Runnable() {
    @Override
    public void run() {
    try {
        test();
    } finally {
        if (!_stopTest) {
            _testHandler.postDelayed(_checker, 3000);
        }
    }
    }
};
</code>```

This toast message runs on main thread during test() method:

```<code>Toast.makeText(getActivity(), "Recalculating...", Toast.LENGTH_SHORT).show();
</code>```

ends up with exception:

```<code>04-02 09:56:44.229 31232-31232/com.app E/UncaughtException: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
                                                                     at android.widget.Toast.<init>(Toast.java:105)
                                                                     at android.widget.Toast.makeText(Toast.java:262)
                                                                     at com.BaseSupportFragment.test(BaseSupportFragment.java:916)
</code>```

The exception occurs during onBackPressed, which I override to remove the fragment container (which contains the fragment that should show the toast message that fails).

Does anybody know what happens here?

答:
The exception occurs during onBackPressed.

Next time getActivity() is called it returns null, because your fragment currently is not attached to any activity. Thus crash happens.

In onBackPress() you have to cancel scheduled runnables:

```<code>_testHandler.removeCallbacks(_checker);
</code>```

Body:
I've got a method test() that runs every 3 seconds in main thread using the following Runnable and Handler decleration:

private Runnable _checker = new Runnable() {
    @Override
    public void run() {
    try {
        test();
    } finally {
        if (!_stopTest) {
            _testHandler.postDelayed(_checker, 3000);
        }
    }
    }
};

This toast message runs on main thread during test() method:

Toast.makeText(getActivity(), "Recalculating...", Toast.LENGTH_SHORT).show();

ends up with exception:

04-02 09:56:44.229 31232-31232/com.app E/UncaughtException: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
                                                                     at android.widget.Toast.<init>(Toast.java:105)
                                                                     at android.widget.Toast.makeText(Toast.java:262)
                                                                     at com.BaseSupportFragment.test(BaseSupportFragment.java:916)

The exception occurs during onBackPressed, which I override to remove the fragment container (which contains the fragment that should show the toast message that fails).

Does anybody know what happens here?

Body:
The exception occurs during onBackPressed.

Next time getActivity() is called it returns null, because your fragment currently is not attached to any activity. Thus crash happens.

In onBackPress() you have to cancel scheduled runnables:

_testHandler.removeCallbacks(_checker);


问:
Add toolbar in certain fragment
I have a main activity:

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</code>```

This activity just has a framelayout and uses this layout to add, replace, and delete fragments.

I have 2 fragments:

LoginFragment  (constraintLayout)

```<code><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#4CF">

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Go to Register"
    android:layout_marginLeft="8dp"
    app:layout_constraintLeft_toLeftOf="parent"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    android:layout_marginBottom="8dp"
    app:layout_constraintVertical_bias="0.500" />
</code>```

RegisterFragment  (constraintLayout)

```<code><android.support.v7.widget.Toolbar
    android:id="@+id/my_toolbar"
    android:layout_width="0dp"
    android:layout_height="56dp"
    android:background="?attr/colorPrimary"
    android:elevation="4dp"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    tools:layout_editor_absoluteY="1dp"
    android:layout_marginLeft="8dp"
    app:layout_constraintLeft_toLeftOf="parent"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp" />

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Welcome to the Register fragment"
    tools:layout_editor_absoluteY="205dp"
    tools:layout_editor_absoluteX="62dp" />
</code>```

The login fragment shows up first. This should have no actionbar. There is a button in this fragment which will replace this login fragment with the register fragment. In this fragment I want the actionbar to show up so that it can have the back arrow in the actionbar to go back to the login view. I have no idea though where to place the toolbar widget in the code? I have tried to set it in the register fragment, but it kept displaying oddly.

答:
Remove Toobar from your RegisterFragment and place it to your activity_main.xml file.

```<code>?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:minHeight="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>
</code>```

Show and hide Toolbar programmatically from your fragment's OnCreate() method. Use YOUR_ActionBar.show() to show Actionbar and YOUR_ActionBar.hide() to hide Actionbar.

LoginFragment

```<code>// ActionBar
ActionBar mActionBar;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // ActionBar
    mActionBar = ((AppCompatActivity)getActivity()).getSupportActionBar();
    mActionBar.hide();

}
</code>```

RegisterFragment

```<code>// ActionBar
ActionBar mActionBar;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // ActionBar
    mActionBar = ((AppCompatActivity)getActivity()).getSupportActionBar();
    mActionBar.show();

}
</code>```

Title: Add toolbar in certain fragment

Body:
I have a main activity:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

This activity just has a framelayout and uses this layout to add, replace, and delete fragments.

I have 2 fragments:

LoginFragment  (constraintLayout)

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#4CF">

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Go to Register"
    android:layout_marginLeft="8dp"
    app:layout_constraintLeft_toLeftOf="parent"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    android:layout_marginBottom="8dp"
    app:layout_constraintVertical_bias="0.500" />

RegisterFragment  (constraintLayout)

<android.support.v7.widget.Toolbar
    android:id="@+id/my_toolbar"
    android:layout_width="0dp"
    android:layout_height="56dp"
    android:background="?attr/colorPrimary"
    android:elevation="4dp"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    tools:layout_editor_absoluteY="1dp"
    android:layout_marginLeft="8dp"
    app:layout_constraintLeft_toLeftOf="parent"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp" />

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Welcome to the Register fragment"
    tools:layout_editor_absoluteY="205dp"
    tools:layout_editor_absoluteX="62dp" />

The login fragment shows up first. This should have no actionbar. There is a button in this fragment which will replace this login fragment with the register fragment. In this fragment I want the actionbar to show up so that it can have the back arrow in the actionbar to go back to the login view. I have no idea though where to place the toolbar widget in the code? I have tried to set it in the register fragment, but it kept displaying oddly.

Body:
Remove Toobar from your RegisterFragment and place it to your activity_main.xml file.

?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:minHeight="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

Show and hide Toolbar programmatically from your fragment's OnCreate() method. Use YOUR_ActionBar.show() to show Actionbar and YOUR_ActionBar.hide() to hide Actionbar.

LoginFragment

// ActionBar
ActionBar mActionBar;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // ActionBar
    mActionBar = ((AppCompatActivity)getActivity()).getSupportActionBar();
    mActionBar.hide();

}

RegisterFragment

// ActionBar
ActionBar mActionBar;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // ActionBar
    mActionBar = ((AppCompatActivity)getActivity()).getSupportActionBar();
    mActionBar.show();

}


问:
How to use factory provider?
I need to inject a service into another service in an Angular 2 application.

After reading the docs I deduced, that the best approach is to use a Factory Provider. However, two questions have arisen:

1) The docs recommend the creation of a HeroServiceProvider class with two "code segments":

```<code>let heroServiceFactory = (logger: Logger, userService: UserService) => {
  return new HeroService(logger, userService.user.isAuthorized);
};

export let heroServiceProvider =
  { provide: HeroService,
    useFactory: heroServiceFactory,
    deps: [Logger, UserService]
  };
</code>```

My question is how should the class generally look like? Where should one add the above code segments?

2) How should/could one use this factory? I see, it should be imported as:

```<code>import { heroServiceProvider } from './hero.service.provider';

@Component({
  selector: 'my-selector',
  template: `
  `,
  providers: [heroServiceProvider]
})
</code>```

How could then the desired parametrized service retrieved and accessed?

答:
1) The first part of your question is easy: you just keep the snippet you provided in a separate file and import it in the component as shown in your question:

import { heroServiceProvider } from './hero.service.provider';

2) As for the actual usage, you don't really need to change service-related code in the component. Just keep using it if the original service was injected. You don't even need to modify your component constructor. The idea of the service provider is that you can customize your service on a per-component basis by having custom service provider for each component, and you would do component-specific initialization in the factory function. Just don't forget to list your service provider in the decorator of your component, Angular is taking care of the rest "automagically".

Title: How to use factory provider?

Body:
I need to inject a service into another service in an Angular 2 application.

After reading the docs I deduced, that the best approach is to use a Factory Provider. However, two questions have arisen:

1) The docs recommend the creation of a HeroServiceProvider class with two "code segments":

let heroServiceFactory = (logger: Logger, userService: UserService) => {
  return new HeroService(logger, userService.user.isAuthorized);
};

export let heroServiceProvider =
  { provide: HeroService,
    useFactory: heroServiceFactory,
    deps: [Logger, UserService]
  };

My question is how should the class generally look like? Where should one add the above code segments?

2) How should/could one use this factory? I see, it should be imported as:

import { heroServiceProvider } from './hero.service.provider';

@Component({
  selector: 'my-selector',
  template: `
  `,
  providers: [heroServiceProvider]
})

How could then the desired parametrized service retrieved and accessed?


问:
compare multiple strings in foreach
I am making some programming for a hotel. They want an email receipt if a booking has been made.

I am working with a razor mergefield called: @GuaranteePolicy

A guest can book 1 or multiple rooms. If there is booked multiple rooms, the GuaranteePolicy has to be set on each room. But if the GuaranteePolicy is the same on each room, I have to print the GuaranteePolicy in the footer.

So as I see it I have to compare all the GuaranteePolicy mergefields in each room, and see if they consist of the same text? That I do not know how to solve.

I loop through the multiple rooms, and print if the GuaranteePolicy is different. That is working fine:

```<code>@if (!string.IsNullOrWhiteSpace(room.GuaranteePolicy))
{
    <tr>
        <th>
            <span><strong>GuaranteePolicy:</strong></span>
        </th>
    </tr>
    <tr>
        <th>
            <span>@room.GuaranteePolicy</span>
        </th>
    </tr>
}
</code>```

But how can I compare the text in multiple room.GuaranteePolicy and check if the text in each room is the same?

```<code> @if (room.GuaranteePolicy == ? )
{
    <tr>
        <th>
            <span>@room.GuaranteePolicy</span>
        </th>
    </tr>
    <tr>
         <th>
            <span>@room.GuaranteePolicy</span>
         </th>
    </tr>
}
</code>```

答:
In order to find out if all rooms have the same GuaranteePolicy property value, you should prepare ViewModel with that information and send it to the View afterwards.

Simplified room class:

```<code>public class Room
{
    public string GuaranteePolicy { get; set; }
}
</code>```

Loginc inside your controller that returns View in which you are displaying information:

```<code>List<Room> rooms = GetSelectedRooms(); //example

bool samePolicy = false;
var firstRoom = rooms.FirstOrDefault();
if (firstRoom != null)
{
    samePolicy = rooms.All(r => r.GuaranteePolicy == firstRoom.GuaranteePolicy);
}

//Attach samePolicy onto ViewModel or ViewBag so you can use it inside Razor view
</code>```

Title: compare multiple strings in foreach

Body:
I am making some programming for a hotel. They want an email receipt if a booking has been made.

I am working with a razor mergefield called: @GuaranteePolicy

A guest can book 1 or multiple rooms. If there is booked multiple rooms, the GuaranteePolicy has to be set on each room. But if the GuaranteePolicy is the same on each room, I have to print the GuaranteePolicy in the footer.

So as I see it I have to compare all the GuaranteePolicy mergefields in each room, and see if they consist of the same text? That I do not know how to solve.

I loop through the multiple rooms, and print if the GuaranteePolicy is different. That is working fine:

@if (!string.IsNullOrWhiteSpace(room.GuaranteePolicy))
{

            GuaranteePolicy:

            @room.GuaranteePolicy

}

But how can I compare the text in multiple room.GuaranteePolicy and check if the text in each room is the same?

 @if (room.GuaranteePolicy == ? )
{

            @room.GuaranteePolicy

            @room.GuaranteePolicy

}

Body:
In order to find out if all rooms have the same GuaranteePolicy property value, you should prepare ViewModel with that information and send it to the View afterwards.

Simplified room class:

public class Room
{
    public string GuaranteePolicy { get; set; }
}

Loginc inside your controller that returns View in which you are displaying information:

List<Room> rooms = GetSelectedRooms(); //example

bool samePolicy = false;
var firstRoom = rooms.FirstOrDefault();
if (firstRoom != null)
{
    samePolicy = rooms.All(r => r.GuaranteePolicy == firstRoom.GuaranteePolicy);
}

//Attach samePolicy onto ViewModel or ViewBag so you can use it inside Razor view


问:
Converting the Select Case with To and Is to c# problems
I am convertng vb.net to c# 2010 as my job, and none of the automatic tools I have can succeed completely.   In special example, this case:

```<code>'searchString is a string paramter from a long method
Select Case searchString
   Case "paid"
      'Do something long here
   Case "oaaaaa" To "ozzzzzz", "maaaaaa" To "mzzzzzz"
      'Do other long code
   Case Else
      'other long code
End Select
</code>```

I am mostly java developer before this, so not great with c# and none with vb.net.  I do not understand the "oaaaa to ...." part and this part is not converting.  Can you please point me to right place to find the c# version of this?

答: C# doesn't seem to have the concept of Case ... To.  See http://msdn.microsoft.com/en-us/library/cy37t14y(VS.80).aspx.  The C# example says "This language is not supported".</p>

Body:
I am convertng vb.net to c# 2010 as my job, and none of the automatic tools I have can succeed completely.   In special example, this case:

'searchString is a string paramter from a long method
Select Case searchString
   Case "paid"
      'Do something long here
   Case "oaaaaa" To "ozzzzzz", "maaaaaa" To "mzzzzzz"
      'Do other long code
   Case Else
      'other long code
End Select

I am mostly java developer before this, so not great with c# and none with vb.net.  I do not understand the "oaaaa to ...." part and this part is not converting.  Can you please point me to right place to find the c# version of this?


问:
Homebrew: Error: update-report should not be called directly
Running brew update I get the following:

```<code>/usr/local/Library/brew.sh: line 32: /usr/local/Library/ENV/scm/git: No such file or directory
/usr/local/Library/brew.sh: line 32: /usr/local/Library/ENV/scm/git: No such file or directory
[etc..]
Error: update-report should not be called directly!
</code>```

Calling brew config reports the following:

```<code>HOMEBREW_VERSION: 0.9.9
ORIGIN: https://github.com/Homebrew/brew.git
HEAD: 90e84453f9adda65de6b9274987d06e46caa5d37
Last commit: 4 hours ago
Core tap ORIGIN: https://github.com/Homebrew/homebrew-core
Core tap HEAD: 05ce2548bad01807c6be2aece21ab70d221755e6
Core tap last commit: 8 weeks ago
HOMEBREW_PREFIX: /usr/local
HOMEBREW_REPOSITORY: /usr/local
HOMEBREW_CELLAR: /usr/local/Cellar
HOMEBREW_BOTTLE_DOMAIN: https://homebrew.bintray.com
CPU: quad-core 64-bit ivybridge
Homebrew Ruby: 2.0.0-p648
Clang: 7.3 build 703
Git: 2.7.0 => /usr/local/bin/git
Perl: /usr/bin/perl
Python: /Users/username/anaconda/bin/python => /Users/username/anaconda/bin/python2.7
Ruby: /usr/bin/ruby => /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby
Java: 1.7.0_79, 1.6.0_65-b14-468
OS X: 10.11.4-x86_64
Xcode: 7.3
CLT: 7.3.0.0.1.1457485338
X11: 2.7.8 => /opt/X11
</code>```

Any idea how to fix this?  I wonder if Sophos Antivirus might be causing problems again..

答:
I met the same problem when I tried

```<code>brew tap homebrew/science
brew install opencv3
brew update
</code>```

However, typing

```<code>brew update
</code>```

again has solved my problem.

```<code>Updated 2 taps (caskroom/cask, homebrew/core).
==> Cleaning up /Library/Caches/Homebrew...
Removing: /Library/Caches/Homebrew/ant-1.9.7.yosemite.bottle.tar.gz... (5.4MB)
Removing: /Library/Caches/Homebrew/cmake-3.2.1.yosemite.bottle.1.tar.gz... (10.4MB)
Removing: /Library/Caches/Homebrew/gecode-4.3.3.yosemite.bottle.tar.gz... (2.8MB)
Removing: /Library/Caches/Homebrew/leptonica-1.71_1.yosemite.bottle.tar.gz... (1.9MB)
Removing: /Library/Caches/Homebrew/libpng-1.6.16.yosemite.bottle.tar.gz... (431.8KB)
Removing: /Library/Caches/Homebrew/libtiff-4.0.3.yosemite.bottle.tar.gz... (1MB)
Removing: /Library/Caches/Homebrew/minizinc-1.6.tar.gz... (18.2MB)
Removing: /Library/Caches/Homebrew/pkg-config-0.28.yosemite.bottle.2.tar.gz... (220.1KB)
Removing: /Library/Caches/Homebrew/tesseract-3.02.02_3.yosemite.bottle.tar.gz... (19MB)
==> Migrating /Library/Caches/Homebrew to /Users/zenglinwang/Library/Caches/Homebrew...
==> Deleting /Library/Caches/Homebrew...
Warning: Failed to delete /Library/Caches/Homebrew.
Please do so manually.
==> New / Updated / Deleted Formulae
.................
==> Migrating HOMEBREW_REPOSITORY (please wait)...
==> Migrated HOMEBREW_REPOSITORY to /usr/local/Homebrew!
Homebrew no longer needs to have ownership of /usr/local. If you wish you can
return /usr/local to its default ownership with:
  sudo chown root:wheel /usr/local
</code>```

Body:
Running brew update I get the following:

/usr/local/Library/brew.sh: line 32: /usr/local/Library/ENV/scm/git: No such file or directory
/usr/local/Library/brew.sh: line 32: /usr/local/Library/ENV/scm/git: No such file or directory
[etc..]
Error: update-report should not be called directly!

Calling brew config reports the following:

HOMEBREW_VERSION: 0.9.9
ORIGIN: https://github.com/Homebrew/brew.git
HEAD: 90e84453f9adda65de6b9274987d06e46caa5d37
Last commit: 4 hours ago
Core tap ORIGIN: https://github.com/Homebrew/homebrew-core
Core tap HEAD: 05ce2548bad01807c6be2aece21ab70d221755e6
Core tap last commit: 8 weeks ago
HOMEBREW_PREFIX: /usr/local
HOMEBREW_REPOSITORY: /usr/local
HOMEBREW_CELLAR: /usr/local/Cellar
HOMEBREW_BOTTLE_DOMAIN: https://homebrew.bintray.com
CPU: quad-core 64-bit ivybridge
Homebrew Ruby: 2.0.0-p648
Clang: 7.3 build 703
Git: 2.7.0 => /usr/local/bin/git
Perl: /usr/bin/perl
Python: /Users/username/anaconda/bin/python => /Users/username/anaconda/bin/python2.7
Ruby: /usr/bin/ruby => /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby
Java: 1.7.0_79, 1.6.0_65-b14-468
OS X: 10.11.4-x86_64
Xcode: 7.3
CLT: 7.3.0.0.1.1457485338
X11: 2.7.8 => /opt/X11

Any idea how to fix this?  I wonder if Sophos Antivirus might be causing problems again..

Body:
I met the same problem when I tried

brew tap homebrew/science
brew install opencv3
brew update

However, typing

brew update

again has solved my problem.

Updated 2 taps (caskroom/cask, homebrew/core).
==> Cleaning up /Library/Caches/Homebrew...
Removing: /Library/Caches/Homebrew/ant-1.9.7.yosemite.bottle.tar.gz... (5.4MB)
Removing: /Library/Caches/Homebrew/cmake-3.2.1.yosemite.bottle.1.tar.gz... (10.4MB)
Removing: /Library/Caches/Homebrew/gecode-4.3.3.yosemite.bottle.tar.gz... (2.8MB)
Removing: /Library/Caches/Homebrew/leptonica-1.71_1.yosemite.bottle.tar.gz... (1.9MB)
Removing: /Library/Caches/Homebrew/libpng-1.6.16.yosemite.bottle.tar.gz... (431.8KB)
Removing: /Library/Caches/Homebrew/libtiff-4.0.3.yosemite.bottle.tar.gz... (1MB)
Removing: /Library/Caches/Homebrew/minizinc-1.6.tar.gz... (18.2MB)
Removing: /Library/Caches/Homebrew/pkg-config-0.28.yosemite.bottle.2.tar.gz... (220.1KB)
Removing: /Library/Caches/Homebrew/tesseract-3.02.02_3.yosemite.bottle.tar.gz... (19MB)
==> Migrating /Library/Caches/Homebrew to /Users/zenglinwang/Library/Caches/Homebrew...
==> Deleting /Library/Caches/Homebrew...
Warning: Failed to delete /Library/Caches/Homebrew.
Please do so manually.
==> New / Updated / Deleted Formulae
.................
==> Migrating HOMEBREW_REPOSITORY (please wait)...
==> Migrated HOMEBREW_REPOSITORY to /usr/local/Homebrew!
Homebrew no longer needs to have ownership of /usr/local. If you wish you can
return /usr/local to its default ownership with:
  sudo chown root:wheel /usr/local