问:
Tensorflow.js: Error when checking target ... expected layer to have n dimensions
I'm just starting out with Tensorflow.js, and am trying to build a simple model that takes as input 28 by 28 arrays (each representing a picture). Something isn't connecting quite right though. Running the snippet below, I get:

```<code>errors.ts:48 Uncaught (in promise) Error: Error when checking target: expected dense_Dense1 to have 2 dimension(s). but got array with shape 100,28,28
    at new e (errors.ts:48)
    at Od (training.ts:147)
    at e.standardizeUserData (training.ts:1133)
    at training_tensors.ts:427
    at common.ts:14
    at Object.next (common.ts:14)
    at common.ts:14
    at new Promise (<anonymous>)
    at op (common.ts:14)
    at kd (training_tensors.ts:408)
</code>```

Here's the code itself:

// build the model
var input = tf.input({shape: [28,28]})
var h1 = tf.layers.reshape({targetShape: [28*28]}).apply(input)
var h2 = tf.layers.dense({units: 100}).apply(h1)
var model = tf.model({inputs: input, outputs: h2})
model.compile({optimizer: 'sgd', loss: 'meanSquaredError', lr: 0.0001})
model.summary();

// get training data and train
var trainX = tf.ones([100,28,28]);

model.fit(trainX, trainX, {
  batchSize: 10,
  epochs: 1,
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src='https://cdnjs.cloudflare.com/ajax/libs/tensorflow/1.1.2/tf.min.js'></script></code>```

What confuses me is that the model.summary() call returns:

```<code>_________________________________________________________________
layer_utils.ts:152 Layer (type)                 Output shape              Param #
layer_utils.ts:64 =================================================================
layer_utils.ts:152 input1 (InputLayer)          [null,28,28]              0
layer_utils.ts:74 _________________________________________________________________
layer_utils.ts:152 reshape_Reshape1 (Reshape)   [null,784]                0
layer_utils.ts:74 _________________________________________________________________
layer_utils.ts:152 dense_Dense1 (Dense)         [null,100]                78500
layer_utils.ts:74 =================================================================
layer_utils.ts:83 Total params: 78500
layer_utils.ts:84 Trainable params: 78500
layer_utils.ts:85 Non-trainable params: 0
layer_utils.ts:86 _________________________________________________________________
</code>```

This suggests the reshape layer should be passing an array with shape (batch, 784) to the dense layer, but the error suggests otherwise.

Does anyone know what I'm doing wrong here? Any suggestions would be welcome!

答:
My input had shape (batch, 28, 28), while the model output had shape (batch, 100). However, I asked my model to predict trainX given inputs trainX (the second and first arguments to model.fit, respectively).

To fix this I just needed to update the shape of the values to be predicted to (batch, 100):

```<code>// build the model
var input = tf.input({shape: [28,28]})
var h1 = tf.layers.reshape({targetShape: [28*28]}).apply(input)
var h2 = tf.layers.dense({units: 17}).apply(h1)
var model = tf.model({inputs: input, outputs: h2})
model.compile({optimizer: 'sgd', loss: 'meanSquaredError', lr: 0.0001})
model.summary();

// get training data and train
var trainX = tf.ones([100,28,28]),
    trainY = tf.ones([100, 17])

model.fit(trainX, trainY, {
  batchSize: 10,
  epochs: 1,
}).then(function() {
  console.log( model.predict(trainX).dataSync() )
})
</code>```

Body:
I'm just starting out with Tensorflow.js, and am trying to build a simple model that takes as input 28 by 28 arrays (each representing a picture). Something isn't connecting quite right though. Running the snippet below, I get:

errors.ts:48 Uncaught (in promise) Error: Error when checking target: expected dense_Dense1 to have 2 dimension(s). but got array with shape 100,28,28
    at new e (errors.ts:48)
    at Od (training.ts:147)
    at e.standardizeUserData (training.ts:1133)
    at training_tensors.ts:427
    at common.ts:14
    at Object.next (common.ts:14)
    at common.ts:14
    at new Promise (<anonymous>)
    at op (common.ts:14)
    at kd (training_tensors.ts:408)

Here's the code itself:

// build the model
var input = tf.input({shape: [28,28]})
var h1 = tf.layers.reshape({targetShape: [28*28]}).apply(input)
var h2 = tf.layers.dense({units: 100}).apply(h1)
var model = tf.model({inputs: input, outputs: h2})
model.compile({optimizer: 'sgd', loss: 'meanSquaredError', lr: 0.0001})
model.summary();

// get training data and train
var trainX = tf.ones([100,28,28]);

model.fit(trainX, trainX, {
  batchSize: 10,
  epochs: 1,
})

What confuses me is that the model.summary() call returns:

_________________________________________________________________
layer_utils.ts:152 Layer (type)                 Output shape              Param #
layer_utils.ts:64 =================================================================
layer_utils.ts:152 input1 (InputLayer)          [null,28,28]              0
layer_utils.ts:74 _________________________________________________________________
layer_utils.ts:152 reshape_Reshape1 (Reshape)   [null,784]                0
layer_utils.ts:74 _________________________________________________________________
layer_utils.ts:152 dense_Dense1 (Dense)         [null,100]                78500
layer_utils.ts:74 =================================================================
layer_utils.ts:83 Total params: 78500
layer_utils.ts:84 Trainable params: 78500
layer_utils.ts:85 Non-trainable params: 0
layer_utils.ts:86 _________________________________________________________________

This suggests the reshape layer should be passing an array with shape (batch, 784) to the dense layer, but the error suggests otherwise.

Does anyone know what I'm doing wrong here? Any suggestions would be welcome!

Body:
My input had shape (batch, 28, 28), while the model output had shape (batch, 100). However, I asked my model to predict trainX given inputs trainX (the second and first arguments to model.fit, respectively).

To fix this I just needed to update the shape of the values to be predicted to (batch, 100):

// build the model
var input = tf.input({shape: [28,28]})
var h1 = tf.layers.reshape({targetShape: [28*28]}).apply(input)
var h2 = tf.layers.dense({units: 17}).apply(h1)
var model = tf.model({inputs: input, outputs: h2})
model.compile({optimizer: 'sgd', loss: 'meanSquaredError', lr: 0.0001})
model.summary();

// get training data and train
var trainX = tf.ones([100,28,28]),
    trainY = tf.ones([100, 17])

model.fit(trainX, trainY, {
  batchSize: 10,
  epochs: 1,
}).then(function() {
  console.log( model.predict(trainX).dataSync() )
})


来源: stackexchange

问:
How to calculate the fraction of sequence that matches given datatables with start and end coordinates?
Given two datatables with start and end coordinates for sequences of integers:

```<code>df1 <- data.table(CAT = c(rep("A", 3), rep("B", 3), rep("C", 3)),
              START = c(1, 11, 21, 1, 21, 41, 1, 11, 21),
              END = c(10, 20, 30, 20, 40, 60, 10, 20, 30)
)
df2 <- data.table(CAT = c(rep("A", 3), rep("B", 3), rep("C", 3)),
              START = c(1, 11, 21, 31, 41, 51, 1, 11, 21),
              END = c(5, 17, 23, 38, 48, 54, 9, 17, 26)
)
</code>```

How can I count the number of integers in each sequence in df1 that are within the start and end coordinates of any sequence in df2 with matching CAT? I am currently using a for loop:

```<code>seq2 <- Vectorize(seq.default, vectorize.args = c("from", "to"))
df1$MATCH <- NA
for (i in 1:nrow(df1)){
  df2_sub <- subset(df2, df2$CAT == df1$CAT[i])
  df2_int <- unlist(seq2(from = df2_sub$START, to = df2_sub$END))
  df1_int <- seq(df1$START[i], df1$END[i])
  df1$MATCH[i] <- length(na.omit(match(df1_int, df2_int)))
}
</code>```

which returns

```<code>df1
</code>```

```<code>   CAT START END MATCH
1:   A     1  10     5
2:   A    11  20     7
3:   A    21  30     3
4:   B     1  20     0
5:   B    21  40     8
6:   B    41  60    12
7:   C     1  10     9
8:   C    11  20     7
9:   C    21  30     6
</code>```

However, the datatables and vectors I am applying this to are very large? Is anyone able to suggest a way to improve performance? Perhaps using data.table?

答:
There is no need to create sequences which are collapsed afterwards.

As mentioned by Cole, the foverlaps() function can be used to identify overlapping sequences. With some simple arithmetic, the lengths of the overlaps can be calculated which are aggregated for each row of df1, finally:

```<code>library(data.table)
foverlaps(df1[, rn := .I], setkey(df2, CAT, START, END))[
  , ovl := (pmin(END, i.END) - pmax(START, i.START) + 1)][
    , .(MATCH = sum(ovl)), by = .(rn)][
      is.na(MATCH), MATCH := 0][]
</code>```

```<code>   rn MATCH
1:  1     5
2:  2     7
3:  3     3
4:  4     0
5:  5     8
6:  6    12
7:  7     9
8:  8     7
9:  9     6
</code>```

The development version 1.12.3 of data.table comes with a new nafill() function:

```<code>library(data.table) # version 1.12.3
foverlaps(df1[, rn := .I], setkey(df2, CAT, START, END))[
  , ovl := (pmin(END, i.END) - pmax(START, i.START) + 1)][
    , .(MATCH = sum(ovl)), by = .(rn)][
      , MATCH := nafill(MATCH, fill = 0)][]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Given two datatables with start and end coordinates for sequences of integers:

df1 <- data.table(CAT = c(rep("A", 3), rep("B", 3), rep("C", 3)),
              START = c(1, 11, 21, 1, 21, 41, 1, 11, 21),
              END = c(10, 20, 30, 20, 40, 60, 10, 20, 30)
)
df2 <- data.table(CAT = c(rep("A", 3), rep("B", 3), rep("C", 3)),
              START = c(1, 11, 21, 31, 41, 51, 1, 11, 21),
              END = c(5, 17, 23, 38, 48, 54, 9, 17, 26)
)

How can I count the number of integers in each sequence in df1 that are within the start and end coordinates of any sequence in df2 with matching CAT? I am currently using a for loop:

seq2 <- Vectorize(seq.default, vectorize.args = c("from", "to"))
df1$MATCH <- NA
for (i in 1:nrow(df1)){
  df2_sub <- subset(df2, df2$CAT == df1$CAT[i])
  df2_int <- unlist(seq2(from = df2_sub$START, to = df2_sub$END))
  df1_int <- seq(df1$START[i], df1$END[i])
  df1$MATCH[i] <- length(na.omit(match(df1_int, df2_int)))
}

which returns

df1

   CAT START END MATCH
1:   A     1  10     5
2:   A    11  20     7
3:   A    21  30     3
4:   B     1  20     0
5:   B    21  40     8
6:   B    41  60    12
7:   C     1  10     9
8:   C    11  20     7
9:   C    21  30     6

However, the datatables and vectors I am applying this to are very large? Is anyone able to suggest a way to improve performance? Perhaps using data.table?

Body:
There is no need to create sequences which are collapsed afterwards.

As mentioned by Cole, the foverlaps() function can be used to identify overlapping sequences. With some simple arithmetic, the lengths of the overlaps can be calculated which are aggregated for each row of df1, finally:

library(data.table)
foverlaps(df1[, rn := .I], setkey(df2, CAT, START, END))[
  , ovl := (pmin(END, i.END) - pmax(START, i.START) + 1)][
    , .(MATCH = sum(ovl)), by = .(rn)][
      is.na(MATCH), MATCH := 0][]

   rn MATCH
1:  1     5
2:  2     7
3:  3     3
4:  4     0
5:  5     8
6:  6    12
7:  7     9
8:  8     7
9:  9     6

The development version 1.12.3 of data.table comes with a new nafill() function:

library(data.table) # version 1.12.3
foverlaps(df1[, rn := .I], setkey(df2, CAT, START, END))[
  , ovl := (pmin(END, i.END) - pmax(START, i.START) + 1)][
    , .(MATCH = sum(ovl)), by = .(rn)][
      , MATCH := nafill(MATCH, fill = 0)][]


问:
laravel how to store image in 4 different folder at same time

my below code stores image 2 different at the same time but I am trying to
  store image in 4 different folders at the same time, but it not storing 4
  different folder it only passing image in 2 folders how to slow this
  problem

This code only Stores in Two Folder

```<code>public function store(Request $request)

    {

      $this->validate($request, [

          'image' => 'required|image|mimes:jpeg,png,jpg|max:2048',
          ]);

            $input['image'] = time().'.'.$request->image->getClientOriginalExtension();
            $request->image->move(public_path('Folder-a/'), $input['image']);
            $folder1 = public_path('Folder-1/') . $input['image'];
            $folder2 = public_path(Folder-2/') . $input['image'];
            $folder3 = public_path('Folder-3/') . $input['image'];
            $folder4 = public_path(Folder-4/') . $input['image'];
            \File::copy($folder1, $folder2, $folder3, $folder4 );

        Service::create($input);

        return back()->with('success',' CREATED SUCCESSFULLY .');

    }
</code>```

@ Manojkiran.A you provided code

```<code><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Service;
use Illuminate\Support\Facades\File;
use saveFilesMultipleTimes;
class ServiceController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function store(Request $request)
{
$this->validate($request, ['image' => 'required|image|mimes:jpeg,png,jpg|max:2048',]);
$mainFolderPath = public_path('Folder-a/');
$folder1 = public_path('Folder-1/');
$folder2 = public_path('Folder-2/');
$folder3 = public_path('Folder-3/');
$folder4 = public_path('Folder-4/');
$fileObject = $request->image;
$filenamesWithPath = self::saveFilesMultipleTimes( $fileObject, $mainFolderPath, [$folder1, $folder2,
$folder3, $folder4]);
dd($filenamesWithPath);
function saveFilesMultipleTimes( \Illuminate\Http\UploadedFile$requestFile, $mainFolderPath,$paths)
{
$fileName = $requestFile->getClientOriginalName();
$movedFile = $requestFile->move($mainFolderPath, $fileName);
$currentFile = $movedFile->getPathName();
foreach ( (array) $paths as $eachPath)
{
@mkdir( $eachPath);
@copy($movedFile->getPathName(), $eachPath . $fileName);
$dirctory[] = $eachPath.$fileName;
}
return $dirctory;
}
Service::create($input);
return back()->with('success',' CREATED SUCCESSFULLY .');
}
</code>```

}

答:
You are trying to use \File::copy method which has only two args - source and destination. So, you should just save your file and copy it separately as much as you need.

https://laravel.com/api/5.8/Illuminate/Filesystem/Filesystem.html#method_copy

```<code>public function store(Request $request)
{
    $this->validate($request, [
        'image' => 'required|image|mimes:jpeg,png,jpg|max:2048',
    ]);

    $input['image'] = time().'.'.$request->image->getClientOriginalExtension();

    $folder1 = public_path('Folder-1/');

    $path1 = $folder1 . $input['image']; // path 1

    $request->image->move($folder1, $input['image']); // image saved in first folder

    $path2 = public_path('Folder-2/') . $input['image']; // path 2
    $path3 = public_path('Folder-3/') . $input['image']; // path 3
    $path4 = public_path('Folder-4/') . $input['image']; // path 4

    \File::copy($path1, $path2);
    \File::copy($path1, $path3);
    \File::copy($path1, $path4);

    Service::create($input);

    return back()->with('success',' CREATED SUCCESSFULLY .');
}
</code>```

Body:
my below code stores image 2 different at the same time but I am trying to
  store image in 4 different folders at the same time, but it not storing 4
  different folder it only passing image in 2 folders how to slow this
  problem

This code only Stores in Two Folder

public function store(Request $request)

    {

      $this->validate($request, [

          'image' => 'required|image|mimes:jpeg,png,jpg|max:2048',
          ]);

            $input['image'] = time().'.'.$request->image->getClientOriginalExtension();
            $request->image->move(public_path('Folder-a/'), $input['image']);
            $folder1 = public_path('Folder-1/') . $input['image'];
            $folder2 = public_path(Folder-2/') . $input['image'];
            $folder3 = public_path('Folder-3/') . $input['image'];
            $folder4 = public_path(Folder-4/') . $input['image'];
            \File::copy($folder1, $folder2, $folder3, $folder4 );

        Service::create($input);

        return back()->with('success',' CREATED SUCCESSFULLY .');

    }

@ Manojkiran.A you provided code

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Service;
use Illuminate\Support\Facades\File;
use saveFilesMultipleTimes;
class ServiceController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function store(Request $request)
{
$this->validate($request, ['image' => 'required|image|mimes:jpeg,png,jpg|max:2048',]);
$mainFolderPath = public_path('Folder-a/');
$folder1 = public_path('Folder-1/');
$folder2 = public_path('Folder-2/');
$folder3 = public_path('Folder-3/');
$folder4 = public_path('Folder-4/');
$fileObject = $request->image;
$filenamesWithPath = self::saveFilesMultipleTimes( $fileObject, $mainFolderPath, [$folder1, $folder2,
$folder3, $folder4]);
dd($filenamesWithPath);
function saveFilesMultipleTimes( \Illuminate\Http\UploadedFile$requestFile, $mainFolderPath,$paths)
{
$fileName = $requestFile->getClientOriginalName();
$movedFile = $requestFile->move($mainFolderPath, $fileName);
$currentFile = $movedFile->getPathName();
foreach ( (array) $paths as $eachPath)
{
@mkdir( $eachPath);
@copy($movedFile->getPathName(), $eachPath . $fileName);
$dirctory[] = $eachPath.$fileName;
}
return $dirctory;
}
Service::create($input);
return back()->with('success',' CREATED SUCCESSFULLY .');
}

}

Body:
You are trying to use \File::copy method which has only two args - source and destination. So, you should just save your file and copy it separately as much as you need.

https://laravel.com/api/5.8/Illuminate/Filesystem/Filesystem.html#method_copy

public function store(Request $request)
{
    $this->validate($request, [
        'image' => 'required|image|mimes:jpeg,png,jpg|max:2048',
    ]);

    $input['image'] = time().'.'.$request->image->getClientOriginalExtension();

    $folder1 = public_path('Folder-1/');

    $path1 = $folder1 . $input['image']; // path 1

    $request->image->move($folder1, $input['image']); // image saved in first folder

    $path2 = public_path('Folder-2/') . $input['image']; // path 2
    $path3 = public_path('Folder-3/') . $input['image']; // path 3
    $path4 = public_path('Folder-4/') . $input['image']; // path 4

    \File::copy($path1, $path2);
    \File::copy($path1, $path3);
    \File::copy($path1, $path4);

    Service::create($input);

    return back()->with('success',' CREATED SUCCESSFULLY .');
}


问:
ARM Cortex-M interrupt handler in C++
Is it possible to write an interrupt handler in C++ for ARM Cortex chips like those of ST and NXP.

Currently I develop a lot of code in C++ for ARM cortex chips. I am a bit fed up with having to call a static/global/singleton C++ object from a C callback function. Is there a way to not having to through the C function.

Is there a way to directly call a C++ object functions when a interrupt occurs?

答:
It is possible to write the interrupt handler in any language that compiles to native code.

It still has to use C language linkage with the interrupt handler calling convention.  That means no member functions.  (Formally, static member functions are illegal as well, although they usually work in practice.  Non-static member functions cannot be used.)

In C++, first enable the C language linkage with extern "C".  Also use any compiler-specific keyword for interrupt handlers that you would have used in C, such as __interrupt.

Inside the function you can use the full power of C++ -- objects, for-in loops, smart pointers, template instances, etc.  Although you still want to be careful about how much work you do in interrupt context, and C++ tends to hide the complexity so you no longer have a feel for how many machine instructions are being generated.

On ARM Cortex M chips, there's a table of function pointers at a preset memory address.  The table may be constructed in C or assembly, and if your interrupt handlers aren't exported with the correct name, the linker won't be able to find the addresses that belong in the table.  C language linkage ensures that any name mangling is performed in a way compatible with the symbol references in the startup code.

Other processor families use a fixed address only for the reset vector, and install other interrupt handlers by writing each handler address into a special-function register corresponding to its interrupt.  For these, only calling convention matters and not the function name/linkage.  ARM Cortex-M lets you write a special function register to find the whole vector table at an alternate address, but not to relocate individual handlers.

Title: ARM Cortex-M interrupt handler in C++


问:
Remove duplicate elements by class with JQuery
I want to delete duplicate span.film-date elements using the secondary class. For example I only want to keep the first span with the classes of "film-date Wed29May" and the first span with the classes of "film-date Thur30May".

```<code><div class="film-time-list">
<span class="film-date Wed29May">Wed 29 May</span>
<a class="film-tickets" href="#">2.30pm</a>
<span class="film-date Wed29May">Wed 29 May</span>
<a class="film-tickets" href="#">5.20pm</a>
<span class="film-date Thur30May">Thur 30 May</span>
<a class="film-tickets" href="#">2.30pm</a>
<span class="film-date Thur30May">Thur 30 May</span>
<a class="film-tickets" href="#">5.20pm</a>
</div>
</code>```

I thought this would be straight forward enough but as the class that is output dynamically could be any date this snippet won't work which was my initial thought.

```<code>$('.couldBeAnyClass').not(':first').remove();
</code>```

Any pointers would be great!

My output would be:

```<code>Wed 29 May 2.30pm 5.20pm
Thur 30 May 2.30pm 5.20pm
</code>```

答:
First I would get all elements by the base class. Then I would join the full class of those elements and remove all duplicates.

;window.onload = function(){
  //REM: Looping through all .film-date elements
  for(var tListOfSpans = document.querySelectorAll('.film-date'), i=tListOfSpans.length-1; i>=0; i--){
    var tSelector = '.' + tListOfSpans[i].className.split(' ').join('.');

    //REM: Removing all but the first .film-date plus whatever class elements but the first
    for(var tListOfSelects = document.querySelectorAll(tSelector), j=tListOfSelects.length-1; j>0; j--){
      tListOfSelects[j].parentNode.removeChild(tListOfSelects[j])
    }
  }
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="film-time-list">
  <span class="film-date Wed29May">Wed 29 May</span>
  2.30pm
  <span class="film-date Wed29May">Wed 29 May</span>
  5.20pm
  <span class="film-date Thur30May">Thur 30 May</span>
  2.30pm
  <span class="film-date Thur30May">Thur 30 May</span>
  5.20pm
</div></code>```

Edit:

The HTML of the question changed. Hence I changed mine accordingly.

Body:
I want to delete duplicate span.film-date elements using the secondary class. For example I only want to keep the first span with the classes of "film-date Wed29May" and the first span with the classes of "film-date Thur30May".

Wed 29 May
2.30pm
Wed 29 May
5.20pm
Thur 30 May
2.30pm
Thur 30 May
5.20pm

I thought this would be straight forward enough but as the class that is output dynamically could be any date this snippet won't work which was my initial thought.

$('.couldBeAnyClass').not(':first').remove();

Any pointers would be great!

My output would be:

Wed 29 May 2.30pm 5.20pm
Thur 30 May 2.30pm 5.20pm

Body:
First I would get all elements by the base class. Then I would join the full class of those elements and remove all duplicates.

;window.onload = function(){
  //REM: Looping through all .film-date elements
  for(var tListOfSpans = document.querySelectorAll('.film-date'), i=tListOfSpans.length-1; i>=0; i--){
    var tSelector = '.' + tListOfSpans[i].className.split(' ').join('.');

    //REM: Removing all but the first .film-date plus whatever class elements but the first
    for(var tListOfSelects = document.querySelectorAll(tSelector), j=tListOfSelects.length-1; j>0; j--){
      tListOfSelects[j].parentNode.removeChild(tListOfSelects[j])
    }
  }
};

<div class="film-time-list">
  <span class="film-date Wed29May">Wed 29 May</span>
  <a class="film-tickets" href="#">2.30pm</a>
  <span class="film-date Wed29May">Wed 29 May</span>
  <a class="film-tickets" href="#">5.20pm</a>
  <span class="film-date Thur30May">Thur 30 May</span>
  <a class="film-tickets" href="#">2.30pm</a>
  <span class="film-date Thur30May">Thur 30 May</span>
  <a class="film-tickets" href="#">5.20pm</a>
</div>

Edit:

The HTML of the question changed. Hence I changed mine accordingly.


问:
calling a function within a function
I've had a look through several of the related questions and just can't seem to see the issue!

the following two functions are within my function include file and for some reason I cannot seem to get the check_orientation function to return scale to the display_months_news function.

I'm fairly sure I'm just missing something really obviously.

the display_news function

```<code>function display_months_news()
{
    //header('Content-type: image/jpeg');
    $year = date("y");
    $year = "20" .$year;
    $month = date("m");
    if ($month) {
        switch ($month){
            case "01": $month = "January"; break;
            case "02": $month = "February"; break;
            case "03": $month = "March"; break;
            case "04": $month = "April"; break;
            case "05": $month = "May"; break;
            case "06": $month = "June"; break;
            case "07": $month = "July"; break;
            case "08": $month = "August"; break;
            case "09": $month = "September"; break;
            case "10": $month = "October"; break;
            case "11": $month = "November"; break;
            case "12": $month = "December"; break;
        }
    } else {
        echo '<p>The date field is empty.</p>';
    }
    $nowdate = $month." ".$year;

    $result = mysql_query("SELECT * FROM news ORDER BY sqldate DESC LIMIT 6") or die(mysql_error());

    while ($row = mysql_fetch_array($result)) {
        global $imgurl;
        $imgurl = $row['img1'];

        check_orientation4($imgurl);

        $comcount = comment_count($row['nid']);
        if ($comcount == NULL) {$comcount = 0;}

        echo '<div class="news-preview-container">';
        echo '<div class="news-preview-container-date">';
        echo "<P>" .$row['mmonth']. " ".$row['dday']. ", " .$row['yyear']. "</p><BR>";
        echo '</div>';
        echo '<div class="news-preview-container-title">';
        echo "<p><a href='article.php?id=" .$row['nid']."'>" .$row['title']."</a></p><BR>";
        echo '</div>';
        echo '<div class="news-preview-container-inner">';
        echo '<div class="news-preview-container-text">';
        echo '<p>'.ShortenText($row['body']).'</p>';
        echo '</div>';
        echo '<div class="news-preview-container-image"><img src="'.$imgurl.'"'.$scale.'"></div><BR></div>';
        echo '<div class="news-preview-container-bottombar">Posted in '.$row[tag].' / '.$comcount.' Comments</div>';
        echo '</div>';

    }
}
</code>```

and the check_orientation function

```<code>function check_orientation4($imgurls){

if ($imgurls == NULL){ echo "";  }
else {
        $imgurlshrunk = NULL;
        $maxsize = 120;
        $filename = NULL;
        $height = NULL;
        $width = NULL;
        $scale = NULL;
        $imgurlshrunk = $imgurls;
        $filename = basename($imgurlshrunk);
        $filename = "admin/uploads/" . $filename;
        list($width,$height,$type,$attr) = getimagesize("$filename");
        $wRatio = $maxsize / $width;
        $hRatio= $maxsize / $height;

    global $scale;

    if ( ($width <= $maxsize) && ($height <= $maxsize))
      {

        $scale = "";
        return $scale;
      }
    elseif ( ($wRatio * $height) < $maxsize)
    {
        $scale = "width = '100%'";
        return $scale;
    }
    elseif  ($height == NULL)
    {

        echo "empty height";
    }
    else
    {
    global $height;
        $scale = "height = '100%'";
        return $scale;
    }       }}
</code>```

Thanks in advance to whoever points out the silly mistake i'm missing!

答:
You're not assigning the return value of check_orientation4 to anything.

```<code>check_orientation4($imgurl);
</code>```

should be

```<code>$scale = check_orientation4($imgurl);
</code>```

ContentLicense: CC BY-SA 3.0

Title: calling a function within a function

Body:
I've had a look through several of the related questions and just can't seem to see the issue!

the following two functions are within my function include file and for some reason I cannot seem to get the check_orientation function to return scale to the display_months_news function.

I'm fairly sure I'm just missing something really obviously.

the display_news function

function display_months_news()
{
    //header('Content-type: image/jpeg');
    $year = date("y");
    $year = "20" .$year;
    $month = date("m");
    if ($month) {
        switch ($month){
            case "01": $month = "January"; break;
            case "02": $month = "February"; break;
            case "03": $month = "March"; break;
            case "04": $month = "April"; break;
            case "05": $month = "May"; break;
            case "06": $month = "June"; break;
            case "07": $month = "July"; break;
            case "08": $month = "August"; break;
            case "09": $month = "September"; break;
            case "10": $month = "October"; break;
            case "11": $month = "November"; break;
            case "12": $month = "December"; break;
        }
    } else {
        echo '
The date field is empty.
';
    }
    $nowdate = $month." ".$year;

    $result = mysql_query("SELECT * FROM news ORDER BY sqldate DESC LIMIT 6") or die(mysql_error());

    while ($row = mysql_fetch_array($result)) {
        global $imgurl;
        $imgurl = $row['img1'];

        check_orientation4($imgurl);

        $comcount = comment_count($row['nid']);
        if ($comcount == NULL) {$comcount = 0;}

        echo '
';
        echo '
';
        echo "
" .$row['mmonth']. " ".$row['dday']. ", " .$row['yyear']. "

";
        echo '
';
        echo '
';
        echo "
" .$row['title']."

";
        echo '
';
        echo '
';
        echo '
';
        echo '
'.ShortenText($row['body']).'
';
        echo '
';
        echo '

';
        echo '
Posted in '.$row[tag].' / '.$comcount.' Comments
';
        echo '
';

    }
}

and the check_orientation function

function check_orientation4($imgurls){

if ($imgurls == NULL){ echo "";  }
else {
        $imgurlshrunk = NULL;
        $maxsize = 120;
        $filename = NULL;
        $height = NULL;
        $width = NULL;
        $scale = NULL;
        $imgurlshrunk = $imgurls;
        $filename = basename($imgurlshrunk);
        $filename = "admin/uploads/" . $filename;
        list($width,$height,$type,$attr) = getimagesize("$filename");
        $wRatio = $maxsize / $width;
        $hRatio= $maxsize / $height;

    global $scale;

    if ( ($width <= $maxsize) && ($height <= $maxsize))
      {

        $scale = "";
        return $scale;
      }
    elseif ( ($wRatio * $height) < $maxsize)
    {
        $scale = "width = '100%'";
        return $scale;
    }
    elseif  ($height == NULL)
    {

        echo "empty height";
    }
    else
    {
    global $height;
        $scale = "height = '100%'";
        return $scale;
    }       }}

Thanks in advance to whoever points out the silly mistake i'm missing!

Body:
You're not assigning the return value of check_orientation4 to anything.

check_orientation4($imgurl);

should be

$scale = check_orientation4($imgurl);


问:
React get height of component
I need to know the height of a React Component inside another React component. I am aware that the height of an element can be reached by calling this.cmref.current.clientHeight. I'm looking for something like this:

child component:

const Comp = () =>{
    return(

some other stuff here

    )
}
export default Comp
```

<p>parent component:</p>

<pre class="lang-js prettyprint-override"><code>class App extends React.Component{
    constructor(props){
        super(props);
        this.compref = React.createRef();
    }
    componentDidSomething(){
        const height = this.compref.current.clientHeight;
        //which will be undefined
    }
    render(){
        return(
            <div>
                <Comp ref={this.compref} />
            </div>
        )
    }
}
</code>```

Is this possible? Thanks in advance.

答:
You'll need to actually ref the div of the child component in order to get the element you want instead of the child component itself. To do this you could pass a function to the child that the child then passes to the div. Working example below:

const Comp = (props) =>{
    return(

some other stuff here

    )
}

class App extends React.Component{
    constructor(props){
        super(props);
        this.compref = React.createRef();
    }

    componentDidMount(){
        const height = this.compref.current.clientHeight;
        //which will be undefined --- No more!
        console.log('height: ', height);
    }

    onCompRef = (ref) => {
      this.compref.current = ref;
    }

    render(){
        return(

                <Comp onRef={this.onCompRef} />

        )
    }
}

ReactDOM.render(<App />, document.getElementById("root"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>

<div id='root' style='width: 100%; height: 100%'>
</div></code>```

Title: React get height of component

Body:
I need to know the height of a React Component inside another React component. I am aware that the height of an element can be reached by calling this.cmref.current.clientHeight. I'm looking for something like this:

child component:

const Comp = () =>{
    return(

some other stuff here

    )
}
export default Comp

parent component:

class App extends React.Component{
    constructor(props){
        super(props);
        this.compref = React.createRef();
    }
    componentDidSomething(){
        const height = this.compref.current.clientHeight;
        //which will be undefined
    }
    render(){
        return(

                <Comp ref={this.compref} />

        )
    }
}

Is this possible? Thanks in advance.

Body:
You'll need to actually ref the div of the child component in order to get the element you want instead of the child component itself. To do this you could pass a function to the child that the child then passes to the div. Working example below:

const Comp = (props) =>{
    return(
        <div ref={props.onRef}>some other stuff here</div>
    )
}

class App extends React.Component{
    constructor(props){
        super(props);
        this.compref = React.createRef();
    }

    componentDidMount(){
        const height = this.compref.current.clientHeight;
        //which will be undefined --- No more!
        console.log('height: ', height);
    }

    onCompRef = (ref) => {
      this.compref.current = ref;
    }

    render(){
        return(
            <div>
                <Comp onRef={this.onCompRef} />
            </div>
        )
    }
}

ReactDOM.render(<App />, document.getElementById("root"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>

<div id='root' style='width: 100%; height: 100%'>
</div>


问:
How to input values into already defined arrays?
Write a program which outputs 10 given numbers into two rows, one for odd and one for even numbers. Use arrays.

After declaring an input array for 10 numbers which the user enters, I tried declaring separate arrays for odd and even values which would later be sorted by a for-loop.

I get stuck when I need to assign these values n to odd or even arrays.

```<code>int input[10];
int odd[]{};
int even[]{};
int n;

for(n=0;n<10;n++)
{
    if ((input[n])%2==0)
    {
      odd[n] = n;
    }
    else
    {
      even[n] = n;
    }
</code>```

答:
You don't need dynamic allocation for this. We can just make two arrays and fill them as needed.

```<code>static constexpr std::size_t N = 10;
const int input[N] = { /* user input here */ };

int odd[N] = {};
int even[N] = {};

std::size_t countOdd = 0;
std::size_t countEven = 0;

for (std::size_t i = 0; i < N; i++)
{
    if (input[i] % 2 == 0)
       even[countEven++] = input[i];
    else
       odd[countOdd++] = input[i];
}
</code>```

There will be exactly N (10) elements "wasted" at the end of odd and even in total (with some unknown distribution), but who cares? Ten automatic-storage ints! That's nothing.  As long as we keep track of how many odds and how many evens we "care about", everything's fine.

Now for the two-row output:

```<code>for (std::size_t i = 0; i < countOdd; i++)
    std::cout << odd[i] << ' ';
std::cout << '\n';

for (std::size_t i = 0; i < countEven; i++)
    std::cout << even[i] << ' ';
std::cout << '\n';
</code>```

Easy!

I used std::size_t where appropriate for array indices, rather than int, but you could ignore that for now if you like. I also fixed your modulo operation, and you were storing the indices of the even/odd values, not the values themselves.

Full program example:

```<code>#include <iostream>
#include <cstddef>  // for std::size_t

int main()
{
    static constexpr std::size_t N = 10;
    const int input[N] = { 1,5,9,14,3,99,82,42,43,70};

    int odd[N] = {};
    int even[N] = {};

    std::size_t countOdd = 0;
    std::size_t countEven = 0;

    for (std::size_t i = 0; i < N; i++)
    {
        if (input[i] % 2 == 0)
           even[countEven++] = input[i];
        else
           odd[countOdd++] = input[i];
    }

    for (std::size_t i = 0; i < countOdd; i++)
        std::cout << odd[i] << ' ';
    std::cout << '\n';

    for (std::size_t i = 0; i < countEven; i++)
        std::cout << even[i] << ' ';
    std::cout << '\n';
}

// g++ -std=c++17 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
// 1 5 9 3 99 43
// 14 82 42 70
</code>```

(live demo)

Body:
Write a program which outputs 10 given numbers into two rows, one for odd and one for even numbers. Use arrays.

After declaring an input array for 10 numbers which the user enters, I tried declaring separate arrays for odd and even values which would later be sorted by a for-loop.

I get stuck when I need to assign these values n to odd or even arrays.

int input[10];
int odd[]{};
int even[]{};
int n;

for(n=0;n<10;n++)
{
    if ((input[n])%2==0)
    {
      odd[n] = n;
    }
    else
    {
      even[n] = n;
    }

Body:
You don't need dynamic allocation for this. We can just make two arrays and fill them as needed.

static constexpr std::size_t N = 10;
const int input[N] = { /* user input here */ };

int odd[N] = {};
int even[N] = {};

std::size_t countOdd = 0;
std::size_t countEven = 0;

for (std::size_t i = 0; i < N; i++)
{
    if (input[i] % 2 == 0)
       even[countEven++] = input[i];
    else
       odd[countOdd++] = input[i];
}

There will be exactly N (10) elements "wasted" at the end of odd and even in total (with some unknown distribution), but who cares? Ten automatic-storage ints! That's nothing.  As long as we keep track of how many odds and how many evens we "care about", everything's fine.

Now for the two-row output:

for (std::size_t i = 0; i < countOdd; i++)
    std::cout << odd[i] << ' ';
std::cout << '\n';

for (std::size_t i = 0; i < countEven; i++)
    std::cout << even[i] << ' ';
std::cout << '\n';

Easy!

I used std::size_t where appropriate for array indices, rather than int, but you could ignore that for now if you like. I also fixed your modulo operation, and you were storing the indices of the even/odd values, not the values themselves.

Full program example:

#include <iostream>
#include <cstddef>  // for std::size_t

int main()
{
    static constexpr std::size_t N = 10;
    const int input[N] = { 1,5,9,14,3,99,82,42,43,70};

    int odd[N] = {};
    int even[N] = {};

    std::size_t countOdd = 0;
    std::size_t countEven = 0;

    for (std::size_t i = 0; i < N; i++)
    {
        if (input[i] % 2 == 0)
           even[countEven++] = input[i];
        else
           odd[countOdd++] = input[i];
    }

    for (std::size_t i = 0; i < countOdd; i++)
        std::cout << odd[i] << ' ';
    std::cout << '\n';

    for (std::size_t i = 0; i < countEven; i++)
        std::cout << even[i] << ' ';
    std::cout << '\n';
}

// g++ -std=c++17 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
// 1 5 9 3 99 43
// 14 82 42 70

(live demo)


问:
Data part of Response is a long script instead of desired json object
I am building a web app using laravel and vuejs. I have made a axios get request to get a list of users .
I am getting a Promise object, and from what i have read. Reason for getting a promise object is because it's an async request.

I have tried .then() to get data part of the response. But i am getting a huge script instead of desired data.

```<code>axios......then(function(response){
    console.log(response.data);
})
</code>```

Initially what i did was

```<code> var res = axios.get('/allUsers');
   console.log(res)
</code>```

That time i came to know about promise object and read about.
When i checked network in dev tools, status code is 200 and i can see list of users. So i guess my request is successfully completed.

What should be done to get the list of the users. That list i will be using to update my UI.

答:
Depending on what you're getting back for data there are a few ways to handle this. You may need to convert the data after the you get receive the response.

```<code>axios.get('some_url')
    .then(res => res.json())
    .then(data => {
        // do something with the data
    }).catch(err) {
        conosole.error(err);
    }
</code>```

if you're seeing the data come through properly in the response and you're getting what you need without doing that then just do

```<code>axios.get('some url').then(res => {
  // do something in here with the data here
})
</code>```

also make sure you're getting back json if that's what you're looking for. check your response to see if its html or json because they can be handled a bit differently

as an "Edit" you could also handle this with async await so you dont end up in callback hell

```<code>async function fetchData() {
    try {
      const res = await axios.get('some url');
      // next step might not be necessary
      const data = await res.json();
      // do something with the data
      console.log(data); // if converting it was necessary
      console.log(res); // if not converting
    } catch (err) {
      console.error(err);
    }
}
</code>```

Body:
I am building a web app using laravel and vuejs. I have made a axios get request to get a list of users .
I am getting a Promise object, and from what i have read. Reason for getting a promise object is because it's an async request.

I have tried .then() to get data part of the response. But i am getting a huge script instead of desired data.

axios......then(function(response){
    console.log(response.data);
})

Initially what i did was

 var res = axios.get('/allUsers');
   console.log(res)

That time i came to know about promise object and read about.
When i checked network in dev tools, status code is 200 and i can see list of users. So i guess my request is successfully completed.

What should be done to get the list of the users. That list i will be using to update my UI.

Body:
Depending on what you're getting back for data there are a few ways to handle this. You may need to convert the data after the you get receive the response.

axios.get('some_url')
    .then(res => res.json())
    .then(data => {
        // do something with the data
    }).catch(err) {
        conosole.error(err);
    }

if you're seeing the data come through properly in the response and you're getting what you need without doing that then just do

axios.get('some url').then(res => {
  // do something in here with the data here
})

also make sure you're getting back json if that's what you're looking for. check your response to see if its html or json because they can be handled a bit differently

as an "Edit" you could also handle this with async await so you dont end up in callback hell

async function fetchData() {
    try {
      const res = await axios.get('some url');
      // next step might not be necessary
      const data = await res.json();
      // do something with the data
      console.log(data); // if converting it was necessary
      console.log(res); // if not converting
    } catch (err) {
      console.error(err);
    }
}


问:
Transfer Ipython namespace to ipdb
I am in the middle of an ipython session. I've loaded a module foo which contains a function foo.bar. While working, I notice that foo.bar gives some weird output when I feed it some input x, where x is a variable in my local ipython scope. I would like to investigate the behavior in a debugger.

How would I set a breakpoint at foo.bar and run foo.bar(x) in a debugger?

I know about pdb.set_trace(), but it would require me to open up the code of the foo module to insert a breakpoint manually, save it, reload the module in ipython, etc. There has to be a better way.

答:
I believe you can use pdb.runcall in this case:

```<code>import pdb
pdb.runcall(foo.bar, x)
</code>```

Title: Transfer Ipython namespace to ipdb

Body:
I believe you can use pdb.runcall in this case:

import pdb
pdb.runcall(foo.bar, x)


问:
Android Things Rasperry PI GPS and Bluetooth Error
I am getting an error once I load my app in Android Things on Rasperry PI, it shows a message about "Bluetooth has stopped".
This happens just after registering the GPS Driver. it does not affect the functionality and it is only at the first time.
It has already some permissions in the xml

```<code><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="com.google.android.things.permission.MANAGE_GNSS_DRIVERS" />
    <uses-permission android:name="com.google.android.things.permission.USE_PERIPHERAL_IO" />
</code>```

Looks like it requires to switch the port to GPS or unregister Bluetooth first... By the way I am not using bluetooth feature in the app. any idea?
thanks

```<code>if (context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            Log.e(TAG, "No permission");
            return;
        }

        try {
            // Register the GPS driver
            mGpsDriver = new NmeaGpsDriver(context, "UART0", UART_BAUD, ACCURACY);
            mGpsDriver.register();
</code>```

答:
This is a known limitation of the Raspberry Pi, as per the pinout documentation:

The Raspberry Pi has pins that are multiplexed between various board functions. Some board functions cannot be used simultaneously (for example, enabling Bluetooth and using the UART0 port for peripheral I/O).

So there may be a process running in the background which is still using Bluetooth and causing the driver to crash.

Body:
I am getting an error once I load my app in Android Things on Rasperry PI, it shows a message about "Bluetooth has stopped".
This happens just after registering the GPS Driver. it does not affect the functionality and it is only at the first time.
It has already some permissions in the xml

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="com.google.android.things.permission.MANAGE_GNSS_DRIVERS" />
    <uses-permission android:name="com.google.android.things.permission.USE_PERIPHERAL_IO" />

Looks like it requires to switch the port to GPS or unregister Bluetooth first... By the way I am not using bluetooth feature in the app. any idea?
thanks

if (context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            Log.e(TAG, "No permission");
            return;
        }

        try {
            // Register the GPS driver
            mGpsDriver = new NmeaGpsDriver(context, "UART0", UART_BAUD, ACCURACY);
            mGpsDriver.register();


答:
```<code>const Comp = React.forwardRef((props, ref) => (
  <div ref={ref}> some other stuff here </div>
));

class App extends React.Component{
    constructor(props){
        super(props);
        this.compref = React.createRef();
    }
    componentDidMount(){
        const height = this.compref.clientHeight;
        console.log("hieght", height);
    }
    render(){
        return(
            <div>
                <Comp ref={(el) => this.compref = el} />
            </div>
        )
    }
}

ReactDOM.render(<App />, document.querySelector("#app"))
</code>```

Could you try this way. Hope it helps. Please refer forward refs https://reactjs.org/docs/forwarding-refs.html

Title: React get height of component

Body:
const Comp = React.forwardRef((props, ref) => (
  <div ref={ref}> some other stuff here </div>
));

class App extends React.Component{
    constructor(props){
        super(props);
        this.compref = React.createRef();
    }
    componentDidMount(){
        const height = this.compref.clientHeight;
        console.log("hieght", height);
    }
    render(){
        return(
            <div>
                <Comp ref={(el) => this.compref = el} />
            </div>
        )
    }
}

ReactDOM.render(<App />, document.querySelector("#app"))

Could you try this way. Hope it helps. Please refer forward refs https://reactjs.org/docs/forwarding-refs.html


问:
Is there a R function to order by character or factor of intervals?
After several functions I get a table, which has ordered characters, some starting with "(" or "[" followed by numbers. (intervals, coming from a cut(x) on the data)

What i want to achieve is an order by the startvalue of the invervals, so that (100,124] does not come before (70,100] (see example)
edit: the order of column1 (class) should stay as it is.

well i tried to do it with the order and setorder from data.table but failed so far. I think I need to split the column with strsplit and then order by the first element of it, but that can't be the "best" solution

```<code>test <- data.frame(class = c("class1",   "class1",   "class1",   "class1",   "class2", "class2", "class2", "class2", "class2", "class2", "class2", "class2", "class2"),
                   attr = c("1","2","4","5","(100,124]", "(124,180]" ,"(180,Inf]", "(37,50]" ,  "(5,37]"  ,  "(50,56]"  , "(56,70]"  ,"(70,100]"  ,"[0,5]" ),
                  value = c(415.14,115.13,422.52,37.07,167.40,135.04,67.01,280.03,81.18,237.83,285.62,302.63,3.37))

</code>```

aim:

```<code>class   attr    value
class1  1   415.14
class1  2   115.13
class1  4   422.52
class1  5   37.07
class2  [0,5]   3.37
class2  (5,37]  81.18
class2  (37,50] 280.03
class2  (50,56] 237.83
class2  (56,70] 285.62
class2  (70,100]    302.63
class2  (100,124]   167.40
class2  (124,180]   135.04
class2  (180,Inf]   67.01
</code>```

答:
1) base R Replace comma and everything after it as well as any non-digits with an empty string.  Convert that to numeric and compute the indexes that would order it, o.  Finally subscript test by o.

```<code>o <- with(test, order(class, as.numeric(gsub(",.*|\\D", "", attr))))
test[o, ]
</code>```

giving:

```<code>    class      attr     value
1  class1         1  977.0947
2  class1         2  299.9418
3  class1         4 1398.7519
4  class1         5  170.8434
13 class2     [0,5]  299.1390
9  class2    (5,37]  326.5092
8  class2   (37,50]  923.6778
10 class2   (50,56]  734.9950
11 class2   (56,70]  820.7536
12 class2  (70,100]  779.0926
5  class2 (100,124]  308.5136
6  class2 (124,180]  234.6386
7  class2 (180,Inf]  100.1264
</code>```

1a) This variation would also work. It matches an optional initial non-digit followed by digits followed by anything else and replaces it all with just the digits.  Then it proceeds as above.

```<code>o <- with(test, order(class, as.numeric(gsub("^\\D?(\\d+).*", "\\1", attr))))
test[o, ]
</code>```

2) dplyr

The above could also be done using dplyr arrange like this:

```<code>library(dplyr)

test %>% arrange(class, attr %>% gsub(",.*|\\D", "", .) %>% as.numeric)
</code>```

2a) A variation is to remove (/[ and the comma etc. parts in separate sub statements:

```<code>test %>%
  arrange(class, attr %>%
                   sub("^\\D", "", .) %>%
                   sub(",.*", "", .) %>%
                    as.numeric)
</code>```

Body:
After several functions I get a table, which has ordered characters, some starting with "(" or "[" followed by numbers. (intervals, coming from a cut(x) on the data)

What i want to achieve is an order by the startvalue of the invervals, so that (100,124] does not come before (70,100] (see example)
edit: the order of column1 (class) should stay as it is.

well i tried to do it with the order and setorder from data.table but failed so far. I think I need to split the column with strsplit and then order by the first element of it, but that can't be the "best" solution

test <- data.frame(class = c("class1",   "class1",   "class1",   "class1",   "class2", "class2", "class2", "class2", "class2", "class2", "class2", "class2", "class2"),
                   attr = c("1","2","4","5","(100,124]", "(124,180]" ,"(180,Inf]", "(37,50]" ,  "(5,37]"  ,  "(50,56]"  , "(56,70]"  ,"(70,100]"  ,"[0,5]" ),
                  value = c(415.14,115.13,422.52,37.07,167.40,135.04,67.01,280.03,81.18,237.83,285.62,302.63,3.37))

aim:

class   attr    value
class1  1   415.14
class1  2   115.13
class1  4   422.52
class1  5   37.07
class2  [0,5]   3.37
class2  (5,37]  81.18
class2  (37,50] 280.03
class2  (50,56] 237.83
class2  (56,70] 285.62
class2  (70,100]    302.63
class2  (100,124]   167.40
class2  (124,180]   135.04
class2  (180,Inf]   67.01

Body:
1) base R Replace comma and everything after it as well as any non-digits with an empty string.  Convert that to numeric and compute the indexes that would order it, o.  Finally subscript test by o.

o <- with(test, order(class, as.numeric(gsub(",.*|\\D", "", attr))))
test[o, ]

giving:

    class      attr     value
1  class1         1  977.0947
2  class1         2  299.9418
3  class1         4 1398.7519
4  class1         5  170.8434
13 class2     [0,5]  299.1390
9  class2    (5,37]  326.5092
8  class2   (37,50]  923.6778
10 class2   (50,56]  734.9950
11 class2   (56,70]  820.7536
12 class2  (70,100]  779.0926
5  class2 (100,124]  308.5136
6  class2 (124,180]  234.6386
7  class2 (180,Inf]  100.1264

1a) This variation would also work. It matches an optional initial non-digit followed by digits followed by anything else and replaces it all with just the digits.  Then it proceeds as above.

o <- with(test, order(class, as.numeric(gsub("^\\D?(\\d+).*", "\\1", attr))))
test[o, ]

2) dplyr

The above could also be done using dplyr arrange like this:

library(dplyr)

test %>% arrange(class, attr %>% gsub(",.*|\\D", "", .) %>% as.numeric)

2a) A variation is to remove (/[ and the comma etc. parts in separate sub statements:

test %>%
  arrange(class, attr %>%
                   sub("^\\D", "", .) %>%
                   sub(",.*", "", .) %>%
                    as.numeric)


问:
SQL Server: if "datetime2" < 1753, then "datetime" NULL?
My intention is to insert data from source table into target table. Source table has datetime2 column and target table has datetime column. If datetime2 value does not fit (< year 1753) into datetime field, it will be converted to null. Here is an example

```<code>DROP TABLE dbo.test1
--source table
CREATE TABLE dbo.test1 (wday DATETIME2 NULL)
go

INSERT  INTO dbo.test1
        (wday
        )
        SELECT  '2008-02-01 00:00:00.000'
        UNION ALL
        SELECT  '2009-02-01 00:00:00.000'
        UNION ALL
        SELECT  '0001-02-01 00:00:00.000'

DROP TABLE dbo.test2
--target table
CREATE TABLE dbo.test2 (wday DATETIME NULL)
go

--insert only valid datetime dates, < 1753 will be converted to nulls
INSERT INTO dbo.test2
        (wday
        )
        SELECT  CASE WHEN DATEDIFF(YEAR, dbo.test1.wday, GETDATE()) < 111
                     THEN NULL
                     ELSE CAST(dbo.test1.wday AS DATETIME)
                END
        FROM    dbo.test1
</code>```

The code does not work. Also using datediff here is not valid logic, how to implement this?

答:
why not just</p>

```<code>INSERT  dbo.test2
        (wday
        )
        SELECT  CASE WHEN dbo.test1.wday < '17530101'
                     THEN NULL
                     ELSE CAST(dbo.test1.wday AS DATETIME)
                END
        FROM    dbo.test1
</code>```

Body:
My intention is to insert data from source table into target table. Source table has datetime2 column and target table has datetime column. If datetime2 value does not fit (< year 1753) into datetime field, it will be converted to null. Here is an example

DROP TABLE dbo.test1
--source table
CREATE TABLE dbo.test1 (wday DATETIME2 NULL)
go

INSERT  INTO dbo.test1
        (wday
        )
        SELECT  '2008-02-01 00:00:00.000'
        UNION ALL
        SELECT  '2009-02-01 00:00:00.000'
        UNION ALL
        SELECT  '0001-02-01 00:00:00.000'

DROP TABLE dbo.test2
--target table
CREATE TABLE dbo.test2 (wday DATETIME NULL)
go

--insert only valid datetime dates, < 1753 will be converted to nulls
INSERT INTO dbo.test2
        (wday
        )
        SELECT  CASE WHEN DATEDIFF(YEAR, dbo.test1.wday, GETDATE()) < 111
                     THEN NULL
                     ELSE CAST(dbo.test1.wday AS DATETIME)
                END
        FROM    dbo.test1

The code does not work. Also using datediff here is not valid logic, how to implement this?

Body:
why not just

INSERT  dbo.test2
        (wday
        )
        SELECT  CASE WHEN dbo.test1.wday < '17530101'
                     THEN NULL
                     ELSE CAST(dbo.test1.wday AS DATETIME)
                END
        FROM    dbo.test1


问:
Lodash uniqWith, how say lodash keep last duplicate
Hello i'm using lodash uniqWith method for remove duplicated items which have same id in my array.

but lodash keep first duplicated item.
But i wan't to keep last duplicated item.

what can i do for that ?

```<code>var result = _.uniqWith(editedData, function(arrVal, othVal) {
      return arrVal.id === othVal.id;
    });
    console.log(result)
</code>```

答:
Easiest way? Reverse the array first (after cloning it to avoid mutation).

```<code>var result = _.uniqWith(_.reverse(_.clone(editedData)), function(arrVal, othVal) {...});
</code>```

You can also simplify your code:

```<code>var result = _.uniqWith(_.reverse(_.clone(editedData)), ({ id: a }, { id: b }) => a === b);
</code>```

Body:
Hello i'm using lodash uniqWith method for remove duplicated items which have same id in my array.

but lodash keep first duplicated item.
But i wan't to keep last duplicated item.

what can i do for that ?

var result = _.uniqWith(editedData, function(arrVal, othVal) {
      return arrVal.id === othVal.id;
    });
    console.log(result)

Body:
Easiest way? Reverse the array first (after cloning it to avoid mutation).

var result = _.uniqWith(_.reverse(_.clone(editedData)), function(arrVal, othVal) {...});

You can also simplify your code:

var result = _.uniqWith(_.reverse(_.clone(editedData)), ({ id: a }, { id: b }) => a === b);


问:
Altering a column to be nullable
I want to alter a table column to be nullable. I have used:

```<code>ALTER TABLE Merchant_Pending_Functions Modify NumberOfLocations NULL
</code>```

This gives an error at Modify. What is the correct syntax?

答:
Oracle

ALTER TABLE Merchant_Pending_Functions MODIFY([column]  NOT NULL);

Title: Altering a column to be nullable

Body:
I want to alter a table column to be nullable. I have used:

ALTER TABLE Merchant_Pending_Functions Modify NumberOfLocations NULL

This gives an error at Modify. What is the correct syntax?


问:
I am getting error on submitting the form
While connecting to mongodb, I am getting a warning

"DeprecationWarning: current URL string parser is deprecated, and will
  be removed in a future version. To use the new parser, pass option {
  useNewUrlParser: true } to MongoClient.connect."

while submitting the form - I am getting

The database connection must be open to store files
          at GridFSStorage._handleFile (C:\Users\charan puli\Desktop\upload\node_modules\multer-gridfs-storage\lib\gridfs.js:341:17)
          at C:\Users\charan puli\Desktop\upload\node_modules\multer\lib\make-middleware.js:144:17
          at allowAll (C:\Users\charan puli\Desktop\upload\node_modules\multer\index.js:8:3)
          at wrappedFileFilter (C:\Users\charan puli\Desktop\upload\node_modules\multer\index.js:44:7)
          at Busboy. (C:\Users\charan puli\Desktop\upload\node_modules\multer\lib\make-middleware.js:114:7)
          at Busboy.emit (events.js:182:13)

```<code>//////////////////app.js///////////////////////

//middle wares

app.use(bodyparser.json())

app.use(methodOverride('_method'))

app.set("view engine","ejs")

//connection

var mongoURI='mongodb+srv://user:password@clusterpuli-xs9yc.mongodb.net/test?retryWrites=true'

mongoose.connect(mongoURI,{useNewUrlParser:true})
        .then(()=>{console.log('connected successfully');
        })
        .catch(err=>{console.log(err);
        })

var conn=mongoose.connection
var gfs
conn.once('open',() =>{
gfs = Grid(conn.db, mongoose.mongo);

  gfs.collection('questions')
})
//create storage object

var storage = new GridFsStorage({
    url: mongoURI,
    file: (req, file) => {
      return new Promise((resolve, reject) => {
        crypto.randomBytes(16, (err, buf) => {
          if (err) {
            return reject(err);
          }
          const filename =buf.toString('hex')+path.extname(file.originalname);
          const fileInfo = {
            filename: filename,
            bucketName: 'questions'
          };
          resolve(fileInfo);
        });
      });
    }
  });
  const upload = multer({ storage });
//@route /upload POST

app.post('/upload',upload.single('file'),(req,res)=>{
    res.json({'file':req.file})
})

 var port= 3000
app.get("/",(req,res)=>{
    res.render('index')
})

app.listen(port,()=>{
    console.log(`app is running at ${port}`);

})

////////////////////////////////////
</code>```

expected - json file object, connected Successfully

actual   - database connection must be open

答:
This should work for you, I have tested it:

```<code>//connection

const mongoURI = 'mongodb+srv://user:password@clusterpuli-xs9yc.mongodb.net/test?retryWrites=true';

const promise = mongoose.connect(mongoURI, { useNewUrlParser: true });

const conn = mongoose.connection;
let gfs;

conn.once('open',() => {
  gfs = Grid(conn, mongoose.mongo);
  gfs.collection('questions');
});

//create storage object
const storage = new GridFsStorage({
  db: promise,
  file: (req, file) => {
    return new Promise((resolve, reject) => {
      crypto.randomBytes(16, (err, buf) => {
        if (err) {
          return reject(err);
        }
        const filename = buf.toString('hex') + path.extname(file.originalname);
        const fileInfo = {
          filename: filename,
          bucketName: 'questions'
        };
        resolve(fileInfo);
      });
    });
  }
});
const upload = multer({ storage });
</code>```

See this reference here for further information:
Multer's GridFS storage engine

It has to do with the new url parser of the new mongo client of the Node.js MongoDB Driver API. See this reference: MongoClient

I had the same issue that's why I ended up on your question.

Body:
While connecting to mongodb, I am getting a warning

"DeprecationWarning: current URL string parser is deprecated, and will
  be removed in a future version. To use the new parser, pass option {
  useNewUrlParser: true } to MongoClient.connect."

while submitting the form - I am getting

The database connection must be open to store files
          at GridFSStorage._handleFile (C:\Users\charan puli\Desktop\upload\node_modules\multer-gridfs-storage\lib\gridfs.js:341:17)
          at C:\Users\charan puli\Desktop\upload\node_modules\multer\lib\make-middleware.js:144:17
          at allowAll (C:\Users\charan puli\Desktop\upload\node_modules\multer\index.js:8:3)
          at wrappedFileFilter (C:\Users\charan puli\Desktop\upload\node_modules\multer\index.js:44:7)
          at Busboy. (C:\Users\charan puli\Desktop\upload\node_modules\multer\lib\make-middleware.js:114:7)
          at Busboy.emit (events.js:182:13)

//////////////////app.js///////////////////////

//middle wares

app.use(bodyparser.json())

app.use(methodOverride('_method'))

app.set("view engine","ejs")

//connection

var mongoURI='mongodb+srv://user:password@clusterpuli-xs9yc.mongodb.net/test?retryWrites=true'

mongoose.connect(mongoURI,{useNewUrlParser:true})
        .then(()=>{console.log('connected successfully');
        })
        .catch(err=>{console.log(err);
        })

var conn=mongoose.connection
var gfs
conn.once('open',() =>{
gfs = Grid(conn.db, mongoose.mongo);

  gfs.collection('questions')
})
//create storage object

var storage = new GridFsStorage({
    url: mongoURI,
    file: (req, file) => {
      return new Promise((resolve, reject) => {
        crypto.randomBytes(16, (err, buf) => {
          if (err) {
            return reject(err);
          }
          const filename =buf.toString('hex')+path.extname(file.originalname);
          const fileInfo = {
            filename: filename,
            bucketName: 'questions'
          };
          resolve(fileInfo);
        });
      });
    }
  });
  const upload = multer({ storage });
//@route /upload POST

app.post('/upload',upload.single('file'),(req,res)=>{
    res.json({'file':req.file})
})

 var port= 3000
app.get("/",(req,res)=>{
    res.render('index')
})

app.listen(port,()=>{
    console.log(`app is running at ${port}`);

})

////////////////////////////////////

expected - json file object, connected Successfully

actual   - database connection must be open

Body:
This should work for you, I have tested it:

//connection

const mongoURI = 'mongodb+srv://user:password@clusterpuli-xs9yc.mongodb.net/test?retryWrites=true';

const promise = mongoose.connect(mongoURI, { useNewUrlParser: true });

const conn = mongoose.connection;
let gfs;

conn.once('open',() => {
  gfs = Grid(conn, mongoose.mongo);
  gfs.collection('questions');
});

//create storage object
const storage = new GridFsStorage({
  db: promise,
  file: (req, file) => {
    return new Promise((resolve, reject) => {
      crypto.randomBytes(16, (err, buf) => {
        if (err) {
          return reject(err);
        }
        const filename = buf.toString('hex') + path.extname(file.originalname);
        const fileInfo = {
          filename: filename,
          bucketName: 'questions'
        };
        resolve(fileInfo);
      });
    });
  }
});
const upload = multer({ storage });

See this reference here for further information:
Multer's GridFS storage engine

It has to do with the new url parser of the new mongo client of the Node.js MongoDB Driver API. See this reference: MongoClient

I had the same issue that's why I ended up on your question.


问:
What are Non-overlapping community detection algorithms that I can use using Python iGraph?
What are Non-overlapping community detection algorithms that I can use using Python iGraph?

I tried to search a lot on this but I cound't find answer, please guide me here...

答:
As far as I know most of the community detection algorithms that are implemented in iGraph are for non-overlapping networks.

A quote from the paper A Comparative Analysis of Community Detection Algorithms on Artificial Networks by Yang et. al. goes like this:

In this paper, we evaluate eight different state-of-the-art community detection algorithms available in the
  “igraph” package, which is a widely used collection of network analysis tools in R, Python, C and C++, on the
  LFR benchmark for undirected, unweighted graphs with non-overlapping communities.

This blog post does a good job at comparing various community detection algorithms available in iGraph.


问:
C++ error unexplained: error: expected initializer before '&' token
i know there's a few other posts like this, but i've been on this single error for over an hour now and can't figure it out. here's the code that's giving trouble

```<code>istream& operator>>(istream& in, UndirectedGraph& g)
{
    int numVerticies;
    in >> numVerticies;
    g = UndirectedGraph(numVerticies);

    for(int i = 0; i < numVerticies; i++)
    {
        int temp;
        in >> temp;
        if(temp != i)
        {
            g.linkedAdjacencyList[i]->value = temp;
        }
    }

    int edges;
    in >> edges;
    g.edges = edges;
    for(int i = 0; i < edges; i++)
    {
        int first;
        int second;
        in >> first >> second;
        addEdge(first, second);
    }
    return in;
}

ostream& operator<<(ostream& out, UndirectedGraph& g)
{
    out << g.numVerticies << endl;

    for(int i = 0; i < g.numVerticies; i++)
    {
        out << g.linkedAdjacencyList[i] << " ";
    }
    out << endl;

    out << g.edges << endl;

    for(int i = 0; i < g.numVerticies; i++)
    {
        out << linkedAdjacencyList[i]->value;
        Node* whereto;
        whereto = linkedAdjacencyList[i]->adj;
        while(whereto->adj != NULL)
        {
            out << " " << whereto->value;
            whereto->adj = whereto->adj->adj;
        }
    }
    return out;
}

int main()
{

    ifstream inFile;
    inFile.open("hw8.in");

    UndirectedGraph graph;
    inFile >> graph;
</code>```

...

here, the errors are on lines 1 and 28, with the overloading of istream and ostream.

Thanks for your help!

答:
There seem to be a couple of problems. Firstly, are the insertion and extraction operators member methods or just helper functions? For the latter, the signature would be something like

```<code>istream & operator>>(istream& in, UndirectedGraph &g)
</code>```

For the former

```<code>istream &UndirectedGraph::operator>>(istream& in, UndirectedGraph &g)
</code>```

In either case, as illustrated above, you should make the UndirectedGraph parameter a reference argument. Otherwise, you are just passing in the parameter by value, which is probably not what you want.

Body:
i know there's a few other posts like this, but i've been on this single error for over an hour now and can't figure it out. here's the code that's giving trouble

istream& operator>>(istream& in, UndirectedGraph& g)
{
    int numVerticies;
    in >> numVerticies;
    g = UndirectedGraph(numVerticies);

    for(int i = 0; i < numVerticies; i++)
    {
        int temp;
        in >> temp;
        if(temp != i)
        {
            g.linkedAdjacencyList[i]->value = temp;
        }
    }

    int edges;
    in >> edges;
    g.edges = edges;
    for(int i = 0; i < edges; i++)
    {
        int first;
        int second;
        in >> first >> second;
        addEdge(first, second);
    }
    return in;
}

ostream& operator<<(ostream& out, UndirectedGraph& g)
{
    out << g.numVerticies << endl;

    for(int i = 0; i < g.numVerticies; i++)
    {
        out << g.linkedAdjacencyList[i] << " ";
    }
    out << endl;

    out << g.edges << endl;

    for(int i = 0; i < g.numVerticies; i++)
    {
        out << linkedAdjacencyList[i]->value;
        Node* whereto;
        whereto = linkedAdjacencyList[i]->adj;
        while(whereto->adj != NULL)
        {
            out << " " << whereto->value;
            whereto->adj = whereto->adj->adj;
        }
    }
    return out;
}

int main()
{

    ifstream inFile;
    inFile.open("hw8.in");

    UndirectedGraph graph;
    inFile >> graph;

...

here, the errors are on lines 1 and 28, with the overloading of istream and ostream.

Thanks for your help!

Body:
There seem to be a couple of problems. Firstly, are the insertion and extraction operators member methods or just helper functions? For the latter, the signature would be something like

istream & operator>>(istream& in, UndirectedGraph &g)

For the former

istream &UndirectedGraph::operator>>(istream& in, UndirectedGraph &g)

In either case, as illustrated above, you should make the UndirectedGraph parameter a reference argument. Otherwise, you are just passing in the parameter by value, which is probably not what you want.


问:
Updates doesn't take affect in django orm, Is there something wrong in my code?
I need to update multiple rows in a url_field in one of my models, each product_id has its own corresponding new values to be loading. What's wrong with my code? No errors are returned.

```<code>idlist= ["",""]
url = ["https://www.sample.com","https://www.sample2.com"]
i = 0

while i < len(item_idlist):
Model.objects.filter(item_id=idlist[i].update(product_url=url[i]))
i += 1
</code>```

I expect that every iterations will update my data inside the model.

答:
You could use a for loop combined with zip:

```<code>for id, url in zip(idlist, urls):
     m = Model.objects.filter(item_id=id)
     m.update(product_url = url)
</code>```

Body:
I need to update multiple rows in a url_field in one of my models, each product_id has its own corresponding new values to be loading. What's wrong with my code? No errors are returned.

idlist= ["",""]
url = ["https://www.sample.com","https://www.sample2.com"]
i = 0

while i < len(item_idlist):
Model.objects.filter(item_id=idlist[i].update(product_url=url[i]))
i += 1

I expect that every iterations will update my data inside the model.

Body:
You could use a for loop combined with zip:

for id, url in zip(idlist, urls):
     m = Model.objects.filter(item_id=id)
     m.update(product_url = url)


问:
EXISTS not working with subquery in WITH clause
I ran into a query where the EXISTS clause is not working properly. The query returns results even for items where no matching record exist, seemingly ignoring the EXISTS completely. It used to work fine and I think the troubles started after upgrading from Oracle 12.1 to 12.2.

Below is the complete query (only changed table & column names to make them a little more readable, but I left all the logic in case it's related to that):

```<code>WITH FirstDateFilter AS (
    SELECT ReferenceDate,
           Type,
           LAG(Type, 1, 0) OVER (ORDER BY ReferenceDate) AS PreviousType
    FROM ReferenceDateTable
    WHERE ItemId = :itemId
    AND   ReferenceDate <= :endDate
    AND   Type IN (:type1, :type2)
), SecondDateFilter AS (
    SELECT ReferenceDate
    FROM FirstDateFilter
    WHERE ReferenceDate >= :startDate
    AND   ReferenceDate >= ( SELECT StartDate FROM StartDateTable WHERE ItemId = :itemId )
    AND   Type = :type1
    AND   PreviousType = :type1
)
SELECT ReferenceDate, Value
FROM ResultTable
WHERE ItemId = :itemId
AND EXISTS ( SELECT * FROM SecondDateFilter WHERE SecondDateFilter.ReferenceDate = ResultTable.ReferenceDate )
</code>```

After playing around with some test data, I think the (partially?) responsible line for the failure is the subquery AND   ReferenceDate >= ( SELECT StartDate FROM StartDateTable WHERE ItemId = :itemId ) in the second WITH.

I have found that any of the following edits result in the EXISTS working as expected again:

JOIN ResultTable with SecondDateFilter (on ReferenceDate)

Put ( SELECT ReferenceDate FROM SecondDateFilter WHERE SecondDateFilter.ReferenceDate = ResultTable.ReferenceDate ) in the SELECT ... FROM ResultTable

Comment out StartDateTable subquery (no longer filtering on that table, but otherwise it works again)

Move StartDateTable subquery to the first WITH

The last solution actually fixes my problem with this query (technically not the same, but the underlying business logic checks out that the result will always be the same), but I was wondering if there was a general problem with the EXISTS clause (potentially only in Oracle 12.2?) that I should be aware of. I have a lot more queries that make use of it.

Below is a test script that duplicates the error. The query below returns 2 rows as expected, but removing the commented line gives 5 rows.

```<code>CREATE TABLE ReferenceDateTable
    (
     ItemId number,
     ReferenceDate date,
     Type varchar2(1)
    );
INSERT INTO ReferenceDateTable (ItemId, ReferenceDate, Type) VALUES (1, to_date('19000201', 'YYYYMMDD'), '1');
INSERT INTO ReferenceDateTable (ItemId, ReferenceDate, Type) VALUES (1, to_date('19000202', 'YYYYMMDD'), '1');
INSERT INTO ReferenceDateTable (ItemId, ReferenceDate, Type) VALUES (1, to_date('19000203', 'YYYYMMDD'), '2');
INSERT INTO ReferenceDateTable (ItemId, ReferenceDate, Type) VALUES (1, to_date('19000204', 'YYYYMMDD'), '1');
INSERT INTO ReferenceDateTable (ItemId, ReferenceDate, Type) VALUES (1, to_date('19000205', 'YYYYMMDD'), '1');

CREATE TABLE ResultTable
    (
     ItemId number,
     ReferenceDate date,
     Value number
    );
INSERT INTO ResultTable (ItemId, ReferenceDate, Value) VALUES (1, to_date('19000201', 'YYYYMMDD'), 1);
INSERT INTO ResultTable (ItemId, ReferenceDate, Value) VALUES (1, to_date('19000202', 'YYYYMMDD'), 2);
INSERT INTO ResultTable (ItemId, ReferenceDate, Value) VALUES (1, to_date('19000203', 'YYYYMMDD'), 3);
INSERT INTO ResultTable (ItemId, ReferenceDate, Value) VALUES (1, to_date('19000204', 'YYYYMMDD'), 4);
INSERT INTO ResultTable (ItemId, ReferenceDate, Value) VALUES (1, to_date('19000205', 'YYYYMMDD'), 5);

CREATE TABLE StartDateTable
    (
     ItemId number,
     StartDate date
    );
INSERT INTO StartDateTable (ItemId, StartDate) VALUES (1, to_date('19000101', 'YYYYMMDD'));

WITH FirstDateFilter AS (
    SELECT ReferenceDate,
           Type,
           LAG(Type, 1, 0) OVER (ORDER BY ReferenceDate) AS PreviousType
    FROM ReferenceDateTable
    WHERE ItemId = 1
    AND   ReferenceDate <= to_date('19000205', 'YYYYMMDD')
    AND   Type IN ('1', '2')
), SecondDateFilter AS (
    SELECT ReferenceDate
    FROM FirstDateFilter
    WHERE ReferenceDate >= to_date('19000201', 'YYYYMMDD')
    --AND   ReferenceDate >= ( SELECT StartDate FROM StartDateTable WHERE ItemId = 1 )
    AND   Type = '1'
    AND   PreviousType = '1'
)
SELECT ReferenceDate, Value
FROM ResultTable
WHERE ItemId = 1
AND EXISTS ( SELECT * FROM SecondDateFilter WHERE SecondDateFilter.ReferenceDate = ResultTable.ReferenceDate )
;
</code>```

答:
As per Jonathan's comments over on Twitter, the suggested workaround is to use the unnest hint in the outer exists subquery, as the issue is due to a bug (potentially Bug 28319114).

```<code>[...]
SELECT ReferenceDate, Value
FROM ResultTable
WHERE ItemId = 1
AND EXISTS ( SELECT /*+ UNNEST */ * FROM SecondDateFilter WHERE SecondDateFilter.ReferenceDate = ResultTable.ReferenceDate )
</code>```

Body:
I ran into a query where the EXISTS clause is not working properly. The query returns results even for items where no matching record exist, seemingly ignoring the EXISTS completely. It used to work fine and I think the troubles started after upgrading from Oracle 12.1 to 12.2.

Below is the complete query (only changed table & column names to make them a little more readable, but I left all the logic in case it's related to that):

WITH FirstDateFilter AS (
    SELECT ReferenceDate,
           Type,
           LAG(Type, 1, 0) OVER (ORDER BY ReferenceDate) AS PreviousType
    FROM ReferenceDateTable
    WHERE ItemId = :itemId
    AND   ReferenceDate <= :endDate
    AND   Type IN (:type1, :type2)
), SecondDateFilter AS (
    SELECT ReferenceDate
    FROM FirstDateFilter
    WHERE ReferenceDate >= :startDate
    AND   ReferenceDate >= ( SELECT StartDate FROM StartDateTable WHERE ItemId = :itemId )
    AND   Type = :type1
    AND   PreviousType = :type1
)
SELECT ReferenceDate, Value
FROM ResultTable
WHERE ItemId = :itemId
AND EXISTS ( SELECT * FROM SecondDateFilter WHERE SecondDateFilter.ReferenceDate = ResultTable.ReferenceDate )

After playing around with some test data, I think the (partially?) responsible line for the failure is the subquery AND   ReferenceDate >= ( SELECT StartDate FROM StartDateTable WHERE ItemId = :itemId ) in the second WITH.

I have found that any of the following edits result in the EXISTS working as expected again:

JOIN ResultTable with SecondDateFilter (on ReferenceDate)

Put ( SELECT ReferenceDate FROM SecondDateFilter WHERE SecondDateFilter.ReferenceDate = ResultTable.ReferenceDate ) in the SELECT ... FROM ResultTable

Comment out StartDateTable subquery (no longer filtering on that table, but otherwise it works again)

Move StartDateTable subquery to the first WITH

The last solution actually fixes my problem with this query (technically not the same, but the underlying business logic checks out that the result will always be the same), but I was wondering if there was a general problem with the EXISTS clause (potentially only in Oracle 12.2?) that I should be aware of. I have a lot more queries that make use of it.

Below is a test script that duplicates the error. The query below returns 2 rows as expected, but removing the commented line gives 5 rows.

CREATE TABLE ReferenceDateTable
    (
     ItemId number,
     ReferenceDate date,
     Type varchar2(1)
    );
INSERT INTO ReferenceDateTable (ItemId, ReferenceDate, Type) VALUES (1, to_date('19000201', 'YYYYMMDD'), '1');
INSERT INTO ReferenceDateTable (ItemId, ReferenceDate, Type) VALUES (1, to_date('19000202', 'YYYYMMDD'), '1');
INSERT INTO ReferenceDateTable (ItemId, ReferenceDate, Type) VALUES (1, to_date('19000203', 'YYYYMMDD'), '2');
INSERT INTO ReferenceDateTable (ItemId, ReferenceDate, Type) VALUES (1, to_date('19000204', 'YYYYMMDD'), '1');
INSERT INTO ReferenceDateTable (ItemId, ReferenceDate, Type) VALUES (1, to_date('19000205', 'YYYYMMDD'), '1');

CREATE TABLE ResultTable
    (
     ItemId number,
     ReferenceDate date,
     Value number
    );
INSERT INTO ResultTable (ItemId, ReferenceDate, Value) VALUES (1, to_date('19000201', 'YYYYMMDD'), 1);
INSERT INTO ResultTable (ItemId, ReferenceDate, Value) VALUES (1, to_date('19000202', 'YYYYMMDD'), 2);
INSERT INTO ResultTable (ItemId, ReferenceDate, Value) VALUES (1, to_date('19000203', 'YYYYMMDD'), 3);
INSERT INTO ResultTable (ItemId, ReferenceDate, Value) VALUES (1, to_date('19000204', 'YYYYMMDD'), 4);
INSERT INTO ResultTable (ItemId, ReferenceDate, Value) VALUES (1, to_date('19000205', 'YYYYMMDD'), 5);

CREATE TABLE StartDateTable
    (
     ItemId number,
     StartDate date
    );
INSERT INTO StartDateTable (ItemId, StartDate) VALUES (1, to_date('19000101', 'YYYYMMDD'));

WITH FirstDateFilter AS (
    SELECT ReferenceDate,
           Type,
           LAG(Type, 1, 0) OVER (ORDER BY ReferenceDate) AS PreviousType
    FROM ReferenceDateTable
    WHERE ItemId = 1
    AND   ReferenceDate <= to_date('19000205', 'YYYYMMDD')
    AND   Type IN ('1', '2')
), SecondDateFilter AS (
    SELECT ReferenceDate
    FROM FirstDateFilter
    WHERE ReferenceDate >= to_date('19000201', 'YYYYMMDD')
    --AND   ReferenceDate >= ( SELECT StartDate FROM StartDateTable WHERE ItemId = 1 )
    AND   Type = '1'
    AND   PreviousType = '1'
)
SELECT ReferenceDate, Value
FROM ResultTable
WHERE ItemId = 1
AND EXISTS ( SELECT * FROM SecondDateFilter WHERE SecondDateFilter.ReferenceDate = ResultTable.ReferenceDate )
;

Body:
As per Jonathan's comments over on Twitter, the suggested workaround is to use the unnest hint in the outer exists subquery, as the issue is due to a bug (potentially Bug 28319114).

[...]
SELECT ReferenceDate, Value
FROM ResultTable
WHERE ItemId = 1
AND EXISTS ( SELECT /*+ UNNEST */ * FROM SecondDateFilter WHERE SecondDateFilter.ReferenceDate = ResultTable.ReferenceDate )


问:
Grails 3.3.10 urlmapping doesn't work anymore
I just update my app to grails 3.3.10.
It's a simple app that use spring security 3.2.3.
My url map is this:

```<code>class UrlMappings {

    static mappings = {
        "/$controller/$action?/$id?(.$format)?" {
            constraints {
                // apply constraints here
            }
        }

        "/"(controller: "home", action: "index")
        "500"(controller: "error", action: "error500", [params: params])
        "404"(view: '/error/notFound')
    }
}
</code>```

after update from 3.3.9 to 3.3.10 the / is not anymore redirect to home controller.
If I roll back it then it works again.
Documentation on grails web site has a broken link for 3.3.10 version. They change something or it sounds to me it's a bug. Any ideas?

UPDATE
thanks to @MiloBen I did a step forward, and now I it seems to be redirect to home but now I got a 403 in the home page. Let me recap.
My UrlsMapping.groovy is the same, see above.
My application.groovy is this now:

```<code>[pattern: '/', access: ['permitAll']],
[pattern: '/error', access: ['permitAll']],
[pattern: '/login/**', access: ['permitAll']],
[pattern: '/assets/**', access: ['permitAll']],
[pattern: '/home/**', access: ['permitAll']]
</code>```

I cannot figure out what is the problem now, it seems permitAll should kick in and let me see my home page /home, which is redirected in / by the UrlMapping.

答:
I had similar issue.

In the file grails-app/conf/application.groovy I found these lines:

```<code>    [pattern: '/index', access: 'permitAll'],
    [pattern: '/index.gsp', access: 'permitAll'],
</code>```

I did not have index.gsp file the lines referred to, but it somehow worked in grails 3.3.8 and started failing in 3.3.10. Removing those two lines fixed my issue.

Body:
I just update my app to grails 3.3.10.
It's a simple app that use spring security 3.2.3.
My url map is this:

class UrlMappings {

    static mappings = {
        "/$controller/$action?/$id?(.$format)?" {
            constraints {
                // apply constraints here
            }
        }

        "/"(controller: "home", action: "index")
        "500"(controller: "error", action: "error500", [params: params])
        "404"(view: '/error/notFound')
    }
}

after update from 3.3.9 to 3.3.10 the / is not anymore redirect to home controller.
If I roll back it then it works again.
Documentation on grails web site has a broken link for 3.3.10 version. They change something or it sounds to me it's a bug. Any ideas?

UPDATE
thanks to @MiloBen I did a step forward, and now I it seems to be redirect to home but now I got a 403 in the home page. Let me recap.
My UrlsMapping.groovy is the same, see above.
My application.groovy is this now:

[pattern: '/', access: ['permitAll']],
[pattern: '/error', access: ['permitAll']],
[pattern: '/login/**', access: ['permitAll']],
[pattern: '/assets/**', access: ['permitAll']],
[pattern: '/home/**', access: ['permitAll']]

I cannot figure out what is the problem now, it seems permitAll should kick in and let me see my home page /home, which is redirected in / by the UrlMapping.

Body:
I had similar issue.

In the file grails-app/conf/application.groovy I found these lines:

    [pattern: '/index', access: 'permitAll'],
    [pattern: '/index.gsp', access: 'permitAll'],

I did not have index.gsp file the lines referred to, but it somehow worked in grails 3.3.8 and started failing in 3.3.10. Removing those two lines fixed my issue.


问:
How to check if a column exists in a SQL Server table
I need to add a specific column if it does not exist. I have something like the following, but it always returns false:

```<code>IF EXISTS(SELECT *
          FROM   INFORMATION_SCHEMA.COLUMNS
          WHERE  TABLE_NAME = 'myTableName'
                 AND COLUMN_NAME = 'myColumnName')
</code>```

How can I check if a column exists in a table of the SQL Server database?

答:
Execute the below query to check if the column exists in the given table:</p>

```<code>IF(SELECT COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'TableName' AND COLUMN_NAME = 'ColumnName') IS NOT NULL
PRINT 'Column Exists in the given table';
</code>```

OwnerDisplayName: Maciej

Body:
I need to add a specific column if it does not exist. I have something like the following, but it always returns false:

IF EXISTS(SELECT *
          FROM   INFORMATION_SCHEMA.COLUMNS
          WHERE  TABLE_NAME = 'myTableName'
                 AND COLUMN_NAME = 'myColumnName')

How can I check if a column exists in a table of the SQL Server database?

LastEditorDisplayName: Maciej

Body:
Execute the below query to check if the column exists in the given table:

IF(SELECT COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'TableName' AND COLUMN_NAME = 'ColumnName') IS NOT NULL
PRINT 'Column Exists in the given table';


问:
How do I properly fade in and out using jQuery?
Can anyone help me with this simple bit of jQuery? I am building a carousel that features many sliding
s. Each one has a short description accompanying it, which I want to fade out when the carousel slides, and fade in when the carousel stops at another
. The problem is that when the carousel controls are clicked rapidly, the fades take a while to catch up. Also the current simple fadeIn/Out option doesn't work well when clicking to an
 much further through the carousel (from the small grey discs underneath infographic). I've tried a few options but I'm not really getting anywhere.

The page is here: http://weaver-wp.weavertest.com/radiation-infographic/

Thanks for any help :)

David

答:
The trick is to stop the operation before you start the next one:

http://api.jquery.com/stop/

bottom line, you stop all previous animations before you call in the next one. This avoids building up a queue of animations.