问:
R: Merge lists containing vectors and scalars
I have N lists that have some identical column names. Here is a MWE with two list:

```<code>ls <- list()
ls[[1]] <- list("a"=1:2,
                "b"=20,
                "c"=numeric(0))
names(ls[[1]]$a) <- c("a1", "a2")

ls[[2]] <- list("a"=3:4,
                "b"=30,
                "c"=1:4,
                "d"="f")
names(ls[[2]]$a) <- c("a1", "a2")
</code>```

Is it possible merge these into a resulting list lsRes, where lsRes has the following properties:

lsRes$a contains two elements, where the first is the named vector
c(1,2) (with names c(a1, a2)) and the second a named vector c(3,4)
(with names (c(a1.a2)))

lsRes$b contains two elements, where the first is 20 and the second is 30

lsRes$c contains two elements, where the first is numeric(0) and the second is 1:4

lsRes$d contains
two elements, where the first is NA and the second is "f"

I looked at this and this, but they describe different cases

答:
Assuming that we need to have the output also as a list, we create the common names and then assign those doesn't any of the common names to NA

```<code>nm1 <- unique(unlist(sapply(ls, names)))
lsRes <- lapply(ls, function(x) {x[setdiff(nm1, names(x))] <- NA; x})
lengths(lsRes)
#[1] 4 4
</code>```

If we need to have a list of 4 elements, then use transpose

```<code>library(purrr)
lsRes %>%
      transpose
</code>```

Body:
I have N lists that have some identical column names. Here is a MWE with two list:

ls <- list()
ls[[1]] <- list("a"=1:2,
                "b"=20,
                "c"=numeric(0))
names(ls[[1]]$a) <- c("a1", "a2")

ls[[2]] <- list("a"=3:4,
                "b"=30,
                "c"=1:4,
                "d"="f")
names(ls[[2]]$a) <- c("a1", "a2")

Is it possible merge these into a resulting list lsRes, where lsRes has the following properties:

lsRes$a contains two elements, where the first is the named vector
c(1,2) (with names c(a1, a2)) and the second a named vector c(3,4)
(with names (c(a1.a2)))

lsRes$b contains two elements, where the first is 20 and the second is 30

lsRes$c contains two elements, where the first is numeric(0) and the second is 1:4

lsRes$d contains
two elements, where the first is NA and the second is "f"

I looked at this and this, but they describe different cases

Body:
Assuming that we need to have the output also as a list, we create the common names and then assign those doesn't any of the common names to NA

nm1 <- unique(unlist(sapply(ls, names)))
lsRes <- lapply(ls, function(x) {x[setdiff(nm1, names(x))] <- NA; x})
lengths(lsRes)
#[1] 4 4

If we need to have a list of 4 elements, then use transpose

library(purrr)
lsRes %>%
      transpose


来源: stackexchange

问:
Jquery slideToggle help!
Is there any other way to do slide toggle, couse in IE7 does´t work!?

*$(document).ready(function() {

$(".tela").hide();

```<code>   $("li.menu-pai").click(function(){
      $(this).show().next().slideToggle("fast");
 });
</code>```

})*

```<code><div id="menu_sidebar">
     <ul>
        <li class="menu-pai"><a href="#">Iltem</a></li>
            <ul class="tela">
                <li><a href="#">sub-item</a></li>
            <li><a href="#">sub-item</a></li>
                        <li><a href="#">sub-item</a></li>
                </ul>
        </ul>
</div>
</code>```

答:
try put ul inside li

```<code><div id="menu_sidebar">
     <ul>
        <li class="menu-pai"><a href="#">Iltem</a>
            <ul class="tela">
               <li><a href="#">sub-item</a></li>
               <li><a href="#">sub-item</a></li>
               <li><a href="#">sub-item</a></li>
            </ul></li>
        <li>Other Item</li>
     </ul>
</div>
</code>```

and call

```<code>$("#menu_sidebar li.menu-pai a").click(function(){
   $(this).find('ul').slideToggle("fast");
});
</code>```

I don't know if this is going to work.

And don't use show/hide methods if you use slide, call .slideUp(0); at start.

ContentLicense: CC BY-SA 2.5

Title: Jquery slideToggle help!

Body:
Is there any other way to do slide toggle, couse in IE7 does´t work!?

*$(document).ready(function() {

$(".tela").hide();

   $("li.menu-pai").click(function(){
      $(this).show().next().slideToggle("fast");
 });

})*

Iltem

sub-item

sub-item

sub-item

Body:
try put ul inside li

<div id="menu_sidebar">
     <ul>
        <li class="menu-pai"><a href="#">Iltem</a>
            <ul class="tela">
               <li><a href="#">sub-item</a></li>
               <li><a href="#">sub-item</a></li>
               <li><a href="#">sub-item</a></li>
            </ul></li>
        <li>Other Item</li>
     </ul>
</div>

and call

$("#menu_sidebar li.menu-pai a").click(function(){
   $(this).find('ul').slideToggle("fast");
});

I don't know if this is going to work.

And don't use show/hide methods if you use slide, call .slideUp(0); at start.


问:
caffe2 Tensor<CUDAContext> assignment, construction or copy
This is a long shot, if you think the question is too localized, please do vote to close. I have searched on the caffe2 github repository, opened an issue asking the same question, opened another issue at the caffe2_ccp_tutorials repository because its author seems to understand it best, read the doxygen documentation on caffe2::Tensor and caffe2::CUDAContext,
and even gone through the caffe2 source code, and in specific the tensor.h, context_gpu.h and context_gpu.cc.

I understand that currently caffe2 does not allow copying device memory to a tensor. I am willing to expand the library and do a pull request in order to achieve this. My reason behind this is that I do all image pre-processing using cv::cuda::* methods which operate on device memory, and as such I think it is clearly a problem doing the pre-processing on the gpu, only to download the result back on the host, and then have it re-uploaded to the network from host to device.

Looking at the constructors of Tensor<Context> I can see that maybe only

```<code>template<class SrcContext , class ContextForCopy >
Tensor (const Tensor< SrcContext > &src, ContextForCopy *context)
</code>```

might achieve what I want, but I have no idea how to set the <ContextForCopy> and then use it for construction.

Furthermore, I see that I can construct the Tensor with the correct dimensions, and then maybe using

```<code>template <typename T>
T* mutable_data()
</code>```

I can assign/copy the data.
The data itself is stored in std::vector<cv::cuda::GpuMat, so I will have to iterate it, and then use either cuda::PtrStepSz or cuda::PtrStep to access the underlying device allocated data.
That is the same data that I need to copy/assign into the caffe2::Tensor<CUDAContext>.

I've been trying to find out how internally the Tensor<CPUContext> is copied to Tensor<CUDAContext> since I've seen examples of it, but I can't figure it out, although I think the method used is CopyFrom. The usual examples as already mentioned, copy from CPU to GPU:

```<code>TensorCPU tensor_cpu(...);
TensorCUDA tensor_cuda = workspace.CreateBlob("input")->GetMutable<TensorCUDA>();
tensor_cuda->ResizeLike(tensor_cpu);
tensor_cuda->ShareData(tensor_cpu);
</code>```

I am quite suprised nobody has run into this task yet, and a brief search yields only one open issue where the author (@peterneher) is asking the same thing more or less.

答:
I have managed to figure this out.
The simplest way is to tell OpenCV which memory location to use.
This can be done by using the 7th and 8th overload of the cv::cuda::GpuMat constructor shown below:

```<code>cv::cuda::GpuMat::GpuMat(int    rows,
                         int    cols,
                         int    type,
                         void *     data,
                         size_t     step = Mat::AUTO_STEP
                        )

cv::cuda::GpuMat::GpuMat(Size   size,
                         int    type,
                         void *     data,
                         size_t     step = Mat::AUTO_STEP
                        )
</code>```

Doing so implies that the caffe2::TensorCUDA has been declared and allocated beforehand:

```<code>std::vector<caffe2::TIndex> dims({1, 3, 224, 224});
caffe2::TensorCUDA tensor;
auto ptr = tensor.mutable_data<float>();
cv::cuda::GpuMat matrix(224, 224, CV_32F, ptr);
</code>```

For example, processing a 3 channel BGR float matrix using cv::cuda::split:

```<code>cv::cuda::GpuMat mfloat;
// TODO: put your BGR float data in `mfloat`
auto ptr = tensor.mutable_data<float>();
size_t width = mfloat.cols * mfloat.rows;
std::vector<cv::cuda::GpuMat> input_channels {
    cv::cuda::GpuMat(mfloat.rows, mfloat.cols, CV_32F, &ptr[0]),
    cv::cuda::GpuMat(mfloat.rows, mfloat.cols, CV_32F, &ptr[width]),
    cv::cuda::GpuMat(mfloat.rows, mfloat.cols, CV_32F, &ptr[width * 2])
};
cv::cuda::split(mfloat, input_channels);
</code>```

Hope this will help anyone dwelling into the C++ side of Caffe2.

NOTE that caffe2::Predictor won't work with caffe2::TensorCUDA, you will have instead to manually propagate the tensor.
For more information on this, the caffe2_cpp_tutorial mnist.cc.

ContentLicense: CC BY-SA 3.0

Body:
This is a long shot, if you think the question is too localized, please do vote to close. I have searched on the caffe2 github repository, opened an issue asking the same question, opened another issue at the caffe2_ccp_tutorials repository because its author seems to understand it best, read the doxygen documentation on caffe2::Tensor and caffe2::CUDAContext,
and even gone through the caffe2 source code, and in specific the tensor.h, context_gpu.h and context_gpu.cc.

I understand that currently caffe2 does not allow copying device memory to a tensor. I am willing to expand the library and do a pull request in order to achieve this. My reason behind this is that I do all image pre-processing using cv::cuda::* methods which operate on device memory, and as such I think it is clearly a problem doing the pre-processing on the gpu, only to download the result back on the host, and then have it re-uploaded to the network from host to device.

Looking at the constructors of Tensor<Context> I can see that maybe only

template<class SrcContext , class ContextForCopy >
Tensor (const Tensor< SrcContext > &src, ContextForCopy *context)

might achieve what I want, but I have no idea how to set the <ContextForCopy> and then use it for construction.

Furthermore, I see that I can construct the Tensor with the correct dimensions, and then maybe using

template <typename T>
T* mutable_data()

I can assign/copy the data.
The data itself is stored in std::vector<cv::cuda::GpuMat, so I will have to iterate it, and then use either cuda::PtrStepSz or cuda::PtrStep to access the underlying device allocated data.
That is the same data that I need to copy/assign into the caffe2::Tensor<CUDAContext>.

I've been trying to find out how internally the Tensor<CPUContext> is copied to Tensor<CUDAContext> since I've seen examples of it, but I can't figure it out, although I think the method used is CopyFrom. The usual examples as already mentioned, copy from CPU to GPU:

TensorCPU tensor_cpu(...);
TensorCUDA tensor_cuda = workspace.CreateBlob("input")->GetMutable<TensorCUDA>();
tensor_cuda->ResizeLike(tensor_cpu);
tensor_cuda->ShareData(tensor_cpu);

I am quite suprised nobody has run into this task yet, and a brief search yields only one open issue where the author (@peterneher) is asking the same thing more or less.

Body:
I have managed to figure this out.
The simplest way is to tell OpenCV which memory location to use.
This can be done by using the 7th and 8th overload of the cv::cuda::GpuMat constructor shown below:

cv::cuda::GpuMat::GpuMat(int    rows,
                         int    cols,
                         int    type,
                         void *     data,
                         size_t     step = Mat::AUTO_STEP
                        )

cv::cuda::GpuMat::GpuMat(Size   size,
                         int    type,
                         void *     data,
                         size_t     step = Mat::AUTO_STEP
                        )

Doing so implies that the caffe2::TensorCUDA has been declared and allocated beforehand:

std::vector<caffe2::TIndex> dims({1, 3, 224, 224});
caffe2::TensorCUDA tensor;
auto ptr = tensor.mutable_data<float>();
cv::cuda::GpuMat matrix(224, 224, CV_32F, ptr);

For example, processing a 3 channel BGR float matrix using cv::cuda::split:

cv::cuda::GpuMat mfloat;
// TODO: put your BGR float data in `mfloat`
auto ptr = tensor.mutable_data<float>();
size_t width = mfloat.cols * mfloat.rows;
std::vector<cv::cuda::GpuMat> input_channels {
    cv::cuda::GpuMat(mfloat.rows, mfloat.cols, CV_32F, &ptr[0]),
    cv::cuda::GpuMat(mfloat.rows, mfloat.cols, CV_32F, &ptr[width]),
    cv::cuda::GpuMat(mfloat.rows, mfloat.cols, CV_32F, &ptr[width * 2])
};
cv::cuda::split(mfloat, input_channels);

Hope this will help anyone dwelling into the C++ side of Caffe2.

NOTE that caffe2::Predictor won't work with caffe2::TensorCUDA, you will have instead to manually propagate the tensor.
For more information on this, the caffe2_cpp_tutorial mnist.cc.


问:
What is the purpose of inheriting from enable_shared_from_this?
What is the point for a class T to inherit from std::enable_shared_from_this<T> ? I can't seem to figure out why you wouldn't just create a std::shared_ptr<this> ?

答:
Cppreference has a good example on why.

If you want to return a std::shared_ptr of this while *this is already owned by a std::shared_ptr and you don't return shared_from_this() but return a new std::shared_ptr<T>(this) instead then you will end up with 2 shared pointers that don't know they're both owning the same object and thus the use_count() will be wrong which will cause a double delete, which is undefined behavior.


问:
TypoScript to add a class only for "li" elements belonging to an "ol" list
the next TS code works great for my TYPO3 7.6 installation:

```<code>tt_content.highlight_list.20.text.20.parseFunc.externalBlocks = table,blockquote,ol,li,ul
tt_content.highlight_list.20.text.20.parseFunc.externalBlocks {
    ul {
        stripNL = 1
        callRecursive = 1
        callRecursive.tagStdWrap.HTMLparser.tags.ul.fixAttrib.class.default = row
    }
    li {
        stripNL = 1
        callRecursive = 1
        callRecursive.tagStdWrap.HTMLparser = 1
        callRecursive.tagStdWrap.HTMLparser.tags.li.fixAttrib.class.default = col-4 col-sm-2 col-md-2
    }
    ol {
        stripNL = 1
        callRecursive = 1
        callRecursive.tagStdWrap.HTMLparser = 1
    }
}
</code>```

Now I would like the class col-4 col-sm-2 col-md-2 is not present for li items only belonging to ol elements. For ul, they should be kept.

Trying the next line (or other variants) just breaks the markup:

```<code>tt_content.highlight_list.20.text.20.parseFunc.externalBlocks.ol.callRecursive.tagStdWrap.HTMLparser.tags.li.fixAttrib.class.default =
</code>```

Any hints?

答:
What I don't understand is that for TYPO3 6.1.12, the next Typoscript added the classes "col-4.col-sm-2.col-md-2" only to "ol" lists:</p>

```<code>tt_content.highlight_list.20.text.20.parseFunc.externalBlocks = table,blockquote,ol,ul,li
tt_content.highlight_list.20.text.20.parseFunc.externalBlocks {
  li.stripNL = 1
  li.callRecursive = 1
  li.callRecursive.tagStdWrap.HTMLparser = 1
  li.callRecursive.tagStdWrap.HTMLparser.tags.li {
    fixAttrib.class.default = col-4 col-sm-2 col-md-2
  }
  ul.stripNL = 1
  ul.callRecursive = 1
  ul.callRecursive.tagStdWrap.HTMLparser = 1
  ul.callRecursive.tagStdWrap.HTMLparser.tags.ul {
    fixAttrib.class.default = row
  }
}
</code>```

Body:
the next TS code works great for my TYPO3 7.6 installation:

tt_content.highlight_list.20.text.20.parseFunc.externalBlocks = table,blockquote,ol,li,ul
tt_content.highlight_list.20.text.20.parseFunc.externalBlocks {
    ul {
        stripNL = 1
        callRecursive = 1
        callRecursive.tagStdWrap.HTMLparser.tags.ul.fixAttrib.class.default = row
    }
    li {
        stripNL = 1
        callRecursive = 1
        callRecursive.tagStdWrap.HTMLparser = 1
        callRecursive.tagStdWrap.HTMLparser.tags.li.fixAttrib.class.default = col-4 col-sm-2 col-md-2
    }
    ol {
        stripNL = 1
        callRecursive = 1
        callRecursive.tagStdWrap.HTMLparser = 1
    }
}

Now I would like the class col-4 col-sm-2 col-md-2 is not present for li items only belonging to ol elements. For ul, they should be kept.

Trying the next line (or other variants) just breaks the markup:

tt_content.highlight_list.20.text.20.parseFunc.externalBlocks.ol.callRecursive.tagStdWrap.HTMLparser.tags.li.fixAttrib.class.default =

Any hints?

Body:
What I don't understand is that for TYPO3 6.1.12, the next Typoscript added the classes "col-4.col-sm-2.col-md-2" only to "ol" lists:

tt_content.highlight_list.20.text.20.parseFunc.externalBlocks = table,blockquote,ol,ul,li
tt_content.highlight_list.20.text.20.parseFunc.externalBlocks {
  li.stripNL = 1
  li.callRecursive = 1
  li.callRecursive.tagStdWrap.HTMLparser = 1
  li.callRecursive.tagStdWrap.HTMLparser.tags.li {
    fixAttrib.class.default = col-4 col-sm-2 col-md-2
  }
  ul.stripNL = 1
  ul.callRecursive = 1
  ul.callRecursive.tagStdWrap.HTMLparser = 1
  ul.callRecursive.tagStdWrap.HTMLparser.tags.ul {
    fixAttrib.class.default = row
  }
}


问:
Submit form not allowed if tag empty
I have form with ngTagsInput field that I submit on button click.

But if user press space a few times and text value looks like text: "    " then I am not allowed to submit my form because formName.$valid is false. Is there any way to allow that to happen with ngTagsInput API? or any other way to accomplish that?

答: It is doable with allowLeftoverText set to true. </p>

Title: Submit form not allowed if tag empty


问:
PhoneGap application: "ERROR: Start Page at `www/index.html` was not found"
I have created a Phone Gap based application on iPhone. After the first run, I have dragged my www folder, containing index.html into the project, but still I am getting the following error in the simulator:

ERROR: Start Page at www/index.html was not found.

Do I have to mention the name of index.html in a plist file or anywhere else? How can I resolve this; can any one help me?

答:
in xcode target - Copy Bundle Resource
add www folder</p>


问:
Which button selection to use in vba?
I am sure this is probably an easy question. I am trying to assign new macros to buttons that I put on a sheet. Here is my code for assigning the macros to the buttons.

```<code>    .Shapes("Atlanta MFG").OnAction = "Atlanta"
    .Shapes("Denver MFG").OnAction = "Denver"
    .Shapes("Louisville MFG").OnAction = "Louisville"
</code>```

My code runs all the way through. Then this snippet above is the last part. It will assign the Atlanta macro to the Atlanta button, but then after that the code just STOPS. The other buttons do not get assigned and it looks like the code just completely stops. Then I can hit f8 to start it all over again. Why is my code stopping and not assigning the macros to the rest of the buttons after it does the first one? Thank you in advance! I am guessing I need to add some type of other code to make in continue assigning the macros to them.

UPDATE--------------------------------------------------------------

```<code>With ActiveSheet
    .BUTTONS.Add(53.25, 36.75, 190.5, 41.25).Select
    .BUTTONS("Button 1").Text = "Atlanta MFG"
    .BUTTONS("Button 1").name = "Atlanta MFG"
    .Shapes("Atlanta MFG").IncrementTop -12

    .BUTTONS.Add(53.25, 36.75, 190.5, 41.25).Select
    .Shapes("Button 2").IncrementLeft 222
    .Shapes("Button 2").IncrementTop -12
    .BUTTONS("Button 2").Text = "Denver MFG"
    .BUTTONS("Button 2").name = "Denver MFG"
    .BUTTONS("Button 7").Text = "Modesto MFG"
    .BUTTONS("Button 7").name = "Modesto MFG"
    .BUTTONS("Button 8").Text = "Seattle MFG"
    .BUTTONS("Button 8").name = "Seattle MFG"
    .BUTTONS("Button 9").Text = "Tustin MFG"
    .BUTTONS("Button 9").name = "Tustin MFG"
    .BUTTONS("Button 10").Text = "York MFG"
    .BUTTONS("Button 10").name = "York MFG"
    .BUTTONS("Button 11").Text = "Button 11"
    .BUTTONS("Button 11").name = "Button 11"
    .BUTTONS("Button 12").Text = "Button 12"
    .BUTTONS("Button 12").name = "Button 12"

    .Shapes("Atlanta MFG").OnAction = "Atlanta"
    .Shapes("Denver MFG").OnAction = "Denver"
    .Shapes("Jackson MFG").OnAction = "Jackson"
    .Shapes("Louisville MFG").OnAction = "Louisville"

    Range("A1").Select

End With
</code>```

So I am adding like 10 buttons not all of the code is there. I add the buttons then move them some, then I make the Private subs for each location. For example,

```<code>Private Sub Atlanta()

MsgBox "Atlanta MFG do your thing!"

End Sub
</code>```

I have one of those for each location. When I run it, I can click on the Atlanta button, but every one after that I can't click on. They just make it so I can move the box around and not actually run the button.

SECOND UPDATE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Apparently it is working. I am not sure if hitting ctrl-shift-f9 did it or what... but I tried it this morning, hit ctrl-shift-f9, then it all ran. So maybe I was just messing up last night. Thanks for the help!

答: If you've ever put a break or watch on a row, Excel can sometimes think it's still there. Try control + shift + F9 to clear them all before trying again</p>

Title: Which button selection to use in vba?

Body:
I am sure this is probably an easy question. I am trying to assign new macros to buttons that I put on a sheet. Here is my code for assigning the macros to the buttons.

    .Shapes("Atlanta MFG").OnAction = "Atlanta"
    .Shapes("Denver MFG").OnAction = "Denver"
    .Shapes("Louisville MFG").OnAction = "Louisville"

My code runs all the way through. Then this snippet above is the last part. It will assign the Atlanta macro to the Atlanta button, but then after that the code just STOPS. The other buttons do not get assigned and it looks like the code just completely stops. Then I can hit f8 to start it all over again. Why is my code stopping and not assigning the macros to the rest of the buttons after it does the first one? Thank you in advance! I am guessing I need to add some type of other code to make in continue assigning the macros to them.

UPDATE--------------------------------------------------------------

With ActiveSheet
    .BUTTONS.Add(53.25, 36.75, 190.5, 41.25).Select
    .BUTTONS("Button 1").Text = "Atlanta MFG"
    .BUTTONS("Button 1").name = "Atlanta MFG"
    .Shapes("Atlanta MFG").IncrementTop -12

    .BUTTONS.Add(53.25, 36.75, 190.5, 41.25).Select
    .Shapes("Button 2").IncrementLeft 222
    .Shapes("Button 2").IncrementTop -12
    .BUTTONS("Button 2").Text = "Denver MFG"
    .BUTTONS("Button 2").name = "Denver MFG"
    .BUTTONS("Button 7").Text = "Modesto MFG"
    .BUTTONS("Button 7").name = "Modesto MFG"
    .BUTTONS("Button 8").Text = "Seattle MFG"
    .BUTTONS("Button 8").name = "Seattle MFG"
    .BUTTONS("Button 9").Text = "Tustin MFG"
    .BUTTONS("Button 9").name = "Tustin MFG"
    .BUTTONS("Button 10").Text = "York MFG"
    .BUTTONS("Button 10").name = "York MFG"
    .BUTTONS("Button 11").Text = "Button 11"
    .BUTTONS("Button 11").name = "Button 11"
    .BUTTONS("Button 12").Text = "Button 12"
    .BUTTONS("Button 12").name = "Button 12"

    .Shapes("Atlanta MFG").OnAction = "Atlanta"
    .Shapes("Denver MFG").OnAction = "Denver"
    .Shapes("Jackson MFG").OnAction = "Jackson"
    .Shapes("Louisville MFG").OnAction = "Louisville"

    Range("A1").Select

End With

So I am adding like 10 buttons not all of the code is there. I add the buttons then move them some, then I make the Private subs for each location. For example,

Private Sub Atlanta()

MsgBox "Atlanta MFG do your thing!"

End Sub

I have one of those for each location. When I run it, I can click on the Atlanta button, but every one after that I can't click on. They just make it so I can move the box around and not actually run the button.

SECOND UPDATE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Apparently it is working. I am not sure if hitting ctrl-shift-f9 did it or what... but I tried it this morning, hit ctrl-shift-f9, then it all ran. So maybe I was just messing up last night. Thanks for the help!


问:
Remove a character from java string using hex code
i would like to remove a character from java string using hex code:

i am trying following code but seems to not be correct as the character isn't replaced: ÿ

```<code>String str ="test  ÿ";
str.replaceAll("\\x{9F}","")
</code>```

is there any thing wrong with the syntax of the hex code? Thanks.

答:
To mach ÿ you need \u00ff instead, as Jon mentioned.

```<code>String replaced = str.replace("\u00ff", "");
</code>```

in your case.

Body:
i would like to remove a character from java string using hex code:

i am trying following code but seems to not be correct as the character isn't replaced: ÿ

String str ="test  ÿ";
str.replaceAll("\\x{9F}","")

is there any thing wrong with the syntax of the hex code? Thanks.

Body:
To mach ÿ you need \u00ff instead, as Jon mentioned.

String replaced = str.replace("\u00ff", "");

in your case.


问:
spring security manual login best practice
I'm using spring security to implement a programmatic, manual user login. I have a scenario where I have positively established the user's identity, and wish to log them in. I don't know their password, and so can't use the regular login code path where you submit a form to a url, which spring intercepts via a servlet Filter, doing all of it's auth+session magic.

I've searched, and it seems most people create their own Authentication object, and then tell spring about via:

```<code>PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(user, "", user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
</code>```

Indeed, this works. Spring even puts it into the session for me, making subsequent http requests maintain their auth status.

However, I feel like this is a dirty hack. I'll present some details that I hope will give concrete examples of the problems associated with using setAuthentication() inside a controller to achieve a manual login:

To give an idea, my config is:

```<code>httpSecurity
    .authorizeRequests()
    .antMatchers("/test/**").permitAll()
    .antMatchers("/admin/**", "/api/admin/**").hasRole("USER_SUPER_ADMIN")
    .and()
    .formLogin()
    .loginPage("/sign-in?sp")
    .loginProcessingUrl("/api/auth/sign-in")
    .successHandler(createLoginSuccessHandler())
    .failureHandler(createLoginFailureHandler())
    .permitAll()
    .and()
    .logout()
    .logoutUrl("/api/auth/sign-out")
    .logoutSuccessHandler(createLogoutSuccessHandler())
    .and()
    .sessionManagement()
    .maximumSessions(1)
    .maxSessionsPreventsLogin(true)
    .sessionRegistry(sessionRegistry)
;
</code>```

Key points in the above config:

I use custom success and failure handlers for the form login

I want to config behavior for max concurrent sessions per user

I want to maintain spring's default session fixation protection (changing session id upon login).

I want to use a session registry

... more of these session/login functionalities, had I chosen to config it.

I stepped through the code to see how spring processes a form login. As expected, Spring does all the session/login functionalities that my HttpSecurity config told it to do when I use the form login. But, when I do my own custom/manual login via SecurityContextHolder.getContext().setAuthentication(), it does NONE of those functionalities. This is because spring does all of it's session/login functionalities stuff inside of a servlet Filter, and my programmatic code can't really call a Filter. Now, I can attempt to add the missing functionalities myself, duplicating their code: I see that the spring Filter uses: ConcurrentSessionControlAuthenticationStrategy, ChangeSessionIdAuthenticationStrategy, and RegisterSessionAuthenticationStrategy. I can create these objects myself, configure them, and call them after my custom login. But, that's really lame to duplicate all that spring code. Furthermore, there's still other behaviors I'm missing - I noticed that when using the form login code path, that spring triggers some login events which don't get triggered when I do my custom login. And there's probably other stuff that I'm missing or don't understand. The whole process is pretty complicated, and I feel like there's a high chance of introducing bugs if this isn't done right, not to mention that library updates would be a pain if I started duplicating spring code.

So, I feel like I'm approaching this from the wrong way. Should I be using a different strategy, so that I'm not bypassing so much of the stuff that spring does for me? Maybe I should try to make my own AuthenticationProvider to accomplish this custom login?

*To clarify, my code more or less works. But, I feel like I accomplished it using a poor strategy because I had to write code duplicating a lot of stuff that spring does for me. Further, my code doesn't perfectly replicate what spring does, making me wonder what negative implications might result. There must be a better way to programatically achieve login.

答:
For custom web authentication you should implement combination of a custom authentication filter (for example AbstractAuthenticationProcessingFilter or just GenericFilterBean), a custom authentication provider (AuthenticationProvider) or/and custom authentication token (AbstractAuthenticationToken).

For example, see source of Spring Security Kerberos.

See also:

The AuthenticationManager, ProviderManager and AuthenticationProvider

ContentLicense: CC BY-SA 4.0

Body:
I'm using spring security to implement a programmatic, manual user login. I have a scenario where I have positively established the user's identity, and wish to log them in. I don't know their password, and so can't use the regular login code path where you submit a form to a url, which spring intercepts via a servlet Filter, doing all of it's auth+session magic.

I've searched, and it seems most people create their own Authentication object, and then tell spring about via:

PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(user, "", user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);

Indeed, this works. Spring even puts it into the session for me, making subsequent http requests maintain their auth status.

However, I feel like this is a dirty hack. I'll present some details that I hope will give concrete examples of the problems associated with using setAuthentication() inside a controller to achieve a manual login:

To give an idea, my config is:

httpSecurity
    .authorizeRequests()
    .antMatchers("/test/**").permitAll()
    .antMatchers("/admin/**", "/api/admin/**").hasRole("USER_SUPER_ADMIN")
    .and()
    .formLogin()
    .loginPage("/sign-in?sp")
    .loginProcessingUrl("/api/auth/sign-in")
    .successHandler(createLoginSuccessHandler())
    .failureHandler(createLoginFailureHandler())
    .permitAll()
    .and()
    .logout()
    .logoutUrl("/api/auth/sign-out")
    .logoutSuccessHandler(createLogoutSuccessHandler())
    .and()
    .sessionManagement()
    .maximumSessions(1)
    .maxSessionsPreventsLogin(true)
    .sessionRegistry(sessionRegistry)
;

Key points in the above config:

I use custom success and failure handlers for the form login

I want to config behavior for max concurrent sessions per user

I want to maintain spring's default session fixation protection (changing session id upon login).

I want to use a session registry

... more of these session/login functionalities, had I chosen to config it.

I stepped through the code to see how spring processes a form login. As expected, Spring does all the session/login functionalities that my HttpSecurity config told it to do when I use the form login. But, when I do my own custom/manual login via SecurityContextHolder.getContext().setAuthentication(), it does NONE of those functionalities. This is because spring does all of it's session/login functionalities stuff inside of a servlet Filter, and my programmatic code can't really call a Filter. Now, I can attempt to add the missing functionalities myself, duplicating their code: I see that the spring Filter uses: ConcurrentSessionControlAuthenticationStrategy, ChangeSessionIdAuthenticationStrategy, and RegisterSessionAuthenticationStrategy. I can create these objects myself, configure them, and call them after my custom login. But, that's really lame to duplicate all that spring code. Furthermore, there's still other behaviors I'm missing - I noticed that when using the form login code path, that spring triggers some login events which don't get triggered when I do my custom login. And there's probably other stuff that I'm missing or don't understand. The whole process is pretty complicated, and I feel like there's a high chance of introducing bugs if this isn't done right, not to mention that library updates would be a pain if I started duplicating spring code.

So, I feel like I'm approaching this from the wrong way. Should I be using a different strategy, so that I'm not bypassing so much of the stuff that spring does for me? Maybe I should try to make my own AuthenticationProvider to accomplish this custom login?

*To clarify, my code more or less works. But, I feel like I accomplished it using a poor strategy because I had to write code duplicating a lot of stuff that spring does for me. Further, my code doesn't perfectly replicate what spring does, making me wonder what negative implications might result. There must be a better way to programatically achieve login.


问:
How to css style angular2's Ng2-completer plugin input box and dropdown color?
I am using angular2/4's Ng2-Completer plugin and am having trouble with styling of the component. I want to change the background dropdown to "red" and the input box to be blue.

The following is my plunkr:
https://plnkr.co/edit/sVnfpBiEb5jBdtul4ls9?p=preview

I tried to include the following CSS, but it does not appear to impact anything:

```<code>    .completer-row {
        display: inherit;
        background:blue;
    }

    .completer-selected-row {
        background-color: lightblue;
        color: yellow;
    }

    .completer-row p {
        position: relative;
        top: 50%;
        transform: translateY(50%);
    }

    .completer-dropdown-holder {
        position: absolute;
        background: red;
    }

    .customid {
    background:blue;
    }
</code>```

My component:

```<code>    import { Component } from '@angular/core';
    import { CompleterService, CompleterData } from 'ng2-completer';
    import {Observable} from 'rxjs/Observable';
    import 'rxjs/Rx';

    @Component({
      selector: 'my-app',
  styleUrls: [
    './app.component.css'
  ],
      template: `<h1>Search color</h1>
                <ng2-completer id="customid" [(ngModel)]="searchStr" [datasource]="searchData" [minSearchLength]="0" [clearSelected]="true" (selected)="onSelected($event)"></ng2-completer>
                <p>Selected: {{selectedColor}}</p>
                `
    })
    export class AppComponent {
      protected searchStr: string;
      protected dataService: CompleterData;
      protected selectedColor: string;
      protected searchData = ['red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'black'];

      protected onSelected(item: CompleterItem) {
        this.selectedColor = item? item.title: "";
      }
    }
</code>```

答:
You can style the angular ng2 completer like this:</p>

```<code>::ng-deep .completer-row{

        }
</code>```

Body:
I am using angular2/4's Ng2-Completer plugin and am having trouble with styling of the component. I want to change the background dropdown to "red" and the input box to be blue.

The following is my plunkr:
https://plnkr.co/edit/sVnfpBiEb5jBdtul4ls9?p=preview

I tried to include the following CSS, but it does not appear to impact anything:

    .completer-row {
        display: inherit;
        background:blue;
    }

    .completer-selected-row {
        background-color: lightblue;
        color: yellow;
    }

    .completer-row p {
        position: relative;
        top: 50%;
        transform: translateY(50%);
    }

    .completer-dropdown-holder {
        position: absolute;
        background: red;
    }

    .customid {
    background:blue;
    }

My component:

    import { Component } from '@angular/core';
    import { CompleterService, CompleterData } from 'ng2-completer';
    import {Observable} from 'rxjs/Observable';
    import 'rxjs/Rx';

    @Component({
      selector: 'my-app',
  styleUrls: [
    './app.component.css'
  ],
      template: `
Search color

                <ng2-completer id="customid" [(ngModel)]="searchStr" [datasource]="searchData" [minSearchLength]="0" [clearSelected]="true" (selected)="onSelected($event)"></ng2-completer>

Selected: {{selectedColor}}

                `
    })
    export class AppComponent {
      protected searchStr: string;
      protected dataService: CompleterData;
      protected selectedColor: string;
      protected searchData = ['red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'black'];

      protected onSelected(item: CompleterItem) {
        this.selectedColor = item? item.title: "";
      }
    }

Body:
You can style the angular ng2 completer like this:

::ng-deep .completer-row{

        }


问:
Attribute img not allowed on element img at this point
Hello I've got a problem.
I started coding yesterday and I got an error when I wanted to verify my website on W3Validator:

Error: Attribute img not allowed on element img at this point.

Here is the code which causes the problem:

```<code><li><a href="https://twitter.com/Koeen_Yt?lang=fr"><img src="twitter.png" alt="Twitter" img style="vertical-align:middle" width="100" height="85" > Follow moi grow ! </a></li>
</code>```

答:
Remove img attribute from img tag, it is not a attribute of image,

Use this

 Follow moi grow !
```

Body:
Hello I've got a problem.
I started coding yesterday and I got an error when I wanted to verify my website on W3Validator:

Error: Attribute img not allowed on element img at this point.

Here is the code which causes the problem:

 Follow moi grow !

Body:
Remove img attribute from img tag, it is not a attribute of image,

Use this

<li><a href="https://twitter.com/Koeen_Yt?lang=fr"><img src="twitter.png" alt="Twitter" style="vertical-align:middle" width="100" height="85" > Follow moi grow ! </a></li>


问:
AngularJS filters dynamic apply depending on expression
I have snippet of a view. vm.items is an object, each item of object contains an email or phone and the code    correspondingly. For example {value:'123456', code: 'phone'}.

```<code>.contacts
    .contact(ng-repeat='item in vm.items track by $index')
      span {{item | phone}}
</code>```

The question is how could i apply filter only when item is a phone. It means the code of item is phone, and when it is an email leave it as is. I thought i could use ternary operator and have something like this: span {{item | item.code === "phone"? phone : '' }}, but i didn't succeed. I cannot change the phone filter code and pass any parameters to this filter. I cannot create new filter for email.

答:
I would do following:</p>

```<code>{{ item.code === "phone" ? (item | phone) : item }}
</code>```

Body:
I have snippet of a view. vm.items is an object, each item of object contains an email or phone and the code    correspondingly. For example {value:'123456', code: 'phone'}.

.contacts
    .contact(ng-repeat='item in vm.items track by $index')
      span {{item | phone}}

The question is how could i apply filter only when item is a phone. It means the code of item is phone, and when it is an email leave it as is. I thought i could use ternary operator and have something like this: span {{item | item.code === "phone"? phone : '' }}, but i didn't succeed. I cannot change the phone filter code and pass any parameters to this filter. I cannot create new filter for email.

Body:
I would do following:

{{ item.code === "phone" ? (item | phone) : item }}


问:
Screen size issue with ionic on iPhone X
I'm trying to export my app in ionic 3. But when I launch in the iPhone X emulator, the screen have 2 empty espaces in the top and bottom (screen problem?).

Anyone help to adapt the resolution to iPhone X resolution?

答: Cordova plugin statusbar is updated to work for iPhoneX in 2.3.0 Please check the release notes </p>


问:
Android TextView text is showing up as black squares?
I have a TextView in my application that works fine until I pause the application (by pressing home) and launch it again. It should just resume the activity, but for some reason the TextView doesn't display the text properly after it resumes the activity. The text is showing up as black squares, like this:

http://i.stack.imgur.com/5mtvy.png

Does anyone know how to fix this?

EDIT: Here's my code:
The TextView is created in a layout xml that has a GLSurfaceView (called GameView) and on top of that a TextView. Here's the xml code:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="MainActivity" >

    <GameView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/gv"
        />

    <TextView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:textColor="@android:color/black"
        android:id="@+id/tv" />

</RelativeLayout>
</code>```

And here is the code in the MainActivity class onCreate method:

```<code>    setContentView(R.layout.activity_main);
    GameView gameView = (GameView) findViewById(R.id.gv);
    TextView textView = (TextView) findViewById(R.id.tv);
</code>```

The onPause, onResume, onStart, onStop methods have nothing related to the TextView.
The TextView is saved into an instance variable for MainActivity and later, TextView.setText() is called to set the text of the TextView.

EDIT: I was able to fix this problem by commenting out one line: GLES20.glDeleteTextures(...) that was being called onPause() I have NO idea how this is even related or why calling this function caused that issue, but when I comment it out the problem goes away and when I bring this line back the problem comes back with it. If anyone can explain how one relates to the other, it would be greatly appreciated.

答:
I encountered the same situation.

Just make sure your deleting view(which uses opengl) texture action in the thread you created it.

In your case, GameView is the key.

Body:
I have a TextView in my application that works fine until I pause the application (by pressing home) and launch it again. It should just resume the activity, but for some reason the TextView doesn't display the text properly after it resumes the activity. The text is showing up as black squares, like this:

http://i.stack.imgur.com/5mtvy.png

Does anyone know how to fix this?

EDIT: Here's my code:
The TextView is created in a layout xml that has a GLSurfaceView (called GameView) and on top of that a TextView. Here's the xml code:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="MainActivity" >

    <GameView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/gv"
        />

    <TextView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:textColor="@android:color/black"
        android:id="@+id/tv" />

</RelativeLayout>

And here is the code in the MainActivity class onCreate method:

    setContentView(R.layout.activity_main);
    GameView gameView = (GameView) findViewById(R.id.gv);
    TextView textView = (TextView) findViewById(R.id.tv);

The onPause, onResume, onStart, onStop methods have nothing related to the TextView.
The TextView is saved into an instance variable for MainActivity and later, TextView.setText() is called to set the text of the TextView.

EDIT: I was able to fix this problem by commenting out one line: GLES20.glDeleteTextures(...) that was being called onPause() I have NO idea how this is even related or why calling this function caused that issue, but when I comment it out the problem goes away and when I bring this line back the problem comes back with it. If anyone can explain how one relates to the other, it would be greatly appreciated.


问:
Select entire group if one selection has the given value
```<code> datetime                                label            option_title option_value  lead difference

 1 2016-07-22                                   GE  3 - Commercial Review            3     2         -1
 2 2017-02-20                                   GE    2 - Solution Review            2     1         -1
 3 2017-02-20                                   GE 1 - Opportunity Review            1     2          1
 4 2017-04-18                                   GE    2 - Solution Review            2     3          1
 5 2017-04-19                                   GE  3 - Commercial Review            3     4          1
 6 2017-04-19                                   GE    4 - Submit Proposal            4     5          1
 7 2017-08-08                                   GE   5 - Proposal Awarded            5    NA         NA
 8 2016-08-02                                 HSBC   5 - Proposal Awarded            5     6          1
 9 2016-12-13                                 HSBC   6 - Delivery Phase 1            6     7          1
10 2017-08-07                                 HSBC       7 - Phase 1 Live            7    NA         NA
11 2016-07-22                                Lowes      Pre-Qualification            0    NA         NA
12 2016-08-02                          Danske Bank   6 - Delivery Phase 1            6    NA         NA
13 2016-07-22 AP Moller Maersk (IT Transformation)  3 - Commercial Review            3    NA         NA
14 2016-07-22                   BHP Billiton - APJ      Pre-Qualification            0     2          2
15 2016-07-26                   BHP Billiton - APJ    2 - Solution Review            2     0         -2
16 2016-07-26                   BHP Billiton - APJ      Pre-Qualification            0     2          2
</code>```

I would like to create a new data frame off of this one that selects only the "labels" that have a negative "difference" value. However, I want to select ALL of the similar "labels" like so:

```<code> datetime                                label            option_title option_value  lead difference

 1 2016-07-22                                   GE  3 - Commercial Review            3     2         -1
 2 2017-02-20                                   GE    2 - Solution Review            2     1         -1
 3 2017-02-20                                   GE 1 - Opportunity Review            1     2          1
 4 2017-04-18                                   GE    2 - Solution Review            2     3          1
 5 2017-04-19                                   GE  3 - Commercial Review            3     4          1
 6 2017-04-19                                   GE    4 - Submit Proposal            4     5          1
 7 2017-08-08                                   GE   5 - Proposal Awarded            5    NA         NA
 8 2016-07-22                   BHP Billiton - APJ      Pre-Qualification            0     2          2
 9 2016-07-26                   BHP Billiton - APJ    2 - Solution Review            2     0         -2
10 2016-07-26                   BHP Billiton - APJ      Pre-Qualification            0     2          2
</code>```

I'm not sure how to do this in dplyr....would SQL be better for this? (I haven't used the sql package in R much)

答:
Another possible way you could do this is with dplyr:

library(dplyr)

df %>% group_by(label) %>% filter(any(difference < 0))

#> # A tibble: 10 x 6
#> # Groups:   label [2]
#>      datetime              label           option_title option_value  lead
#>        <date>              <chr>                  <chr>        <int> <int>
#>  1 2016-07-22                 GE  3 - Commercial Review            3     2
#>  2 2017-02-20                 GE    2 - Solution Review            2     1
#>  3 2017-02-20                 GE 1 - Opportunity Review            1     2
#>  4 2017-04-18                 GE    2 - Solution Review            2     3
#>  5 2017-04-19                 GE  3 - Commercial Review            3     4
#>  6 2017-04-19                 GE    4 - Submit Proposal            4     5
#>  7 2017-08-08                 GE   5 - Proposal Awarded            5    NA
#>  8 2016-07-22 BHP Billiton - APJ      Pre-Qualification            0     2
#>  9 2016-07-26 BHP Billiton - APJ    2 - Solution Review            2     0
#> 10 2016-07-26 BHP Billiton - APJ      Pre-Qualification            0     2
#> # ... with 1 more variables: difference <int>
```

<p><strong>Data</strong></p>

<pre class="lang-r prettyprint-override"><code>library(readr)
df <- read_csv("rowid, datetime,                                label,            option_title, option_value,  lead, difference
1, 2016-07-22,                                   GE,  3 - Commercial Review,            3,     2,         -1
2, 2017-02-20,                                   GE,    2 - Solution Review,            2,     1,         -1
3, 2017-02-20,                                   GE, 1 - Opportunity Review,            1,     2,          1
4, 2017-04-18,                                   GE,    2 - Solution Review,            2,     3,          1
5, 2017-04-19,                                   GE,  3 - Commercial Review,            3,     4,          1
6, 2017-04-19,                                   GE,    4 - Submit Proposal,            4,     5,          1
7, 2017-08-08,                                   GE,   5 - Proposal Awarded,            5,    NA,         NA
8, 2016-08-02,                                 HSBC,   5 - Proposal Awarded,            5,     6,          1
9, 2016-12-13,                                 HSBC,   6 - Delivery Phase 1,            6,     7,          1
10, 2017-08-07,                                 HSBC,       7 - Phase 1 Live,            7,    NA,         NA
11, 2016-07-22,                                Lowes,      Pre-Qualification,            0,    NA,         NA
12, 2016-08-02,                          Danske Bank,   6 - Delivery Phase 1,            6,    NA,         NA
13, 2016-07-22, AP Moller Maersk (IT Transformation),  3 - Commercial Review,            3,    NA,         NA
14, 2016-07-22,                   BHP Billiton - APJ,      Pre-Qualification,            0,     2,          2
15, 2016-07-26,                   BHP Billiton - APJ,    2 - Solution Review,            2,     0,         -2
16, 2016-07-26,                   BHP Billiton - APJ,      Pre-Qualification,            0,     2,          2")

df <- df[-1]
</code>```

Body:
 datetime                                label            option_title option_value  lead difference

 1 2016-07-22                                   GE  3 - Commercial Review            3     2         -1
 2 2017-02-20                                   GE    2 - Solution Review            2     1         -1
 3 2017-02-20                                   GE 1 - Opportunity Review            1     2          1
 4 2017-04-18                                   GE    2 - Solution Review            2     3          1
 5 2017-04-19                                   GE  3 - Commercial Review            3     4          1
 6 2017-04-19                                   GE    4 - Submit Proposal            4     5          1
 7 2017-08-08                                   GE   5 - Proposal Awarded            5    NA         NA
 8 2016-08-02                                 HSBC   5 - Proposal Awarded            5     6          1
 9 2016-12-13                                 HSBC   6 - Delivery Phase 1            6     7          1
10 2017-08-07                                 HSBC       7 - Phase 1 Live            7    NA         NA
11 2016-07-22                                Lowes      Pre-Qualification            0    NA         NA
12 2016-08-02                          Danske Bank   6 - Delivery Phase 1            6    NA         NA
13 2016-07-22 AP Moller Maersk (IT Transformation)  3 - Commercial Review            3    NA         NA
14 2016-07-22                   BHP Billiton - APJ      Pre-Qualification            0     2          2
15 2016-07-26                   BHP Billiton - APJ    2 - Solution Review            2     0         -2
16 2016-07-26                   BHP Billiton - APJ      Pre-Qualification            0     2          2

I would like to create a new data frame off of this one that selects only the "labels" that have a negative "difference" value. However, I want to select ALL of the similar "labels" like so:

 datetime                                label            option_title option_value  lead difference

 1 2016-07-22                                   GE  3 - Commercial Review            3     2         -1
 2 2017-02-20                                   GE    2 - Solution Review            2     1         -1
 3 2017-02-20                                   GE 1 - Opportunity Review            1     2          1
 4 2017-04-18                                   GE    2 - Solution Review            2     3          1
 5 2017-04-19                                   GE  3 - Commercial Review            3     4          1
 6 2017-04-19                                   GE    4 - Submit Proposal            4     5          1
 7 2017-08-08                                   GE   5 - Proposal Awarded            5    NA         NA
 8 2016-07-22                   BHP Billiton - APJ      Pre-Qualification            0     2          2
 9 2016-07-26                   BHP Billiton - APJ    2 - Solution Review            2     0         -2
10 2016-07-26                   BHP Billiton - APJ      Pre-Qualification            0     2          2

I'm not sure how to do this in dplyr....would SQL be better for this? (I haven't used the sql package in R much)

Body:
Another possible way you could do this is with dplyr:

library(dplyr)

df %>% group_by(label) %>% filter(any(difference < 0))

#> # A tibble: 10 x 6
#> # Groups:   label [2]
#>      datetime              label           option_title option_value  lead
#>        <date>              <chr>                  <chr>        <int> <int>
#>  1 2016-07-22                 GE  3 - Commercial Review            3     2
#>  2 2017-02-20                 GE    2 - Solution Review            2     1
#>  3 2017-02-20                 GE 1 - Opportunity Review            1     2
#>  4 2017-04-18                 GE    2 - Solution Review            2     3
#>  5 2017-04-19                 GE  3 - Commercial Review            3     4
#>  6 2017-04-19                 GE    4 - Submit Proposal            4     5
#>  7 2017-08-08                 GE   5 - Proposal Awarded            5    NA
#>  8 2016-07-22 BHP Billiton - APJ      Pre-Qualification            0     2
#>  9 2016-07-26 BHP Billiton - APJ    2 - Solution Review            2     0
#> 10 2016-07-26 BHP Billiton - APJ      Pre-Qualification            0     2
#> # ... with 1 more variables: difference <int>

Data

library(readr)
df <- read_csv("rowid, datetime,                                label,            option_title, option_value,  lead, difference
1, 2016-07-22,                                   GE,  3 - Commercial Review,            3,     2,         -1
2, 2017-02-20,                                   GE,    2 - Solution Review,            2,     1,         -1
3, 2017-02-20,                                   GE, 1 - Opportunity Review,            1,     2,          1
4, 2017-04-18,                                   GE,    2 - Solution Review,            2,     3,          1
5, 2017-04-19,                                   GE,  3 - Commercial Review,            3,     4,          1
6, 2017-04-19,                                   GE,    4 - Submit Proposal,            4,     5,          1
7, 2017-08-08,                                   GE,   5 - Proposal Awarded,            5,    NA,         NA
8, 2016-08-02,                                 HSBC,   5 - Proposal Awarded,            5,     6,          1
9, 2016-12-13,                                 HSBC,   6 - Delivery Phase 1,            6,     7,          1
10, 2017-08-07,                                 HSBC,       7 - Phase 1 Live,            7,    NA,         NA
11, 2016-07-22,                                Lowes,      Pre-Qualification,            0,    NA,         NA
12, 2016-08-02,                          Danske Bank,   6 - Delivery Phase 1,            6,    NA,         NA
13, 2016-07-22, AP Moller Maersk (IT Transformation),  3 - Commercial Review,            3,    NA,         NA
14, 2016-07-22,                   BHP Billiton - APJ,      Pre-Qualification,            0,     2,          2
15, 2016-07-26,                   BHP Billiton - APJ,    2 - Solution Review,            2,     0,         -2
16, 2016-07-26,                   BHP Billiton - APJ,      Pre-Qualification,            0,     2,          2")

df <- df[-1]


问:
Java Sorting Tabular Data and Output to JSON?
Picture Excel data, rows and columns, with the ability to sort either for ASC or DESC on any column.

I'm looking to replicate this functionality within Java then output the data into JSON - This JSON data is being placed within an API that can be queried and return tabular style data which is sorted based on a specific column name.

What is the best approach to this?

JTable seems to look like it may help, https://docs.oracle.com/javase/tutorial/uiswing/components/table.html#sorting, although I'm currently unsure how to then map this data that is filtered into a JSON object.

Any pointers / thoughts?

答:
See my example below. I have used GSON dependency shown below to convert a Vector to a JSON string. And I have used JTable.convertRowIndexToModel() API to get table rows in correct order.</p>

```<code><dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.6.2</version>
</dependency>

public class TableDataToJson {

  public static void main(String[] args) {

    JFrame frame = new JFrame("Table data to JSON");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    final DefaultTableModel tableModel = new DefaultTableModel(
        new Object[][] {{"Sugar", 14}, {"Eggs", 8}, {"Butter", 12}, {"Flour", 10}},
        new Object[] {"Item name", "Price"}) {

      @Override
      public Class<?> getColumnClass(int columnIndex) {
        if (columnIndex == 1) {
          return Integer.class;
        }
        return super.getColumnClass(columnIndex);
      }
    };
    final JTable table = new JTable(tableModel);
    table.setAutoCreateRowSorter(true);

    JButton button = new JButton("Print JSON");
    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        Vector vectorInModelOrder = tableModel.getDataVector();
        Vector vectorInViewOrder = new Vector();
        for (int i = 0; i < vectorInModelOrder.size(); i++) {
          vectorInViewOrder.add(vectorInModelOrder.get(table.convertRowIndexToModel(i)));
        }

        Gson gson = new Gson();
        System.out.println(gson.toJson(vectorInViewOrder));
      }
    });

    frame.getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
    frame.getContentPane().add(button, BorderLayout.SOUTH);
    frame.pack();
    frame.setVisible(true);
  }
}
</code>```

Body:
See my example below. I have used GSON dependency shown below to convert a Vector to a JSON string. And I have used JTable.convertRowIndexToModel() API to get table rows in correct order.

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.6.2</version>
</dependency>

public class TableDataToJson {

  public static void main(String[] args) {

    JFrame frame = new JFrame("Table data to JSON");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    final DefaultTableModel tableModel = new DefaultTableModel(
        new Object[][] {{"Sugar", 14}, {"Eggs", 8}, {"Butter", 12}, {"Flour", 10}},
        new Object[] {"Item name", "Price"}) {

      @Override
      public Class<?> getColumnClass(int columnIndex) {
        if (columnIndex == 1) {
          return Integer.class;
        }
        return super.getColumnClass(columnIndex);
      }
    };
    final JTable table = new JTable(tableModel);
    table.setAutoCreateRowSorter(true);

    JButton button = new JButton("Print JSON");
    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        Vector vectorInModelOrder = tableModel.getDataVector();
        Vector vectorInViewOrder = new Vector();
        for (int i = 0; i < vectorInModelOrder.size(); i++) {
          vectorInViewOrder.add(vectorInModelOrder.get(table.convertRowIndexToModel(i)));
        }

        Gson gson = new Gson();
        System.out.println(gson.toJson(vectorInViewOrder));
      }
    });

    frame.getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
    frame.getContentPane().add(button, BorderLayout.SOUTH);
    frame.pack();
    frame.setVisible(true);
  }
}


问:
Convert python long/int to fixed size byte array
I'm trying to implement RC4 and DH key exchange in python. Problem is that I have no idea about how to convert the python long/int from the key exchange to the byte array I need for the RC4 implementation. Is there a simple way to convert a long to the required length byte array?

Update: forgot to mention that the numbers I'm dealing with are 768 bit unsigned integers.

答:
```<code>i = 0x12345678
s = struct.pack('<I',i)
b = struct.unpack('BBBB',s)
</code>```


问:
Fetch List of Items from Quote
We are using "softlayer api client" in our java application. we are trying to fetch complete quote details(Quote Information & items/Products Details which are part of the quote). We found method to fetch quote information. However, We don't find method which gives items/products which are part of quote. Is there any method to get the List of items that are available.</p>

答:
You can use this methods:

https://sldn.softlayer.com/reference/services/SoftLayer_Billing_Order_Quote/getOrder
https://sldn.softlayer.com/reference/services/SoftLayer_Billing_Order_Quote/getRecalculatedOrderContainer

e.g RESTFul

```<code>GET https://api.softlayer.com/rest/v3.1/SoftLayer_Billing_Order_Quote/$QUOTEID/getOrder
</code>```

Title: Fetch List of Items from Quote

Body:
You can use this methods:

https://sldn.softlayer.com/reference/services/SoftLayer_Billing_Order_Quote/getOrder
https://sldn.softlayer.com/reference/services/SoftLayer_Billing_Order_Quote/getRecalculatedOrderContainer

e.g RESTFul

GET https://api.softlayer.com/rest/v3.1/SoftLayer_Billing_Order_Quote/$QUOTEID/getOrder


问:
Alternative to using static factory (as cannot have abstract static methods)
I'm trying to build a functional package parser. I have a base class Datagram, now I was naively imagining I'd have it defined like this:

(Note on edit, this class is not abstract!)

```<code>public class Datagram
{
    public abstract static Datagram CreateFromDatagram(Datagram datagram);
}
</code>```

And then for specfic datagrams, say Ethernet and Tcp as an exampe:

```<code>public class EthernetDatagram : Datagram, IPayloadDatagram
{
    public override static Datagram CreateFromDatagram(Datagram datagram)
    {
        return new EthernetDatagram();
    }

    public Datagram Payload { get; }
}

public class TcpDatagram : Datagram, IPayloadDatagram
{
    public overrides static Datagram CreateFromDatagram(Datagram datagram)
    {
        return new TcpDatagram();
    }

    public Datagram Payload { get; }
}
</code>```

The reason for this (impossible) abstract static method is I want to have an extension method which allows me to "chain" all these packets together:

```<code>public static class DatagramExtensions
{
    public static T As<T>(this IPayloadDatagram datagram) where T : Datagram
    {
        return (T)T.CreateFromDatagram(datagram.Payload);
    }
}
</code>```

So, all I'd need to do to have a completely new datagram type ANewDatagram is have it define it's factory method CreateFromDatagram, and I'll be able to then merrily use my functional extension:

```<code>SomeDatagram.As<EthernetDatagram>().As<TcpDatagram>().As<ANewDatagram>()...
</code>```

and it'll all be extensible.

Given this isn't going to work as I can't inherit abstract classes, what would be a good alternative to instantiating a generic class like this?

I could use reflection, but then that's hiding it from the user. When I try create ANewDatagram I have to remember that I'm reflecting a CreateFromDatagram method later on.

I am currently using reflection to get the constructor - but there's no way for me to enforce there's a specific constructor that takes the payload. If someone creates a new Datagram there's no guarantee they add the right constructor, I'd have to inform them this in comments, which will very likely be missed, and the point of failure is at run-time at the latest possible point.

Is there a better alternative, architecturally, or with some form of interface/inheritence that could get around this issue?

(If anyone wants to see the full source code I'm working with, I'm trying to add these extensions to the packet interpretation library as part of https://github.com/PcapDotNet/Pcap.Net, with as little modification as possible)

答:
I would suggest a different solution. I would apply the Depdency Inversion Principle

Update with new Solution:

```<code>public class Datagram
{
    public byte[] Data { get; set; }
}

public interface IPayload
{
    Datagram Payload { get; }

}

public interface IConvertible
{
    IPayload Convert(IPayload load);
}

public class EthernetDatagram : IPayload , IConvertible
{
    public Datagram Payload
    {
        get
        {
            return null;
        }
    }

    public IPayload Convert(IPayload load)
    {
        return new EthernetDatagram();
    }
}

public class TcpDatagram : IConvertible, IPayload
{
    public Datagram Payload
    {
        get
        {
            return null;
        }
    }

    public IPayload Convert(IPayload load)
    {
        return null;
    }
}

public static  class Extension
{
    public static IPayload As<T>(this IPayload load) where T : class, IConvertible, new()
    {
        IConvertible conv = new T();
        return conv.Convert(load);
    }
}

class Program
{
    static void Main(string[] args)
    {
        IPayload load = new TcpDatagram();

        var result = load.As<EthernetDatagram>();
    }
}
</code>```

With this solution you go the other way around. You leave the path of hard reflection and move it to different layer of abstraction by passing the concrete type you want to 'convert' to and have full control. All you have to do for new datagrams is to implement both interfaces as long as you wish a converting between them.
Is this more suitable for your problem?

Update to the comments:

The new solution will overcome the disadvantages of the former solution.
No reflection and specification of the 'converted' type by a generic parameter. You can chain calls to 'As' together to reach exactly what you want.
The only thing you now have to provide is the interface implementation, a default ctor and thats it.

Body:
I'm trying to build a functional package parser. I have a base class Datagram, now I was naively imagining I'd have it defined like this:

(Note on edit, this class is not abstract!)

public class Datagram
{
    public abstract static Datagram CreateFromDatagram(Datagram datagram);
}

And then for specfic datagrams, say Ethernet and Tcp as an exampe:

public class EthernetDatagram : Datagram, IPayloadDatagram
{
    public override static Datagram CreateFromDatagram(Datagram datagram)
    {
        return new EthernetDatagram();
    }

    public Datagram Payload { get; }
}

public class TcpDatagram : Datagram, IPayloadDatagram
{
    public overrides static Datagram CreateFromDatagram(Datagram datagram)
    {
        return new TcpDatagram();
    }

    public Datagram Payload { get; }
}

The reason for this (impossible) abstract static method is I want to have an extension method which allows me to "chain" all these packets together:

public static class DatagramExtensions
{
    public static T As<T>(this IPayloadDatagram datagram) where T : Datagram
    {
        return (T)T.CreateFromDatagram(datagram.Payload);
    }
}

So, all I'd need to do to have a completely new datagram type ANewDatagram is have it define it's factory method CreateFromDatagram, and I'll be able to then merrily use my functional extension:

SomeDatagram.As<EthernetDatagram>().As<TcpDatagram>().As<ANewDatagram>()...

and it'll all be extensible.

Given this isn't going to work as I can't inherit abstract classes, what would be a good alternative to instantiating a generic class like this?

I could use reflection, but then that's hiding it from the user. When I try create ANewDatagram I have to remember that I'm reflecting a CreateFromDatagram method later on.

I am currently using reflection to get the constructor - but there's no way for me to enforce there's a specific constructor that takes the payload. If someone creates a new Datagram there's no guarantee they add the right constructor, I'd have to inform them this in comments, which will very likely be missed, and the point of failure is at run-time at the latest possible point.

Is there a better alternative, architecturally, or with some form of interface/inheritence that could get around this issue?

(If anyone wants to see the full source code I'm working with, I'm trying to add these extensions to the packet interpretation library as part of https://github.com/PcapDotNet/Pcap.Net, with as little modification as possible)

Body:
I would suggest a different solution. I would apply the Depdency Inversion Principle

Update with new Solution:

public class Datagram
{
    public byte[] Data { get; set; }
}

public interface IPayload
{
    Datagram Payload { get; }

}

public interface IConvertible
{
    IPayload Convert(IPayload load);
}

public class EthernetDatagram : IPayload , IConvertible
{
    public Datagram Payload
    {
        get
        {
            return null;
        }
    }

    public IPayload Convert(IPayload load)
    {
        return new EthernetDatagram();
    }
}

public class TcpDatagram : IConvertible, IPayload
{
    public Datagram Payload
    {
        get
        {
            return null;
        }
    }

    public IPayload Convert(IPayload load)
    {
        return null;
    }
}

public static  class Extension
{
    public static IPayload As<T>(this IPayload load) where T : class, IConvertible, new()
    {
        IConvertible conv = new T();
        return conv.Convert(load);
    }
}

class Program
{
    static void Main(string[] args)
    {
        IPayload load = new TcpDatagram();

        var result = load.As<EthernetDatagram>();
    }
}

With this solution you go the other way around. You leave the path of hard reflection and move it to different layer of abstraction by passing the concrete type you want to 'convert' to and have full control. All you have to do for new datagrams is to implement both interfaces as long as you wish a converting between them.
Is this more suitable for your problem?

Update to the comments:

The new solution will overcome the disadvantages of the former solution.
No reflection and specification of the 'converted' type by a generic parameter. You can chain calls to 'As' together to reach exactly what you want.
The only thing you now have to provide is the interface implementation, a default ctor and thats it.


问:
SQL Server transaction not committing
I have a SQL Server transaction which adds a column to a table, and then it adds some value to that column. It runs perfectly, but it doesn't commit the changes.

I checked with @@trancount, and it's value is 1 after running the query.

What is wrong with the transaction?

Thanks!

```<code>BEGIN TRANSACTION
    ALTER TABLE Table
        ADD ColumnName VARCHAR(200) NULL;
    GO

    BEGIN TRY
        UPDATE ColumnName
        SET ColumnName = 'some value'

        COMMIT TRANSACTION
    END TRY
    BEGIN CATCH
        ROLLBACK TRANSACTION;
    END CATCH;
</code>```

答:
If you do it this way, it will work. XACT_ABORT will automatically rollback the transaction if an error occurs at runtime. I have had problems with using TRY...CATCH in the past, and in this case, it doesn't seem warranted.

```<code>SET XACT_ABORT ON
BEGIN TRANSACTION
    ALTER TABLE Table
        ADD ColumnName VARCHAR(200) NULL;

    UPDATE Table
        SET ColumnName = 'some value';

    COMMIT TRANSACTION;

SET XACT_ABORT OFF
</code>```

UPDATE

I found this, which explains the process better, if you still want to use the TRY...CATCH construct.

Try...Catch inside Transactions

Title: SQL Server transaction not committing

Body:
I have a SQL Server transaction which adds a column to a table, and then it adds some value to that column. It runs perfectly, but it doesn't commit the changes.

I checked with @@trancount, and it's value is 1 after running the query.

What is wrong with the transaction?

Thanks!

BEGIN TRANSACTION
    ALTER TABLE Table
        ADD ColumnName VARCHAR(200) NULL;
    GO

    BEGIN TRY
        UPDATE ColumnName
        SET ColumnName = 'some value'

        COMMIT TRANSACTION
    END TRY
    BEGIN CATCH
        ROLLBACK TRANSACTION;
    END CATCH;

Body:
If you do it this way, it will work. XACT_ABORT will automatically rollback the transaction if an error occurs at runtime. I have had problems with using TRY...CATCH in the past, and in this case, it doesn't seem warranted.

SET XACT_ABORT ON
BEGIN TRANSACTION
    ALTER TABLE Table
        ADD ColumnName VARCHAR(200) NULL;

    UPDATE Table
        SET ColumnName = 'some value';

    COMMIT TRANSACTION;

SET XACT_ABORT OFF

UPDATE

I found this, which explains the process better, if you still want to use the TRY...CATCH construct.

Try...Catch inside Transactions


问:
How to connect to this database where the url starts as "jdbc:as400//..."
I am working on a project where I have to fetch data from a database. I found from the db properties in eclipse, that the url is starting as "jdbc:as400//...". Is there any way other than using IBM.Data.DB2.iSeries. I am using visual studio 2012 to build a windows application.</p>

答: It looks like DriverManager uses JDBC, so if you need a JDBC driver for IBM i, you can retrieve JTOpen from sourceforge. The driver file in there is jt400.jar.


问:
What happens if we define wrong flag for -mfpu?
For example, if I have a chip -mcpu=cortex-a7 , I should define -mfpu=neon-vfpv4 , not -mfpu=neon . However, I'm wondering what will happen if I define -mfpu=neon on Cortex-A7? Will it just ignore the flag and don't do the SIMD, or what will it do with the wrong flag like that?

答: If you do this compiler won't use VFPv4 instructions and potentially generate suboptimal code.</p>


问:
GLSL Unsupported Version
I'm trying to compile GLSL shaders for use in LWJGL with OpenGL. I'm on macOS Sierra.

I get the following error when trying to compile the shaders:

```<code>ERROR: 0:1: '' :  version '400' is not supported
ERROR: 0:1: '' : syntax error: #version
</code>```

The shader code works on Windows, but when testing on macOS it doesn't.
Here's the shader code:

```<code>#version 400 core

in vec3 position;
in vec2 textureCoords;

out vec2 pass_textureCoords;

uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;

void main(void)
{
    gl_Position = projectionMatrix * viewMatrix * vec4(position, 1.0);
    pass_textureCoords = textureCoords;
}
</code>```

Here is how i'm loading the shader...

```<code>    private static int loadShader(String file, int type) throws IOException {
        StringBuilder shaderSource = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(
                    ShaderProgram.class.getClassLoader().getResourceAsStream("shaders/" + file))
            )) {

            String line;
            while ((line = reader.readLine()) != null) {
                shaderSource.append(line).append('\n');
            }

            System.out.println(shaderSource.toString());

            int shaderID = GL20.glCreateShader(type);

            GL20.glShaderSource(shaderID, shaderSource);
            GL20.glCompileShader(shaderID);

            if (GL20.glGetShaderi(shaderID, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE) {
                System.out.println(GL20.glGetShaderInfoLog(shaderID, 500));
                System.err.println("Error compiling shader " + file);
                System.exit(-1);
            }

            return shaderID;
        }
    }
</code>```

The print statement returns the correct output, yet it still gives me the error.

I've searched all over stackoverflow for a solution, yet everyone says that they're compiling it without line breaks, which i have. I'm confused as to why this is occurring.

答: If the other answer doesn't solve the problem for you, I suspect you're creating an OpenGL context with the wrong OpenGL version. You will need to create a context with the Core Profile - this also means that legacy functions and features are not supported, so if you've used any of those, you'll need to replace them with newer equivalents. (The core profile is not backwards-compatible.)

Title: GLSL Unsupported Version

Body:
I'm trying to compile GLSL shaders for use in LWJGL with OpenGL. I'm on macOS Sierra.

I get the following error when trying to compile the shaders:

ERROR: 0:1: '' :  version '400' is not supported
ERROR: 0:1: '' : syntax error: #version

The shader code works on Windows, but when testing on macOS it doesn't.
Here's the shader code:

#version 400 core

in vec3 position;
in vec2 textureCoords;

out vec2 pass_textureCoords;

uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;

void main(void)
{
    gl_Position = projectionMatrix * viewMatrix * vec4(position, 1.0);
    pass_textureCoords = textureCoords;
}

Here is how i'm loading the shader...

    private static int loadShader(String file, int type) throws IOException {
        StringBuilder shaderSource = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(
                    ShaderProgram.class.getClassLoader().getResourceAsStream("shaders/" + file))
            )) {

            String line;
            while ((line = reader.readLine()) != null) {
                shaderSource.append(line).append('\n');
            }

            System.out.println(shaderSource.toString());

            int shaderID = GL20.glCreateShader(type);

            GL20.glShaderSource(shaderID, shaderSource);
            GL20.glCompileShader(shaderID);

            if (GL20.glGetShaderi(shaderID, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE) {
                System.out.println(GL20.glGetShaderInfoLog(shaderID, 500));
                System.err.println("Error compiling shader " + file);
                System.exit(-1);
            }

            return shaderID;
        }
    }

The print statement returns the correct output, yet it still gives me the error.

I've searched all over stackoverflow for a solution, yet everyone says that they're compiling it without line breaks, which i have. I'm confused as to why this is occurring.


问:
Simplify/RESTify my routes!
Here is a sample of my routes.rb
Basically I have users that have pictures and that can rate other people's pictures

This is not very RESTful at all, but I cannot figure out how to turn this around?

```<code>  resources :users do
    member do
      post :reset_password
    end
  end
  # to list images
  get 'images/list/:order/:page/:per_page/:category', :to => 'images#list_filtered'
  # to rate images
  post 'images/rate', :to => 'images#rate'
  # to list a user's images
  get 'images/user/:user_id/:category/:order/:page/:per_page', :to => "images#user"
  # to list users that rated an image
  get 'users/rated/:image_id', :to => 'users#rated'
</code>```

答:
Here are a couple of things I would recommend:

Use images#index instead of images#list_filtered and pass order, page, per_page and category as parameter: /images?order=...&per_page=...&page=...

Make images nested under users as resources and then make images a top level resource that is independent of user (so that you can view all images or you can view user specific images).

```
resources :users do
  member do
    post :reset_password
  end
  resources :images
end

resources :images do
  post :rate
  get :rated
end
```

You should then be able to view images using /images.

You should be able to rate an individual image using /images/:id/rate.

You should be able to view users who rated an image using /images/:id/rated.

You should be able to list a user's images using /user/:id/images.

Title: Simplify/RESTify my routes!

Body:
Here is a sample of my routes.rb
Basically I have users that have pictures and that can rate other people's pictures

This is not very RESTful at all, but I cannot figure out how to turn this around?

  resources :users do
    member do
      post :reset_password
    end
  end
  # to list images
  get 'images/list/:order/:page/:per_page/:category', :to => 'images#list_filtered'
  # to rate images
  post 'images/rate', :to => 'images#rate'
  # to list a user's images
  get 'images/user/:user_id/:category/:order/:page/:per_page', :to => "images#user"
  # to list users that rated an image
  get 'users/rated/:image_id', :to => 'users#rated'

Body:
Here are a couple of things I would recommend:

Use images#index instead of images#list_filtered and pass order, page, per_page and category as parameter: /images?order=...&per_page=...&page=...

Make images nested under users as resources and then make images a top level resource that is independent of user (so that you can view all images or you can view user specific images).

resources :users do
  member do
    post :reset_password
  end
  resources :images
end

resources :images do
  post :rate
  get :rated
end

You should then be able to view images using /images.

You should be able to rate an individual image using /images/:id/rate.

You should be able to view users who rated an image using /images/:id/rated.

You should be able to list a user's images using /user/:id/images.


问:
How can I limit text box width of QLineEdit to display at most four characters?
I am working with a GUI based on PySide. I made a (one line) text box with QLineEdit and the input is just four characters long, a restriction I already successfully applied.

The problem is I have a wider than needed text box (i.e. there is a lot of unused space after the text). How can I shorten the length of the text box?

I know this is something that is easily fixed by designing the text box with Designer; however, this particular text box is not created in Designer.

答:
If what you want is modify your QLineEdit width and fix it, use:

#setFixedWidth(int w)
MyLineEdit.setFixedWidth(120)
```


问:
Is it possible to avoid the for-loop to compute matrix entries?
I have to use a nested for-loop to compute the entries of a Eigen::MatrixXd type matrix output columnwise. Here input[0], input[1] and input[2] are defined as Eigen::ArrayXXd in order to use the elementwise oprerations. This part seems to be the bottleneck for my code. Can anyone help me to accelerate this loop? Thanks! </p>

```<code> for (int i = 0; i < r; i++) {
    for (int j = 0; j < r; j++) {
      for (int k = 0; k < r; k++) {
        output.col(i * (r * r) + j * r + k) =
            input[0].col(i) * input[1].col(j) * input[2].col(k);
      }
    }
  }
</code>```

答:
To reduce the number of flops, you should cache the result of input[0]*input[1]:

```<code>ArrayXd tmp(input[0].rows());
for (int i = 0; i < r; i++) {
 for (int j = 0; j < r; j++) {
  tmp = input[0].col(i) * input[1].col(j);
  for (int k = 0; k < r; k++) {
    output.col(i * (r * r) + j * r + k) = tmp * input[2].col(k);
  }
 }
}
</code>```

Then, to fully use your CPU, enable AVX/FMA with -march=native and of course compiler optimizations (-O3).

Then, to get an idea of what you could gain more, measure accurately the time taken by this part, count the number of multiplications (r^2*(n+r*n)), and then compute the number of floating point operations per second you achieve. Then compare it to the capacity of your CPU. If you're good, then the only option is to multithread one of the for loop using, e.g., OpenMP. The choice of which for loop depends on the size of your inputs, but you can try with the outer one, making sure each thread has its own tmp array.

Body:
I have to use a nested for-loop to compute the entries of a Eigen::MatrixXd type matrix output columnwise. Here input[0], input[1] and input[2] are defined as Eigen::ArrayXXd in order to use the elementwise oprerations. This part seems to be the bottleneck for my code. Can anyone help me to accelerate this loop? Thanks!

 for (int i = 0; i < r; i++) {
    for (int j = 0; j < r; j++) {
      for (int k = 0; k < r; k++) {
        output.col(i * (r * r) + j * r + k) =
            input[0].col(i) * input[1].col(j) * input[2].col(k);
      }
    }
  }

Body:
To reduce the number of flops, you should cache the result of input[0]*input[1]:

ArrayXd tmp(input[0].rows());
for (int i = 0; i < r; i++) {
 for (int j = 0; j < r; j++) {
  tmp = input[0].col(i) * input[1].col(j);
  for (int k = 0; k < r; k++) {
    output.col(i * (r * r) + j * r + k) = tmp * input[2].col(k);
  }
 }
}

Then, to fully use your CPU, enable AVX/FMA with -march=native and of course compiler optimizations (-O3).

Then, to get an idea of what you could gain more, measure accurately the time taken by this part, count the number of multiplications (r^2*(n+r*n)), and then compute the number of floating point operations per second you achieve. Then compare it to the capacity of your CPU. If you're good, then the only option is to multithread one of the for loop using, e.g., OpenMP. The choice of which for loop depends on the size of your inputs, but you can try with the outer one, making sure each thread has its own tmp array.


问:
How to change cell format on load time in DevExpress Winform
I want to change cell formatting, cell value, alignment at time of cell loading in GridView. </p>

答:
Take a look at this link https://documentation.devexpress.com/windowsforms/3048/Controls-and-Libraries/Data-Grid/Examples/Formatting/How-to-Format-Display-Text-in-Grid-s-Cells-Depending-on-Values-in-Other-Cells

```<code>using DevExpress.XtraGrid.Views.Base;
using System.Globalization;

// The cultures used to format the values for the two different currencies.
CultureInfo ciUSA = new CultureInfo("en-US");
CultureInfo ciEUR = new CultureInfo("fr-FR", false);

private void gridView1_CustomColumnDisplayText(object sender, CustomColumnDisplayTextEventArgs e)
{

    ColumnView view = sender as ColumnView;

    if (e.Column.FieldName == "Price" && e.ListSourceRowIndex != DevExpress.XtraGrid.GridControl.InvalidRowHandle)
    {
       int currencyType =   (int)view.GetListSourceRowCellValue(e.ListSourceRowIndex, "CurrencyType");
       decimal price = Convert.ToDecimal(e.Value);
       switch (currencyType)
       {
         case 0: e.DisplayText = string.Format(ciUSA, "{0:c}", price); break;
         case 1: e.DisplayText = string.Format(ciEUR, "{0:c}", price); break;
       }
    }
}
</code>```

c# devexpress

Body:
Take a look at this link https://documentation.devexpress.com/windowsforms/3048/Controls-and-Libraries/Data-Grid/Examples/Formatting/How-to-Format-Display-Text-in-Grid-s-Cells-Depending-on-Values-in-Other-Cells

using DevExpress.XtraGrid.Views.Base;
using System.Globalization;

// The cultures used to format the values for the two different currencies.
CultureInfo ciUSA = new CultureInfo("en-US");
CultureInfo ciEUR = new CultureInfo("fr-FR", false);

private void gridView1_CustomColumnDisplayText(object sender, CustomColumnDisplayTextEventArgs e)
{

    ColumnView view = sender as ColumnView;

    if (e.Column.FieldName == "Price" && e.ListSourceRowIndex != DevExpress.XtraGrid.GridControl.InvalidRowHandle)
    {
       int currencyType =   (int)view.GetListSourceRowCellValue(e.ListSourceRowIndex, "CurrencyType");
       decimal price = Convert.ToDecimal(e.Value);
       switch (currencyType)
       {
         case 0: e.DisplayText = string.Format(ciUSA, "{0:c}", price); break;
         case 1: e.DisplayText = string.Format(ciEUR, "{0:c}", price); break;
       }
    }
}

c# devexpress


问:
Laravel 5.5 three table join
Edit: I am using API routes, so i have no views and such

I have a database like this

```<code>User:
   id
   name

card:
   id
   card_number
   user_id

swipe:
   id
   time
   card_number
</code>```

the relationships go as followed  user has one card one card has many swipe

the joins would be as such

```<code>user.id = card.user_id
card.card_number = swipe.card_number
</code>```

In Larvel i have 3 models.

```<code>user
card
swipe
</code>```

user Model

```<code>class user extends Model
{

    public function card()
    {
        return $this->hasOne('App\card','user_id','id');
    }

}
</code>```

in a controller if i do

```<code>$model = user::with('card')->get();
</code>```

i get the card data joined with the user data as expected.

```<code>class card extends Model
{

    public function person()
    {
       return $this->belongsTo('App\user');
    }

    public function swipe(){
        return $this->hasMany('App\swipe','card_number','card_number');
    }
}
</code>```

if i now do

$model = user::with('card.swipe')->get();

which i would expect to return all the users with their cards, and swipes associated to that card.

However what i get is

500 internal server error

What am i doing wrong here?

答:
For Example you can use like this.

```<code>$shares = DB::table('shares')
    ->join('users', 'users.id', '=', 'shares.user_id')
    ->join('follows', 'follows.user_id', '=', 'users.id')
    ->where('follows.follower_id', '=', 3)
    ->get();
</code>```

Title: Laravel 5.5 three table join

Body:
Edit: I am using API routes, so i have no views and such

I have a database like this

User:
   id
   name

card:
   id
   card_number
   user_id

swipe:
   id
   time
   card_number

the relationships go as followed  user has one card one card has many swipe

the joins would be as such

user.id = card.user_id
card.card_number = swipe.card_number

In Larvel i have 3 models.

user
card
swipe

user Model

class user extends Model
{

    public function card()
    {
        return $this->hasOne('App\card','user_id','id');
    }

}

in a controller if i do

$model = user::with('card')->get();

i get the card data joined with the user data as expected.

class card extends Model
{

    public function person()
    {
       return $this->belongsTo('App\user');
    }

    public function swipe(){
        return $this->hasMany('App\swipe','card_number','card_number');
    }
}

if i now do

$model = user::with('card.swipe')->get();

which i would expect to return all the users with their cards, and swipes associated to that card.

However what i get is

500 internal server error

What am i doing wrong here?

Body:
For Example you can use like this.

$shares = DB::table('shares')
    ->join('users', 'users.id', '=', 'shares.user_id')
    ->join('follows', 'follows.user_id', '=', 'users.id')
    ->where('follows.follower_id', '=', 3)
    ->get();


问:
Fetch distinct receivers from message model while preserving order
I'm trying to build a messaging app. Here's my model:

```<code>class Message(models.Model):
    sender = models.ForeignKey(User, related_name="sender")
    receiver = models.ForeignKey(User, related_name="receiver")
    msg_content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
</code>```

This is what I tried in the view:

```<code>data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).order_by('-created_at')
</code>```

In the template:

```<code>{% for abc in data %}
    {{ abc.receiver }} <br/>
{% endfor %}
</code>```

Here I want to filter the distinct receivers and re-order them based upon the fact that to whom request.user sent new message recently (as we see on social media platforms).

How can I do that?

答:
Filter messages sent by request.user, order by receiver_id and  -created_at then use distinct on receiver_id

```<code>Message.objects.filter(sender=request.user).order_by('receiver_id','-created_at').distinct('receiver_id')
</code>```

Body:
I'm trying to build a messaging app. Here's my model:

class Message(models.Model):
    sender = models.ForeignKey(User, related_name="sender")
    receiver = models.ForeignKey(User, related_name="receiver")
    msg_content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

This is what I tried in the view:

data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).order_by('-created_at')

In the template:

{% for abc in data %}
    {{ abc.receiver }}

{% endfor %}

Here I want to filter the distinct receivers and re-order them based upon the fact that to whom request.user sent new message recently (as we see on social media platforms).

How can I do that?

Body:
Filter messages sent by request.user, order by receiver_id and  -created_at then use distinct on receiver_id

Message.objects.filter(sender=request.user).order_by('receiver_id','-created_at').distinct('receiver_id')


问:
Prototype Events: Use Input Value From When Event is Created
I have recently read how to do this but cannot for the life of me find it again!

Basically, I'm creating some events that listen to form inputs and update their values when triggered. How do I pass the initial input value (the value of the input when the event is created) to the event so that I can compare it with the current value?

答:
The DOM already stores that value for you (for input types, not select).

```<code>element.observe('click', function(){
    // In this context, this == element
    if (this.defaultValue != this.value) {
        // value is different
    }
}
</code>```

Body:
The DOM already stores that value for you (for input types, not select).

element.observe('click', function(){
    // In this context, this == element
    if (this.defaultValue != this.value) {
        // value is different
    }
}