问:
Serialize DataTable into JSON Object in C# Newtonsoft
I am Developing WEB API using ASP.NET. I have little bit trouble while serializing the datatable. When I serialize the DataTable it serialized as a Json String. But I need either JSON Object or JSON ARRAY.

My code

```<code>[ActionName("EMPID")]
public System.Collections.IEnumerable Get()
{
    SqlConnection myConnection = new SqlConnection();
    string connString = ConfigurationManager
                          .ConnectionStrings["DefaultConnection"]
                          .ConnectionString;

    myConnection.ConnectionString = connString;
    DataTable dataTable = new DataTable();

    string query = "select EMPLOYEE_ID,FIRST_NAME,SALARY from Employee ";

    SqlConnection conn = new SqlConnection(connString);
    SqlCommand cmd = new SqlCommand(query, conn);
    conn.Open();
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    da.Fill(dataTable);

    var JSONString = JsonConvert.SerializeObject(dataTable);
    return JSONString;
}

public class Employee
{
    public int EmployeeId { get; set; }
    public string Name { get; set; }
    public int ManagerId { get; set; }
}
</code>```

But it returns as JSON String. I need as a JSON Object.

Example

"[{\"EMPLOYEE_ID\":2,\"FIRST_NAME\":\"Michael\",\"SALARY\":800000},{\"EMPLOYEE_ID\":3,\"FIRST_NAME\":\"Roy\",\"SALARY\":700000},{\"EMPLOYEE_ID\":4,\"FIRST_NAME\":\"Tom\",\"SALARY\":600000},{\"EMPLOYEE_ID\":5,\"FIRST_NAME\":\"Jerry\",\"SALARY\":650000},{\"EMPLOYEE_ID\":6,\"FIRST_NAME\":\"Philip\",\"SALARY\":7500000},{\"EMPLOYEE_ID\":7,\"FIRST_NAME\":\"Sachin\",\"SALARY\":1100000},{\"EMPLOYEE_ID\":8,\"FIRST_NAME\":\"Anshu\",\"SALARY\":1200000},{\"EMPLOYEE_ID\":9,\"FIRST_NAME\":\"Ravish\",\"SALARY\":1000000}]"

But I need to Serialize as Object Like,

{"name":"Manas","gender":"Male","birthday":"1987-8-8"}

I am little bit confused with JSON Serialization & Deserialization.

答:
1) Stop working with DataTable. They're a poor abstraction for the data. Use strongly typed objects. Dapper is handy for this. It is a micro-ORM that works with any ADO.NET data provider. You provide the query, and it will map the results of the query to a strongly typed object (a class). Dapper is available on NuGet.

2) Your action method shouldn't return an IEnumerable. It should return an IEnumerable<T>

3) You should let the framework handle converting your objects to JSON, don't do it yourself. There's no need to involve JSON.NET. If you return your object from your action method, the framework will convert it to JSON for you.

4) You are not using the IDisposable pattern correctly on your disposable objects (SqlConnection). They need to be wrapped in a using statement or disposed of in a finally block.

5) You have two SqlConnection's and only need one.

6) You should utilize the repository pattern instead of doing data access directly in your controller. Follow separation of concerns, have a separate class responsible for this.

Data Repository

```<code>using Dapper; //add this to your using statements

public class EmployeeRepository
{
    private readonly string _connectionString;

    public EmployeeRepository(string connectionString)
    {
        _connectionString = connectionString;
    }

    public List<Employee> GetAllEmployees()
    {
        string query = "select EMPLOYEE_ID, FIRST_NAME, SALARY from Employee";

        using (SqlConnection connection = new SqlConnection(_connectionString))
        {
            // Query is an extension method from Dapper
            List<Employee> employees = connection.Query<Employee>(query).AsList();
            return employees;
        }
    }
}
</code>```

Controller

```<code>public class EmployeeController
{
    private readonly EmployeeRepository _employeeRepository;

    public EmployeeController()
    {
        string connString = ConfigurationManager
                                .ConnectionStrings["DefaultConnection"]
                                .ConnectionString;

        _employeeRepository = new EmployeeRepository(connString);
    }

    [ActionName("EMPID")] //why does this say EMPID?
    public IEnumerable<Employee> Get()
    {
        List<Employee> employees = _employeeRepository.GetAllEmployees();
        return employees;
    }
}
</code>```

Model

```<code>public class Employee
{
    public int EmployeeId { get; set; }

    public string FirstName { get; set; }

    public int Salary { get; set; }
}
</code>```

If you didn't want to use Dapper, you can manually processes the results of your command:

```<code>var employees = new List<Employee>();

using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand("select EMPLOYEE_ID, FIRST_NAME, SALARY from Employee", connection))
{
    connection.Open();

    using(var reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
            Employee employee = new Employee();
            employee.EmployeeId = reader.GetInt32(reader.GetOrdinal("EMPLOYEE_ID"));
            employee.FirstName = reader.GetString(reader.GetOrdinal("FIRST_NAME"));
            employee.Salary = reader.GetInt32(reader.GetOrdinal("SALARY"));
            employees.Add(employee);
        }
    }
}

return employees;
</code>```

Body:
I am Developing WEB API using ASP.NET. I have little bit trouble while serializing the datatable. When I serialize the DataTable it serialized as a Json String. But I need either JSON Object or JSON ARRAY.

My code

[ActionName("EMPID")]
public System.Collections.IEnumerable Get()
{
    SqlConnection myConnection = new SqlConnection();
    string connString = ConfigurationManager
                          .ConnectionStrings["DefaultConnection"]
                          .ConnectionString;

    myConnection.ConnectionString = connString;
    DataTable dataTable = new DataTable();

    string query = "select EMPLOYEE_ID,FIRST_NAME,SALARY from Employee ";

    SqlConnection conn = new SqlConnection(connString);
    SqlCommand cmd = new SqlCommand(query, conn);
    conn.Open();
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    da.Fill(dataTable);

    var JSONString = JsonConvert.SerializeObject(dataTable);
    return JSONString;
}

public class Employee
{
    public int EmployeeId { get; set; }
    public string Name { get; set; }
    public int ManagerId { get; set; }
}

But it returns as JSON String. I need as a JSON Object.

Example

"[{\"EMPLOYEE_ID\":2,\"FIRST_NAME\":\"Michael\",\"SALARY\":800000},{\"EMPLOYEE_ID\":3,\"FIRST_NAME\":\"Roy\",\"SALARY\":700000},{\"EMPLOYEE_ID\":4,\"FIRST_NAME\":\"Tom\",\"SALARY\":600000},{\"EMPLOYEE_ID\":5,\"FIRST_NAME\":\"Jerry\",\"SALARY\":650000},{\"EMPLOYEE_ID\":6,\"FIRST_NAME\":\"Philip\",\"SALARY\":7500000},{\"EMPLOYEE_ID\":7,\"FIRST_NAME\":\"Sachin\",\"SALARY\":1100000},{\"EMPLOYEE_ID\":8,\"FIRST_NAME\":\"Anshu\",\"SALARY\":1200000},{\"EMPLOYEE_ID\":9,\"FIRST_NAME\":\"Ravish\",\"SALARY\":1000000}]"

But I need to Serialize as Object Like,

{"name":"Manas","gender":"Male","birthday":"1987-8-8"}

I am little bit confused with JSON Serialization & Deserialization.

Body:
1) Stop working with DataTable. They're a poor abstraction for the data. Use strongly typed objects. Dapper is handy for this. It is a micro-ORM that works with any ADO.NET data provider. You provide the query, and it will map the results of the query to a strongly typed object (a class). Dapper is available on NuGet.

2) Your action method shouldn't return an IEnumerable. It should return an IEnumerable<T>

3) You should let the framework handle converting your objects to JSON, don't do it yourself. There's no need to involve JSON.NET. If you return your object from your action method, the framework will convert it to JSON for you.

4) You are not using the IDisposable pattern correctly on your disposable objects (SqlConnection). They need to be wrapped in a using statement or disposed of in a finally block.

5) You have two SqlConnection's and only need one.

6) You should utilize the repository pattern instead of doing data access directly in your controller. Follow separation of concerns, have a separate class responsible for this.

Data Repository

using Dapper; //add this to your using statements

public class EmployeeRepository
{
    private readonly string _connectionString;

    public EmployeeRepository(string connectionString)
    {
        _connectionString = connectionString;
    }

    public List<Employee> GetAllEmployees()
    {
        string query = "select EMPLOYEE_ID, FIRST_NAME, SALARY from Employee";

        using (SqlConnection connection = new SqlConnection(_connectionString))
        {
            // Query is an extension method from Dapper
            List<Employee> employees = connection.Query<Employee>(query).AsList();
            return employees;
        }
    }
}

Controller

public class EmployeeController
{
    private readonly EmployeeRepository _employeeRepository;

    public EmployeeController()
    {
        string connString = ConfigurationManager
                                .ConnectionStrings["DefaultConnection"]
                                .ConnectionString;

        _employeeRepository = new EmployeeRepository(connString);
    }

    [ActionName("EMPID")] //why does this say EMPID?
    public IEnumerable<Employee> Get()
    {
        List<Employee> employees = _employeeRepository.GetAllEmployees();
        return employees;
    }
}

Model

public class Employee
{
    public int EmployeeId { get; set; }

    public string FirstName { get; set; }

    public int Salary { get; set; }
}

If you didn't want to use Dapper, you can manually processes the results of your command:

var employees = new List<Employee>();

using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand("select EMPLOYEE_ID, FIRST_NAME, SALARY from Employee", connection))
{
    connection.Open();

    using(var reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
            Employee employee = new Employee();
            employee.EmployeeId = reader.GetInt32(reader.GetOrdinal("EMPLOYEE_ID"));
            employee.FirstName = reader.GetString(reader.GetOrdinal("FIRST_NAME"));
            employee.Salary = reader.GetInt32(reader.GetOrdinal("SALARY"));
            employees.Add(employee);
        }
    }
}

return employees;


来源: stackexchange

问:
Use sed to find and replace a number following by its successor in bash
I have a string that contains multiple occurrences of number ranges, which are separated by a comma, e.g.,

2-12,59-89,90-102,103-492,593-3990,3991-4930

Now I would like to remove all directly neighbouring ranges and remove them from the string, i.e., remove anything that is of the form -(x),(x+1), to get something like this:

2-12,59-492,593-4930

Can anyone think of a method to accomplish this? I can honestly not post anything that I have tried, because all my tries were highly unsuccessful. To me it seems like it is not possible to actually find anything of the form -(x),(x+1) using sed, since that would require doing operations or comparisons of a found number by another number that has to be part of the command that is currently searching for numbers.

If everybody agrees that sed is NOT the correct tool for doing this, I will do it another way, but I am still interested if it's possible.

答:
awk solution:

```<code>awk -F'-' '{   r=$1;
               for (i=2; i<=NF; i++) {
                   split($i, a, ",");
                   r=sprintf("%s%s", r, a[2]-a[1]==1? "" : FS $i)
               }
               print r
           }' file
</code>```

-F'-' - treat -(hyphen) as field separator

r - resulting string

split($i, a, ",") - split adjacent range boundaries into array a by separator ,

a[2]-a[1]==1 - crucial condition, reflects (x),(x+1)

The output:

```<code>2-12,59-492,593-4930
</code>```

ContentLicense: CC BY-SA 3.0

Body:
awk solution:

awk -F'-' '{   r=$1;
               for (i=2; i<=NF; i++) {
                   split($i, a, ",");
                   r=sprintf("%s%s", r, a[2]-a[1]==1? "" : FS $i)
               }
               print r
           }' file

-F'-' - treat -(hyphen) as field separator

r - resulting string

split($i, a, ",") - split adjacent range boundaries into array a by separator ,

a[2]-a[1]==1 - crucial condition, reflects (x),(x+1)

The output:

2-12,59-492,593-4930


问:
Go find files in directory recursively
I want to find all files matching a specific pattern in a directory recursively (including subdirectories). I wrote the code to do this:

```<code>libRegEx, e := regexp.Compile("^.+\\.(dylib)$")
if e != nil {
    log.Fatal(e)
}

files, err := ioutil.ReadDir("/usr/lib")
if err != nil {
    log.Fatal(err)
}

for _, f := range files {
    if libRegEx.MatchString(f.Name()) {
        println(f.Name())
    }
}
</code>```

Unfortunately, it only searches in /usr/bin, but I also want to search for matches in its subdirectories. How can I achieve this? Thanks.

答:
The standard library's filepath package includes Walk for exactly this purpose: "Walk walks the file tree rooted at root, calling walkFn for each file or directory in the tree, including root." For example:

```<code>libRegEx, e := regexp.Compile("^.+\\.(dylib)$")
if e != nil {
    log.Fatal(e)
}

e = filepath.Walk("/usr/lib", func(path string, info os.FileInfo, err error) error {
    if err == nil && libRegEx.MatchString(info.Name()) {
        println(info.Name())
    }
    return nil
})
if e != nil {
    log.Fatal(e)
}
</code>```

Title: Go find files in directory recursively

Body:
I want to find all files matching a specific pattern in a directory recursively (including subdirectories). I wrote the code to do this:

libRegEx, e := regexp.Compile("^.+\\.(dylib)$")
if e != nil {
    log.Fatal(e)
}

files, err := ioutil.ReadDir("/usr/lib")
if err != nil {
    log.Fatal(err)
}

for _, f := range files {
    if libRegEx.MatchString(f.Name()) {
        println(f.Name())
    }
}

Unfortunately, it only searches in /usr/bin, but I also want to search for matches in its subdirectories. How can I achieve this? Thanks.

Body:
The standard library's filepath package includes Walk for exactly this purpose: "Walk walks the file tree rooted at root, calling walkFn for each file or directory in the tree, including root." For example:

libRegEx, e := regexp.Compile("^.+\\.(dylib)$")
if e != nil {
    log.Fatal(e)
}

e = filepath.Walk("/usr/lib", func(path string, info os.FileInfo, err error) error {
    if err == nil && libRegEx.MatchString(info.Name()) {
        println(info.Name())
    }
    return nil
})
if e != nil {
    log.Fatal(e)
}

ContentLicense: CC BY-SA 4.0


问:
How to remove HTML tags in CSV file- PHP
I am trying to download CSV file from php values. But the output file is included with all the html tags.
I have used the following part of code for CSV file.

```<code>     header('Content-Type: application/x-csv');
     header('Content-disposition:attachment;filename=file.csv');
</code>```

CURRENT OUTPUT:

```<code> <tr><td> 2017-11-05 10:38:05 </td> <td>  3 </a> </td> <td>  Full Speed </a>
 </td><td>56</td><td> <div id= "level2" > Level 2 </div> </td></tr>
 <tr><td>2017-11-05 10:37:03 </td> <td>
</code>```

Expected OUTPUT:

```<code> 2017-11-05 10:38:05, 3 , Full , Level 2 , 2017-11-05 10:37:03.
</code>```

NOTE: data is extracted from array variables in php (not from sql/database)

答:
Just run strip_tags() on the string you want to filter.

If you dont want to strip all tags, you can use the second parameter of strip_tags*

```<code>$str = ' <tr><td> 2017-11-05 10:38:05 </td> <td>  3 </a> </td> <td>  Full Speed </a>
 </td><td>56</td><td> <div id= "level2" > Level 2 </div> </td></tr>
 <tr><td>2017-11-05 10:37:03 </td> <td> ';
$str = strip_tags($str); // Your data without html tags
</code>```

If you want to have it in a single line, you can go further and do a str_replace() on it:

```<code>$str = str_replace(PHP_EOL, '', $str);
</code>```

*Lets say, you dont want to remove paragraphs or links, you would call strip_tags() like that:

```<code>$str = strip_tags($str, '<p><a>');
</code>```

Body:
I am trying to download CSV file from php values. But the output file is included with all the html tags.
I have used the following part of code for CSV file.

     header('Content-Type: application/x-csv');
     header('Content-disposition:attachment;filename=file.csv');

CURRENT OUTPUT:

 2017-11-05 10:38:05 	   3  	   Full Speed
 	56
 Level 2

2017-11-05 10:37:03

Expected OUTPUT:

 2017-11-05 10:38:05, 3 , Full , Level 2 , 2017-11-05 10:37:03.

NOTE: data is extracted from array variables in php (not from sql/database)

Body:
Just run strip_tags() on the string you want to filter.

If you dont want to strip all tags, you can use the second parameter of strip_tags*

$str = ' <tr><td> 2017-11-05 10:38:05 </td> <td>  3 </a> </td> <td>  Full Speed </a>
 </td><td>56</td><td> <div id= "level2" > Level 2 </div> </td></tr>
 <tr><td>2017-11-05 10:37:03 </td> <td> ';
$str = strip_tags($str); // Your data without html tags

If you want to have it in a single line, you can go further and do a str_replace() on it:

$str = str_replace(PHP_EOL, '', $str);

*Lets say, you dont want to remove paragraphs or links, you would call strip_tags() like that:

$str = strip_tags($str, '<p><a>');


问:
How to check whether id value is already present in array of objects?
I am trying to check whether an object with a certain id property is already present in the array:

```<code>var items  =[{id:1,name:'ted'},{id:2,name:'john'}]
</code>```

How can I do this with jquery or vanilla js in a compact way? I know I can just create a for loop but is there anything else you can use?

答:
```<code>var items  =[{id:1,name:'ted'},{id:2,name:'john'},{id:3, name:'tod'}];
var id = 2;
var checkid = false;
for(var i =0; i<items.length; i++){
    if(items[i].id ==id) //this condition check if id exists or not)
      checkid=true;
}
</code>```

Body:
I am trying to check whether an object with a certain id property is already present in the array:

var items  =[{id:1,name:'ted'},{id:2,name:'john'}]

How can I do this with jquery or vanilla js in a compact way? I know I can just create a for loop but is there anything else you can use?


问:
SHA checksum for +2GB file using FileStream
Why in this soulution which I found there is no Loop to use buffor few times?

```<code>using System.IO;
using System.Security.Cryptography;

private static string GetChecksum(string file)
{
    using (FileStream stream = File.OpenRead(file))
    {
        SHA256Managed sha = new SHA256Managed();
        byte[] checksum = sha.ComputeHash(stream);
        return BitConverter.ToString(checksum).Replace("-", String.Empty);
    }
}
</code>```

I'm trying to generate SHA checksum for +2GB file. How it should be?

答:
You are using HashAlgorithm.ComputeHash(Stream) override.

The loop is under the hood.

Here is simplified source code of ComputeHash method:

```<code>public byte[] ComputeHash(Stream inputStream)
{
    ...
    // Default the buffer size to 4K.
    byte[] buffer = new byte[4096];
    int bytesRead;
    do {
        bytesRead = inputStream.Read(buffer, 0, 4096);
        if (bytesRead > 0) {
            HashCore(buffer, 0, bytesRead);  // Actual hashing
        }
    } while (bytesRead > 0);
    ...
}
</code>```

As you can see ComputeHash is actually hashing by 4096 byte chunks.

Body:
Why in this soulution which I found there is no Loop to use buffor few times?

using System.IO;
using System.Security.Cryptography;

private static string GetChecksum(string file)
{
    using (FileStream stream = File.OpenRead(file))
    {
        SHA256Managed sha = new SHA256Managed();
        byte[] checksum = sha.ComputeHash(stream);
        return BitConverter.ToString(checksum).Replace("-", String.Empty);
    }
}

I'm trying to generate SHA checksum for +2GB file. How it should be?

Body:
You are using HashAlgorithm.ComputeHash(Stream) override.

The loop is under the hood.

Here is simplified source code of ComputeHash method:

public byte[] ComputeHash(Stream inputStream)
{
    ...
    // Default the buffer size to 4K.
    byte[] buffer = new byte[4096];
    int bytesRead;
    do {
        bytesRead = inputStream.Read(buffer, 0, 4096);
        if (bytesRead > 0) {
            HashCore(buffer, 0, bytesRead);  // Actual hashing
        }
    } while (bytesRead > 0);
    ...
}

As you can see ComputeHash is actually hashing by 4096 byte chunks.


问:
Batch move many .tif files from their directories to respective subdirectories (all named “R20m”)
I am trying to move many .tif images in a batch file. I have a lot of folders with subfolders that all have the same folder structure. I one of this folders is one .tif file that always has a similar name (it contains "SCL" in the name). In that folder there is also a subfolder that always has a name "R20m". I want to move all of these .tif images to their respective R20m subfolder. I am stuck with the syntax. This is what I have so far:

for /r %%g in (*_SCL_*.tif) do Move %%g "%%~dp\R20m"
```

I do not know how to combine the current drive and/or path of the for loop with the R20 folder name.

答:
You are very close. You just omitted the for loop variable name to be expanded. Does this work?

```<code>for /r %%g in (*_SCL_*.tif) do Move "%%~g" "%%~dpgR20m\"
</code>```

Check to see that the new directory exists.

```<code>for /r %%g in (*_SCL_*.tif) do (IF EXIST "%%~dpgR20m\" (Move "%%~g" "%%~dpgR20m\"))
</code>```

Body:
I am trying to move many .tif images in a batch file. I have a lot of folders with subfolders that all have the same folder structure. I one of this folders is one .tif file that always has a similar name (it contains "SCL" in the name). In that folder there is also a subfolder that always has a name "R20m". I want to move all of these .tif images to their respective R20m subfolder. I am stuck with the syntax. This is what I have so far:

for /r %%g in (*_SCL_*.tif) do Move %%g "%%~dp\R20m"

I do not know how to combine the current drive and/or path of the for loop with the R20 folder name.

Body:
You are very close. You just omitted the for loop variable name to be expanded. Does this work?

for /r %%g in (*_SCL_*.tif) do Move "%%~g" "%%~dpgR20m\"

Check to see that the new directory exists.

for /r %%g in (*_SCL_*.tif) do (IF EXIST "%%~dpgR20m\" (Move "%%~g" "%%~dpgR20m\"))


问:
How to create a loop inside a loop in R
I am new to R and I need some help in relation loops. I need to produce a huge amount to tables from one data set and I think that a loop inside a loop will solve the problem, but I am having problems getting the right result.

Lets say I have the following data set:

```<code>var1 <- c("A","A","A","A","B","B","B","B")
var2 <- c(1,2,1,2,1,2,1,2)
df <- data.frame(var1,var2)
</code>```

And I want to extract the data in 4 tables:

Result of "A" & 1

Result of "A" & 2

Result of "B" & 1

Result of "B" & 2

I have this loop, but I cannot get the 4 tables. Can anyone help!

```<code>for (i in df$var1) {

    dummy<- df%>%filter(var1 == i)

    for (j in dummy$var2) {

       nTab <- paste0("tab_", j, sep ="")
       assign(nTab, dummy%>%filter (var2 == j))

   }
}
</code>```

答:
Expanding on @Gregor's comment, and the question here,

Save all data frames in list to separate .csv files,

you can use Map() with the split() function to output the newly created dataframes to individual csv files:

Code:

```<code>s=split(df, f = paste(df$var1, df$var2, sep = "_"))
Map(write.csv,s, paste0("table_",names(s),".csv"),row.names=F)
</code>```

which will write the csv's to your current working directory, with the names "table_A_1.csv", etc based on the value of var1 and var2.

Title: How to create a loop inside a loop in R

Body:
I am new to R and I need some help in relation loops. I need to produce a huge amount to tables from one data set and I think that a loop inside a loop will solve the problem, but I am having problems getting the right result.

Lets say I have the following data set:

var1 <- c("A","A","A","A","B","B","B","B")
var2 <- c(1,2,1,2,1,2,1,2)
df <- data.frame(var1,var2)

And I want to extract the data in 4 tables:

Result of "A" & 1

Result of "A" & 2

Result of "B" & 1

Result of "B" & 2

I have this loop, but I cannot get the 4 tables. Can anyone help!

for (i in df$var1) {

    dummy<- df%>%filter(var1 == i)

    for (j in dummy$var2) {

       nTab <- paste0("tab_", j, sep ="")
       assign(nTab, dummy%>%filter (var2 == j))

   }
}

Body:
Expanding on @Gregor's comment, and the question here,

Save all data frames in list to separate .csv files,

you can use Map() with the split() function to output the newly created dataframes to individual csv files:

Code:

s=split(df, f = paste(df$var1, df$var2, sep = "_"))
Map(write.csv,s, paste0("table_",names(s),".csv"),row.names=F)

which will write the csv's to your current working directory, with the names "table_A_1.csv", etc based on the value of var1 and var2.


答:
Why in this soulution which I found there is no Loop to use buffor few times?

Because ComputeHash takes care of reading the entire stream and computing the hash value.

Title: SHA checksum for +2GB file using FileStream


问:
TinyMCE: Possible to disallowing specified values in given attributes?
I want to add a rule where i set "position:absolute" inside the style attribute to invalid. I can set tags and attributes to invalid using invalid_elements or valid_elements (see link)..

This has to be disallowed trough the source_editor ("code" button) and paste plugin

http://tinymce.moxiecode.com/wiki.php/Configuration:Cleanup/Output

The problem is that people are "hacking" the css/xhtml ending up putting a absolute positoned div covering the entire page..

How could this be prevented? Is there any built in functionality in TinyMCE, or could it be achieved trough JS/jQuery and RegEx? (I use the jQuery version of TinyMCE)

答:
You can not specify invalid attributes, only elements.

Anything the user does on their side can not be trusted.  You must sanitize the input on the server side.

You could do a simple regex like:

```<code>$data = preg_replace('/position\s*:\s*\w+;?/','',$data);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You can not specify invalid attributes, only elements.

Anything the user does on their side can not be trusted.  You must sanitize the input on the server side.

You could do a simple regex like:

$data = preg_replace('/position\s*:\s*\w+;?/','',$data);


问:
Unable to retrieve data from firebase to a List
I am not getting my Database name items in my autocompletetextview. I am not sure what is wrong with my code.

Here is my small firebase Database.

```<code> [ null, { "Coordinaat" : 75,
  "Naam" : "Cream"
}, {
  "Coordinaat" : 47885,
  "Naam" : "Cacao"
}, {
  "Coordinaat" : 48456,
  "Naam" : "Cola"
}, {
  "Coordinaat" : 25164,
  "Naam" : "Yoghurt"
}, {
  "Coordinaat" : 54,
  "Naam " : "Carrot"
}, {
  "Coordinaat" : 57,
  "Naam" : "Yum"
} ]
</code>```

Here is my ProductClass.

```<code>public class Product {
public String name;
public int coordinaat;

public Product()
{

}

public Product(String name, int coordinaat)
{
   this.name = name;
   this.coordinaat = coordinaat;
}

public void setcoordinaat(int coordinaat) {
    this.coordinaat = coordinaat;
}

public void setname(String name)
 {
     this.name = name;
 }

public String getname()
{
    return name;
}

public int getcoordinaat()
{
    return coordinaat;
}
}
</code>```

Here is my activity code.

```<code>public class tweede extends AppCompatActivity {

       private static final String[] producten = new String[] { "Yoghurt",
        "Cream", "Cacao", "Cola", "Yummy", "Chocolate" , "Can" , "Cannabis" , "Caramel", "Carrot", "Coconut" };
DatabaseReference databaseProducten;

      //ListView lstviewProducten;
    List <Product> lstPro = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tweede);
    databaseProducten = FirebaseDatabase.getInstance().getReference();
    AutocmpleteMeth();
   // lstviewProducten = (ListView) findViewById(R.id.listView2);
}
@Override
protected void onStart() {
    super.onStart();
    databaseProducten.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            lstPro.clear();
            for(DataSnapshot productenSnapshot : dataSnapshot.getChildren())
            {
                Product product = productenSnapshot.getValue(Product.class);
                lstPro.add(product);
            }
            AutocmpleteMeth();  }

        @Override public void onCancelled(DatabaseError databaseError) {
        }
    });
}
public void AutocmpleteMeth()
{
    // Hieronder is het code voor Autocomplete [BEGIN]
    AutoCompleteTextView ACTV;
    ACTV=(AutoCompleteTextView)findViewById(R.id.autoCompleteTextView2);
    ArrayAdapter<Product> adapter = new ArrayAdapter<Product>(this, android.R.layout.simple_dropdown_item_1line, lstPro);
    ACTV.setAdapter(adapter);
    ACTV.setThreshold(1);
    //Autocmplete [END]
}
</code>```

}

That what i am getting on my phone..

答:
What you are getting there, is the address of your Product class from the memory. You need to know that The Firebase Realtime Database SDK will serialize all visible fields and JavaBean-type getter methods on an instance of an object using reflection to discover them. So, if it sees a field "name", it will serialize a property called "name". If it sees a getter method called "getName", it will serialize a property also called "name".

The problem in your code is that your getters and setter are named incorrectly. This is the correct way in which you can use Product class:

```<code>public class Product {
    public String name;
    public int coordinaat;

    public Product() {}

    public Product(String name, int coordinaat) {
        this.name = name;
        this.coordinaat = coordinaat;
    }

    public void setCoordinaat(int coordinaat) {
        this.coordinaat = coordinaat;
    }

    public void setName(String name){
        this.name = name;
    }

    public String getName(){
        return name;
    }

    public int getCoordinaat(){
        return coordinaat;
    }

    public String toString(){
        return name;
    }
}
</code>```

See that i have changed setcoordinaat in setCoordinaat, setname in setName, getname in getName and getcoordinaat in getCoordinaat.

Assuming that instead of null the name of the node is records and is a direct child of your Firebase root, to display those values, please use the following code:

```<code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<String> list = new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            long Coordinaat = ds.child("Coordinaat").getValue(Long.class);
            String Naam = ds.child("Naam").getValue(String.class);
            Log.d("TAG", Coordinaat + " / " + Naam);
            list.add(Coordinaat + " / " + Naam);
        }
        Log.d("TAG", list);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
rootRef.addListenerForSingleValueEvent(eventListener);
</code>```

The output will be:

```<code>3212 / Cream
47885 / Cacao
5 / Cola
466468 / Youghurt
</code>```

Body:
I am not getting my Database name items in my autocompletetextview. I am not sure what is wrong with my code.

Here is my small firebase Database.

 [ null, { "Coordinaat" : 75,
  "Naam" : "Cream"
}, {
  "Coordinaat" : 47885,
  "Naam" : "Cacao"
}, {
  "Coordinaat" : 48456,
  "Naam" : "Cola"
}, {
  "Coordinaat" : 25164,
  "Naam" : "Yoghurt"
}, {
  "Coordinaat" : 54,
  "Naam " : "Carrot"
}, {
  "Coordinaat" : 57,
  "Naam" : "Yum"
} ]

Here is my ProductClass.

public class Product {
public String name;
public int coordinaat;

public Product()
{

}

public Product(String name, int coordinaat)
{
   this.name = name;
   this.coordinaat = coordinaat;
}

public void setcoordinaat(int coordinaat) {
    this.coordinaat = coordinaat;
}

public void setname(String name)
 {
     this.name = name;
 }

public String getname()
{
    return name;
}

public int getcoordinaat()
{
    return coordinaat;
}
}

Here is my activity code.

public class tweede extends AppCompatActivity {

       private static final String[] producten = new String[] { "Yoghurt",
        "Cream", "Cacao", "Cola", "Yummy", "Chocolate" , "Can" , "Cannabis" , "Caramel", "Carrot", "Coconut" };
DatabaseReference databaseProducten;

      //ListView lstviewProducten;
    List <Product> lstPro = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tweede);
    databaseProducten = FirebaseDatabase.getInstance().getReference();
    AutocmpleteMeth();
   // lstviewProducten = (ListView) findViewById(R.id.listView2);
}
@Override
protected void onStart() {
    super.onStart();
    databaseProducten.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            lstPro.clear();
            for(DataSnapshot productenSnapshot : dataSnapshot.getChildren())
            {
                Product product = productenSnapshot.getValue(Product.class);
                lstPro.add(product);
            }
            AutocmpleteMeth();  }

        @Override public void onCancelled(DatabaseError databaseError) {
        }
    });
}
public void AutocmpleteMeth()
{
    // Hieronder is het code voor Autocomplete [BEGIN]
    AutoCompleteTextView ACTV;
    ACTV=(AutoCompleteTextView)findViewById(R.id.autoCompleteTextView2);
    ArrayAdapter<Product> adapter = new ArrayAdapter<Product>(this, android.R.layout.simple_dropdown_item_1line, lstPro);
    ACTV.setAdapter(adapter);
    ACTV.setThreshold(1);
    //Autocmplete [END]
}

}

That what i am getting on my phone..

Body:
What you are getting there, is the address of your Product class from the memory. You need to know that The Firebase Realtime Database SDK will serialize all visible fields and JavaBean-type getter methods on an instance of an object using reflection to discover them. So, if it sees a field "name", it will serialize a property called "name". If it sees a getter method called "getName", it will serialize a property also called "name".

The problem in your code is that your getters and setter are named incorrectly. This is the correct way in which you can use Product class:

public class Product {
    public String name;
    public int coordinaat;

    public Product() {}

    public Product(String name, int coordinaat) {
        this.name = name;
        this.coordinaat = coordinaat;
    }

    public void setCoordinaat(int coordinaat) {
        this.coordinaat = coordinaat;
    }

    public void setName(String name){
        this.name = name;
    }

    public String getName(){
        return name;
    }

    public int getCoordinaat(){
        return coordinaat;
    }

    public String toString(){
        return name;
    }
}

See that i have changed setcoordinaat in setCoordinaat, setname in setName, getname in getName and getcoordinaat in getCoordinaat.

Assuming that instead of null the name of the node is records and is a direct child of your Firebase root, to display those values, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<String> list = new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            long Coordinaat = ds.child("Coordinaat").getValue(Long.class);
            String Naam = ds.child("Naam").getValue(String.class);
            Log.d("TAG", Coordinaat + " / " + Naam);
            list.add(Coordinaat + " / " + Naam);
        }
        Log.d("TAG", list);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
rootRef.addListenerForSingleValueEvent(eventListener);

The output will be:

3212 / Cream
47885 / Cacao
5 / Cola
466468 / Youghurt


问:
Why does C manage the heap, instead of the operating system?
In other words, why doesn't free() just return the memory to the operating system, and malloc simply request memory from the operating system?

This unpacks to three closely related questions:

Why does C need to manage its own heap? (Is it because the OS will only allow you to allocate and free contiguous memory of a minimum size?)

Assuming what I wrote in parentheses is true, why is it?

Can this problem affect the operating system itself, so that it's unable to allocate blocks of memory to any running processes?

答:
Why does C need to manage its own heap?

It's not actually specified that it needs to, but it needs to implement malloc() and friends the way they are described in the standard. So if there was an OS already providing such an interface, a C implementation could just provide a tiny wrapper.

Is it because the OS will only allow you to allocate and free contiguous memory of a minimum size? And if that's true, what's the reason?

Yes. A typical OS will manage paged memory and map or unmap processes whole pages of memory. The unit of memory that can be "paged" depends on the hardware architecture. You might want to read some details on how memory management units (MMU) work. On architectures without MMU, the operating system might not do anything and a C implementation would just fullfill malloc() requests from a fixed location in physical address space.


问:
Working with PhantomJS with Selenium
I wanted to increase the selenium performance (working on selenium-python). So I thought of switching to a headless browser as GUI is not a necessary.
I set path variable for phantomJS and ran

```<code>driver = webdriver.PhantomJS()
</code>```

Upon getting an error I set the path and service arguments while initializing the driver (going through several dozens of stackoverflow and google groups

```<code>phantomjs_path = r"C:\Users\sachin.nandakumar\AppData\Local\Continuum\anaconda3\phantomjs\bin\phantomjs.exe"
service_args = [ '--proxy=10.118.132.29:80', '--proxy-type=http',]
driver = webdriver.PhantomJS(executable_path=phantomjs_path,service_args=service_args)
</code>```

But I still get the same error. (Error specified below in detail)

Later I tried with HtmlUnitDriver as well. But the same error occurs again.

Is there any issues for headless browsers to work behind proxies (corporate firewall?). Or if it is regarding some authentication issues, I didn’t find a way on how to tackle them.

```<code>E
======================================================================
ERROR: test_start (__main__.TestWeb)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "...Crawler\crawl_core\src_main\run.py", line 26, in setUp
    driver =     webdriver.PhantomJS(executable_path=phantomjs_path,service_args=service_args)
  File "...\anaconda3\lib\site-packages\selenium\webdriver\phantomjs\webdriver.py", line 58, in __init__
desired_capabilities=desired_capabilities)
  File "...\anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 151, in __init__
self.start_session(desired_capabilities, browser_profile)
  File "...\anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 240, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
  File "...\anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 308, in execute
self.error_handler.check_response(response)
  File "...\anaconda3\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 165, in check_response
raise exception_class(value)
selenium.common.exceptions.WebDriverException: Message: <HTML><HEAD>

<TITLE>Access Denied</TITLE>

</HEAD>

<BODY>

<FONT face="Helvetica">

<big><strong></strong></big><BR>

</FONT>

<blockquote>

<TABLE border=0 cellPadding=1 width="80%">

<TR><TD>

<FONT face="Helvetica">

<big>Access Denied (authentication_failed)</big>

<BR>

<BR>

</FONT>

</TD></TR>

<TR><TD>

<FONT face="Helvetica">

Your credentials could not be authenticated: "General authentication failure due to bad user ID or authentication token.". You will not be permitted access until your credentials can be verified.

</FONT>

</TD></TR>

<TR><TD>

<FONT face="Helvetica">

This is typically caused by an incorrect username and/or password, but could also be caused by network problems.

</FONT>

</TD></TR>

<TR><TD>

<FONT face="Helvetica" SIZE=2>

<BR>

For assistance, contact your network support team.

</FONT>

</TD></TR>

</TABLE>

</blockquote>

</FONT>

</BODY></HTML>
</code>```

答:
PhantomJS is no more in active development. So you should not be running PhantomJS. Switch to chrome and you should be fine. And check if the proxy requires authentication.

get chromedriver from here, https://sites.google.com/a/chromium.org/chromedriver/downloads

Title: Working with PhantomJS with Selenium

Body:
I wanted to increase the selenium performance (working on selenium-python). So I thought of switching to a headless browser as GUI is not a necessary.
I set path variable for phantomJS and ran

driver = webdriver.PhantomJS()

Upon getting an error I set the path and service arguments while initializing the driver (going through several dozens of stackoverflow and google groups

phantomjs_path = r"C:\Users\sachin.nandakumar\AppData\Local\Continuum\anaconda3\phantomjs\bin\phantomjs.exe"
service_args = [ '--proxy=10.118.132.29:80', '--proxy-type=http',]
driver = webdriver.PhantomJS(executable_path=phantomjs_path,service_args=service_args)

But I still get the same error. (Error specified below in detail)

Later I tried with HtmlUnitDriver as well. But the same error occurs again.

Is there any issues for headless browsers to work behind proxies (corporate firewall?). Or if it is regarding some authentication issues, I didn’t find a way on how to tackle them.

E
======================================================================
ERROR: test_start (__main__.TestWeb)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "...Crawler\crawl_core\src_main\run.py", line 26, in setUp
    driver =     webdriver.PhantomJS(executable_path=phantomjs_path,service_args=service_args)
  File "...\anaconda3\lib\site-packages\selenium\webdriver\phantomjs\webdriver.py", line 58, in __init__
desired_capabilities=desired_capabilities)
  File "...\anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 151, in __init__
self.start_session(desired_capabilities, browser_profile)
  File "...\anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 240, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
  File "...\anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 308, in execute
self.error_handler.check_response(response)
  File "...\anaconda3\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 165, in check_response
raise exception_class(value)
selenium.common.exceptions.WebDriverException: Message:

<TITLE>Access Denied</TITLE>

<big></big>

<big>Access Denied (authentication_failed)</big>

Your credentials could not be authenticated: "General authentication failure due to bad user ID or authentication token.". You will not be permitted access until your credentials can be verified.

This is typically caused by an incorrect username and/or password, but could also be caused by network problems.

For assistance, contact your network support team.


问:
iPhone Retina Graphics
I have a question RE Retina display graphics (and potentially iPad 2 graphics if the rumours of double resolution displays are to be believed).

Is there any advantage to having two graphics:
Graphic.png 480x320
and
Graphic@2.png 960x640

and letting the iPhone use the @2 version for retina displays rather than just having Graphic.png at the higher res and letting iPhones with normal displays squash it?

答:
Yes. If you didn't use two separate graphics (normal and "@2x"), any device without the retina display would have to store its graphics using four times as much memory. It's a simple matter of storing an insignificant amount of compressed images (PNGs) so you don't have to kill legacy devices' memory.

Not only that, but performance will drop from having to handle such large images on devices that are generally slower.

Finally, the result of scaling huge images is usually really ugly, because UIKit uses the nearest-neighbor algorithm when scaling.

Title: iPhone Retina Graphics


问:
How can I slide image onmouseover link programmatically
I try to prepare a simple work portfolio. I select works programmatically from database. I just want to do on mouse over a work change background image of div.

```<code><div>
    <div style="width:100%; position:absolute;">
    <ul>
    <li style="background-image:url(1.png);"></li>
    <li style="background-image:url(2.png);"></li>
    <li style="background-image:url(3.png);"></li>
    </ul>
    </div>

    <div class="row">
        <div class="col-lg-4">
            <a href="#">WORK 1</a>
        </div>
        <div class="col-lg-4">
            <a href="#">WORK 2</a>
        </div>
        <div class="col-lg-4">
            <a href="#">WORK 3</a>
        </div>
    </div>
</div>
</code>```

On above ul li tags these are my images when I mouse over links on bottom i will slide one of them. How can I slide images. Should I identitiy every li tag?

答:
Add identifiers to your work-items. Like work_1, work_2 etc. And add a class to every item.

```<code><div>
    <div style="width:100%; position:absolute;">
    <ul>
    <li id="work_1" class="work-item" style="background-image:url(1.png);"></li>
    <li id="work_2" class="work-item" style="background-image:url(2.png);"></li>
    <li id="work_3" class="work-item" style="background-image:url(3.png);"></li>
    </ul>
    </div>

    <div class="row">
        <div class="col-lg-4">
            <a href="#" data-show="work_1">WORK 1</a>
        </div>
        <div class="col-lg-4">
            <a href="#" data-show="work_2">WORK 2</a>
        </div>
        <div class="col-lg-4">
            <a href="#" data_show="work_3">WORK 3</a>
        </div>
    </div>
</div>
</code>```

With every hover on each item you hide all items, and show the one your element is linked to.

```<code><script>
$('.work_hover').mouseover(function() {
    var id_to_show = $(this).attr('show');
    $('.work-item').hide();
    $('#' + id_to_show).show();
});
</script>
</code>```

To finish the slider you can add cool animations to the show and hide methods

Body:
I try to prepare a simple work portfolio. I select works programmatically from database. I just want to do on mouse over a work change background image of div.

            WORK 1

            WORK 2

            WORK 3

On above ul li tags these are my images when I mouse over links on bottom i will slide one of them. How can I slide images. Should I identitiy every li tag?

Body:
Add identifiers to your work-items. Like work_1, work_2 etc. And add a class to every item.

<div>
    <div style="width:100%; position:absolute;">
    <ul>
    <li id="work_1" class="work-item" style="background-image:url(1.png);"></li>
    <li id="work_2" class="work-item" style="background-image:url(2.png);"></li>
    <li id="work_3" class="work-item" style="background-image:url(3.png);"></li>
    </ul>
    </div>

    <div class="row">
        <div class="col-lg-4">
            <a href="#" data-show="work_1">WORK 1</a>
        </div>
        <div class="col-lg-4">
            <a href="#" data-show="work_2">WORK 2</a>
        </div>
        <div class="col-lg-4">
            <a href="#" data_show="work_3">WORK 3</a>
        </div>
    </div>
</div>

With every hover on each item you hide all items, and show the one your element is linked to.

<script>
$('.work_hover').mouseover(function() {
    var id_to_show = $(this).attr('show');
    $('.work-item').hide();
    $('#' + id_to_show).show();
});
</script>

To finish the slider you can add cool animations to the show and hide methods


问:
How to calculate average of arrays from array list?
I have an ArrayList in VB.NET.

For example ArrayList has two arrays: AList(arr,arr):

```<code>Dim AList As ArrayList = New ArrayList((1,2,3,4,5,6,7,8,9,10)
                                       (2,3,4,5,6,7,8,9,10,11))
</code>```

All I want is average of given arrays so:

So final Array will be (1.5,2.5,3.5,4.5,5.5.........10.5)

Note: Arraylist count and length of arrays will variable.

I tried the following code:

```<code>For k = 0 To 9
    Dim sum As Short
    Dim a As Array

    For z = 0 To 1
        sum = sum + AList.Item(a(k))
    Next

    finalarr(k) = sum / 2
    RichTextBox1.AppendText(finalarr(k))
Next
</code>```

答:
```<code>Dim i As Integer = 0
Dim count As Inetger = 0
Dim avgList As List(Of Integer) = New List(Of Integer)()

For Each arr As Integer() In AList
    i = 0
    count += 1
    For Each thing as Integer In arr
        i += 1
        If avgList.Count >= i Then
            avgList.Item(i) = ((avgList.Item(i) + thing) / count)
        Else
            avgList.Add(i)
        End If
    Next
Next
</code>```

Body:
I have an ArrayList in VB.NET.

For example ArrayList has two arrays: AList(arr,arr):

Dim AList As ArrayList = New ArrayList((1,2,3,4,5,6,7,8,9,10)
                                       (2,3,4,5,6,7,8,9,10,11))

All I want is average of given arrays so:

So final Array will be (1.5,2.5,3.5,4.5,5.5.........10.5)

Note: Arraylist count and length of arrays will variable.

I tried the following code:

For k = 0 To 9
    Dim sum As Short
    Dim a As Array

    For z = 0 To 1
        sum = sum + AList.Item(a(k))
    Next

    finalarr(k) = sum / 2
    RichTextBox1.AppendText(finalarr(k))
Next


问:
Confusion about realloc function
I read about dynamic memory allocation in C using this reference.

That document Say's :

realloc() should only be used for dynamically allocated memory. If the
  memory is not dynamically allocated, then behavior is undefined.

If we use realloc() something like this:

```<code>int main()
{
    int *ptr;
    int *ptr_new = (int *)realloc(ptr, sizeof(int));

    return 0;
}
</code>```

According to that reference, this program is undefined because pointer ptr not allocated dynamically.

But, If I use something like:

```<code>int main()
{
    int *ptr = NULL;
    int *ptr_new = (int *)realloc(ptr, sizeof(int));

    return 0;
}
</code>```

Is it also undefined behavior according to that reference?

I thing second case does not invoked undefined behaviour. Am I right?

答:
The first case is obviously undefined behavior because we don't know where the ptr is pointing or what the ptr is holding at that time. And c standard says that 7.20.3.4.2 The realloc function

The realloc function deallocates the old object pointed to by ptr and
  returns a pointer to a new object that has the size specified by size.

So first case is Undefined behavior.

In second case compiler knows what ptr has so it is valid but realloc()
will act as malloc() according to 7.20.3.4.3 The realloc function

If ptr is a null pointer, the realloc function behaves like the
  malloc function for the specified size.

Title: Confusion about realloc function

Body:
I read about dynamic memory allocation in C using this reference.

That document Say's :

realloc() should only be used for dynamically allocated memory. If the
  memory is not dynamically allocated, then behavior is undefined.

If we use realloc() something like this:

int main()
{
    int *ptr;
    int *ptr_new = (int *)realloc(ptr, sizeof(int));

    return 0;
}

According to that reference, this program is undefined because pointer ptr not allocated dynamically.

But, If I use something like:

int main()
{
    int *ptr = NULL;
    int *ptr_new = (int *)realloc(ptr, sizeof(int));

    return 0;
}

Is it also undefined behavior according to that reference?

I thing second case does not invoked undefined behaviour. Am I right?


问:
Clickable Text View not Working
I am a learner in Android development, I was learning SQLite database in the program where I need your help.

The program I have developed gets the input from the user and stores the values in SQLite database, I have also made a clickable text view which is supposed to show the stored data.

The problem I am facing is when I run the program and directly click on Show Data (Textview) it opens the alert dialogue and displays the data however when I enter the data and then after that if I try to click on "Show Data" the text view become disabled.

Please help.

Below are my XML and Java files.

XML

```<code><?xml version="1.0" encoding="utf-8"?>
<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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.junaidmalik.sqlitedemo.SqliteDemo">

    <EditText
        android:id="@+id/rollnum"
        android:hint="Enter Roll Number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="number"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.503"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.16" />

    <EditText
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:hint="Enter Name"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.503"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/rollnum"
        app:layout_constraintVertical_bias="0.018" />

    <EditText
        android:id="@+id/marks"
        android:hint="Enter Marks"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="number"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.503"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/name"
        app:layout_constraintVertical_bias="0.03" />

    <Button
        android:id="@+id/btnupdt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Update"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/marks"
        app:layout_constraintVertical_bias="0.125" />

    <TextView
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
        android:id="@+id/search"
        android:clickable="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Show Data >>"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnupdt" />
</android.support.constraint.ConstraintLayout>
</code>```

and below is the Java file

```<code>package com.example.junaidmalik.sqlitedemo;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class SqliteDemo extends AppCompatActivity {

    EditText et1, et2, et3;
    TextView search;
    SqliteDemoHelper myData;

    Button btnupdt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sqlite_demo);

        et1 = (EditText) findViewById(R.id.rollnum);
        et2 = (EditText) findViewById(R.id.name);
        et3 = (EditText) findViewById(R.id.marks);
        search = (TextView) findViewById(R.id.search);

        btnupdt = (Button) findViewById(R.id.btnupdt);

        btnupdt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                int rn = Integer.parseInt(et1.getText().toString());
                int mks = Integer.parseInt(et3.getText().toString());
                String name = (String) et2.getText().toString();

                SqliteDemoHelper demoHelper = new SqliteDemoHelper(SqliteDemo.this);
                SQLiteDatabase db = demoHelper.getWritableDatabase();

                ContentValues values = new ContentValues();
                values.put("sid", rn);
                values.put("sname", name);
                values.put("marks", mks);

                long row = db.insert("Students", null, values);

                demoHelper.getReadableDatabase();

                String projection[] = {"sid", "sname", "marks"};

                Cursor c = db.query("Students", projection, null, null, null, null, null);
                c.moveToLast();
                System.out.println("Name is : " + c.getString(1) + " and " + "Roll Number is :" + c.getString(0));
                Toast.makeText(SqliteDemo.this, "Database Updated", Toast.LENGTH_SHORT).show();

                setContentView(R.layout.activity_sqlite_demo);

            }

        });

        search.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                setContentView(R.layout.activity_sqlite_demo);

                SqliteDemoHelper demoHelper = new SqliteDemoHelper(SqliteDemo.this);
                SQLiteDatabase db = demoHelper.getWritableDatabase();
                Cursor res = db.rawQuery("Select * from Students",null);

                if (res.getCount() == 0) {
                    showMessage("Error", "Nothing Found");
                    return;
                }

                StringBuffer buffer = new StringBuffer();
                while (res.moveToNext()) {
                    buffer.append("sid :" + res.getString(0) + "\n");
                    buffer.append("name : " + res.getString(1) + "\n");
                    buffer.append("Marks :" + res.getString(2) + "\n\n");
                }

                showMessage("Data is - ", buffer.toString());

            }
        });}

    public void showMessage(String title, String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(true);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.show();
    }

}
</code>```

答:
```<code>search.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            setContentView(R.layout.activity_sqlite_demo);
....
..
}});
</code>```

Remove setcontentView from search click event.

Probably view in the layout activity_sqlite_demo need to be reintialize if you call method setcontentview again.

Title: Clickable Text View not Working

Body:
I am a learner in Android development, I was learning SQLite database in the program where I need your help.

The program I have developed gets the input from the user and stores the values in SQLite database, I have also made a clickable text view which is supposed to show the stored data.

The problem I am facing is when I run the program and directly click on Show Data (Textview) it opens the alert dialogue and displays the data however when I enter the data and then after that if I try to click on "Show Data" the text view become disabled.

Please help.

Below are my XML and Java files.

XML

<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.junaidmalik.sqlitedemo.SqliteDemo">

    <EditText
        android:id="@+id/rollnum"
        android:hint="Enter Roll Number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="number"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.503"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.16" />

    <EditText
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:hint="Enter Name"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.503"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/rollnum"
        app:layout_constraintVertical_bias="0.018" />

    <EditText
        android:id="@+id/marks"
        android:hint="Enter Marks"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="number"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.503"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/name"
        app:layout_constraintVertical_bias="0.03" />

    <Button
        android:id="@+id/btnupdt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Update"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/marks"
        app:layout_constraintVertical_bias="0.125" />

    <TextView
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
        android:id="@+id/search"
        android:clickable="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Show Data >>"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnupdt" />
</android.support.constraint.ConstraintLayout>

and below is the Java file

package com.example.junaidmalik.sqlitedemo;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class SqliteDemo extends AppCompatActivity {

    EditText et1, et2, et3;
    TextView search;
    SqliteDemoHelper myData;

    Button btnupdt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sqlite_demo);

        et1 = (EditText) findViewById(R.id.rollnum);
        et2 = (EditText) findViewById(R.id.name);
        et3 = (EditText) findViewById(R.id.marks);
        search = (TextView) findViewById(R.id.search);

        btnupdt = (Button) findViewById(R.id.btnupdt);

        btnupdt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                int rn = Integer.parseInt(et1.getText().toString());
                int mks = Integer.parseInt(et3.getText().toString());
                String name = (String) et2.getText().toString();

                SqliteDemoHelper demoHelper = new SqliteDemoHelper(SqliteDemo.this);
                SQLiteDatabase db = demoHelper.getWritableDatabase();

                ContentValues values = new ContentValues();
                values.put("sid", rn);
                values.put("sname", name);
                values.put("marks", mks);

                long row = db.insert("Students", null, values);

                demoHelper.getReadableDatabase();

                String projection[] = {"sid", "sname", "marks"};

                Cursor c = db.query("Students", projection, null, null, null, null, null);
                c.moveToLast();
                System.out.println("Name is : " + c.getString(1) + " and " + "Roll Number is :" + c.getString(0));
                Toast.makeText(SqliteDemo.this, "Database Updated", Toast.LENGTH_SHORT).show();

                setContentView(R.layout.activity_sqlite_demo);

            }

        });

        search.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                setContentView(R.layout.activity_sqlite_demo);

                SqliteDemoHelper demoHelper = new SqliteDemoHelper(SqliteDemo.this);
                SQLiteDatabase db = demoHelper.getWritableDatabase();
                Cursor res = db.rawQuery("Select * from Students",null);

                if (res.getCount() == 0) {
                    showMessage("Error", "Nothing Found");
                    return;
                }

                StringBuffer buffer = new StringBuffer();
                while (res.moveToNext()) {
                    buffer.append("sid :" + res.getString(0) + "\n");
                    buffer.append("name : " + res.getString(1) + "\n");
                    buffer.append("Marks :" + res.getString(2) + "\n\n");
                }

                showMessage("Data is - ", buffer.toString());

            }
        });}

    public void showMessage(String title, String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(true);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.show();
    }

}

Body:
search.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            setContentView(R.layout.activity_sqlite_demo);
....
..
}});

Remove setcontentView from search click event.

Probably view in the layout activity_sqlite_demo need to be reintialize if you call method setcontentview again.


问:
copy files to sdcard before executing instrumentation tests
what's the best approach to copy data to sdcard before all instrumentation tests.
So far, my idea is to create Gradle task to do that. Do you have an idea how to do it more robust and simple?</p>

答:
I did something similar with a gradle task :

```<code>//Copy file form device to project
task copyFileForTest{
    group = "My_tasks"
    description ="Copy auth token from device to project"
    doFirst {
        println 'Getting file for Unit tests'
        def resFolder = new File(projectDir.absolutePath+'/src/test/res')
        exec {
            commandLine android.getAdbExecutable(),'pull', '-a', '/storage/emulated/0/Android/data/org.myproject.debug/files/file.txt', "${resFolder.absolutePath}"
        }
    }
}
</code>```

And then to be sure it will run after my instrumentation test:

```<code>copyFileForTest.mustRunAfter 'connectedAndroidTest'
</code>```

Body:
I did something similar with a gradle task :

//Copy file form device to project
task copyFileForTest{
    group = "My_tasks"
    description ="Copy auth token from device to project"
    doFirst {
        println 'Getting file for Unit tests'
        def resFolder = new File(projectDir.absolutePath+'/src/test/res')
        exec {
            commandLine android.getAdbExecutable(),'pull', '-a', '/storage/emulated/0/Android/data/org.myproject.debug/files/file.txt', "${resFolder.absolutePath}"
        }
    }
}

And then to be sure it will run after my instrumentation test:

copyFileForTest.mustRunAfter 'connectedAndroidTest'


问:
How to create dotted rounded ImageView?
I want create dotted rounded ImageView. I think I should use Paint but it does not work.

```<code>private Paint dashPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
{
    dashPaint.setStyle(Paint.Style.STROKE);
    dashPaint.setColor(Color.WHITE);
    dashPaint.setAlpha(120);
    dashPaint.setPathEffect(new DashPathEffect(new float[]{
            5, 5
    }, 0.0f));
    dashPaint.setStrokeWidth(Easify.dp(1.2f));
}
</code>```

答:
public class DottedImageView extends ImageView {

```<code>public DottedImageView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
}

private Paint dashPaint=new Paint(Paint.ANTI_ALIAS_FLAG);
{
    dashPaint.setStyle(Paint.Style.STROKE);
    dashPaint.setColor(Color.WHITE);
    dashPaint.setAlpha(120);
    dashPaint.setPathEffect(new DashPathEffect(new float[]{15, 15
    }, 0f));
    dashPaint.setStrokeWidth(3);
}

@Override
protected void dispatchDraw(Canvas canvas) {
    super.dispatchDraw(canvas);
    int rad=Math.min(canvas.getWidth(), canvas.getHeight())/2;
    rad-=dashPaint.getStrokeWidth();
    dashPaint.setColor(Color.WHITE);
    canvas.drawCircle(canvas.getWidth()/2, canvas.getHeight()/2,rad, dashPaint);
}
</code>```

}

Title: How to create dotted rounded ImageView?

Body:
I want create dotted rounded ImageView. I think I should use Paint but it does not work.

private Paint dashPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
{
    dashPaint.setStyle(Paint.Style.STROKE);
    dashPaint.setColor(Color.WHITE);
    dashPaint.setAlpha(120);
    dashPaint.setPathEffect(new DashPathEffect(new float[]{
            5, 5
    }, 0.0f));
    dashPaint.setStrokeWidth(Easify.dp(1.2f));
}

Body:
public class DottedImageView extends ImageView {

public DottedImageView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
}

private Paint dashPaint=new Paint(Paint.ANTI_ALIAS_FLAG);
{
    dashPaint.setStyle(Paint.Style.STROKE);
    dashPaint.setColor(Color.WHITE);
    dashPaint.setAlpha(120);
    dashPaint.setPathEffect(new DashPathEffect(new float[]{15, 15
    }, 0f));
    dashPaint.setStrokeWidth(3);
}

@Override
protected void dispatchDraw(Canvas canvas) {
    super.dispatchDraw(canvas);
    int rad=Math.min(canvas.getWidth(), canvas.getHeight())/2;
    rad-=dashPaint.getStrokeWidth();
    dashPaint.setColor(Color.WHITE);
    canvas.drawCircle(canvas.getWidth()/2, canvas.getHeight()/2,rad, dashPaint);
}

}


问:
Apply drop caps to each word in a link
I'd like to recreate the menu effect seen at http://www.thedecoratorsource.co.uk using CSS fonts and drop caps.

I know that I can use

```<code>p.introduction:first-letter {
font-size : 300%;
}
</code>```

which will give me the first word with a larger first characerer but I want to apply it to each word. I'm guessing there isn't a way to do this with CSS(3). Would my best bet with javascript? I've already got Moo on the page so this would be my preferred method.

I don't want to add extra HTML to my links to achieve this.

Thanks

答:
This isn't drop caps (that's when you have a big capital letter at the start of a paragraph that takes three or four lines). This is Small Caps.

Easiest way is to find a small caps font, and capitalise every word. Sadly the only font I can find on google web font api that has small caps might not have the right character:

http://code.google.com/webfonts/family?family=Walter+Turncoat&subset=latin

Title: Apply drop caps to each word in a link

Body:
I'd like to recreate the menu effect seen at http://www.thedecoratorsource.co.uk using CSS fonts and drop caps.

I know that I can use

p.introduction:first-letter {
font-size : 300%;
}

which will give me the first word with a larger first characerer but I want to apply it to each word. I'm guessing there isn't a way to do this with CSS(3). Would my best bet with javascript? I've already got Moo on the page so this would be my preferred method.

I don't want to add extra HTML to my links to achieve this.

Thanks


问:
Getting Window from view model
I have created a custom messageBox Window to replace the typical MessageBox.

My custom messageBox (child Window) needs parent window to be passed as an argument. The parent window is where child window will be located within in the location specified (Top Left, Top Center, etc.) also as an argument.

So when calling my custom messageBox from view model, I need to get the Window to pass it through. How can I get the Window associated to the view model?

Maybe using an Interface like commented here? I am trying to implement it but this.DataContext.View does not exist.

I am using Visual Studio 2008.

ATTEMPT #1: mm8 solution

```<code><Window x:Class="MyNamespace.Main"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:viewmodel="clr-namespace:MyNamespace.ViewModels">
    <Window.Resources>
        <viewmodel:MainViewModel x:Key="wMainViewModel" />
    </Window.Resources>

    <Grid DataContext="{StaticResource wMainViewModel}">
    </Grid>
</Window>
</code>```

Taken into account that I initialize DataContext from xaml and not in code-behind from constructor, how can I pass the view to the view model¿?

答:
How can I get the Window associated to the view model?

You could inject the view model with an interface that the window implements:

```<code>public interface IView
{
    double Top { get; }
    double Left { get; }
    double Height { get; }
    double Width { get; }
}

public partial class MainWindow : Window, IView
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModel(this);
    }
}

public class ViewModel
{
    private readonly IView _view;

    public ViewModel(IView view)
    {
        _view = view;
    }

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

Then the view model knows only about an interface (which maybe should be called something else than IView).

If you want an ugly and non-MVVM friendly shortcut, you could use the Application class:

```<code>var win = Application.Current.MainWindow;
</code>```

A factory class to create everything:

```<code>public MainWindow WindowFactory()
{
    MainWindow mainWindow = new MainWindow();
    ViewModel viewModel = new ViewModel();
    mainWindow.DataContext = viewModel;

    return mainWindow;
}
</code>```

Title: Getting Window from view model

Body:
I have created a custom messageBox Window to replace the typical MessageBox.

My custom messageBox (child Window) needs parent window to be passed as an argument. The parent window is where child window will be located within in the location specified (Top Left, Top Center, etc.) also as an argument.

So when calling my custom messageBox from view model, I need to get the Window to pass it through. How can I get the Window associated to the view model?

Maybe using an Interface like commented here? I am trying to implement it but this.DataContext.View does not exist.

I am using Visual Studio 2008.

ATTEMPT #1: mm8 solution

<Window x:Class="MyNamespace.Main"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:viewmodel="clr-namespace:MyNamespace.ViewModels">
    <Window.Resources>
        <viewmodel:MainViewModel x:Key="wMainViewModel" />
    </Window.Resources>

    <Grid DataContext="{StaticResource wMainViewModel}">
    </Grid>
</Window>

Taken into account that I initialize DataContext from xaml and not in code-behind from constructor, how can I pass the view to the view model¿?

Body:
How can I get the Window associated to the view model?

You could inject the view model with an interface that the window implements:

public interface IView
{
    double Top { get; }
    double Left { get; }
    double Height { get; }
    double Width { get; }
}

public partial class MainWindow : Window, IView
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModel(this);
    }
}

public class ViewModel
{
    private readonly IView _view;

    public ViewModel(IView view)
    {
        _view = view;
    }

    //...
}

Then the view model knows only about an interface (which maybe should be called something else than IView).

If you want an ugly and non-MVVM friendly shortcut, you could use the Application class:

var win = Application.Current.MainWindow;

A factory class to create everything:

public MainWindow WindowFactory()
{
    MainWindow mainWindow = new MainWindow();
    ViewModel viewModel = new ViewModel();
    mainWindow.DataContext = viewModel;

    return mainWindow;
}


问:
python - How to parse numbers around a specific word/phrase
Suppose that I have a text like this:

Our favorite numbers are 5, 6, and 7, but his favorite number is 0. Also, this text contains 2 sentences.

Let's say I'd like to get favorite numbers only in this text, for instance. I won't be able to know if there's a favorite number in this text, unless the phrase favorite number is present. So I'm basically trying to parse numbers around the phrase favorite number (or favorite numbers). The expected result should be something like this:

['5', '6', '7', '0']
```

<p>I tried using regex for that but I've failed so far. What's the most logical way to do this?</p>

<p>Edit: After reading @LouiseDavies's question, I'll add another example below:</p>

<p><code>Alice has 2 favorite numbers: 11 and 12. Bob has 10 favorite numbers: 0, 100, 1264, 598, 78496, 33546, 1028896, 23, 48, 6.</code></p>

<p>So in this example, my output should be something like this (the order doesn't matter):</p>

```['11', '12', '0', '100', '1264', '598', '78496', '33546', '1028896', '23', '48', '6']
```

答:
You didn't show any code so I won't write a complete solution.

You could split at ., filter the sentences that have "favourite number" and extract the numbers from those sentences. You shouldn't try to write a regex for the whole sentence.

Here's a start:

```<code>text = "Our favorite numbers are 5, 6, and 7, but his favorite number is 0. Also, this text contains 2 sentences."

import re
pattern = re.compile("favou?rite numbers?", re.I)

print([sentence for sentence in text.split('.') if pattern.search(sentence)])
# ['Our favorite numbers are 5, 6, and 7, but his favorite number is 0']
</code>```

Now that you have the list of interesting sentences, you're one list comprehension and one re.findall('d+') away from a complete solution.

Body:
Suppose that I have a text like this:

Our favorite numbers are 5, 6, and 7, but his favorite number is 0. Also, this text contains 2 sentences.

Let's say I'd like to get favorite numbers only in this text, for instance. I won't be able to know if there's a favorite number in this text, unless the phrase favorite number is present. So I'm basically trying to parse numbers around the phrase favorite number (or favorite numbers). The expected result should be something like this:

['5', '6', '7', '0']

I tried using regex for that but I've failed so far. What's the most logical way to do this?

Edit: After reading @LouiseDavies's question, I'll add another example below:

Alice has 2 favorite numbers: 11 and 12. Bob has 10 favorite numbers: 0, 100, 1264, 598, 78496, 33546, 1028896, 23, 48, 6.

So in this example, my output should be something like this (the order doesn't matter):

['11', '12', '0', '100', '1264', '598', '78496', '33546', '1028896', '23', '48', '6']

Body:
You didn't show any code so I won't write a complete solution.

You could split at ., filter the sentences that have "favourite number" and extract the numbers from those sentences. You shouldn't try to write a regex for the whole sentence.

Here's a start:

text = "Our favorite numbers are 5, 6, and 7, but his favorite number is 0. Also, this text contains 2 sentences."

import re
pattern = re.compile("favou?rite numbers?", re.I)

print([sentence for sentence in text.split('.') if pattern.search(sentence)])
# ['Our favorite numbers are 5, 6, and 7, but his favorite number is 0']

Now that you have the list of interesting sentences, you're one list comprehension and one re.findall('d+') away from a complete solution.


问:
.Net Core 2 Builds and Runs Locally - Error Error MSB3073 on Publish - Since VS 15.4.3
I have a .Net Core 2.0 solution that has been working great for a few months now. I am ready to make another push and let people look at it.  Builds and runs great locally, however, I am unable to publish it (to Azure or even Locally - so it is not an Azure issue) anymore.  The only real significant change was upgrading to Visual Studio 15.4.3 since my last push.

This is the error:

Severity  Code    Description Project File    Line    Suppression State
  Error     The command ""dotnet" exec --runtimeconfig "C:\Avantia
  Projects\Time
  Card\avantia-timesheet\Solution\Almanac\bin\Release\netcoreapp2.0\Avantia.Almanac.runtimeconfig.json"
  --depsfile "C:\Avantia Projects\Time Card\avantia-timesheet\Solution\Almanac\bin\Release\netcoreapp2.0\Avantia.Almanac.deps.json"
  "C:\Program
  Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.mvc.razor.viewcompilation\2.0.0\build\netstandard2.0\Microsoft.AspNetCore.Mvc.Razor.ViewCompilation.dll"
  @"obj\Release\netcoreapp2.0\microsoft.aspnetcore.mvc.razor.viewcompilation.rsp""
  exited with code 1.   Almanac C:\Program
  Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.mvc.razor.viewcompilation\2.0.0\build\netstandard2.0\Microsoft.AspNetCore.Mvc.Razor.ViewCompilation.targets 60

I have read many articles out there, mostly saying to delete the bin and obj folders.  Which I have in all three projects within the solution.  I then did a dotnet restore and again, everything builds and runs locally but will not Publish successfully.

This was originally written in 1.x and converted to 2.0 but that conversion took place when 2.0 RTM came out many publishes ago.

答:
This does not make sense to me (seeing that the error above talks about Razor) but in my opinion Microsoft needs to figure something out for this based on their suggestions.

So, the MS docs suggest Twilio for 2 factor authentication.  Fine.  Then Twilio suggests another package called Authy which is over 2 years old and clearly not .Net core.

I removed Authy from my solution at this point seeing that it is only something I want to get to and do not Need at this time.  That took care of the problem in publishing.

I assume perhaps because it is not .Net core?  Either way, things can now progress forward.


问:
How to loop over multiple filtered regex strings
I do not know how to better track down the question. What I want to do is to look for every e-mail-address matching my regEx in different div.test, to create  links.

This does work, but if there are multiple mail addresses inside one div, only the first one gets highlighted. Whats the problem?

```<code>var regEx = /(\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)/;

$(".test").filter(function() {
    return $(this).html().match(regEx);
}).each(function() {
    $(this).html($(this).html().replace(regEx, "<a href=\"mailto:$1\">$1</a>"));
});
</code>```

href="http://jsbin.com/sazegipufi/1/edit?html,js,output" rel="nofollow noreferrer">JSBIN

答:
You must add the global (g) flag to you regexp:

```<code>var regEx = /(\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)/g
</code>```

Otherwise your regex will halt after the first match.

Body:
I do not know how to better track down the question. What I want to do is to look for every e-mail-address matching my regEx in different div.test, to create  links.

This does work, but if there are multiple mail addresses inside one div, only the first one gets highlighted. Whats the problem?

var regEx = /(\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)/;

$(".test").filter(function() {
    return $(this).html().match(regEx);
}).each(function() {
    $(this).html($(this).html().replace(regEx, "$1"));
});

JSBIN

Body:
You must add the global (g) flag to you regexp:

var regEx = /(\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)/g

Otherwise your regex will halt after the first match.


问:
Get row number of UITableview with multiple sections
I have a UITableView, with multiple sections in it, and each section has multiple rows. I want to get the row number of selected cell with respect to the entire table and not the section only.

example:

I have two sections in the UITableView, section 1 has 3 rows and section 2 has 5 rows.

When I select sections 2's 2nd row, I should get the 5 as the row number in didSelectRowAtIndexPath method, rather than getting 2 as the row number (which is with respect to the section).

I tried to get the row number myself by doing the following, but it does not seem to work:

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];

NSLog(@"%d",indexPath.row);

int theRow =  indexPath.row;

NSLog(@"%d",theRow);
}
</code>```

I was thinking of storing the row number in an intvariable, and then add row numbers to it myself, but the code crashes when trying to store  indexpath.row in theRow .

Please help. Thank you

答:
Let say I implement the code below in didSelectRowAt / didSelectItemAt callbacks ...

UITableView

```<code>var index: Int = indexPath.row
for i in 0..<indexPath.section {
    index += tableView.numberOfRows(inSection: i)
}
</code>```

UICollectionView

```<code>var index: Int = indexPath.item
for i in 0..<indexPath.section {
    index += collectionView.numberOfItems(inSection: i)
}
</code>```

Example: 2 sections, 3 rows(items) each. Selected row(item) 1 in the section 1, index = 4

Body:
I have a UITableView, with multiple sections in it, and each section has multiple rows. I want to get the row number of selected cell with respect to the entire table and not the section only.

example:

I have two sections in the UITableView, section 1 has 3 rows and section 2 has 5 rows.

When I select sections 2's 2nd row, I should get the 5 as the row number in didSelectRowAtIndexPath method, rather than getting 2 as the row number (which is with respect to the section).

I tried to get the row number myself by doing the following, but it does not seem to work:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];

NSLog(@"%d",indexPath.row);

int theRow =  indexPath.row;

NSLog(@"%d",theRow);
}

I was thinking of storing the row number in an intvariable, and then add row numbers to it myself, but the code crashes when trying to store  indexpath.row in theRow .

Please help. Thank you

Body:
Let say I implement the code below in didSelectRowAt / didSelectItemAt callbacks ...

UITableView

var index: Int = indexPath.row
for i in 0..<indexPath.section {
    index += tableView.numberOfRows(inSection: i)
}

UICollectionView

var index: Int = indexPath.item
for i in 0..<indexPath.section {
    index += collectionView.numberOfItems(inSection: i)
}

Example: 2 sections, 3 rows(items) each. Selected row(item) 1 in the section 1, index = 4


问:
jquery validate and error styles

how do i get rid of the borders in ul > li ?

i have :

```<code>    errorLabelContainer: $("ul", $('div.error')), wrapper: 'li',

errorContainer: $('div.error'),
</code>```

i tried :

```<code> div.message{
background: transparent url(images\ad_next.png) no-repeat scroll left center;
padding-left: 17px; border:0px;
}
div.message ul, li { border:0px; }
div.error{
    background-color:#F3E6E6;
    border-color: #924949;
    border-style: solid solid solid solid;
    border-width: 2px;
    padding: 5px;
}
</code>```

答:
Have u tried this </p>

```<code>var validator = $("#formId").validate({
            errorPlacement: function(error, element) {
                error.css({border:"0px"});
            }
        });
</code>```

Title: jquery validate and error styles

Body:
how do i get rid of the borders in ul > li ?

i have :

    errorLabelContainer: $("ul", $('div.error')), wrapper: 'li',

errorContainer: $('div.error'),

i tried :

 div.message{
background: transparent url(images\ad_next.png) no-repeat scroll left center;
padding-left: 17px; border:0px;
}
div.message ul, li { border:0px; }
div.error{
    background-color:#F3E6E6;
    border-color: #924949;
    border-style: solid solid solid solid;
    border-width: 2px;
    padding: 5px;
}

Body:
Have u tried this

var validator = $("#formId").validate({
            errorPlacement: function(error, element) {
                error.css({border:"0px"});
            }
        });


问:
error:Connection reset (Gradle sync failed: Connection reset)
I am importing constraint-layout-start to android studio 3.0. I have kept in androidstudioproject folder that's the the path where all my android studio projects are stored. after importing its showing connection reset error. Here is the log file link: https://drive.google.com/file/d/1W1mGmIc67baZb4C5nGGecWm15ggB0Wp5/view?usp=sharing

i have all the SDK installed. tried to manually change the sdk verion to 21 which was running perfectly for my other projects, but here it didn't work.

i checked all the files are okay, i am not getting why this error occurs.
images of gradle page are given below.

build.gradle

gradle

答:
Add google repository to your gradle file:

```<code>repositories {
    maven()
    //other repositories...
    google()
}
</code>```

Try to download from SDK manager:
SDK Manager Android Studio

Check your gradle and plugin version:

https://developer.android.com/studio/releases/gradle-plugin.html#updating-gradle

Body:
Add google repository to your gradle file:

repositories {
    maven()
    //other repositories...
    google()
}

Try to download from SDK manager:
SDK Manager Android Studio

Check your gradle and plugin version:

https://developer.android.com/studio/releases/gradle-plugin.html#updating-gradle


问:
Ignoring Duplicate Records SQL
In need of some help :)

So I have a table of records with the following columns:

```<code>Key (PK, FK, int) DT (smalldatetime) Value (real)
</code>```

The DT is a datetime for every half hour of the day with an associated value

E.g.

```<code>Key       DT                       VALUE
1000      2010-01-01 08:00:00      80
1000      2010-01-01 08:30:00      75
1000      2010-01-01 09:00:00      100
</code>```

I have a Query that finds the max value every 24 hour period and its associated time however, on one day the max value occurs twice and hence duplicates the date which is causing processing issues. I have tried using rownumber() which works but I can't use a calculated column in my where clause?
Currently I have:

```<code>SELECT       cast(T1.DT as date) as 'Date',Cast(T1.DT as time(0)) as 'HH', ROW_NUMBER() over (PARTITION BY  cast(DT as date) ORDER BY DT) AS 'RowNumber'
FROM        TABLE_1 AS T1
INNER JOIN  (
                SELECT CAST([DT] as date) as 'DATE'
                ,       MAX([VALUE]) as 'MAX_HH'
                FROM    TABLE_1
                WHERE   DT > '6-nov-2016' and [KEY] = '1000'
                GROUP BY CAST([DT] as date)
            ) AS MAX_DT
        ON  MAX_DT.[DATE] = CAST(T1.[DT] as date)
        AND T1.VALUE = MAX_DT.MAX_HH
WHERE       DT > '6-nov-2016' and [KEY] = '1000'
ORDER BY DT
</code>```

This results in

```<code>Key       DT               VALUE       HH
1000      2010-01-01       80          07:00:00
1000      2010-02-01       100         17:30:00
1000      2010-02-01       100         18:00:00
</code>```

I need to remove the duplicate date (I Have no preference which HH it takes)

I think I've explained that terribly, let me know if it makes no sense and i'll try and re write

Any ideas?

答:
With SQL you can use SELECT DISTINCT,

The SELECT DISTINCT statement is used to return only distinct (different) values.

Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.

The SELECT DISTINCT statement is used to return only distinct (different) values.

Title: Ignoring Duplicate Records SQL

Body:
In need of some help :)

So I have a table of records with the following columns:

Key (PK, FK, int) DT (smalldatetime) Value (real)

The DT is a datetime for every half hour of the day with an associated value

E.g.

Key       DT                       VALUE
1000      2010-01-01 08:00:00      80
1000      2010-01-01 08:30:00      75
1000      2010-01-01 09:00:00      100

I have a Query that finds the max value every 24 hour period and its associated time however, on one day the max value occurs twice and hence duplicates the date which is causing processing issues. I have tried using rownumber() which works but I can't use a calculated column in my where clause?
Currently I have:

SELECT       cast(T1.DT as date) as 'Date',Cast(T1.DT as time(0)) as 'HH', ROW_NUMBER() over (PARTITION BY  cast(DT as date) ORDER BY DT) AS 'RowNumber'
FROM        TABLE_1 AS T1
INNER JOIN  (
                SELECT CAST([DT] as date) as 'DATE'
                ,       MAX([VALUE]) as 'MAX_HH'
                FROM    TABLE_1
                WHERE   DT > '6-nov-2016' and [KEY] = '1000'
                GROUP BY CAST([DT] as date)
            ) AS MAX_DT
        ON  MAX_DT.[DATE] = CAST(T1.[DT] as date)
        AND T1.VALUE = MAX_DT.MAX_HH
WHERE       DT > '6-nov-2016' and [KEY] = '1000'
ORDER BY DT

This results in

Key       DT               VALUE       HH
1000      2010-01-01       80          07:00:00
1000      2010-02-01       100         17:30:00
1000      2010-02-01       100         18:00:00

I need to remove the duplicate date (I Have no preference which HH it takes)

I think I've explained that terribly, let me know if it makes no sense and i'll try and re write

Any ideas?


问:
TensorFlow's RNN units and cells
The constructor for many of the RNN classes (BasicRNNCell, LSTMCell, and so on) accepts an argument named num_units. This sets the number of units in the cell.

I thought this identified the number of elements the RNN should process in sequence. So if you want an RNN to process sequences of length N, you'd have N units per cell. Is this correct? What exactly is an RNN unit?

答:
here num_units refers to the number of units in LSTM(or rnn) cell.

num_units can be interpreted as the analogy of hidden layer from the feed forward neural network.The number of nodes in hidden layer of a feed forward neural network is equivalent to num_units number of LSTM units in a LSTM cell at every time step of the network.Following picture should clear any confusion-
enter image description here

(cited from https://jasdeep06.github.io/posts/Understanding-LSTM-in-Tensorflow-MNIST/

Title: TensorFlow's RNN units and cells