问:
ERROR: UndefVarError: y not defined
I am trying to run a mixed-effects model in julia (R is too slow for my data), but I keep getting this error.

I have installed DataArrays, DataFrames , MixedModels, and RDatasets packages and am following the tutorial here --> http://dmbates.github.io/MixedModels.jl/latest/man/fitting/#Fitting-linear-mixed-effects-models-1

These are my steps:

```<code>using DataArrays, DataFrames , MixedModels, RDatasets
</code>```

I get these warnings

WARNING: Method definition ==(Base.Nullable{S}, Base.Nullable{T}) in
  module Base at nullable.jl:238 overwritten in module NullableArrays at
  /home/home/.julia/v0.6/NullableArrays/src/operators.jl:128. WARNING:
  Method definition model_response(DataFrames.ModelFrame) in module
  DataFrames at
  /home/home/.julia/v0.6/DataFrames/src/statsmodels/formula.jl:352
  overwritten in module MixedModels at
  /home/home/.julia/v0.6/MixedModels/src/pls.jl:65. WARNING: Method
  definition ==(Base.Nullable{S}, Base.Nullable{T}) in module Base at
  nullable.jl:238 overwritten in module NullableArrays at
  /home/home/.julia/v0.6/NullableArrays/src/operators.jl:128. WARNING:
  Method definition ==(Base.Nullable{S}, Base.Nullable{T}) in module
  Base at nullable.jl:238 overwritten in module NullableArrays at
  /home/home/.julia/v0.6/NullableArrays/src/operators.jl:128. WARNING:
  Method definition model_response(DataFrames.ModelFrame) in module
  DataFrames at
  /home/home/.julia/v0.6/DataFrames/src/statsmodels/formula.jl:352
  overwritten in module MixedModels at
  /home/home/.julia/v0.6/MixedModels/src/pls.jl:65. WARNING: Method
  definition model_response(DataFrames.ModelFrame) in module DataFrames
  at /home/home/.julia/v0.6/DataFrames/src/statsmodels/formula.jl:352
  overwritten in module MixedModels at
  /home/home/.julia/v0.6/MixedModels/src/pls.jl:65.

I get an R dataset from lme4 package (used in the tutorial)

```<code>inst = dataset("lme4", "InstEval")

julia> head(inst)
6×7 DataFrames.DataFrame
│ Row │ S   │ D      │ Studage │ Lectage │ Service │ Dept │ Y │
├─────┼─────┼────────┼─────────┼─────────┼─────────┼──────┼───┤
│ 1   │ "1" │ "1002" │ "2"     │ "2"     │ "0"     │ "2"  │ 5 │
│ 2   │ "1" │ "1050" │ "2"     │ "1"     │ "1"     │ "6"  │ 2 │
│ 3   │ "1" │ "1582" │ "2"     │ "2"     │ "0"     │ "2"  │ 5 │
│ 4   │ "1" │ "2050" │ "2"     │ "2"     │ "1"     │ "3"  │ 3 │
│ 5   │ "2" │ "115"  │ "2"     │ "1"     │ "0"     │ "5"  │ 2 │
│ 6   │ "2" │ "756"  │ "2"     │ "1"     │ "0"     │ "5"  │ 4 │
</code>```

I run the model as shown in the tutorial

```<code>m2 = fit!(lmm(y ~ 1 + dept*service + (1|s) + (1|d), inst))
</code>```

and get

```<code>ERROR: UndefVarError: y not defined
  Stacktrace:
  [1] macro expansion at ./REPL.jl:97 [inlined]
  [2] (::Base.REPL.##1#2{Base.REPL.REPLBackend})() at ./event.jl:73
</code>```

The same thing happens when I try it with my own data loaded using "readtable" from DataFrames package

I am running julia 0.6.0 and all packages are freshly installed. My system is arch linux 4.11.7-1 with all the latest packages. Julia installs without a problem, but some packages give warnings (see above).

Title: ERROR: UndefVarError: y not defined

Body:
I am trying to run a mixed-effects model in julia (R is too slow for my data), but I keep getting this error.

I have installed DataArrays, DataFrames , MixedModels, and RDatasets packages and am following the tutorial here --> http://dmbates.github.io/MixedModels.jl/latest/man/fitting/#Fitting-linear-mixed-effects-models-1

These are my steps:

using DataArrays, DataFrames , MixedModels, RDatasets

I get these warnings

WARNING: Method definition ==(Base.Nullable{S}, Base.Nullable{T}) in
  module Base at nullable.jl:238 overwritten in module NullableArrays at
  /home/home/.julia/v0.6/NullableArrays/src/operators.jl:128. WARNING:
  Method definition model_response(DataFrames.ModelFrame) in module
  DataFrames at
  /home/home/.julia/v0.6/DataFrames/src/statsmodels/formula.jl:352
  overwritten in module MixedModels at
  /home/home/.julia/v0.6/MixedModels/src/pls.jl:65. WARNING: Method
  definition ==(Base.Nullable{S}, Base.Nullable{T}) in module Base at
  nullable.jl:238 overwritten in module NullableArrays at
  /home/home/.julia/v0.6/NullableArrays/src/operators.jl:128. WARNING:
  Method definition ==(Base.Nullable{S}, Base.Nullable{T}) in module
  Base at nullable.jl:238 overwritten in module NullableArrays at
  /home/home/.julia/v0.6/NullableArrays/src/operators.jl:128. WARNING:
  Method definition model_response(DataFrames.ModelFrame) in module
  DataFrames at
  /home/home/.julia/v0.6/DataFrames/src/statsmodels/formula.jl:352
  overwritten in module MixedModels at
  /home/home/.julia/v0.6/MixedModels/src/pls.jl:65. WARNING: Method
  definition model_response(DataFrames.ModelFrame) in module DataFrames
  at /home/home/.julia/v0.6/DataFrames/src/statsmodels/formula.jl:352
  overwritten in module MixedModels at
  /home/home/.julia/v0.6/MixedModels/src/pls.jl:65.

I get an R dataset from lme4 package (used in the tutorial)

inst = dataset("lme4", "InstEval")

julia> head(inst)
6×7 DataFrames.DataFrame
│ Row │ S   │ D      │ Studage │ Lectage │ Service │ Dept │ Y │
├─────┼─────┼────────┼─────────┼─────────┼─────────┼──────┼───┤
│ 1   │ "1" │ "1002" │ "2"     │ "2"     │ "0"     │ "2"  │ 5 │
│ 2   │ "1" │ "1050" │ "2"     │ "1"     │ "1"     │ "6"  │ 2 │
│ 3   │ "1" │ "1582" │ "2"     │ "2"     │ "0"     │ "2"  │ 5 │
│ 4   │ "1" │ "2050" │ "2"     │ "2"     │ "1"     │ "3"  │ 3 │
│ 5   │ "2" │ "115"  │ "2"     │ "1"     │ "0"     │ "5"  │ 2 │
│ 6   │ "2" │ "756"  │ "2"     │ "1"     │ "0"     │ "5"  │ 4 │

I run the model as shown in the tutorial

m2 = fit!(lmm(y ~ 1 + dept*service + (1|s) + (1|d), inst))

and get

ERROR: UndefVarError: y not defined
  Stacktrace:
  [1] macro expansion at ./REPL.jl:97 [inlined]
  [2] (::Base.REPL.##1#2{Base.REPL.REPLBackend})() at ./event.jl:73

The same thing happens when I try it with my own data loaded using "readtable" from DataFrames package

I am running julia 0.6.0 and all packages are freshly installed. My system is arch linux 4.11.7-1 with all the latest packages. Julia installs without a problem, but some packages give warnings (see above).

Body:
have a go with the @formula macro:

julia> fit!(lmm(@formula(Y ~ (1 | Dept)), inst), true)
f_1: 250160.38873 [1.0]
f_2: 250175.99074 [1.75]
f_3: 250123.06531 [0.25]
f_4: 250602.3424 [0.0]
f_5: 250137.66303 [0.4375]
f_6: 250129.76244 [0.325]
f_7: 250125.94066 [0.280268]
f_8: 250121.15016 [0.23125]
f_9: 250119.12389 [0.2125]
f_10: 250114.7257 [0.175]
f_11: 250105.61264 [0.1]
f_12: 250602.3424 [0.0]
f_13: 250107.52714 [0.118027]
f_14: 250106.36924 [0.107778]
f_15: 250105.04638 [0.0925]
f_16: 250104.72722 [0.085]
f_17: 250104.93086 [0.0749222]
f_18: 250104.70046 [0.0831588]
f_19: 250104.70849 [0.0839088]
f_20: 250104.69659 [0.0824088]
f_21: 250104.69632 [0.0822501]
f_22: 250104.69625 [0.0821409]
f_23: 250104.69625 [0.0820659]
f_24: 250104.69624 [0.0821118]
f_25: 250104.69624 [0.0821193]
f_26: 250104.69624 [0.082111]
f_27: 250104.69624 [0.0821118]
f_28: 250104.69624 [0.0821117]
f_29: 250104.69624 [0.0821118]
f_30: 250104.69624 [0.0821118]
Linear mixed model fit by maximum likelihood
 Formula: Y ~ 1 | Dept
     logLik        -2 logLik          AIC             BIC
 -1.25052348×10⁵  2.50104696×10⁵  2.50110696×10⁵  2.50138308×10⁵

Variance components:
              Column     Variance   Std.Dev.
 Dept     (Intercept)  0.011897242 0.10907448
 Residual              1.764556375 1.32836605
 Number of obs: 73421; levels of grouping factors: 14

  Fixed-effects parameters:
             Estimate Std.Error z value P(>|z|)
(Intercept)   3.21373  0.029632 108.455  <1e-99

The warnings are the usual "Julia (and the package ecosystem) is still in flux" messages. But I wonder whether the docs always keep pace with the code.


来源: stackexchange

问:
What does an example MongoDB error look like on the NodeJS native driver?
I can't seem to find any examples of MongoDB error objects in their documentation or on the internet.

What does an example MongoDB error object look like? I'd like to "handle" the error and/or reformat it for my own purposes, depending on what the error is.

答:
MongoError objects

With newer versions of the node-mongodb-driver (>= 2) things are a little bit different.

Inside the nodejs driver source code 2.2 you can see that the error object properties can be various (see line 34). Only name and message fields are always available.

This is an interesting piece of code from mongodb-core/lib/error.js (v2.2), look at the last for loop.

```<code>function MongoError(message) {
  this.name = 'MongoError';
  this.message = message;
  Error.captureStackTrace(this, MongoError);
}

MongoError.create = function(options) {
  var err = null;
  if(options instanceof Error) {
    err = new MongoError(options.message);
    err.stack = options.stack;
  } else if(typeof options == 'string') {
    err = new MongoError(options);
  } else {
    err = new MongoError(options.message || options.errmsg || options.$err || "n/a");
    // Other options
    for(var name in options) {
      err[name] = options[name];
    }
  }
  return err;
}
</code>```

So, an error object will looks, at least, like this:

```<code>{
   "name": : "MongoError",
   "message": "E11000 duplicate key error collection: main_db.stores index..."
}
</code>```

err.code field

So, there is no guarantee for other fields, but code is pretty common (and very useful). This number is a mongodb internal error code and the driver just add it to the MongoError object when available. You can find the latest error codes list inside a mongodb source code file: error_codes.yml.

An interesting example about how the nodejs driver manage mongodb error codes, is the collection bulkWrite source code, that uses the toError utils with a code to throw a MongoError.

node-mongodb-driver 3.x

The MongoError source code has been refactored but the error model is essentially the same.

ContentLicense: CC BY-SA 3.0

Body:
MongoError objects

With newer versions of the node-mongodb-driver (>= 2) things are a little bit different.

Inside the nodejs driver source code 2.2 you can see that the error object properties can be various (see line 34). Only name and message fields are always available.

This is an interesting piece of code from mongodb-core/lib/error.js (v2.2), look at the last for loop.

function MongoError(message) {
  this.name = 'MongoError';
  this.message = message;
  Error.captureStackTrace(this, MongoError);
}

MongoError.create = function(options) {
  var err = null;
  if(options instanceof Error) {
    err = new MongoError(options.message);
    err.stack = options.stack;
  } else if(typeof options == 'string') {
    err = new MongoError(options);
  } else {
    err = new MongoError(options.message || options.errmsg || options.$err || "n/a");
    // Other options
    for(var name in options) {
      err[name] = options[name];
    }
  }
  return err;
}

So, an error object will looks, at least, like this:

{
   "name": : "MongoError",
   "message": "E11000 duplicate key error collection: main_db.stores index..."
}

err.code field

So, there is no guarantee for other fields, but code is pretty common (and very useful). This number is a mongodb internal error code and the driver just add it to the MongoError object when available. You can find the latest error codes list inside a mongodb source code file: error_codes.yml.

An interesting example about how the nodejs driver manage mongodb error codes, is the collection bulkWrite source code, that uses the toError utils with a code to throw a MongoError.

node-mongodb-driver 3.x

The MongoError source code has been refactored but the error model is essentially the same.

ContentLicense: CC BY-SA 4.0


问:
How to search and select text in dropdown using selenium webdriver
I am new to Selenium and i am stuck in one implementation
My requirements are

Go to Settings page

Look for the dropdown

Fetch all values from dropdown

Look for a certain text in dropdown

If the text is not selected,Select the particular text in  dropdown

My code is as follows

```<code>void setru()
    {
        driver.switchTo().frame("contentFrame");
        Select rudropdown=new Select(driver.findElement(By.id("DefaultOrganisationDropDown")));
        List<WebElement> drop=rudropdown.getOptions();
        int e=drop.size();
        for(int i=0;i<e;i++)
        {
            String temp=drop.get(i).getText();
            String actual_RU="000139, NEXTRAN CORPORATION - JACKSONVILLE";
            boolean flag=false;
            if(temp.contains("000139"))
            {
                flag=true;
                rudropdown.selectByValue("actual_RU");

            }

        }
</code>```

But this is giving me error message.
org.openqa.selenium.NoSuchElementException: Cannot locate option with value: actual_RU

答:
There seems to be a typo mistake. Use below code

```<code>rudropdown.selectByValue(actual_RU);
</code>```

Instead of

```<code>rudropdown.selectByValue("actual_RU");
</code>```

Body:
I am new to Selenium and i am stuck in one implementation
My requirements are

Go to Settings page

Look for the dropdown

Fetch all values from dropdown

Look for a certain text in dropdown

If the text is not selected,Select the particular text in  dropdown

My code is as follows

void setru()
    {
        driver.switchTo().frame("contentFrame");
        Select rudropdown=new Select(driver.findElement(By.id("DefaultOrganisationDropDown")));
        List<WebElement> drop=rudropdown.getOptions();
        int e=drop.size();
        for(int i=0;i<e;i++)
        {
            String temp=drop.get(i).getText();
            String actual_RU="000139, NEXTRAN CORPORATION - JACKSONVILLE";
            boolean flag=false;
            if(temp.contains("000139"))
            {
                flag=true;
                rudropdown.selectByValue("actual_RU");

            }

        }

But this is giving me error message.
org.openqa.selenium.NoSuchElementException: Cannot locate option with value: actual_RU

Body:
There seems to be a typo mistake. Use below code

rudropdown.selectByValue(actual_RU);

Instead of

rudropdown.selectByValue("actual_RU");


问:
How to right fold using LINQ?
Using LINQ, we can perform a left fold on a list via Aggregate:

```<code>var numbers = new[] { 1, 2, 3, 4 };
var value = numbers.Aggregate((a, b) => a - b); // ((1 - 2) - 3) - 4 == -8
</code>```

Is there a similar way using LINQ to perform a right fold?

```<code>var value = numbers.Aggregate(???); // 1 - (2 - (3 - 4)) == -2
</code>```

答: In case you already using MoreLinq check AggregateRight method

Title: How to right fold using LINQ?

Body:
Using LINQ, we can perform a left fold on a list via Aggregate:

var numbers = new[] { 1, 2, 3, 4 };
var value = numbers.Aggregate((a, b) => a - b); // ((1 - 2) - 3) - 4 == -8

Is there a similar way using LINQ to perform a right fold?

var value = numbers.Aggregate(???); // 1 - (2 - (3 - 4)) == -2


问:
Why does my PHP PDO Select in while not working with page limit? Also issue with Array in select
Why does hello not display to the screen, why is the while loop not executed?
Also I have an issue because the array $zipcodeA[$x] may contain random zip codes like 90564 80564 70564 88464 98754 but the database tman may contain info such as 90564 90564 90564 80564 70564 70564 88464 98754. How do I get the select to go through all the zip codes that are in the array $zipcodeA[$x] instead of just pulling info of one of each zip code?  The database holds random zip codes and many zip codes can be duplicates, the array only many different zip codes with no duplicates</p>

```<code>for($x = 0; $x <= $v; $x++)
{
$stmt = $conn->prepare("SELECT * FROM tman WHERE approve = 'Y' AND zip = :zipp ORDER BY id desc limit :limit");
$stmt->bindParam(":zipp", $zipcodeA[$x], PDO::PARAM_INT);
$stmt->bindValue(':limit', (int) $limit, PDO::PARAM_INT);
echo '<br>zipcode: ' . $zipcodeA[$x] . '<br>';
$stmt->execute();
    while($row = $stmt->fetch(PDO::FETCH_ASSOC))
    {
      $id2 = $row['id'];
      $name = $row['name'];
      echo 'hello';

    }
}
</code>```

答:
Try to do it like this :</p>

```<code>$limit = ($pageno - 1) * $rows_per_page . ',' . $rows_per_page;
for($x = 0; $x <= $v; $x++) {
    $stmt = $conn->prepare("SELECT * FROM tman WHERE approve = 'Y' AND zip = :zipp ORDER BY id desc LIMIT " . $limit);
    $stmt->bindParam(":zipp", $zipcodeA[$x], PDO::PARAM_INT);
    echo '<br>zipcode: ' . $zipcodeA[$x] . '<br>';
    $stmt->execute();
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!empty($result)) {
        $id2 = $result['id'];
        $name = $result['name'];
        echo 'hello';
    }
}
</code>```

Body:
Why does hello not display to the screen, why is the while loop not executed?
Also I have an issue because the array $zipcodeA[$x] may contain random zip codes like 90564 80564 70564 88464 98754 but the database tman may contain info such as 90564 90564 90564 80564 70564 70564 88464 98754. How do I get the select to go through all the zip codes that are in the array $zipcodeA[$x] instead of just pulling info of one of each zip code?  The database holds random zip codes and many zip codes can be duplicates, the array only many different zip codes with no duplicates

for($x = 0; $x <= $v; $x++)
{
$stmt = $conn->prepare("SELECT * FROM tman WHERE approve = 'Y' AND zip = :zipp ORDER BY id desc limit :limit");
$stmt->bindParam(":zipp", $zipcodeA[$x], PDO::PARAM_INT);
$stmt->bindValue(':limit', (int) $limit, PDO::PARAM_INT);
echo '
zipcode: ' . $zipcodeA[$x] . '
';
$stmt->execute();
    while($row = $stmt->fetch(PDO::FETCH_ASSOC))
    {
      $id2 = $row['id'];
      $name = $row['name'];
      echo 'hello';

    }
}

Body:
Try to do it like this :

$limit = ($pageno - 1) * $rows_per_page . ',' . $rows_per_page;
for($x = 0; $x <= $v; $x++) {
    $stmt = $conn->prepare("SELECT * FROM tman WHERE approve = 'Y' AND zip = :zipp ORDER BY id desc LIMIT " . $limit);
    $stmt->bindParam(":zipp", $zipcodeA[$x], PDO::PARAM_INT);
    echo '<br>zipcode: ' . $zipcodeA[$x] . '<br>';
    $stmt->execute();
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!empty($result)) {
        $id2 = $result['id'];
        $name = $result['name'];
        echo 'hello';
    }
}


问:
How can I pass my user entered information to my database using php?
The users enter their name and number in the textfields. The this information is passed then sent to the data.php file where I am trying to get it to write to my database. The data base name is called hello.

```<code><!-- connect to database -->
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "hello";

// Create connection
 $conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "wooo connected";
}

//<!-- post added information to database -->
if ($_POST['name']) {
 if ($_POST['number']) {

 $sql = "INSERT INTO hello (id, name, number)
VALUES ('', '$_POST['name']', '$_POST['number'')";
if(mysqli_query($conn, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
  }
 }
} ?>
</code>```

From looking at my code I believe the issue is with this line.

```<code>   $sql = "INSERT INTO hello (id, name, number)
VALUES ('', '$_POST['name']', '$_POST['number']')";
</code>```

There is a blank left at the star for the auto incremented id that I have set in phpmyadmin.
I can hard code an entry such as:

```<code>$sql = "INSERT INTO hello (id, name, number)
VALUES ('', 'john', '12345)";
</code>```

These hard coded entries are put into the database but i can't get the user entered data to go in.

答:
Remove single quotes from $_POST['name'] and $_POST['number'] as below</p>

```<code>$sql = "INSERT INTO hello (id, name, number)
VALUES ('', $_POST['name'], $_POST['number'])";
</code>```

Body:
The users enter their name and number in the textfields. The this information is passed then sent to the data.php file where I am trying to get it to write to my database. The data base name is called hello.

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "hello";

// Create connection
 $conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "wooo connected";
}

//
if ($_POST['name']) {
 if ($_POST['number']) {

 $sql = "INSERT INTO hello (id, name, number)
VALUES ('', '$_POST['name']', '$_POST['number'')";
if(mysqli_query($conn, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
  }
 }
} ?>

From looking at my code I believe the issue is with this line.

   $sql = "INSERT INTO hello (id, name, number)
VALUES ('', '$_POST['name']', '$_POST['number']')";

There is a blank left at the star for the auto incremented id that I have set in phpmyadmin.
I can hard code an entry such as:

$sql = "INSERT INTO hello (id, name, number)
VALUES ('', 'john', '12345)";

These hard coded entries are put into the database but i can't get the user entered data to go in.

Body:
Remove single quotes from $_POST['name'] and $_POST['number'] as below

$sql = "INSERT INTO hello (id, name, number)
VALUES ('', $_POST['name'], $_POST['number'])";


问:
SQL Server 2014 installation stuck (hung up) or taking very long time to finish
I'm trying to install SQL Server 2014 but it stays in the same spot (Install_VCRuntime_Cpu32_Action) for hours. It's already the third time I'm trying to install so I don't know what else to do.

SQL Server 2014 Installation

答:
I had this same issue on SQL express 2014. When I went to check there was indeed a Windows Installer running. I killed that process & SQL proceeded to install just fine.

Found this here:
https://community.spiceworks.com/topic/483582-ms-sql-2014-install-freezing


问:
How can I distinguish between overlapping segments of text using HTML?
Easy question, it is valid to have overlapping spans in html?

Example:

```<code><span id="1">This is <span id="2"> some text </span> some other text </span>
                                              ^                        ^
                                            End1                     End2
</code>```

Edit:

I see now that the spans  closing tag would be ambiguous about which one it is closing, and that first  would close span id = 2, not 1 like I intended.

My problem is, I have a block of text which I'm trying to highlight based on what the mouse hovers over.  This block of text is composed of sections, some of which "overlap" eachother.  I'm trying to use some jQuery and HTML to present this document so when I hover over the sections, the appropriate one will be highlighted.

So, in my example above, the first span is meant to be ended with the first span close tag, and the second span is meant to be ended to with the second span close tag.  This is because of the semantics of my document, these are two overlapping segments.

I want it so when I hover to the left, it will only highlight up to span id = 1 and the first span close, if I hover between the two "overlapping" spans, it will highlight both of them, and if I hover to the right, it will highlight from span id=2 to the last span close.

However, I'm starting to think this isn't possible.  Is there any way I can distinguish segments of text in HTML that allows overlapping?  So my jQuery script that highlights when I hover over different spans will highlight the correct portions.

Should I alternate between div's and spans?  Would that disambiguate what I'm closing then and allow me the do the proper highlighting with my jQuery hover script?  I'm wondering about more than 2 segments overlapping now.  Sigh, I wish I could just be explicate about what I'm closing.

答:
I know, its too late to answer the question. But, this could help someone.

Yes! Its totally correct that no tags can overlap in html. I had exact scenario, mentioned as in above question. But, everything has a solution! We can solve this problem using html tag versioning!

The html snippet, mentioned in the above problem can be break like,

```<code><span id="1_1">This is </span><span id="1_2"><span id="2_1"> some text </span></span><span id="2_2"> some other text </span>
</code>```

Now, you have to add a custom handlers for your mouse hovers. Through handler callbacks, you need to pass span id to JavaScript. In JavaScript controller, you need to preserve a appropriate map of parent id with all child ids ( e.g. for version 1.x; {'1': ['1_1', '1_2', '1_3']} etc ). Now, whenever you hovers a mouse over any span, you would be able to find all of its siblings. Here is the trick! Post this, you just need to add a custom CSS class for all versions. (e.g. if you hovers mouse on id 1_1, all 1_x versions will get highlighted ).

It worked smoothly for me, for all the edge cases.

ContentLicense: CC BY-SA 2.5

Body:
Easy question, it is valid to have overlapping spans in html?

Example:

This is  some text  some other text
                                              ^                        ^
                                            End1                     End2

Edit:

I see now that the spans  closing tag would be ambiguous about which one it is closing, and that first  would close span id = 2, not 1 like I intended.

My problem is, I have a block of text which I'm trying to highlight based on what the mouse hovers over.  This block of text is composed of sections, some of which "overlap" eachother.  I'm trying to use some jQuery and HTML to present this document so when I hover over the sections, the appropriate one will be highlighted.

So, in my example above, the first span is meant to be ended with the first span close tag, and the second span is meant to be ended to with the second span close tag.  This is because of the semantics of my document, these are two overlapping segments.

I want it so when I hover to the left, it will only highlight up to span id = 1 and the first span close, if I hover between the two "overlapping" spans, it will highlight both of them, and if I hover to the right, it will highlight from span id=2 to the last span close.

However, I'm starting to think this isn't possible.  Is there any way I can distinguish segments of text in HTML that allows overlapping?  So my jQuery script that highlights when I hover over different spans will highlight the correct portions.

Should I alternate between div's and spans?  Would that disambiguate what I'm closing then and allow me the do the proper highlighting with my jQuery hover script?  I'm wondering about more than 2 segments overlapping now.  Sigh, I wish I could just be explicate about what I'm closing.

Body:
I know, its too late to answer the question. But, this could help someone.

Yes! Its totally correct that no tags can overlap in html. I had exact scenario, mentioned as in above question. But, everything has a solution! We can solve this problem using html tag versioning!

The html snippet, mentioned in the above problem can be break like,

<span id="1_1">This is </span><span id="1_2"><span id="2_1"> some text </span></span><span id="2_2"> some other text </span>

Now, you have to add a custom handlers for your mouse hovers. Through handler callbacks, you need to pass span id to JavaScript. In JavaScript controller, you need to preserve a appropriate map of parent id with all child ids ( e.g. for version 1.x; {'1': ['1_1', '1_2', '1_3']} etc ). Now, whenever you hovers a mouse over any span, you would be able to find all of its siblings. Here is the trick! Post this, you just need to add a custom CSS class for all versions. (e.g. if you hovers mouse on id 1_1, all 1_x versions will get highlighted ).

It worked smoothly for me, for all the edge cases.


问:
Mqtt connection failed with exception 'Not authorized to connect (5)' android
Hi I am trying to connect to mqtt with my android device that I just registered but it I keep getting the error

```<code>Not authorized to connect (5)
</code>```

This is some of my code

```<code>        client = new MqttAndroidClient(context, connectionURI, clientID);
        client.setCallback(callbacks);

        String username = IOT_DEVICE_USERNAME;
        char[] password = this.getAuthorizationToken().toCharArray();

        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(true);
        options.setUserName(username);
        options.setPassword(password);

        Log.d(TAG, "Connecting to server: " + connectionURI);
        try {
            // connect
            return client.connect(options, context, listener);
        } catch (MqttException e) {
            Log.e(TAG, "Exception caught while attempting to connect to server", e.getCause());
            throw e;
        }
</code>```

where IOT_DEVICE_USERNAME is a string "use-token-auth"
and connectionUri is "tcp://<"organization">.messaging.internetofthings.ibmcloud.com:8883"

Something else that is interesting is that right before this error I get this log

```<code>Unregister alarmreceiver to MqttServiced:<"organisation">:<"DeviceType">:<"deviceId">
</code>```

Here is the stackTrace of the error

```<code>07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err: Not authorized to connect (5)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:28)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at org.eclipse.paho.client.mqttv3.internal.ClientState.notifyReceivedAck(ClientState.java:988)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:140)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at java.lang.Thread.run(Thread.java:818)
</code>```

答:
The problem is fixed. I was indeed using this as the client id in as an imput to the constructor of the MqttAndroidClient object.

```<code>String iotClientId = "d:"+ORG+":"+DEVICE_TYPE+":"+DEVICE_ID;
</code>```

However, since I regestered the Android device as a gateway because it is actually connecting to multiple peripherals where the sensors actually are. To fix this, I the above line to

```<code>String iotClientId = "g:"+ORG+":"+DEVICE_TYPE+":"+DEVICE_ID;
</code>```

Body:
Hi I am trying to connect to mqtt with my android device that I just registered but it I keep getting the error

Not authorized to connect (5)

This is some of my code

        client = new MqttAndroidClient(context, connectionURI, clientID);
        client.setCallback(callbacks);

        String username = IOT_DEVICE_USERNAME;
        char[] password = this.getAuthorizationToken().toCharArray();

        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(true);
        options.setUserName(username);
        options.setPassword(password);

        Log.d(TAG, "Connecting to server: " + connectionURI);
        try {
            // connect
            return client.connect(options, context, listener);
        } catch (MqttException e) {
            Log.e(TAG, "Exception caught while attempting to connect to server", e.getCause());
            throw e;
        }

where IOT_DEVICE_USERNAME is a string "use-token-auth"
and connectionUri is "tcp://<"organization">.messaging.internetofthings.ibmcloud.com:8883"

Something else that is interesting is that right before this error I get this log

Unregister alarmreceiver to MqttServiced:<"organisation">:<"DeviceType">:<"deviceId">

Here is the stackTrace of the error

07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err: Not authorized to connect (5)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:28)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at org.eclipse.paho.client.mqttv3.internal.ClientState.notifyReceivedAck(ClientState.java:988)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:140)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at java.lang.Thread.run(Thread.java:818)

Body:
The problem is fixed. I was indeed using this as the client id in as an imput to the constructor of the MqttAndroidClient object.

String iotClientId = "d:"+ORG+":"+DEVICE_TYPE+":"+DEVICE_ID;

However, since I regestered the Android device as a gateway because it is actually connecting to multiple peripherals where the sensors actually are. To fix this, I the above line to

String iotClientId = "g:"+ORG+":"+DEVICE_TYPE+":"+DEVICE_ID;


问:
FIlter collection_select by value in coffeescript
Well I have this coffeeScript:

```<code>jQuery ->
    $('#cmbPab').change ->
       ubis = $('#cmbUbi').html()
       pabellon = $(this).val()
       options = $('#cmbUbi').filter("FilterByValue")
</code>```

I want it to filter options by value, I already saw railcats stuff but he filters by a different way and I need to do it by value cause value is my id

Here is the cod of both collection_select where cmbPab is my main combo:

```<code>        <div class="form-group">
         <%= f.label :Pabellon %>
         <%= f.collection_select :idubicacion, Mtopabellon.all,
             :codpabellon, :nombre, {prompt: 'Seleccione un pabellón'},
             :class=>'form-control', :id => 'cmbPab'%>
        </div>

        <div class="form-group">
          <%= f.label :Ubicacion %>
          <%= f.collection_select :idubicacion, CrUbicacion.all, :id,
          :nombre, {prompt: 'Seleccione una ubicación'}, :class=>'form-
          control', :id => 'cmbUbi'  %>
        </div>
</code>```

答:
Here is the answer guys! I think this is the best way to do it, maybe not the easier but it works!

https://kernelgarden.wordpress.com/2014/02/26/dynamic-select-boxes-in-rails-4/

Body:
Well I have this coffeeScript:

jQuery ->
    $('#cmbPab').change ->
       ubis = $('#cmbUbi').html()
       pabellon = $(this).val()
       options = $('#cmbUbi').filter("FilterByValue")

I want it to filter options by value, I already saw railcats stuff but he filters by a different way and I need to do it by value cause value is my id

Here is the cod of both collection_select where cmbPab is my main combo:

         <%= f.label :Pabellon %>
         <%= f.collection_select :idubicacion, Mtopabellon.all,
             :codpabellon, :nombre, {prompt: 'Seleccione un pabellón'},
             :class=>'form-control', :id => 'cmbPab'%>

          <%= f.label :Ubicacion %>
          <%= f.collection_select :idubicacion, CrUbicacion.all, :id,
          :nombre, {prompt: 'Seleccione una ubicación'}, :class=>'form-
          control', :id => 'cmbUbi'  %>


问:
C++ primitive array accessing by class
I want to access a primitive type array using a class.
I'm using Visual C++ 2013

```<code>class CInt
{
public:
    CInt() { val_ = 0; }
    CInt(int x) { val_ = x; }

private:
    int val_;
};

int arr[2];
CInt index;

arr[index] = 2; // ERROR!
</code>```

I tried to overload size_t() operator but still doesn't work.
Is something like that possible in C++/C++11?

答:
I suspect you have an error, not because of your class, but where you are doing the array assignment. You must do the array assignment within a function: (this should work, assuming you overloaded the conversion operator correctly)</p>

```<code>arr[index] = 2; // ERROR! <-- you can't do this outside a function

int main() {
    arr[index] = 2; // <-- must be within a function
</code>```

Title: C++ primitive array accessing by class

Body:
I want to access a primitive type array using a class.
I'm using Visual C++ 2013

class CInt
{
public:
    CInt() { val_ = 0; }
    CInt(int x) { val_ = x; }

private:
    int val_;
};

int arr[2];
CInt index;

arr[index] = 2; // ERROR!

I tried to overload size_t() operator but still doesn't work.
Is something like that possible in C++/C++11?

Body:
I suspect you have an error, not because of your class, but where you are doing the array assignment. You must do the array assignment within a function: (this should work, assuming you overloaded the conversion operator correctly)

arr[index] = 2; // ERROR! <-- you can't do this outside a function

int main() {
    arr[index] = 2; // <-- must be within a function


问:
BASH; using find and -exec to remove .pyc files
Using the command line in Ubuntu 16.04.2 LTS. I'm getting towards the end of Zed Shaw's LPTHW, and on the video to ex46.py he exercises the following bash command to find and remove all .pyc byte code files:

```<code>find . -name "*.pyc" -exec rm {}
</code>```

On the video this successfully removes all of Zed Shaw's .pyc files. However, upon typing in the exact same command I get the following error:

```<code>find: missing argument to `-exec'
</code>```

I understand that there are many ways to delete .pyc files, however, since I'm following along with Zed Shaw I'd like to know how to do it using find and -exec. What am I doing wrong?

答:
You could leverage using -delete over -exec rm as the former does not spawn a new process for each of the file instance to delete. Also you could chip in the -type f option to apply the operation for files only.

```<code>find . -type f -name "*.pyc" -delete
</code>```

Body:
Using the command line in Ubuntu 16.04.2 LTS. I'm getting towards the end of Zed Shaw's LPTHW, and on the video to ex46.py he exercises the following bash command to find and remove all .pyc byte code files:

find . -name "*.pyc" -exec rm {}

On the video this successfully removes all of Zed Shaw's .pyc files. However, upon typing in the exact same command I get the following error:

find: missing argument to `-exec'

I understand that there are many ways to delete .pyc files, however, since I'm following along with Zed Shaw I'd like to know how to do it using find and -exec. What am I doing wrong?

Body:
You could leverage using -delete over -exec rm as the former does not spawn a new process for each of the file instance to delete. Also you could chip in the -type f option to apply the operation for files only.

find . -type f -name "*.pyc" -delete


问:
SDK Location not found Android Studio + Gradle
I have seen this same thing posted quite a few times, but whenever I try to import my project to my new work laptop I keep getting this error.

I have pulled the project from git (which his btw running fine on my old laptop).

Then I went to the sdk manager, downloaded all the tools, and all the SDK's available.
In the welcome screen, I went to Configure -> project Defaults -> Project structure.
Android SDK Tab says the path for projects without local.properties will be /Applications/Android Studio.app/sdk
This is correct.
Under SDKs I have all the available SDK's visible.
Project SDK is set to API 18

Yet still I get this error when trying to build my project.
Can anyone tell me where I havent looked yet?

I am running gradle 1.7 when trying to build which is downloaded from services.gradle.org

答:
To fix this problem, I had to define the ANDROID_HOME environment variable in the Windows OS.

To do this, I went to the System control panel.

I selected "Advanced system settings" in the left column.

On the "Advanced" tab, I selected "Environment Variables" at the bottom.

Here, I did not have an ANDROID_HOME variable defined.  For this case, I selected "New..." and:

1) for "Variable name" I typed ANDROID_HOME,

2) for "Variable value", I typed the path to my SDK folder, e.g. "C:\...\AppData\Local\Android\sdk".

I then closed Android Studio and reopened, and everything worked.

Thanks to Dibish (https://stackoverflow.com/users/2244411/dibish) for one of his posts that gave me this idea.


问:
SQL Server Query too slow missing index?
I'm working with SQL Server 2012 and I have an query for the search purpose but It takes too long to execute.. (30 rows = 6sec)

I have checked up the execution plan but he doesn't suggest to put index and I don't know how i can speed up the query.

Here's my query:

```<code>SELECT
    dbo.tbRV.ID, dbo.tbRV.IDCompagnie,
    dbo.tbPatient.Nom + N', ' + dbo.tbPatient.Prenom AS NomPrenomPatient,
    dbo.tbRV.DateRV, dbo.tbRV.HeureDebut,
    dbo.tbRV.IDRessource,
    coalesce(dbo.tbRessource.Nom ,'') + ' '  + coalesce(dbo.tbRessource.Prenom,'') AS NomPrenomRessource,
    dbo.tbPatient.NoApp,
    dbo.tbPatient.NomEtablissement, dbo.tbPatient.Adresse1,
    tbAdresse.Ville, dbo.tbPatient.TelephoneDomicile,
    dbo.tbPatient.TelephoneTravail,
    dbo.tbPatient.TelephonePortable,
    case
       when DD.id is not null then DD.description
       else dbo.tbRVObjet.IDObjet
    end as idobjet,
    dbo.tbPatient.Nom_SansAccent, dbo.tbPatient.Prenom_SansAccent,
    dbo.tbPatient.Nom, dbo.tbPatient.Prenom,
    dbo.tbRV.IDPatient, dbo.tbPatient.NoAssuranceMaladie,
    dbo.tbPatient.DateNaissance, dbo.tbRV.Transit, dbo.tbRV.Annuler,
    tbAdresse.Pays, tbAdresse.Province, dbo.tbPatient.Adresse2,
    dbo.tbPatient.CodePostal,
    case
       when AA.id is not null and AA.ID = tbrvobjet.ID then 1 else 0 end as onlyFirst
FROM
    tbPatient
INNER JOIN
    tbRV ON tbPatient.ID = tbRV.IDPatient
INNER JOIN
    tbRessource ON (tbRV.IDRessource = tbRessource.ID) AND (tbRV.IDCompagnie = tbRessource.IDCompagnie)
INNER JOIN
    tbRVObjet ON tbRV.ID = tbRVObjet.IDRV
OUTER APPLY
    dbo.fn_GetFirstIDRVObjet(tbrv.id) AA
OUTER APPLY (SELECT A.ID, A.Description
             FROM tbForfaitEntete A
             WHERE A.ID = tbRVObjet.IDForfait
               AND ISNULL(tbRVObjet.IsForfaitEntete, 0) = 1 ) DD
OUTER APPLY (SELECT B.Description
             FROM tbRVObjet A
             JOIN tbForfaitEntete B ON (A.IDForfait  = B.ID AND  ISNULL(A.IsForfaitEntete, 0) = 1)
             WHERE AA.ID = A.id ) BB
OUTER APPLY (SELECT tbPaysISO.Pays, tbProvinceISO.Province, tbVilleISO.Ville
             FROM tbPaysISO
             JOIN tbProvinceISO ON (tbPaysISO.Langue = tbProvinceISO.Langue)
                                AND (tbPatient.ProvinceISOChar = tbProvinceISO.ProvinceISOChar)
             JOIN tbVilleISO ON (tbProvinceISO.Langue = tbVilleISO.Langue)
                             AND (tbPatient.IdVille  = tbVilleISO.IDVille)
             WHERE tbPaysISO.Langue = tbpatient.CodeLangue
               AND tbPaysISO.PaysISOChar3 = tbpatient.PaysISOChar3 ) tbAdresse
</code>```

and here's the execution plan in XML:

EDIT:

Here's my query plan URL: https://www.brentozar.com/pastetheplan/?id=HkVYeasNW

Here's my search query :

```<code>Select
    ID, IDPatient, NomPrenomPatient, DateNaissance, NoAssuranceMaladie,
    NomEtablissement, Adresse1, Adresse2, NoApp, ville, province, pays,
    CodePostal, TelephoneDomicile, TelephoneTravail, TelephonePortable,
    DateRV, HeureDebut, IDObjet, IDRessource, NomPrenomRessource,
    Annuler, Transit
From
    rqAfficheRechercheRV
Where
    IDCompagnie = 1
    And (isnull(NomPrenomRessource, '') + isnull(NoApp, '') + isnull(NomEtablissement, '') + isnull(Adresse1, '') + isnull(Ville, '') + isnull(TelephoneDomicile, '') + isnull(TelephoneTravail, '') + isnull(TelephonePortable, '') + isnull(IDObjet, '') + isnull(Nom_SansAccent, '') + isnull(Prenom_SansAccent, '') + isnull(Nom, '') + isnull(Prenom, '') + isnull(IDPatient, '') + isnull(NoAssuranceMaladie, '') + isnull(convert(varchar, DateNaissance), '') + isnull(Pays, '') + isnull(Province, '') + isnull(Adresse2, '') + isnull(CodePostal, '')) like '%881-1360%'
    And isnull(onlyFirst,0) = 1
Order by
    Nom, Prenom, DateRV DESC, HeureDebut ASC
</code>```

rqAfficheRechercheRV  is the view of the query above

答:
It is really very time consuming to read so long query plan.

you have to mention number of record involve.

i) Clustered Index Scan -It tell that column is CI but index is not being utilize

a) Because condition are not SARGable like

```<code>ISNULL(tbRVObjet.IsForfaitEntete, 0) = 1
instead write `(tbRVObjet.IsForfaitEntete = 1 )`
</code>```

Similarly in other places.Even if concern column is not index then also change it to this .

b) Also when there is high cardianility estimate then index is not being use.

ii) I have little doubt in this outer Apply BB query .ARe you sure you will again use tbRVObjet A inside this outer apply or you can directly join from above main tbRVObjet

iii ) Hope all the column use in join condition are int,bit,date etc.If there are varchar column that means there is problem in DB design also.

iv) when this thing really belong to view then why not concatenate it inside
view itself,

```<code>And (isnull(NomPrenomRessource, '') + isnull(NoApp, '') + isnull(NomEtablissement, '') + isnull(Adresse1, '') + isnull(Ville, '') + isnull(TelephoneDomicile, '') + isnull(TelephoneTravail, '') + isnull(TelephonePortable, '') + isnull(IDObjet, '') + isnull(Nom_SansAccent, '') + isnull(Prenom_SansAccent, '') + isnull(Nom, '') + isnull(Prenom, '') + isnull(IDPatient, '') + isnull(NoAssuranceMaladie, '') + isnull(convert(varchar, DateNaissance), '') + isnull(Pays, '') + isnull(Province, '') + isnull(Adresse2, '') + isnull(CodePostal, '')) like '%881-1360%'
</code>```

I have doubts here.

v) What happen when you comment out order by,can't you do without it ?

vi) if you can put code of dbo.fn_GetFirstIDRVObjet also inside outer apply .

vii)Recheck join condition inside outer apply tbAdresse .Are you sure there is no extra join condition.I have doubt about their relationship between these table which is inside this outer apply.

viii) It is vety clear that onlyFirst is either 0 or 1 so no point in writing And isnull(onlyFirst,0) = 1 ,simply write And(onlyFirst = 1

ix) Check the diff in parenthesis here with your own

```<code>((tbRV.IDRessource = tbRessource.ID) AND (tbRV.IDCompagnie = tbRessource.IDCompagnie))
</code>```

and here

```<code>((tbPaysISO.Langue = tbProvinceISO.Langue)
                                AND (tbPatient.ProvinceISOChar = tbProvinceISO.ProvinceISOChar))
             JOIN tbVilleISO ON ((tbProvinceISO.Langue = tbVilleISO.Langue)
                             AND (tbPatient.IdVille  = tbVilleISO.IDVille))
             WHERE tbPaysISO.Langue = tbpatient.CodeLangue
               AND tbPaysISO.PaysISOChar3 = tbpatient.PaysISOChar3
</code>```

x) You are missing dbo prefix in most of the places.Also use With (Nolock)

I think you can comment out all outer apply and their column.Run the query check the Plan,fix the index fine tune the query then start uncommneting outer apply one by one and repeat the process.

Body:
I'm working with SQL Server 2012 and I have an query for the search purpose but It takes too long to execute.. (30 rows = 6sec)

I have checked up the execution plan but he doesn't suggest to put index and I don't know how i can speed up the query.

Here's my query:

SELECT
    dbo.tbRV.ID, dbo.tbRV.IDCompagnie,
    dbo.tbPatient.Nom + N', ' + dbo.tbPatient.Prenom AS NomPrenomPatient,
    dbo.tbRV.DateRV, dbo.tbRV.HeureDebut,
    dbo.tbRV.IDRessource,
    coalesce(dbo.tbRessource.Nom ,'') + ' '  + coalesce(dbo.tbRessource.Prenom,'') AS NomPrenomRessource,
    dbo.tbPatient.NoApp,
    dbo.tbPatient.NomEtablissement, dbo.tbPatient.Adresse1,
    tbAdresse.Ville, dbo.tbPatient.TelephoneDomicile,
    dbo.tbPatient.TelephoneTravail,
    dbo.tbPatient.TelephonePortable,
    case
       when DD.id is not null then DD.description
       else dbo.tbRVObjet.IDObjet
    end as idobjet,
    dbo.tbPatient.Nom_SansAccent, dbo.tbPatient.Prenom_SansAccent,
    dbo.tbPatient.Nom, dbo.tbPatient.Prenom,
    dbo.tbRV.IDPatient, dbo.tbPatient.NoAssuranceMaladie,
    dbo.tbPatient.DateNaissance, dbo.tbRV.Transit, dbo.tbRV.Annuler,
    tbAdresse.Pays, tbAdresse.Province, dbo.tbPatient.Adresse2,
    dbo.tbPatient.CodePostal,
    case
       when AA.id is not null and AA.ID = tbrvobjet.ID then 1 else 0 end as onlyFirst
FROM
    tbPatient
INNER JOIN
    tbRV ON tbPatient.ID = tbRV.IDPatient
INNER JOIN
    tbRessource ON (tbRV.IDRessource = tbRessource.ID) AND (tbRV.IDCompagnie = tbRessource.IDCompagnie)
INNER JOIN
    tbRVObjet ON tbRV.ID = tbRVObjet.IDRV
OUTER APPLY
    dbo.fn_GetFirstIDRVObjet(tbrv.id) AA
OUTER APPLY (SELECT A.ID, A.Description
             FROM tbForfaitEntete A
             WHERE A.ID = tbRVObjet.IDForfait
               AND ISNULL(tbRVObjet.IsForfaitEntete, 0) = 1 ) DD
OUTER APPLY (SELECT B.Description
             FROM tbRVObjet A
             JOIN tbForfaitEntete B ON (A.IDForfait  = B.ID AND  ISNULL(A.IsForfaitEntete, 0) = 1)
             WHERE AA.ID = A.id ) BB
OUTER APPLY (SELECT tbPaysISO.Pays, tbProvinceISO.Province, tbVilleISO.Ville
             FROM tbPaysISO
             JOIN tbProvinceISO ON (tbPaysISO.Langue = tbProvinceISO.Langue)
                                AND (tbPatient.ProvinceISOChar = tbProvinceISO.ProvinceISOChar)
             JOIN tbVilleISO ON (tbProvinceISO.Langue = tbVilleISO.Langue)
                             AND (tbPatient.IdVille  = tbVilleISO.IDVille)
             WHERE tbPaysISO.Langue = tbpatient.CodeLangue
               AND tbPaysISO.PaysISOChar3 = tbpatient.PaysISOChar3 ) tbAdresse

and here's the execution plan in XML:

EDIT:

Here's my query plan URL: https://www.brentozar.com/pastetheplan/?id=HkVYeasNW

Here's my search query :

Select
    ID, IDPatient, NomPrenomPatient, DateNaissance, NoAssuranceMaladie,
    NomEtablissement, Adresse1, Adresse2, NoApp, ville, province, pays,
    CodePostal, TelephoneDomicile, TelephoneTravail, TelephonePortable,
    DateRV, HeureDebut, IDObjet, IDRessource, NomPrenomRessource,
    Annuler, Transit
From
    rqAfficheRechercheRV
Where
    IDCompagnie = 1
    And (isnull(NomPrenomRessource, '') + isnull(NoApp, '') + isnull(NomEtablissement, '') + isnull(Adresse1, '') + isnull(Ville, '') + isnull(TelephoneDomicile, '') + isnull(TelephoneTravail, '') + isnull(TelephonePortable, '') + isnull(IDObjet, '') + isnull(Nom_SansAccent, '') + isnull(Prenom_SansAccent, '') + isnull(Nom, '') + isnull(Prenom, '') + isnull(IDPatient, '') + isnull(NoAssuranceMaladie, '') + isnull(convert(varchar, DateNaissance), '') + isnull(Pays, '') + isnull(Province, '') + isnull(Adresse2, '') + isnull(CodePostal, '')) like '%881-1360%'
    And isnull(onlyFirst,0) = 1
Order by
    Nom, Prenom, DateRV DESC, HeureDebut ASC

rqAfficheRechercheRV  is the view of the query above

Body:
It is really very time consuming to read so long query plan.

you have to mention number of record involve.

i) Clustered Index Scan -It tell that column is CI but index is not being utilize

a) Because condition are not SARGable like

ISNULL(tbRVObjet.IsForfaitEntete, 0) = 1
instead write `(tbRVObjet.IsForfaitEntete = 1 )`

Similarly in other places.Even if concern column is not index then also change it to this .

b) Also when there is high cardianility estimate then index is not being use.

ii) I have little doubt in this outer Apply BB query .ARe you sure you will again use tbRVObjet A inside this outer apply or you can directly join from above main tbRVObjet

iii ) Hope all the column use in join condition are int,bit,date etc.If there are varchar column that means there is problem in DB design also.

iv) when this thing really belong to view then why not concatenate it inside
view itself,

And (isnull(NomPrenomRessource, '') + isnull(NoApp, '') + isnull(NomEtablissement, '') + isnull(Adresse1, '') + isnull(Ville, '') + isnull(TelephoneDomicile, '') + isnull(TelephoneTravail, '') + isnull(TelephonePortable, '') + isnull(IDObjet, '') + isnull(Nom_SansAccent, '') + isnull(Prenom_SansAccent, '') + isnull(Nom, '') + isnull(Prenom, '') + isnull(IDPatient, '') + isnull(NoAssuranceMaladie, '') + isnull(convert(varchar, DateNaissance), '') + isnull(Pays, '') + isnull(Province, '') + isnull(Adresse2, '') + isnull(CodePostal, '')) like '%881-1360%'

I have doubts here.

v) What happen when you comment out order by,can't you do without it ?

vi) if you can put code of dbo.fn_GetFirstIDRVObjet also inside outer apply .

vii)Recheck join condition inside outer apply tbAdresse .Are you sure there is no extra join condition.I have doubt about their relationship between these table which is inside this outer apply.

viii) It is vety clear that onlyFirst is either 0 or 1 so no point in writing And isnull(onlyFirst,0) = 1 ,simply write And(onlyFirst = 1

ix) Check the diff in parenthesis here with your own

((tbRV.IDRessource = tbRessource.ID) AND (tbRV.IDCompagnie = tbRessource.IDCompagnie))

and here

((tbPaysISO.Langue = tbProvinceISO.Langue)
                                AND (tbPatient.ProvinceISOChar = tbProvinceISO.ProvinceISOChar))
             JOIN tbVilleISO ON ((tbProvinceISO.Langue = tbVilleISO.Langue)
                             AND (tbPatient.IdVille  = tbVilleISO.IDVille))
             WHERE tbPaysISO.Langue = tbpatient.CodeLangue
               AND tbPaysISO.PaysISOChar3 = tbpatient.PaysISOChar3

x) You are missing dbo prefix in most of the places.Also use With (Nolock)

I think you can comment out all outer apply and their column.Run the query check the Plan,fix the index fine tune the query then start uncommneting outer apply one by one and repeat the process.


问:
TextWatcher StringBuilder append method appends CharSequence to both StringBuilder objects
I'm trying to replace the displayed value of the EditText view with characters, while at the same time keeping the original input in another StringBuilder object.

Here's the code:

```<code>final StringBuilder stringBuilderHiddenPassword = new StringBuilder();
    final StringBuilder mPass = new StringBuilder();
    pass = new StringBuilder();
    etPassword.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            stringBuilderHiddenPassword.append("*");
            etPassword.removeTextChangedListener(this);
            etPassword.setText(stringBuilderHiddenPassword);
            etPassword.addTextChangedListener(this);
        }

        @Override
        public void afterTextChanged(Editable s) {
            pass.append(s);
            Toast.makeText(Pass.this, pass, Toast.LENGTH_SHORT).show();
        }
    });
</code>```

First inputed character displays in the Toast as the original character inputed, but the 2nd one adds a * to it. So if I input a it displays a, if I input aa, it displays aa*, for aaa it's aa*a** and so on.

How do I separate these objects from being both appended at the same time? The code should append to only stringBuilderHiddenPassword, but it's clear that's not how this method works.

答:
Found a solution by using the replace method on the original string:

```<code>replace = pass.toString().replace("*", "");
Toast.makeText(Pass.this, replace, Toast.LENGTH_SHORT).show();
</code>```

Body:
I'm trying to replace the displayed value of the EditText view with characters, while at the same time keeping the original input in another StringBuilder object.

Here's the code:

final StringBuilder stringBuilderHiddenPassword = new StringBuilder();
    final StringBuilder mPass = new StringBuilder();
    pass = new StringBuilder();
    etPassword.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            stringBuilderHiddenPassword.append("*");
            etPassword.removeTextChangedListener(this);
            etPassword.setText(stringBuilderHiddenPassword);
            etPassword.addTextChangedListener(this);
        }

        @Override
        public void afterTextChanged(Editable s) {
            pass.append(s);
            Toast.makeText(Pass.this, pass, Toast.LENGTH_SHORT).show();
        }
    });

First inputed character displays in the Toast as the original character inputed, but the 2nd one adds a * to it. So if I input a it displays a, if I input aa, it displays aa*, for aaa it's aa*a** and so on.

How do I separate these objects from being both appended at the same time? The code should append to only stringBuilderHiddenPassword, but it's clear that's not how this method works.

Body:
Found a solution by using the replace method on the original string:

replace = pass.toString().replace("*", "");
Toast.makeText(Pass.this, replace, Toast.LENGTH_SHORT).show();


问:
Problem with Event Handling via YUI
When users click "search" input element, the search text inside the input will disappear and since I have several controls like that, I thought I could make the code reusable. Here is my code formerly done and working with jQuery but now in YUI I cannot make it work.</p>

```<code>var subscriptionBoxTarget = "div.main div.main-content div.side-right div.subscription-box input";
var ssbNode = YAHOO.util.Selector.query(subscriptionBoxTarget);
var ssbValue = YAHOO.util.DOM.getAttribute(ssbNode,"value");
var subscriptionBox = new RemovableText(ssbNode,ssbValue,null);
subscriptionBox.bind();
////////////////////////////////

//target : the target of the element which dispatches the event
// defaultText : the default for input[type=text] elements
// callBack : is a function which is run after everthing is completed
function RemovableText(target,defaultText,callBack)
{
    var target = target; //private members
    var defaultText = defaultText;
    var callBack = callBack;

    //instance method
    this.bind = function()
    {
        mouseClick(target,defaultText);
        mouseOff(target,defaultText);
        if(callBack != null)
            callBack();
    }

    //private methods
    var mouseClick = function(eventTarget,defaultValue)
    {
        var _eventTarget = eventTarget;
        var _defaultValue = defaultValue;
        /*$(eventTarget).bind("click",function(){
            var currentValue = $(this).val();
            if(currentValue == defaultValue)
                $(this).val("");
        });*/
         YAHOO.util.Event.addListener(_eventTarget,"click",function(e){
            alert(e);
         });
    }

    var mouseOff = function(eventTarget,defaultValue)
    {
        var _eventTarget = eventTarget;
        var _defaultValue = defaultValue;
        /*$(eventTarget).bind("blur",function(){
            var currentValue = $(this).val();
            if(currentValue == "")
                $(this).val(_defaultValue);
        });*/
         YAHOO.util.Event.addListener(_eventTarget,"blur",function(e){
            alert(e);
         });
    }
}
</code>```

答:
You have a lot of unnecessary code here.

The input parameters passed to the RemovableText constructor are available by closure to all the methods defined inside.  You don't need to, and shouldn't redefine named params as vars.

```<code>function RemovableText(target, defaultText, callback) {
    this.bind = function () {
        YAHOO.util.Event.on(target, 'click', function (e) {
            /* You can reference target, defaultText, and callback in here as well */
        });

        YAHOO.util.Event.on(target, 'blur', function (e) { /* and here */ });

        if (callback) {
            callback();
        }
    };
}
</code>```

The definition of an instance method from within the constructor seems dubious, as is the requirement that the values passed to the constructor must be kept private.  Just assign them to instance properties (this._target = target; etc) and add instance methods to the prototype.  If the functionality you're after is just this simple, then why bother with methods at all?

Using the click event does not support keyboard navigation.  You should use the focus event.

I'm not sure why you would have a callback passed at construction that fires immediately after attaching the event subscribers.

Title: Problem with Event Handling via YUI

Body:
When users click "search" input element, the search text inside the input will disappear and since I have several controls like that, I thought I could make the code reusable. Here is my code formerly done and working with jQuery but now in YUI I cannot make it work.

var subscriptionBoxTarget = "div.main div.main-content div.side-right div.subscription-box input";
var ssbNode = YAHOO.util.Selector.query(subscriptionBoxTarget);
var ssbValue = YAHOO.util.DOM.getAttribute(ssbNode,"value");
var subscriptionBox = new RemovableText(ssbNode,ssbValue,null);
subscriptionBox.bind();
////////////////////////////////

//target : the target of the element which dispatches the event
// defaultText : the default for input[type=text] elements
// callBack : is a function which is run after everthing is completed
function RemovableText(target,defaultText,callBack)
{
    var target = target; //private members
    var defaultText = defaultText;
    var callBack = callBack;

    //instance method
    this.bind = function()
    {
        mouseClick(target,defaultText);
        mouseOff(target,defaultText);
        if(callBack != null)
            callBack();
    }

    //private methods
    var mouseClick = function(eventTarget,defaultValue)
    {
        var _eventTarget = eventTarget;
        var _defaultValue = defaultValue;
        /*$(eventTarget).bind("click",function(){
            var currentValue = $(this).val();
            if(currentValue == defaultValue)
                $(this).val("");
        });*/
         YAHOO.util.Event.addListener(_eventTarget,"click",function(e){
            alert(e);
         });
    }

    var mouseOff = function(eventTarget,defaultValue)
    {
        var _eventTarget = eventTarget;
        var _defaultValue = defaultValue;
        /*$(eventTarget).bind("blur",function(){
            var currentValue = $(this).val();
            if(currentValue == "")
                $(this).val(_defaultValue);
        });*/
         YAHOO.util.Event.addListener(_eventTarget,"blur",function(e){
            alert(e);
         });
    }
}

Body:
You have a lot of unnecessary code here.

The input parameters passed to the RemovableText constructor are available by closure to all the methods defined inside.  You don't need to, and shouldn't redefine named params as vars.

function RemovableText(target, defaultText, callback) {
    this.bind = function () {
        YAHOO.util.Event.on(target, 'click', function (e) {
            /* You can reference target, defaultText, and callback in here as well */
        });

        YAHOO.util.Event.on(target, 'blur', function (e) { /* and here */ });

        if (callback) {
            callback();
        }
    };
}

The definition of an instance method from within the constructor seems dubious, as is the requirement that the values passed to the constructor must be kept private.  Just assign them to instance properties (this._target = target; etc) and add instance methods to the prototype.  If the functionality you're after is just this simple, then why bother with methods at all?

Using the click event does not support keyboard navigation.  You should use the focus event.

I'm not sure why you would have a callback passed at construction that fires immediately after attaching the event subscribers.


问:
How many byte read the std::istream::peek() function
I have try to read the next character in a file with only characters and with a file with only integers. This function return the next value (int or char). Now the question is how many byte read peek()? For first file it seems read one byte while for the second file it seems read four byte. How it's possible?</p>

答:
It depends entirely on the type of stream.

peek() will read one character, however streams have traits associated with them that dictate what is considered a character. The char_traits on a stream controls this.

Here's a handy guide:

```<code>char    : always 1 byte
wchar_t : platform defined. dictated by its *underlying type* Likely 4 bytes
char32_t: at least 4 bytes
char16_t: at least 2 bytes
</code>```

fstream is actually a basic_fstream<char> meaning that it will read the same number of bytes as sizeof(char), which is 1 byte. It will return int_type which is also controlled through traits

Body:
It depends entirely on the type of stream.

peek() will read one character, however streams have traits associated with them that dictate what is considered a character. The char_traits on a stream controls this.

Here's a handy guide:

char    : always 1 byte
wchar_t : platform defined. dictated by its *underlying type* Likely 4 bytes
char32_t: at least 4 bytes
char16_t: at least 2 bytes

fstream is actually a basic_fstream<char> meaning that it will read the same number of bytes as sizeof(char), which is 1 byte. It will return int_type which is also controlled through traits


问:
Populating a list of lists with random items
I have a list of lists with a certain range:

```<code>l = [["this", "is", "a"], ["list", "of"], ["lists", "that", "i", "want"], ["to", "copy"]]
</code>```

And a list of words:

```<code>words = ["lorem", "ipsum", "dolor", "sit", "amet", "id", "sint", "risus", "per", "ut", "enim", "velit", "nunc", "ultricies"]
</code>```

I need to create an exact replica of the list of lists, but with random terms picked from the other list.

This was the first thing that came to mind, but no dice.

```<code>for random.choice in words:
  for x in list:
    for y in x:
      y = random.choice
</code>```

Any ideas? Thank you in advance!

答:
You should flatten your list of lists, then shuffle, then rebuild.  Example:

```<code>import random

def super_shuffle(lol):
  sublist_lengths = [len(sublist) for sublist in lol]
  flat = [item for sublist in lol for item in sublist]
  random.shuffle(flat)
  pos = 0
  shuffled_lol = []
  for length in sublist_lengths:
    shuffled_lol.append(flat[pos:pos+length])
    pos += length
  return shuffled_lol

print super_shuffle([[1,2,3,4],[5,6,7],[8,9]])
</code>```

Prints:

```<code>[[7, 8, 5, 6], [9, 1, 3], [2, 4]]
</code>```

This randomizes across ALL the lists, not just within a single sublist and guarantees no dups.

Body:
I have a list of lists with a certain range:

l = [["this", "is", "a"], ["list", "of"], ["lists", "that", "i", "want"], ["to", "copy"]]

And a list of words:

words = ["lorem", "ipsum", "dolor", "sit", "amet", "id", "sint", "risus", "per", "ut", "enim", "velit", "nunc", "ultricies"]

I need to create an exact replica of the list of lists, but with random terms picked from the other list.

This was the first thing that came to mind, but no dice.

for random.choice in words:
  for x in list:
    for y in x:
      y = random.choice

Any ideas? Thank you in advance!

Body:
You should flatten your list of lists, then shuffle, then rebuild.  Example:

import random

def super_shuffle(lol):
  sublist_lengths = [len(sublist) for sublist in lol]
  flat = [item for sublist in lol for item in sublist]
  random.shuffle(flat)
  pos = 0
  shuffled_lol = []
  for length in sublist_lengths:
    shuffled_lol.append(flat[pos:pos+length])
    pos += length
  return shuffled_lol

print super_shuffle([[1,2,3,4],[5,6,7],[8,9]])

Prints:

[[7, 8, 5, 6], [9, 1, 3], [2, 4]]

This randomizes across ALL the lists, not just within a single sublist and guarantees no dups.


问:
Get first record change timestamp when grouped by two columns SQL Server
I have a table that tracks versions history.I need to get the record the shows the first version change timestamp to the most recent version.

EDIT: Added more records to illustrate what I am looking for.
For example

```<code>id  version     timestamp
(123, 1.5, '2015-03-28 08:21:04'),
(123, 1.5, '2015-03-28 07:21:04'),
(123, 1.5, '2015-03-27 07:21:04'), <-- Latest version,first change for id 123
(123, 1.2, '2015-03-22 12:58:24'),
(123, 1.2, '2015-03-21 13:32:05'),
(123, 1.0, '2015-03-21 09:18:37'),
(123, 1.0, '2015-03-20 04:44:59'),
(234, 1.5, '2016-10-15 23:08:09'), <-- Latest version,first change for id 234
(345, 1.5, '2016-10-10 15:18:09'),
(345, 1.5, '2016-09-02 21:30:00'),
(345, 1.5, '2016-09-01 21:30:00'),
(345, 1.5, '2016-08-02 21:30:00'), <-- Latest version,first change for id 345
(345, 1.0, '2016-07-02 21:30:00')
</code>```

Expected output

```<code>id  version     timestamp
(123, 1.5, '2015-03-27 07:21:04')
(234, 1.5, '2016-10-15 23:08:09')
(345, 1.5, '2016-08-02 21:30:00')
</code>```

I was able to get this by using temp tables.I get the min(dt_create) for each id and version and store it in a temp table.Then I get the max date from this table for each id and then join it again to get the version.Is there a better way to do this?

```<code>create table #temp_version
(
       id varchar(22) NOT NULL,
       version varchar(50) NOT NULL,
       dt_create datetime NOT null
)

insert into #temp_version
select  id,version,min(dt_create) as dt_create
from [version_history] (nolock)
group by id,version

create table #temp_min_date
(
      id varchar(22) NOT NULL,
      dt_create datetime NOT null
)

insert into #temp_min_date
select id,max(dt_create)
from #temp_version
group by id

select a.id,a.version,a.dt_create
from #temp_version a
join #temp_date b on a.id = b.id and
a.dt_create=b.dt_create

drop table #temp_date
drop table #temp_version
</code>```

Body:
I have a table that tracks versions history.I need to get the record the shows the first version change timestamp to the most recent version.

EDIT: Added more records to illustrate what I am looking for.
For example

id  version     timestamp
(123, 1.5, '2015-03-28 08:21:04'),
(123, 1.5, '2015-03-28 07:21:04'),
(123, 1.5, '2015-03-27 07:21:04'), <-- Latest version,first change for id 123
(123, 1.2, '2015-03-22 12:58:24'),
(123, 1.2, '2015-03-21 13:32:05'),
(123, 1.0, '2015-03-21 09:18:37'),
(123, 1.0, '2015-03-20 04:44:59'),
(234, 1.5, '2016-10-15 23:08:09'), <-- Latest version,first change for id 234
(345, 1.5, '2016-10-10 15:18:09'),
(345, 1.5, '2016-09-02 21:30:00'),
(345, 1.5, '2016-09-01 21:30:00'),
(345, 1.5, '2016-08-02 21:30:00'), <-- Latest version,first change for id 345
(345, 1.0, '2016-07-02 21:30:00')

Expected output

id  version     timestamp
(123, 1.5, '2015-03-27 07:21:04')
(234, 1.5, '2016-10-15 23:08:09')
(345, 1.5, '2016-08-02 21:30:00')

I was able to get this by using temp tables.I get the min(dt_create) for each id and version and store it in a temp table.Then I get the max date from this table for each id and then join it again to get the version.Is there a better way to do this?

create table #temp_version
(
       id varchar(22) NOT NULL,
       version varchar(50) NOT NULL,
       dt_create datetime NOT null
)

insert into #temp_version
select  id,version,min(dt_create) as dt_create
from [version_history] (nolock)
group by id,version

create table #temp_min_date
(
      id varchar(22) NOT NULL,
      dt_create datetime NOT null
)

insert into #temp_min_date
select id,max(dt_create)
from #temp_version
group by id

select a.id,a.version,a.dt_create
from #temp_version a
join #temp_date b on a.id = b.id and
a.dt_create=b.dt_create

drop table #temp_date
drop table #temp_version

Body:
Here's a query without any joins:

select
    id, [version], dt_create
from (
    select
        id,
        [version],
        rank() over (partition by id order by [version] desc, dt_create desc) as rnk,
        min(dt_create) over (partition by id, [version]) as dt_create
    from @history
) res
where
    rnk = 1

And there the whole query with your test data:

declare @history table(id varchar(22), [version] varchar(50), dt_create datetime);

insert into @history(id, [version], dt_create) values
    ('123', '1.5', '2015-03-28 08:21:04'),
    ('123', '1.5', '2015-03-28 07:21:04'),
    ('123', '1.5', '2015-03-27 07:21:04'),
    ('123', '1.2', '2015-03-22 12:58:24'),
    ('123', '1.2', '2015-03-21 13:32:05'),
    ('123', '1.0', '2015-03-21 09:18:37'),
    ('123', '1.0', '2015-03-20 04:44:59'),
    ('234', '1.5', '2016-10-15 23:08:09'),
    ('345', '1.5', '2016-10-10 15:18:09'),
    ('345', '1.5', '2016-09-02 21:30:00'),
    ('345', '1.5', '2016-09-01 21:30:00'),
    ('345', '1.5', '2016-08-02 21:30:00'),
    ('345', '1.0', '2016-07-02 21:30:00')

select
    id, [version], dt_create
from (
    select
        id,
        [version],
        rank() over (partition by id order by [version] desc, dt_create desc) as rnk,
        min(dt_create) over (partition by id, [version]) as dt_create
    from @history
) res
where
    rnk = 1


问:
response.result.value in alamofire post method is nil
```<code>        let parametersDictionary = [
        "email" : "name@gmail.com",
        "password" : "password"
    ]
    Alamofire.request("http://nanosoftech.com/store/user_check", method: .post, parameters: (parametersDictionary as NSDictionary) as? Parameters , encoding: JSONEncoding.default, headers: nil).responseJSON { response in
        print("response:", response.result.value)
    }
</code>```

I'm working in post method api and above code is not working. I'm getting nil response. But this url is working properly in postman and android studio too. What is the reason behind this issue?

答:
Just write look Like bellow.. It is working for me</p>

```<code>Alamofire.request("http://era.com.bd/UserSignInSV", method: .post,parameters:["uname":txtUserId.text!,"pass":txtPassword.text!]).responseJSON{(responseData) -> Void in
        if((responseData.result.value != nil)){

            let jsonData = JSON(responseData.result.value)

        }
    }
</code>```

Body:
        let parametersDictionary = [
        "email" : "name@gmail.com",
        "password" : "password"
    ]
    Alamofire.request("http://nanosoftech.com/store/user_check", method: .post, parameters: (parametersDictionary as NSDictionary) as? Parameters , encoding: JSONEncoding.default, headers: nil).responseJSON { response in
        print("response:", response.result.value)
    }

I'm working in post method api and above code is not working. I'm getting nil response. But this url is working properly in postman and android studio too. What is the reason behind this issue?

Body:
Just write look Like bellow.. It is working for me

Alamofire.request("http://era.com.bd/UserSignInSV", method: .post,parameters:["uname":txtUserId.text!,"pass":txtPassword.text!]).responseJSON{(responseData) -> Void in
        if((responseData.result.value != nil)){

            let jsonData = JSON(responseData.result.value)

        }
    }


问:
Where can i download .NET MVC 2.0 runtime?
I am looking for MVC 2.0 runtime for .NET.
Anybody have the link?

Thanks

答:
You can

Download ASP.NET MVC 2 using the Microsoft Web Platform Installer

or

Download ASP.NET MVC 2 from the Download Center


答:
Try this:</p>

```<code>SELECT `ID`, `Group`, `Name`, `Sold`  FROM products WHERE sold = 0 GROUP BY `Group`;
</code>```

Title: How to select only one record of each category?

Body:
Products :
--------------------------------------------
|   ID   |   Group   |   Name   |   Sold   |
--------------------------------------------
|   1    |     A     |   Dell   |    0     |
--------------------------------------------
|   2    |     A     |   Dell   |    0     |
--------------------------------------------
|   3    |     B     |   Dell   |    1     |
--------------------------------------------
|   4    |     B     |   Dell   |    1     |
--------------------------------------------
|   5    |     C     |   Dell   |    0     |
--------------------------------------------
|   6    |     C     |   Dell   |    1     |
--------------------------------------------

Hi everyone, i have a table (products) stored in MySql with many records, for now i'm using this query SELECT * FROM products WHERE sold = 0, in results i get :

--------------------------------------------
|   ID   |   Group   |   Name   |   Sold   |
--------------------------------------------
|   1    |     A     |   Dell   |    0     |
--------------------------------------------
|   2    |     A     |   Dell   |    0     |
--------------------------------------------
|   5    |     C     |   Dell   |    0     |
--------------------------------------------

i want to get only one record from each group, so the results will be like :

--------------------------------------------
|   ID   |   Group   |   Name   |   Sold   |
--------------------------------------------
|   1    |     A     |   Dell   |    0     |
--------------------------------------------
|   5    |     C     |   Dell   |    0     |
--------------------------------------------

Body:
Try this:

SELECT `ID`, `Group`, `Name`, `Sold`  FROM products WHERE sold = 0 GROUP BY `Group`;


问:
Android Mobile Vision API and NN API
In Google I/O 2017, it introduced lots of technologies benefit to develop AI applications.

But I'm kind of confused to Mobile Vision API and NN API.

Any relationship between them ?
Mobile vision API was built on top of NN(Neural Network) API ? Or they're just two independent APIs ?  The NN API will be only called by Tensorflow lite and application will just face to TF-lite.

答:
Mobile Vision API is part of Google Play Services, so it is Android only.

The TF-Lite library is cross platform and presents the same API on both Android and iOS. When running TF-Lite on Android, the library uses the Android Neural Network API and system level runtime to take advantage of hardware acceleration.

Title: Android Mobile Vision API and NN API


问:
Clojure spec: how to validate either one or another map
I have this Clojure code to define my schema for reply objects, which can be either

{:message {:text "Hello"} :delay 3000}

or

{:action "typing_on" :duration 5000}

The reply map can either have :message or :action and respectively optional keys :delay and :duration.

I am trying to express it this way with clojure.spec:

```<code>(s/def ::action #{"typing_on" "typing_off" "mark_seen"})
(s/def ::duration int?)
(s/def ::delay int?)
(s/def ::message map?)

(s/def ::message-reply (s/keys :req-un [::message]
                               :opt-un [::delay]))

(s/def ::action-reply (s/keys :req-un [::action]
                              :opt-un [::duration]))

(s/def ::reply (or ::action-reply ::message-reply))
</code>```

However, these specs will validate with true just the first schema they find within the or clause, in this case ::action-reply.
What I am trying to achieve instead is that either ::action-reply or ::message-reply are valid schemas for ::reply.

答:
I guess you meant to use s/or, not or (which doesn’t really make sense in this context)?

```<code>(s/def ::reply (s/or :action-reply  ::action-reply
                     :message-reply ::message-reply))
</code>```

Perhaps try s/conform on one of your values to see how you can use the conformed (‘spec-destructured’) value:

```<code>(s/conform ::reply {:message {:text "Hello"} :delay 3000})
; => [:message-reply {:message {:text "Hello"}, :delay 3000}]
</code>```

Body:
I have this Clojure code to define my schema for reply objects, which can be either

{:message {:text "Hello"} :delay 3000}

or

{:action "typing_on" :duration 5000}

The reply map can either have :message or :action and respectively optional keys :delay and :duration.

I am trying to express it this way with clojure.spec:

(s/def ::action #{"typing_on" "typing_off" "mark_seen"})
(s/def ::duration int?)
(s/def ::delay int?)
(s/def ::message map?)

(s/def ::message-reply (s/keys :req-un [::message]
                               :opt-un [::delay]))

(s/def ::action-reply (s/keys :req-un [::action]
                              :opt-un [::duration]))

(s/def ::reply (or ::action-reply ::message-reply))

However, these specs will validate with true just the first schema they find within the or clause, in this case ::action-reply.
What I am trying to achieve instead is that either ::action-reply or ::message-reply are valid schemas for ::reply.

Body:
I guess you meant to use s/or, not or (which doesn’t really make sense in this context)?

(s/def ::reply (s/or :action-reply  ::action-reply
                     :message-reply ::message-reply))

Perhaps try s/conform on one of your values to see how you can use the conformed (‘spec-destructured’) value:

(s/conform ::reply {:message {:text "Hello"} :delay 3000})
; => [:message-reply {:message {:text "Hello"}, :delay 3000}]


问:
How do I check whether both parallel AsyncTask threads are finished
I'm calling two AsyncTasks in parallel via this snippet in onCreate:

        if ((DictMode.equals("TATOEBA")) || (DictMode.equals("SENTENCE"))) {

            dictAsyncTask = new DictAsyncTask(DictionaryLookUp.this, "Tatoeba");
//            dictAsyncTask.execute();
            dictAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }

        if ((DictMode.equals("JUKUU")) || (DictMode.equals("SENTENCE"))) {

            dictAsyncTask = new DictAsyncTask(DictionaryLookUp.this, "Jukuu");
//            dictAsyncTask.execute();
            dictAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }
```

<p>during <code>onPostExecute</code> I check whether any data gets retrieved and return from the <code>startActivityForResult</code> call via <code>finish</code>:</p>

<pre class="lang-html prettyprint-override"><code>            if (alldictStuff.size() == 0) {

               ...

               Toast.makeText(DictionaryLookUp.this,"NOTHING FOUND ...",Toast.LENGTH_SHORT).show();

               if ((DictMode.equals("TATOEBA")) || (DictMode.equals("JUKUU")) || (DictMode.equals("SENTENCE"))) {

                    Intent intentCard = new Intent(getApplicationContext(), CardView.class);

                    setResult(Activity.RESULT_OK);

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

but that's obviously flawed since I'm not checking whether both threads return no results, so what's the best way to check whether both threads are finished and returned nothing ? Do I have to use my own variables to track it or is there something neat/built-in I can utilize ?

答:
This is mainly how you want to manage your business logic.
From your onPostExecute() either send intent or send broadcast message to main thread or maintain async task status list and mark finished for each task from onPostExecute().</p>

Body:
I'm calling two AsyncTasks in parallel via this snippet in onCreate:

        if ((DictMode.equals("TATOEBA")) || (DictMode.equals("SENTENCE"))) {

            dictAsyncTask = new DictAsyncTask(DictionaryLookUp.this, "Tatoeba");
//            dictAsyncTask.execute();
            dictAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }

        if ((DictMode.equals("JUKUU")) || (DictMode.equals("SENTENCE"))) {

            dictAsyncTask = new DictAsyncTask(DictionaryLookUp.this, "Jukuu");
//            dictAsyncTask.execute();
            dictAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }

during onPostExecute I check whether any data gets retrieved and return from the startActivityForResult call via finish:

            if (alldictStuff.size() == 0) {

               ...

               Toast.makeText(DictionaryLookUp.this,"NOTHING FOUND ...",Toast.LENGTH_SHORT).show();

               if ((DictMode.equals("TATOEBA")) || (DictMode.equals("JUKUU")) || (DictMode.equals("SENTENCE"))) {

                    Intent intentCard = new Intent(getApplicationContext(), CardView.class);

                    setResult(Activity.RESULT_OK);

                    finish();
                }

but that's obviously flawed since I'm not checking whether both threads return no results, so what's the best way to check whether both threads are finished and returned nothing ? Do I have to use my own variables to track it or is there something neat/built-in I can utilize ?


问:
Using smartcard credentials, obtained by a webpage
I have two servers on a Windows domain that include an active directory that is correctly configured to allow users to login using smartcard credentials. Currently, I can login to server1 and run remote PowerShell commands on server2 using smartcard credentials through WinRM, without any problem.

I would like to build some sort of web service (preferably on node.js) on server1, so that it presents a user with a webpage that prompts for smartcard credentials. Using these credentials, server1 would be able to run remote PowerShell commands on server2.

Is this possible? I saw some references to pcsclite on other posts. Is this all I need? If so, could someone provide a code snip-it of something that could accomplish this?

Maybe a simpler question that could help me get started, would be how could I even use these credentials to connect to a file share on server2 and download a file?

Thanks!

答: Look int using WAP in IIS  to set up a gateway and use Active Directory Client certificate mapping </p>


问:
regexp to match sequence if not starting and ending with a specific character
When it comes to regexps, I'm not very good at finding one that works and suits my needs.I need to match a word say foo if it is not included between a character say [ and another character say ]

```<code> "[foo] foo" // I need to replace foo with bar
 // expected result : "[foo] bar" but not "[bar] bar"
</code>```

I know how to match it if it is not followed by ]

```<code> "foo] foo".replace(/foo(!?\])/g,"bar")
</code>```

And I also know how to match it if it is not preceded by [

```<code> " [foo foo".replace(/(\[)?foo/g,function(_0,_1) {
      return _1:_0?"bar"
 })
</code>```

But I don't know how to put them together.Thank you!

答:
Using a negative lookahead you can use this regex:

```<code>var repl = str.replace(/\bfoo\b(?![^\]\[]*\])/g, 'bar');
</code>```

RegEx Demo

(?![^\]\[]*\]) is a negative lookahead assertion. This asserts failure when it finds a ] without matching [ or ] on the way, thus not matching foo inside [...].

\b is used for word boundary.

Body:
When it comes to regexps, I'm not very good at finding one that works and suits my needs.I need to match a word say foo if it is not included between a character say [ and another character say ]

 "[foo] foo" // I need to replace foo with bar
 // expected result : "[foo] bar" but not "[bar] bar"

I know how to match it if it is not followed by ]

 "foo] foo".replace(/foo(!?\])/g,"bar")

And I also know how to match it if it is not preceded by [

 " [foo foo".replace(/(\[)?foo/g,function(_0,_1) {
      return _1:_0?"bar"
 })

But I don't know how to put them together.Thank you!

Body:
Using a negative lookahead you can use this regex:

var repl = str.replace(/\bfoo\b(?![^\]\[]*\])/g, 'bar');

RegEx Demo

(?![^\]\[]*\]) is a negative lookahead assertion. This asserts failure when it finds a ] without matching [ or ] on the way, thus not matching foo inside [...].

\b is used for word boundary.


问:
Special Characters Shown as Html Code and Asp Post breaks
Hello guys sometimes from user i get string like: N106 ORG ,,test''(09090909)

in code behind i assign this value to textbox with javascript

like:

```<code>$("#Address1").val('@(Model.AddressLineOne)');
</code>```

(@Model.AddressLineOne is the users input address as i mentioned above)

if user input start with ,, and has no ending  it shows like

N106 ORG ,,test'&#39(09090909) so after,, character "" shown as &#39&#39.

Asp gives error on Save

System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client (Address="...  N106 ORG ,,test&#39&#39(09090909).

can you suggest what to do with this characters? p.s alsow i dont want [Allow Html] tag in asp ! i dont need  '&#39 in field and database!

答: OK guys I managed problem, model must be placed like "Model.addressline" not '@Model.addresslin'e when assigned to textbox val in JavaScript.double quots helped!</p>

Body:
Hello guys sometimes from user i get string like: N106 ORG ,,test''(09090909)

in code behind i assign this value to textbox with javascript

like:

$("#Address1").val('@(Model.AddressLineOne)');

(@Model.AddressLineOne is the users input address as i mentioned above)

if user input start with ,, and has no ending  it shows like

N106 ORG ,,test'&#39(09090909) so after,, character "" shown as &#39&#39.

Asp gives error on Save

System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client (Address="...  N106 ORG ,,test&#39&#39(09090909).

can you suggest what to do with this characters? p.s alsow i dont want [Allow Html] tag in asp ! i dont need  '&#39 in field and database!


问:
Encounter order friendly/unfriendly terminal operations vs parallel/sequential vs ordered/unordered streams
Inspired by this question, I started to play with ordered vs unordered streams, parallel vs sequential streams and terminal operations that respect encounter order vs terminal operations that don't respect it.

In one answer to the linked question, a code similar to this one is shown:

```<code>List<Integer> ordered = Arrays.asList(
    1, 2, 3, 4, 4, 3, 2, 1, 1, 2, 3, 4, 4, 3, 2, 1, 1, 2, 3, 4);
List<Integer> result = new CopyOnWriteArrayList<>();

ordered.parallelStream().forEach(result::add);

System.out.println(ordered);
System.out.println(result);
</code>```

And the lists are indeed different. The unordered list even changes from one run to another, showing that the result is actually non-deterministic.

So I created this other example:

```<code>CopyOnWriteArrayList<Integer> result2 = ordered.parallelStream()
        .unordered()
        .collect(Collectors.toCollection(CopyOnWriteArrayList::new));

System.out.println(ordered);
System.out.println(result2);
</code>```

And I expected to see similar results, as the stream is both parallel and unordered (maybe unordered() is redundant, since it's already parallel). However, the resulting list is ordered, i.e. it's equal to the source list.

So my question is why the collected list is ordered? Does collect always respect encounter-order, even for parallel, unordered streams? Is it the specific Collectors.toCollection(...) collector the one that forces encounter-order?

答:
the documentation Stream#collect has already mentioned:

When executed in parallel, multiple intermediate results may be instantiated, populated, and merged so as to maintain isolation of mutable data structures. Therefore, even when executed in parallel with non-thread-safe data structures (such as ArrayList), no additional synchronization is needed for a parallel reduction.

which means the Stream#collect does two primary thing: split & merge.

but I have a special example in jdk-8 that you can fetch the different results, :). when creates a unordered stream by Stream#generate, then you can fetch different result on Collectors#toList, for example:

```<code>Set<Set<Integer>> result = IntStream.range(0, 10).mapToObj(__ -> {
        return unordered().parallel().collect(toSet());
}).collect(toSet());

assert result.each.size() == 100000; // ok
//                   v--- surprised, it was pass
assert result.size() > 1;
</code>```

```<code>Stream<Integer> unordered() {
    AtomicInteger counter = new AtomicInteger();
    return Stream.generate(counter::getAndIncrement).limit(10000);
}
</code>```

Body:
Inspired by this question, I started to play with ordered vs unordered streams, parallel vs sequential streams and terminal operations that respect encounter order vs terminal operations that don't respect it.

In one answer to the linked question, a code similar to this one is shown:

List<Integer> ordered = Arrays.asList(
    1, 2, 3, 4, 4, 3, 2, 1, 1, 2, 3, 4, 4, 3, 2, 1, 1, 2, 3, 4);
List<Integer> result = new CopyOnWriteArrayList<>();

ordered.parallelStream().forEach(result::add);

System.out.println(ordered);
System.out.println(result);

And the lists are indeed different. The unordered list even changes from one run to another, showing that the result is actually non-deterministic.

So I created this other example:

CopyOnWriteArrayList<Integer> result2 = ordered.parallelStream()
        .unordered()
        .collect(Collectors.toCollection(CopyOnWriteArrayList::new));

System.out.println(ordered);
System.out.println(result2);

And I expected to see similar results, as the stream is both parallel and unordered (maybe unordered() is redundant, since it's already parallel). However, the resulting list is ordered, i.e. it's equal to the source list.

So my question is why the collected list is ordered? Does collect always respect encounter-order, even for parallel, unordered streams? Is it the specific Collectors.toCollection(...) collector the one that forces encounter-order?

Body:
the documentation Stream#collect has already mentioned:

When executed in parallel, multiple intermediate results may be instantiated, populated, and merged so as to maintain isolation of mutable data structures. Therefore, even when executed in parallel with non-thread-safe data structures (such as ArrayList), no additional synchronization is needed for a parallel reduction.

which means the Stream#collect does two primary thing: split & merge.

but I have a special example in jdk-8 that you can fetch the different results, :). when creates a unordered stream by Stream#generate, then you can fetch different result on Collectors#toList, for example:

Set<Set<Integer>> result = IntStream.range(0, 10).mapToObj(__ -> {
        return unordered().parallel().collect(toSet());
}).collect(toSet());

assert result.each.size() == 100000; // ok
//                   v--- surprised, it was pass
assert result.size() > 1;

Stream<Integer> unordered() {
    AtomicInteger counter = new AtomicInteger();
    return Stream.generate(counter::getAndIncrement).limit(10000);
}