问:
fetchedResultsController doesn't filter (fetchRequest)
I'm trying to fetch a list of entities filtering by one of its properties (word), I'm using a fetchedResultsController for that and everything looks ok. The list is loaded and showed on my tableView, I'm even able to sort the list, but when I tried to filter it using predicate nothing happens. I don't know what I'm doing wrong. I tried the apple website and some questions from stackoverflow and I really don't know what I'm doing wrong.

Here's my code for fetchedResultsController

```<code>lazy var fetchedResultsController: NSFetchedResultsController<TranslationContainer> = {

    let fetchRequest = NSFetchRequest<TranslationContainer>()

    let entity = TranslationContainer.entity()
    fetchRequest.entity = entity

    let predicate = NSPredicate(format: "word == %@", "Bed")// doesn't filter
    fetchRequest.predicate = predicate

    let sortDescriptor = NSSortDescriptor(key: "word", ascending: true)
    fetchRequest.sortDescriptors = [sortDescriptor]

    fetchRequest.fetchBatchSize = 20

    let fetchedResultsController = NSFetchedResultsController(
        fetchRequest: fetchRequest,
        managedObjectContext: self.managedObjectContext,
        sectionNameKeyPath: nil,
        cacheName: "TranslationContainers")
    fetchedResultsController.delegate = self
    return fetchedResultsController
}()
</code>```

Any suggestion would be really appreciated!

答:
NSFetchedResultsController optionally caches results and the cache content may get out of sync if you just change the NSPredicate like the code above does. One way to get around this is to delete the cache before you set the new predicate:</p>

```<code>NSFetchedResultsController.deleteCache(withName: "TranslationContainers")
fetchedResultsController.fetchRequest?.predicate = predicate
</code>```

Body:
I'm trying to fetch a list of entities filtering by one of its properties (word), I'm using a fetchedResultsController for that and everything looks ok. The list is loaded and showed on my tableView, I'm even able to sort the list, but when I tried to filter it using predicate nothing happens. I don't know what I'm doing wrong. I tried the apple website and some questions from stackoverflow and I really don't know what I'm doing wrong.

Here's my code for fetchedResultsController

lazy var fetchedResultsController: NSFetchedResultsController<TranslationContainer> = {

    let fetchRequest = NSFetchRequest<TranslationContainer>()

    let entity = TranslationContainer.entity()
    fetchRequest.entity = entity

    let predicate = NSPredicate(format: "word == %@", "Bed")// doesn't filter
    fetchRequest.predicate = predicate

    let sortDescriptor = NSSortDescriptor(key: "word", ascending: true)
    fetchRequest.sortDescriptors = [sortDescriptor]

    fetchRequest.fetchBatchSize = 20

    let fetchedResultsController = NSFetchedResultsController(
        fetchRequest: fetchRequest,
        managedObjectContext: self.managedObjectContext,
        sectionNameKeyPath: nil,
        cacheName: "TranslationContainers")
    fetchedResultsController.delegate = self
    return fetchedResultsController
}()

Any suggestion would be really appreciated!

Body:
NSFetchedResultsController optionally caches results and the cache content may get out of sync if you just change the NSPredicate like the code above does. One way to get around this is to delete the cache before you set the new predicate:

NSFetchedResultsController.deleteCache(withName: "TranslationContainers")
fetchedResultsController.fetchRequest?.predicate = predicate


来源: stackexchange

问:
Identical values in an array has to be positioned together
```<code>var array1 = ["ddd","aaa","eee","aaa","fff","bbb","ggg","aaa","ccc","fff"]
</code>```

i have to arrange it in a way that  identical values has to be placed together

output array should be

```<code>["ddd","aaa","aaa","aaa","eee","fff","fff","bbb","ggg","ccc"]
</code>```

how to write the logic for this one ??

答:
Well actually for you request .sort() might be an overkill. You can simply do this by;

function quasiSort(a){
  var h = a.reduce((h,e) => h[e] ? (h[e].push(e), h)
                                 : (h[e] = [e], h), {});
  return Object.keys(h).reduce((r,k) => r.concat(h[k]),[]);
}
var array1 = ["ddd","aaa","eee","aaa","fff","bbb","ggg","aaa","ccc","fff"];
console.log(quasiSort(array1));```

ContentLicense: CC BY-SA 3.0

Body:
var array1 = ["ddd","aaa","eee","aaa","fff","bbb","ggg","aaa","ccc","fff"]

i have to arrange it in a way that  identical values has to be placed together

output array should be

["ddd","aaa","aaa","aaa","eee","fff","fff","bbb","ggg","ccc"]

how to write the logic for this one ??


问:
How to filter an ordered list stored into a string
Is it possible in bash to filter out a part of a string with another given string ?

I have a fixed list of motifs defined in a string. The order IS important and I want to keep only the parts that are passed as a parameter ?

```<code>myDefaultList="s,t,a,c,k"  #order is important
toRetains="k,t,c,u"  #provided by the user, order is not enforced

retained=filter $myDefaultList $toRetains # code to filter

echo $retained  # will print t,c,k"
</code>```

I can write an ugly method that will use IFS, arrays and loops, but I wonder if there's a 'clever' way to do that, using built-in commands ?

答:
```<code>#!/bin/bash

myDefaultList="s,t,a,c,k"
toRetains="s,t,c,u"

IFS=","
for i in $myDefaultList
do
        echo $toRetains | grep $i > /dev/null
        if [ "$?" -eq "0" ]
        then
                retained=$retained" "$i
        fi
done

echo $retained | sed -e 's/ /,/g' -e 's/,//1'
</code>```

I have checked it running for me. Kindly check.

Body:
Is it possible in bash to filter out a part of a string with another given string ?

I have a fixed list of motifs defined in a string. The order IS important and I want to keep only the parts that are passed as a parameter ?

myDefaultList="s,t,a,c,k"  #order is important
toRetains="k,t,c,u"  #provided by the user, order is not enforced

retained=filter $myDefaultList $toRetains # code to filter

echo $retained  # will print t,c,k"

I can write an ugly method that will use IFS, arrays and loops, but I wonder if there's a 'clever' way to do that, using built-in commands ?

Body:
#!/bin/bash

myDefaultList="s,t,a,c,k"
toRetains="s,t,c,u"

IFS=","
for i in $myDefaultList
do
        echo $toRetains | grep $i > /dev/null
        if [ "$?" -eq "0" ]
        then
                retained=$retained" "$i
        fi
done

echo $retained | sed -e 's/ /,/g' -e 's/,//1'

I have checked it running for me. Kindly check.


问:
Cannot define a class or member that utilizes 'dynamic' because the compiler required type 'System.Runtime.CompilerServices.DynamicAttribute'
I'm trying to run a .NET MVC application on my local computer that I got from GitHub.

When I hit run on Visual Studio, everything complies and a new browser window opens with the error:

CS1980: Cannot define a class or member that utilizes 'dynamic' because the compiler required type 'System.Runtime.CompilerServices.DynamicAttribute'

The compiler section in the same window, shows the following error:

I've checked on google and this seems to be the same error.

This guy was using a dynamic type himself, on the other hand I'm not using any dynamic type, this is being auto generated by .NET's compiler, and I'm using .net 4.5 which should has support for dynamics.

I tried to apply the same solution (Changing all System.Core references to 4.0)
but the thing is that all of them are version 4.0 already.

Do you have any idea how could I resolve this?

答: Adding a reference to System.Dynamic.Runtime did it for me.


问:
jQuery ID Return is undefined although HTML ID is defined
I'm trying to retrieve the ID of one element, store it as a variable and then use that ID value to interact with other elements in that section with the same ID.

```<code><div class="mainContent">
<div class="articleContent">
     <h1>header1</h1>
     <p class="articlePara" id="one">para1</p>
</div>
<div class="articleFooter" id="one" onclick="readMore()">
</div>
</div>

<div class="mainContent">
<div class="articleContent">
     <h1>header2</h1>
     <p class="articlePara" id="two">para2</p>
</div>
<div class="articleFooter" id="two" onclick="readMore()">
</div>
</div>
</code>```

And then the JS/jQuery

```<code>function readMore() {
var subID = event.target.id;

var newTarget = document.getElementById(subID).getElementsByClassName("articlePara");

alert(newTarget.id);
}
</code>```

At this point I'm only trying to display the ID of the selected element but it is returning undefined and in most cases people seem to notice that jQuery is getting confused because of the differences between DOM variables and jQuery ones.

jsfiddle: https://jsfiddle.net/dr0f2nu3/

To be completely clear, I want to be able to click on one element, retrieve the ID and then select an element in the family of that clicked element using that ID value.

答:
```<code> $('.articleFooter').click(function() {
        var b=subId; //can be any
        var a="p[id="+b+"]"+"[class='articlePara']";
        $(a).something;
    });
</code>```

Body:
I'm trying to retrieve the ID of one element, store it as a variable and then use that ID value to interact with other elements in that section with the same ID.

header1

para1

header2

para2

And then the JS/jQuery

function readMore() {
var subID = event.target.id;

var newTarget = document.getElementById(subID).getElementsByClassName("articlePara");

alert(newTarget.id);
}

At this point I'm only trying to display the ID of the selected element but it is returning undefined and in most cases people seem to notice that jQuery is getting confused because of the differences between DOM variables and jQuery ones.

jsfiddle: https://jsfiddle.net/dr0f2nu3/

To be completely clear, I want to be able to click on one element, retrieve the ID and then select an element in the family of that clicked element using that ID value.


问:
Applying greyscale effects to images - Photoshop CC 2017
The image below has a kind of faded grey look with what seems to be some slight blurring and works quite well as a generic banner image.

Usually I am provided with these images or just find stock images but I'd be very interested in learning how to apply these effects with Photoshop or CSS. I have a feeling that Photoshop is a more appropriate tool.

The image I'm experimenting with is this:

It isn't the best image but for my testing purposes at least it's a similar shape and size.

I know I can use things like de-saturation or a coloured layer with a colour blend mode for this sort of thing. However, does the first image look like it has a specific effect or is it just a case of trial and error?

I appreciate this is similar to this question.

答:
Maybe you could get the effect by using css blur and overlaying the image with a gray layer with opacity.

You could also just create the effect in photoshop and use that


问:
Excel VBA Deleting rows based upon date
I have a question about the code in this thread

Excel VBA: Delete Old Records

In that thread, is this code

```<code>    Sub ClearOldData()
    Application.ScreenUpdating = False
    Dimi As Long

    With Sheets("Data")

        For i = 2 To LastRow Step -1
            If Int(Date - Cells(i, "F").Value) > 179 Then
                .Rows(i).Delete
            End If
        Next i

    End With
    Application.ScreenUpdating = True
End Sub
</code>```

The problem I am running into is that when I run this code, I receive the following error:

Compile error: Statement invalid outside Type block

Upon first look, the Dim looks to be incorrect as it is listed as Dimi and I can find no reference to VBA using something like that. I changed it to Dim and it still gives the error. This code appears to be correct in all I have researched on this, but I am scratching my head over where the hiccup is at. Anyone have an idea where it is going sideways at?

Thanks

答:
```<code>Dimi As Long
</code>```

Whoever wrote that meant to write Dim i As Long. If you write a Type statement, it looks like this

```<code>Public Type MyType
    TypeID As Long
    TypeName As String
End Type
</code>```

See how those statements within the Type block look like variable declarations without the Dim keyword? That's the nature of the error message you're getting. The compiler sees a variable declaration for the variable Dimi and no Dim keyword and complains that you have type member declarations without a Type statement.

If you change it to Dim As Long you get the same error but instead of the compiler complaining about the variable Dimi, it's complaining about the variable Dim. While Dim is not a valid variable name, it is a valid type member name.

@Shai Rado gives you working code with things like Option Explicit, looping backwards when you're deleting rows, and the requirement to loop from a higher number to a lower number when your step is negative, so I won't repeat those here. This answer just explains why you got the error you did.

Title: Excel VBA Deleting rows based upon date

Body:
I have a question about the code in this thread

Excel VBA: Delete Old Records

In that thread, is this code

    Sub ClearOldData()
    Application.ScreenUpdating = False
    Dimi As Long

    With Sheets("Data")

        For i = 2 To LastRow Step -1
            If Int(Date - Cells(i, "F").Value) > 179 Then
                .Rows(i).Delete
            End If
        Next i

    End With
    Application.ScreenUpdating = True
End Sub

The problem I am running into is that when I run this code, I receive the following error:

Compile error: Statement invalid outside Type block

Upon first look, the Dim looks to be incorrect as it is listed as Dimi and I can find no reference to VBA using something like that. I changed it to Dim and it still gives the error. This code appears to be correct in all I have researched on this, but I am scratching my head over where the hiccup is at. Anyone have an idea where it is going sideways at?

Thanks

Body:
Dimi As Long

Whoever wrote that meant to write Dim i As Long. If you write a Type statement, it looks like this

Public Type MyType
    TypeID As Long
    TypeName As String
End Type

See how those statements within the Type block look like variable declarations without the Dim keyword? That's the nature of the error message you're getting. The compiler sees a variable declaration for the variable Dimi and no Dim keyword and complains that you have type member declarations without a Type statement.

If you change it to Dim As Long you get the same error but instead of the compiler complaining about the variable Dimi, it's complaining about the variable Dim. While Dim is not a valid variable name, it is a valid type member name.

@Shai Rado gives you working code with things like Option Explicit, looping backwards when you're deleting rows, and the requirement to loop from a higher number to a lower number when your step is negative, so I won't repeat those here. This answer just explains why you got the error you did.


问:
Does proxy/stub expose the interface?
Suppose I introduced a COM interface and don't want any third party to use it. I have full control over the sources of the COM component and the IDL file that holds the interface definition. My COM component will need marshalling stuff fro that interface, so I'll need to either implement IMarshal or provide a typelib or provide a proxy/stub.

Obviously if I provide a typelib anyone can inspect it and find what my interface is and how it can be used. That's not what I want.

What if I use proxy/stub? Will it expose the interface and let anyone inspect it or will it keep the interface details covert?

答:
Unfortunately this is not possible. The idea of COM is that clients can discover the components and the interfaces.

In a previous job I worked on a digital rights equipped application and there we deliberately did NOT use COM just to make it more difficult for people to tap into our application. We had to build our own component infrastructure (in addition to other security measures).

ContentLicense: CC BY-SA 2.5

Title: Does proxy/stub expose the interface?


问:
How come Gradle appcompat-v7 error even though the version of the targeSdkVersoin is the same at 24?

The app runs when I build it, and works fine. But I want to solve this problem, cause it may cause problem in the future. The picture shows the error when I hover on it. Any advice on how to fix this issue?

And I'm confused as to why it found two version 24.2.1 and 24.0.0, why is this? Which version is the right one?

Thank You

UPDATE

I run gradlew app:dependencies on the terminal and found this,
if you look at the botton and found this com.android.support:appcompat-v7:24.0.0 (at the bottom):

```<code>+--- com.google.android.gms:play-services:10.2.1
|    +--- com.google.android.gms:play-services-ads:10.2.1
|    |    +--- com.google.android.gms:play-services-ads-lite:10.2.1
|    |    |    \--- com.google.android.gms:play-services-basement:10.2.1
|    |    |         \--- com.android.support:support-v4:24.0.0 -> 24.2.1 (*)
|    |    +--- com.google.android.gms:play-services-base:10.2.1
|    |    |    +--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    |    \--- com.google.android.gms:play-services-tasks:10.2.1
|    |    |         \--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-clearcut:10.2.1
|    |    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    |    \--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    \--- com.google.android.gms:play-services-gass:10.2.1
|    |         \--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    +--- com.google.android.gms:play-services-ads-lite:10.2.1 (*)
|    +--- com.google.android.gms:play-services-analytics:10.2.1
|    |    +--- com.google.android.gms:play-services-analytics-impl:10.2.1
|    |    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    |    \--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    \--- com.google.android.gms:play-services-tagmanager-v4-impl:10.2.1
|    |         +--- com.google.android.gms:play-services-analytics-impl:10.2.1 (*)
|    |         +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |         \--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    +--- com.google.android.gms:play-services-analytics-impl:10.2.1 (*)
|    +--- com.google.android.gms:play-services-appinvite:10.2.1
|    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    \--- com.google.android.gms:play-services-tasks:10.2.1 (*)
|    +--- com.google.android.gms:play-services-auth:10.2.1
|    |    +--- com.google.android.gms:play-services-auth-base:10.2.1
|    |    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    |    \--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    \--- com.google.android.gms:play-services-tasks:10.2.1 (*)
|    +--- com.google.android.gms:play-services-auth-base:10.2.1 (*)
|    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    +--- com.google.android.gms:play-services-cast-framework:10.2.1
|    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-cast:10.2.1
|    |    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    |    +--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    |    \--- **com.android.support:mediarouter-v7:24.0.0**
|    |    |         +--- com.android.support:palette-v7:24.0.0
|    |    |         |    \--- com.android.support:support-v4:24.0.0 -> 24.2.1 (*)
|    |    |         \--- **com.android.support:appcompat-v7:24.0.0** -> 24.2.1 (*)
</code>```

And if I follow the root of it and found com.android.support:mediarouter-v7:24.0.0, so I add it to the dependencies and change it to compile com.android.support:mediarouter-v7:24.2.1, and the error is gone now. Is this the right way of doing it? Btw, I run my app and there is no error(There app still runs before, eventhough there is an error in the gradle).

Thanks

答:
One of the libraries you are using depends on a specific AppCompat version but you  are referencing a different version in your own app.

Find out which library is doing this then exclude the AppCompat references that are causing the fault from the build.

e.g.

```<code>compile("com.your.libary:1.0.0") {
    exclude group: 'com.android.support', module: 'support-annotations'
    exclude group: 'com.android.support', module: 'support-v4'
    exclude group: 'com.android.support', module: 'appcompat-v7'
    exclude group: 'com.android.support', module: 'preference-v7'
}
</code>```

Body:
The app runs when I build it, and works fine. But I want to solve this problem, cause it may cause problem in the future. The picture shows the error when I hover on it. Any advice on how to fix this issue?

And I'm confused as to why it found two version 24.2.1 and 24.0.0, why is this? Which version is the right one?

Thank You

UPDATE

I run gradlew app:dependencies on the terminal and found this,
if you look at the botton and found this com.android.support:appcompat-v7:24.0.0 (at the bottom):

+--- com.google.android.gms:play-services:10.2.1
|    +--- com.google.android.gms:play-services-ads:10.2.1
|    |    +--- com.google.android.gms:play-services-ads-lite:10.2.1
|    |    |    \--- com.google.android.gms:play-services-basement:10.2.1
|    |    |         \--- com.android.support:support-v4:24.0.0 -> 24.2.1 (*)
|    |    +--- com.google.android.gms:play-services-base:10.2.1
|    |    |    +--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    |    \--- com.google.android.gms:play-services-tasks:10.2.1
|    |    |         \--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-clearcut:10.2.1
|    |    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    |    \--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    \--- com.google.android.gms:play-services-gass:10.2.1
|    |         \--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    +--- com.google.android.gms:play-services-ads-lite:10.2.1 (*)
|    +--- com.google.android.gms:play-services-analytics:10.2.1
|    |    +--- com.google.android.gms:play-services-analytics-impl:10.2.1
|    |    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    |    \--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    \--- com.google.android.gms:play-services-tagmanager-v4-impl:10.2.1
|    |         +--- com.google.android.gms:play-services-analytics-impl:10.2.1 (*)
|    |         +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |         \--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    +--- com.google.android.gms:play-services-analytics-impl:10.2.1 (*)
|    +--- com.google.android.gms:play-services-appinvite:10.2.1
|    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    \--- com.google.android.gms:play-services-tasks:10.2.1 (*)
|    +--- com.google.android.gms:play-services-auth:10.2.1
|    |    +--- com.google.android.gms:play-services-auth-base:10.2.1
|    |    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    |    \--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    \--- com.google.android.gms:play-services-tasks:10.2.1 (*)
|    +--- com.google.android.gms:play-services-auth-base:10.2.1 (*)
|    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    +--- com.google.android.gms:play-services-cast-framework:10.2.1
|    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    +--- com.google.android.gms:play-services-cast:10.2.1
|    |    |    +--- com.google.android.gms:play-services-base:10.2.1 (*)
|    |    |    +--- com.google.android.gms:play-services-basement:10.2.1 (*)
|    |    |    \--- **com.android.support:mediarouter-v7:24.0.0**
|    |    |         +--- com.android.support:palette-v7:24.0.0
|    |    |         |    \--- com.android.support:support-v4:24.0.0 -> 24.2.1 (*)
|    |    |         \--- **com.android.support:appcompat-v7:24.0.0** -> 24.2.1 (*)

And if I follow the root of it and found com.android.support:mediarouter-v7:24.0.0, so I add it to the dependencies and change it to compile com.android.support:mediarouter-v7:24.2.1, and the error is gone now. Is this the right way of doing it? Btw, I run my app and there is no error(There app still runs before, eventhough there is an error in the gradle).

Thanks

Body:
One of the libraries you are using depends on a specific AppCompat version but you  are referencing a different version in your own app.

Find out which library is doing this then exclude the AppCompat references that are causing the fault from the build.

e.g.

compile("com.your.libary:1.0.0") {
    exclude group: 'com.android.support', module: 'support-annotations'
    exclude group: 'com.android.support', module: 'support-v4'
    exclude group: 'com.android.support', module: 'appcompat-v7'
    exclude group: 'com.android.support', module: 'preference-v7'
}


问:
Javascript - Read value of a JSON property, if that key doesn't exist return null, in a single line
Let me give a python analogy of what I am looking for:

```<code>fruits_dict = {"banana": 4, "apple": 3}
num_apples = fruits_dict.get("apple", None)
num_oranges = fruits_dict.get("orange", None)
print(num_apples, num_oranges)
</code>```

prints:
    3 None

Now in Javascript, with a similar JS object, we can use hasOwnProperty(key) in a if block

```<code>var fruits_obj = {"banana": 4, "apple": 3};
var num_apples = null;
if (fruits_obj.hasOwnProperty("apple")) {
    num_apples = fruits_obj["apple"];
}
var num_oranges = null;
if (fruits_obj.hasOwnProperty("orange")) {
    num_oranges = fruits_obj["orange"];
}
console.log(num_apples, num_oranges);
</code>```

gives:
    3 null

Is there a better way? Something on the lines of python's get function?

答:
You can implement a dynamic get in your prototype object.</p>

```<code>get: function(key) {
    if (typeof this[key] == 'undefined') return null;
    return this[key]
}
</code>```

Body:
Let me give a python analogy of what I am looking for:

fruits_dict = {"banana": 4, "apple": 3}
num_apples = fruits_dict.get("apple", None)
num_oranges = fruits_dict.get("orange", None)
print(num_apples, num_oranges)

prints:
    3 None

Now in Javascript, with a similar JS object, we can use hasOwnProperty(key) in a if block

var fruits_obj = {"banana": 4, "apple": 3};
var num_apples = null;
if (fruits_obj.hasOwnProperty("apple")) {
    num_apples = fruits_obj["apple"];
}
var num_oranges = null;
if (fruits_obj.hasOwnProperty("orange")) {
    num_oranges = fruits_obj["orange"];
}
console.log(num_apples, num_oranges);

gives:
    3 null

Is there a better way? Something on the lines of python's get function?

Body:
You can implement a dynamic get in your prototype object.

get: function(key) {
    if (typeof this[key] == 'undefined') return null;
    return this[key]
}


问:
Using Jersey 2.x web service on Weblogic 12.1.1
I'm trying to deploy Jersey 2.13 web services to Weblogic 12.1.1. This version of weblogic is compliant with JSR-311 JAX-RS 1.1 specification whereas Jersey 2.x provides implementation for JAX-RS 2.0

Oracle has an instruction on how to upgrade the version of Jersey JAX-RS RI :
http://docs.oracle.com/cd/E24329_01/web.1211/e24983/version.htm

However even this doesn't help solving all of the deployment issues.

I'm packaging the application in EAR containing WAR. In order to override weblogic jars I've included added the following weblogic-application.xml file :

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
<weblogic-application xmlns="http://www.bea.com/ns/weblogic/90">
  <prefer-application-packages>
    <!-- apis -->
    <package-name>javax.ws.rs.*</package-name>
    <!-- guava -->
    <package-name>com.google.common.*</package-name>
    <!-- jersey1 providers -->
    <package-name>com.sun.jersey.*</package-name>
    <!-- media providers -->
    <package-name>org.eclipse.persistence.jaxb.rs.*</package-name>
    <package-name>org.codehaus.jackson.jaxrs.*</package-name>
    <!-- wls -->
    <package-name>weblogic.jaxrs.api.client.*</package-name>
    <package-name>weblogic.jaxrs.internal.api.client.*</package-name>
    <package-name>weblogic.jaxrs.dispatch.*</package-name>
    <package-name>weblogic.jaxrs.monitoring.util.*</package-name>

   </prefer-application-packages>
</weblogic-application>
</code>```

This configuration gives me a following error message on deployment :

```<code>Caused By: java.lang.NoSuchMethodError: org.glassfish.hk2.api.ServiceLocatorFactory.create(Ljava/lang/String;Lorg/glassfish/hk2/api/ServiceLocator;Lorg/glassfish/hk2/extension/ServiceLocatorGenerator;Lorg/glassfish/hk2/api/ServiceLocatorFactory$CreatePolicy;)Lorg/glassfish/hk2/api/ServiceLocator;
</code>```

If I try to replace org.glassfish.hk2.* classes by adding it to prefer-application-packages I receive new errors and it's continuing forever...

Has anyone migrated Jersey to version 2.x on weblogic 12.1.1 or below?

Thanks!

答:
I had the same problem when I upgraded my Jersey to 2.22.

The Weblogic 12.1.3 uses the 1.18 version of Jersey. To upgrade to another one, you can deploy the Jersey 2.x as a library on Weblogic and shared with your applications or config Weblogic to use Jersey from your application by weblogic.xml.

In my case I choose the second option:

weblogic.xml:

```<code><prefer-application-packages>
    <package-name>javax.ws.rs.*</package-name>
    <package-name>com.sun.jersey.*</package-name>
    <package-name>org.glassfish.*</package-name>
    <package-name>org.jvnet.hk2.*</package-name>
    <package-name>jersey.repackaged.org.objectweb.asm.*</package-name>
</prefer-application-packages>
</code>```

Body:
I'm trying to deploy Jersey 2.13 web services to Weblogic 12.1.1. This version of weblogic is compliant with JSR-311 JAX-RS 1.1 specification whereas Jersey 2.x provides implementation for JAX-RS 2.0

Oracle has an instruction on how to upgrade the version of Jersey JAX-RS RI :
http://docs.oracle.com/cd/E24329_01/web.1211/e24983/version.htm

However even this doesn't help solving all of the deployment issues.

I'm packaging the application in EAR containing WAR. In order to override weblogic jars I've included added the following weblogic-application.xml file :

<?xml version="1.0" encoding="ISO-8859-1"?>
<weblogic-application xmlns="http://www.bea.com/ns/weblogic/90">
  <prefer-application-packages>

    <package-name>javax.ws.rs.*</package-name>

    <package-name>com.google.common.*</package-name>

    <package-name>com.sun.jersey.*</package-name>

    <package-name>org.eclipse.persistence.jaxb.rs.*</package-name>
    <package-name>org.codehaus.jackson.jaxrs.*</package-name>

    <package-name>weblogic.jaxrs.api.client.*</package-name>
    <package-name>weblogic.jaxrs.internal.api.client.*</package-name>
    <package-name>weblogic.jaxrs.dispatch.*</package-name>
    <package-name>weblogic.jaxrs.monitoring.util.*</package-name>

   </prefer-application-packages>
</weblogic-application>

This configuration gives me a following error message on deployment :

Caused By: java.lang.NoSuchMethodError: org.glassfish.hk2.api.ServiceLocatorFactory.create(Ljava/lang/String;Lorg/glassfish/hk2/api/ServiceLocator;Lorg/glassfish/hk2/extension/ServiceLocatorGenerator;Lorg/glassfish/hk2/api/ServiceLocatorFactory$CreatePolicy;)Lorg/glassfish/hk2/api/ServiceLocator;

If I try to replace org.glassfish.hk2.* classes by adding it to prefer-application-packages I receive new errors and it's continuing forever...

Has anyone migrated Jersey to version 2.x on weblogic 12.1.1 or below?

Thanks!

Body:
I had the same problem when I upgraded my Jersey to 2.22.

The Weblogic 12.1.3 uses the 1.18 version of Jersey. To upgrade to another one, you can deploy the Jersey 2.x as a library on Weblogic and shared with your applications or config Weblogic to use Jersey from your application by weblogic.xml.

In my case I choose the second option:

weblogic.xml:

<prefer-application-packages>
    <package-name>javax.ws.rs.*</package-name>
    <package-name>com.sun.jersey.*</package-name>
    <package-name>org.glassfish.*</package-name>
    <package-name>org.jvnet.hk2.*</package-name>
    <package-name>jersey.repackaged.org.objectweb.asm.*</package-name>
</prefer-application-packages>


问:
Getting a casting error for no visible reason
I have this piece of code that's been throwing a casting error, and I have no idea why after playing with it for half an hour.  This is the piece of code:

```<code>var zips = DB.Get<Partner_to_ZipCode>()
                .AsQueryable()
                .Include(i => i.Partner)
                .Where(w => w.Partner.Id == id)
                .Select(s => s.ZipCode)
                .ToArray();
</code>```

It's pointing to line 146 of the controller, which is this linq query right here.  "Partner.Id" is an integer as is "id", and ZipCode is a string.  I have no idea what's going on here. I've tried commenting out pieces of code, casting variables, changing the array from a generic to a specific type, none of it did anything.  Any help would be appreciated.

The error message is:

{"message":"An error has occurred.","exceptionMessage":"The specified cast from a materialized 'System.Int32' type to the 'System.String' type is not valid.","exceptionType":"System.InvalidOperationException","stackTrace":"   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader`1.GetValue(DbDataReader reader, Int32 ordinal)\r\n   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper.GetColumnValueWithErrorHandling[TColumn](Int32 ordinal)\r\n   at System.Data.Entity.Core.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper)\r\n   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext()\r\n   at System.Linq.Buffer`1..ctor(IEnumerable`1 source)\r\n   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)\r\n   at PMP.MVC.Controllers.PartnerController.GetTasks(Int32 id) in c:\\Users\\maran\\OneDrive\\Documents\\RF\\main\\src\\PMP.MVC\\PMP.MVC\\Controllers\\PartnerController.cs:line 146\r\n   at lambda_method(Closure , Object , Object[] )\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.c__DisplayClass10.b__9(Object instance, Object[] methodParameters)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Controllers.ActionFilterResult.d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Controllers.ExceptionFilterResult.d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Web.Http.Controllers.ExceptionFilterResult.d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()"}

答:
one of these two might work:

```<code>.Where(w => w.Partner.Id.ToString() == id)

.Where(w => w.Partner.Id == id.ToString())
</code>```

one of those: local variable "id" or w.Partner.Id is a string and the other is a int.

It is safer to cast int to string than other way, because string might contain something else than numbers and you'll need to handle that case.

Body:
I have this piece of code that's been throwing a casting error, and I have no idea why after playing with it for half an hour.  This is the piece of code:

var zips = DB.Get<Partner_to_ZipCode>()
                .AsQueryable()
                .Include(i => i.Partner)
                .Where(w => w.Partner.Id == id)
                .Select(s => s.ZipCode)
                .ToArray();

It's pointing to line 146 of the controller, which is this linq query right here.  "Partner.Id" is an integer as is "id", and ZipCode is a string.  I have no idea what's going on here. I've tried commenting out pieces of code, casting variables, changing the array from a generic to a specific type, none of it did anything.  Any help would be appreciated.

The error message is:

{"message":"An error has occurred.","exceptionMessage":"The specified cast from a materialized 'System.Int32' type to the 'System.String' type is not valid.","exceptionType":"System.InvalidOperationException","stackTrace":"   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader`1.GetValue(DbDataReader reader, Int32 ordinal)\r\n   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper.GetColumnValueWithErrorHandling[TColumn](Int32 ordinal)\r\n   at System.Data.Entity.Core.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper)\r\n   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext()\r\n   at System.Linq.Buffer`1..ctor(IEnumerable`1 source)\r\n   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)\r\n   at PMP.MVC.Controllers.PartnerController.GetTasks(Int32 id) in c:\\Users\\maran\\OneDrive\\Documents\\RF\\main\\src\\PMP.MVC\\PMP.MVC\\Controllers\\PartnerController.cs:line 146\r\n   at lambda_method(Closure , Object , Object[] )\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.c__DisplayClass10.b__9(Object instance, Object[] methodParameters)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Controllers.ActionFilterResult.d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Controllers.ExceptionFilterResult.d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Web.Http.Controllers.ExceptionFilterResult.d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()"}

Body:
one of these two might work:

.Where(w => w.Partner.Id.ToString() == id)

.Where(w => w.Partner.Id == id.ToString())

one of those: local variable "id" or w.Partner.Id is a string and the other is a int.

It is safer to cast int to string than other way, because string might contain something else than numbers and you'll need to handle that case.


问:
Joining three tables w/user input
I have three tables, A, B, C. Table B has foreign keys into both A & C. A & C don't have keys into each other.

I'm trying to write a query where I get every hit from a column in Table C whose primary key (foreign key in B) matches a primary key from Table A (also a foreign key in B). A wrinkle is that I am trying to get this info based on a user input, which will be a separate column in Table A.

Example:

```<code>TABLE A
-------
aID    aName
1      Squeakers
2      Formations
3      Hutsis
4      Pms

TABLE B
-------
bID    aID    cID
1      1      27930
2      1      21405
3      1      24013
4      2      21111
5      1      34100
6      1      20841
7      4      30001

TABLE C
-------
cID      cName
21405    Silver Flyer
27930    Babs McGee
30001    Jimmy McGill
24013    Fletcher Mason
21111    Spike Fester
34100    Hope Sisco
20841    Ellis Traeger
</code>```

So I want a user to put in ‘Squeakers’ and then get something that looks like:

```<code>Squeakers – Babs McGee, Silver Flyer, Fletcher Mason, Hope Sisco, Ellis Trager
</code>```

I've been stuck on this for multiple days and can't figure out the syntax. I'm not sure if I need a sub-query or if it's not all INNER JOINS?

答:
A - Author (one row per author)
Author_Id, Author_Name, Author_Country

B - Author_Books (relationship table between author and books, one row per relation)
AB_ID, Author_ID, Book_ID

C - Books (One row per book)
Book_ID, Book_Name

Now, the query would be

```<code>Select a.Author_Name,b.Book_Name
from Author a, Author_Books B, Books C
where a.author_id =b.Author_ID
and B.Book_ID = C.Book_ID
and a.Author_Country = ? //This is your squeaker clause
</code>```

Title: Joining three tables w/user input

Body:
I have three tables, A, B, C. Table B has foreign keys into both A & C. A & C don't have keys into each other.

I'm trying to write a query where I get every hit from a column in Table C whose primary key (foreign key in B) matches a primary key from Table A (also a foreign key in B). A wrinkle is that I am trying to get this info based on a user input, which will be a separate column in Table A.

Example:

TABLE A
-------
aID    aName
1      Squeakers
2      Formations
3      Hutsis
4      Pms

TABLE B
-------
bID    aID    cID
1      1      27930
2      1      21405
3      1      24013
4      2      21111
5      1      34100
6      1      20841
7      4      30001

TABLE C
-------
cID      cName
21405    Silver Flyer
27930    Babs McGee
30001    Jimmy McGill
24013    Fletcher Mason
21111    Spike Fester
34100    Hope Sisco
20841    Ellis Traeger

So I want a user to put in ‘Squeakers’ and then get something that looks like:

Squeakers – Babs McGee, Silver Flyer, Fletcher Mason, Hope Sisco, Ellis Trager

I've been stuck on this for multiple days and can't figure out the syntax. I'm not sure if I need a sub-query or if it's not all INNER JOINS?

Body:
A - Author (one row per author)
Author_Id, Author_Name, Author_Country

B - Author_Books (relationship table between author and books, one row per relation)
AB_ID, Author_ID, Book_ID

C - Books (One row per book)
Book_ID, Book_Name

Now, the query would be

Select a.Author_Name,b.Book_Name
from Author a, Author_Books B, Books C
where a.author_id =b.Author_ID
and B.Book_ID = C.Book_ID
and a.Author_Country = ? //This is your squeaker clause


答:
```<code>var zips = DB.Get<Partner_to_ZipCode>()
.AsQueryable()
.Include(i => i.Partner)
.Where(w => w.Partner.Id.ToString() == id) // or (w => w.Partner.Id == int.Parse(id)) if id is an integer
.Select(s => s.ZipCode)
.ToArray();
</code>```

Title: Getting a casting error for no visible reason


问:
Smooth rotation in Processing
I was looking at the Processing reference in my classroom and put together a couple of examples in an animation. My professor is not teaching this material in the classroom and told me I might find better luck getting help from the community on Stack Overflow. My problem follows.

When ry reaches 70 the rotation stops. I put a comment in my code at where the problem might be.

I am trying to make a continuous and smooth animation.

int x = 200;
int y = 350;
int cubeWidth = 300;
int cubeHeight = 2;
float rY = 0.1;
float rX = 0.1;

void setup() {
  size(640, 360, P3D);
}

void draw() {

  background(3);
  lights();

  fill(247, 7, 12);

  rY = constrain(rY, 0, 70);
  rX = constrain(rX, 0, 70);
  pushMatrix();
  translate(441, height/cubeHeight, 0);
  rY = rY + .005;
  println(rY);
  rotateY(rY);  // <--- here, when rY hits 70, it stops
  rX += rX;
  rotateX(rX);
  noStroke();
  box(69);
  popMatrix();

  pushMatrix();
  translate(470, height*0.49, -221);
   rY = rY + .005;
  println(rY);
  rotateY(rY);
  rX += rX;
  rotateX(rX);
  noFill();
  stroke(238);
  sphere(282);
  popMatrix();
}
```

答:
as Kevin Workman said, rY = constrain(rY, 0, 70); was the problem. You just gave the rotation an end point. I changed the code a bit, because there were some logical mistakes so it kept adding values till infinity.

rX += rX; adds acceleration so after a while you get a big velocity of the object, for example ( 0.1 + 0.1 = 0.2; next frame 0.2 + 0.2 = 0.4 ... and so on ). If you could imagine that there are 100 frames per second, it gets really fast in no time. so you need only to add velocity, not the acceleration rX +=  1 which each frame will update the rotation by one this angle.

and you wrote code twice so in one frame it gets even bigger. I share the code which I updated maybe it will be more clear to see the changes in it.

```<code>float rY = 0.1;
float rX = 0.1;

void setup() {
  size(640, 360, P3D);
}

void draw() {

  background(3);
  lights();

  fill(125, 175, 225,175);

  pushMatrix();
  translate(width/2, height/2); // you do not need to write translate twice

  //box
  rY += 0.01; // you need only once to add the rotation value per frame
  rotateY(-rY); // negative rotation for the difference from sphere
  rX += 0.01;
  rotateX(-rX);
  noStroke();
  box(50);

  //sphere
  rotateY(rY);
  rotateX(rX);
  noFill();
  stroke(125, 175, 225,125);
  sphere(125);

  popMatrix();

  println(rY);
}
</code>```

Title: Smooth rotation in Processing

Body:
as Kevin Workman said, rY = constrain(rY, 0, 70); was the problem. You just gave the rotation an end point. I changed the code a bit, because there were some logical mistakes so it kept adding values till infinity.

rX += rX; adds acceleration so after a while you get a big velocity of the object, for example ( 0.1 + 0.1 = 0.2; next frame 0.2 + 0.2 = 0.4 ... and so on ). If you could imagine that there are 100 frames per second, it gets really fast in no time. so you need only to add velocity, not the acceleration rX +=  1 which each frame will update the rotation by one this angle.

and you wrote code twice so in one frame it gets even bigger. I share the code which I updated maybe it will be more clear to see the changes in it.

float rY = 0.1;
float rX = 0.1;

void setup() {
  size(640, 360, P3D);
}

void draw() {

  background(3);
  lights();

  fill(125, 175, 225,175);

  pushMatrix();
  translate(width/2, height/2); // you do not need to write translate twice

  //box
  rY += 0.01; // you need only once to add the rotation value per frame
  rotateY(-rY); // negative rotation for the difference from sphere
  rX += 0.01;
  rotateX(-rX);
  noStroke();
  box(50);

  //sphere
  rotateY(rY);
  rotateX(rX);
  noFill();
  stroke(125, 175, 225,125);
  sphere(125);

  popMatrix();

  println(rY);
}


问:
Apache Jmeter JDBC connection issue - JDBC driver class not found
I am trying to connect to PL/SQL 8.0.4.1514 through JMeter.

In JDBC connection configuration ,I have provided the database URL as "jdbc:oracle:thin:@//01HW552780:6129))/tnsfile" and JDBC driver class as "com.plsql.jdbc.Driver"

But getting error as "No suitable driver found for jdbc:oracle:thin:@//01HW552780:6129))/tnsfile"

Could someone rectify me here regarding driver class?

答:
Faced the same problem.

I used oracle.jdbc.OracleDriver as Driver Class.

No need to remove //. It can be present.

In database URL, it should be jdbc:oracle:thin:@//MachineName:Port/Schema

Download or better copy JDBC Jars from your DB installation and paste it under Jmeter/lib path.
For example, I presume you DB as Oracle 12c, it required ojdbc6.jar and ojdbc7.jar copied and pasted under Jmeter/lib folder.

After this activity, the problem vanished away for me.


问:
Open Source Control Libraries with liberal licences for Winforms, WPF and ASP.NET
I am looking for free "Open Source" controls (respectivels control libraries) for Winforms, WPF and ASP.NET with (very) liberal licences (like MIT-, Apache or BSD-Licence; not GPL or LGPL!), which can be used in commercial projects with proprietary licences.

Which ones are your suggestions and what would you recommend?

答:
Beside Codeplex take a look at Sourceforge. There are also good controls for MS technologies with liberal licences (e.g. the "Advanced Tree View" Control, which is under BSD Licence: http://sourceforge.net/projects/treeviewadv/). Sometimes there are also good controls on Codeproject.

Devexpress provides also free controls: https://www.devexpress.com/Products/Free/NetOffer/
But I am not sure, what the conditions are with this collection


问:
Symfony app, the content is displaying twice
First question here.
I'm developing a login page, and I can't figure out why my login form shows twice. I double checked the twig files and the routes and I don't see what could be causing it.

I'm using php server so I'm in the dev env, and I think what is happening is that my debug bar is being replaced with actual page causing to display the content twice. The debugger bar is not showing. I searched on google and I saw that they are mentioning something about the body tag not being closed, so I checked that too. Still noting. I checked if some other file is also calling login template. Nothing... Any suggestions?

Here is an image, which is worth than a thousand words.

Thanks

image shows the login page showing twice

In addition, here is the code that I'm using, which is straight from symfony's documentation:

Controller

```<code>/**
 * @Route("/login", name="security_login")
 */
public function loginAction(Request $request)
{
    $authenticationUtils = $this->get('security.authentication_utils');

    // get the login error if there is one
    $error = $authenticationUtils->getLastAuthenticationError();

    // last username entered by the user
    $lastUsername = $authenticationUtils->getLastUsername();

    return $this->render('security/login.html.twig', array(
        'last_username' => $lastUsername,
        'error'         => $error,
    ));
}
</code>```

Securit.yml

```<code>providers:
    app_user_prov:
        entity:
            class: AppBundle:User
firewalls:
    main:
        pattern: ^/
        anonymous: ~
        guard:
            authenticators:
                - cas_authenticator
</code>```

login twig file:

```<code>{% extends 'base.html.twig' %}

{% block content %}
{% if error %}
    <div class="row">
        <div class="col-lg-12">
            <p class="bg-danger">{{ error.messageKey|trans(error.messageData, 'security') }}</p>
        </div>
    </div>
{% endif %}

    <div class="row">
        <div class="col-lg-12 text-center" style="margin-top:35px;">
            <img style="border:none;" src="loreipsum.png" width="200">
            <br /> <br />
            <form action="{{ path("security_login") }}" method="post" style="margin-top:15px;">
                <div class="form-group">
                    <label for="username">Username or email</label>
                    <input type="text" id="username" name="_username" value="{{ last_username }}" required="required" />
                </div>
                <div class="form-group">
                    <label for="password">Password</label>
                    <input type="password" id="password" name="_password" required="required" />
                </div>
                <input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}">
                <div class="form-group">
                    <input type="submit" id="_submit" name="_submit" value="Submit" />
                </div>
            </form>
        </div>
    </div>
{% endblock %}
</code>```

Base twig file:

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{% block title %}Administration{% endblock %}</title>

    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"
          integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymo

        {% block stylesheets %}{% endblock %}
        <link rel="icon" type="image/x-icon" href="{{ asset('favicon.ico') }}" />

    <!-- jQuery and Bootstrap -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
            integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

    {% block javascripts %}{% endblock %}
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-lg-6">
            <h1 class="text-left">
                <img style="border:none;" src="loremipsum.jpg" width="200">
            </h1>
        </div>
        <div class="col-lg-6">
            <h3 class="text-right"> <br/>Lorem ipsum</h3>
        </div>
    </div>

    {% block content %}{% endblock %}

</div>
</body>
</html>
</code>```

答:
Maybe your login page have not public access:

```<code>- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
</code>```

So symfony show FOS Login first and when you authenticate user, redirect to the previous requested page /login

Body:
First question here.
I'm developing a login page, and I can't figure out why my login form shows twice. I double checked the twig files and the routes and I don't see what could be causing it.

I'm using php server so I'm in the dev env, and I think what is happening is that my debug bar is being replaced with actual page causing to display the content twice. The debugger bar is not showing. I searched on google and I saw that they are mentioning something about the body tag not being closed, so I checked that too. Still noting. I checked if some other file is also calling login template. Nothing... Any suggestions?

Here is an image, which is worth than a thousand words.

Thanks

image shows the login page showing twice

In addition, here is the code that I'm using, which is straight from symfony's documentation:

Controller

/**
 * @Route("/login", name="security_login")
 */
public function loginAction(Request $request)
{
    $authenticationUtils = $this->get('security.authentication_utils');

    // get the login error if there is one
    $error = $authenticationUtils->getLastAuthenticationError();

    // last username entered by the user
    $lastUsername = $authenticationUtils->getLastUsername();

    return $this->render('security/login.html.twig', array(
        'last_username' => $lastUsername,
        'error'         => $error,
    ));
}

Securit.yml

providers:
    app_user_prov:
        entity:
            class: AppBundle:User
firewalls:
    main:
        pattern: ^/
        anonymous: ~
        guard:
            authenticators:
                - cas_authenticator

login twig file:

{% extends 'base.html.twig' %}

{% block content %}
{% if error %}

{{ error.messageKey|trans(error.messageData, 'security') }}

{% endif %}

            <form action="{{ path("security_login") }}" method="post" style="margin-top:15px;">

                    Username or email
                    <input type="text" id="username" name="_username" value="{{ last_username }}" required="required" />

                    Password
                    <input type="password" id="password" name="_password" required="required" />

                <input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}">

                    <input type="submit" id="_submit" name="_submit" value="Submit" />

            </form>

{% endblock %}

Base twig file:

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{% block title %}Administration{% endblock %}</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"
          integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymo

        {% block stylesheets %}{% endblock %}
        <link rel="icon" type="image/x-icon" href="{{ asset('favicon.ico') }}" />

    {% block javascripts %}{% endblock %}

Lorem ipsum

    {% block content %}{% endblock %}

Body:
Maybe your login page have not public access:

- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }

So symfony show FOS Login first and when you authenticate user, redirect to the previous requested page /login


问:
CMS Cache, Gzip and Cloudflare can they all work together?
Lately I've become somewhat obsessed with page speed optimization and I wanted to find out can CMS caching mechanism (For example Joomla cache), Gzip compression and Cloudflare work all together in perfect harmony?

I understand how each system works by itself (more or less), but I don't understand would they work together. Is it even recommended to use all of them at once?

If I use cloudflare do CMS cache and Gzip even matter?

P.S What other tools do you use?

答:
Just a heads up. Some content in certain browsers can experience byte range request issues if you have gzip enabled while using cloudfare.

For instance, depending on server, Safari will (most likely) not play mp4 video served through cloudfare and gzip enabled server. Gzip can interfere with byte-range separation of requests.

I ran into this issue before and figured I would share in case anyone runs into any of these issues.

If you want to have gzip enabled, but experience issues with certain files, you can disable gzip for those specific files in .htaccess by adding this:

```<code><IfModule mod_headers.c>
<FilesMatch "\.mp4$">
    RewriteRule ^(.*)$ $1 [NS,E=no-gzip:1,E=dont-vary:1]
</FilesMatch>
</code>```

Just replace .mp4 with file type if issues with any others.

Body:
Just a heads up. Some content in certain browsers can experience byte range request issues if you have gzip enabled while using cloudfare.

For instance, depending on server, Safari will (most likely) not play mp4 video served through cloudfare and gzip enabled server. Gzip can interfere with byte-range separation of requests.

I ran into this issue before and figured I would share in case anyone runs into any of these issues.

If you want to have gzip enabled, but experience issues with certain files, you can disable gzip for those specific files in .htaccess by adding this:

<IfModule mod_headers.c>
<FilesMatch "\.mp4$">
    RewriteRule ^(.*)$ $1 [NS,E=no-gzip:1,E=dont-vary:1]
</FilesMatch>

Just replace .mp4 with file type if issues with any others.


问:
Using Swift3 Function Parameter in Selector
I'm attempting to pass in a function to add as a target to a UIButton in Swift3, but I'm getting the following error:

```<code>Argument of '#selector' does not refer to an '@objc' method, property, or initializer
</code>```

Here's my code:

```<code>func updateButtonAction(_ action: () -> (), button: UIButton) {
    button.addTarget(self, action: #selector(customFunction(action)), for: .touchUpInside)
}

func customFunction(_ function: () -> ()) {
    function()
}
</code>```

I'm wrapping a passed in function in another function so I know the class that owns it.

I think the issue is that first class functions in Swift aren't supported in Objective-C and the selector keyword only uses Objective-C functions.

Does anyone know a way around this?

答:
Selector is just a fancy synonym for method name. It's not a closure or a function. It's the name of a method on an Obj-C object. Technically, a selector is a string.

customFunction(action) is not a selector. The selector is customFunction(_:).

You are trying to pass an implicit parameter to the selector. That's not how selectors work. You are not calling the method, you are just telling the UIButton which method it should call - UIButton is calling the method and the button is also specifying the parameters.

If you need to pass some code to the event handler, save it on your instance.

```<code>var function: (() -> Void)?

func customFunction() {
    self.function?()
}
</code>```

In general it's a good idea to have only one event handler and not change it.

Also note that your example has no need for first class functions.

Body:
I'm attempting to pass in a function to add as a target to a UIButton in Swift3, but I'm getting the following error:

Argument of '#selector' does not refer to an '@objc' method, property, or initializer

Here's my code:

func updateButtonAction(_ action: () -> (), button: UIButton) {
    button.addTarget(self, action: #selector(customFunction(action)), for: .touchUpInside)
}

func customFunction(_ function: () -> ()) {
    function()
}

I'm wrapping a passed in function in another function so I know the class that owns it.

I think the issue is that first class functions in Swift aren't supported in Objective-C and the selector keyword only uses Objective-C functions.

Does anyone know a way around this?

Body:
Selector is just a fancy synonym for method name. It's not a closure or a function. It's the name of a method on an Obj-C object. Technically, a selector is a string.

customFunction(action) is not a selector. The selector is customFunction(_:).

You are trying to pass an implicit parameter to the selector. That's not how selectors work. You are not calling the method, you are just telling the UIButton which method it should call - UIButton is calling the method and the button is also specifying the parameters.

If you need to pass some code to the event handler, save it on your instance.

var function: (() -> Void)?

func customFunction() {
    self.function?()
}

In general it's a good idea to have only one event handler and not change it.

Also note that your example has no need for first class functions.


问:
How to sort the sequence of checkbox
I have two checkboxes. If I check cb1 first and cb2 next, the ListBox should display the data of the checkboxes in order of checked sequence.

```<code>Public Class Form1

  Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If cb1.Checked = True And cb2.Checked = False Then
      ListBox1.Items.Add(cb1.Text)
      If cb1.Checked = True And cb2.Checked = True Then
        ListBox1.Items.Add(cb1.Text)
      End If
    ElseIf cb2.Checked = True And cb1.Checked = False Then
      ListBox1.Items.Add(cb2.Text)
      If cb2.Checked = True And cb1.Checked = True Then
        ListBox1.Items.Add(cb1.Text)
      End If
    End If
  End Sub
End Class
</code>```

If only one checkbox is checked it displays the data, but if both are checked there's no data displayed in the list box.

答:
You're question is not clear enough for me to be sure of what you want exactly but here is the solution to the question I interpreted:

Your code for checking if both were true was nested within if statements which wouldn't run if they were both true.
Also, dont put an end if at the end of an elseif if you have more criteria to come.

Fixed code:

```<code>Private Sub Button1_Click(sender As System.Object, e As System.EventArgs)         Handles Button1.Click
    If cb1.Checked = True AND cb2.Checked = False Then
        ListBox1.Items.Add(cb1.Text)
    ElseIf cb1.Checked = True AND cb2.Checked = True Then
        ListBox1.Items.Add(cb1.Text)
        ListBox1.Items.Add(cb2.Text)
    End if

    If cb2.Checked = True And cb1.Checked = False Then
        ListBox1.Items.Add(cb2.Text)
    ElseIf cb2.Checked = True And cb1.Checked = True Then
        ListBox1.Items.Add(cb2.Text)
        ListBox1.Items.Add(cb1.Text)
    End If

End Sub
</code>```

You would probably have better luck if you made an event happen automatically after each one is checked. This code will only run once, so if you have only one checked and the code runs, even if the other one is then checked, the code won't run again unless you have it in some sort of loop (until loop could work).

Title: How to sort the sequence of checkbox

Body:
I have two checkboxes. If I check cb1 first and cb2 next, the ListBox should display the data of the checkboxes in order of checked sequence.

Public Class Form1

  Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If cb1.Checked = True And cb2.Checked = False Then
      ListBox1.Items.Add(cb1.Text)
      If cb1.Checked = True And cb2.Checked = True Then
        ListBox1.Items.Add(cb1.Text)
      End If
    ElseIf cb2.Checked = True And cb1.Checked = False Then
      ListBox1.Items.Add(cb2.Text)
      If cb2.Checked = True And cb1.Checked = True Then
        ListBox1.Items.Add(cb1.Text)
      End If
    End If
  End Sub
End Class

If only one checkbox is checked it displays the data, but if both are checked there's no data displayed in the list box.

Body:
You're question is not clear enough for me to be sure of what you want exactly but here is the solution to the question I interpreted:

Your code for checking if both were true was nested within if statements which wouldn't run if they were both true.
Also, dont put an end if at the end of an elseif if you have more criteria to come.

Fixed code:

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs)         Handles Button1.Click
    If cb1.Checked = True AND cb2.Checked = False Then
        ListBox1.Items.Add(cb1.Text)
    ElseIf cb1.Checked = True AND cb2.Checked = True Then
        ListBox1.Items.Add(cb1.Text)
        ListBox1.Items.Add(cb2.Text)
    End if

    If cb2.Checked = True And cb1.Checked = False Then
        ListBox1.Items.Add(cb2.Text)
    ElseIf cb2.Checked = True And cb1.Checked = True Then
        ListBox1.Items.Add(cb2.Text)
        ListBox1.Items.Add(cb1.Text)
    End If

End Sub

You would probably have better luck if you made an event happen automatically after each one is checked. This code will only run once, so if you have only one checked and the code runs, even if the other one is then checked, the code won't run again unless you have it in some sort of loop (until loop could work).


问:
Ajax Call Not Returning Data Django
I want to write a simple ajax method to fire up whenever the document is ready. I have the following JS:

```<code>$(document).ready(function()
    {
    $.ajax({
        type:'GET',
        url: '/get_alert',
        sucess: function(data){
            data = JSON.parse(data);
            alert("Hi");
            console.log(data);
            $('#notification_symbol').css('display','inline');
        },
        error: function(){
            console.log("Hello");
        }
    });
 }
</code>```

I can confirm that the url is working and that the call is being made on ready. However, it is not returning any data. Here is my function in views.py:

```<code>def get_alert(request):
    alert = False
    events = EventInvite.objects.filter(Invitee_id=request.user.id, Status= InvitationStatus.objects.filter(Status='Pending')[0]).order_by('-date')
    for event in events:
        if event.seen:
            alert = True
    dict = {
        'alert':alert,
    }
    print(dict) # Tells me the call is being made on ready...
    return JsonResponse(dict)
</code>```

Any ideas?

答:
Do you have CSRF token code in place? This is usually the issue for me when having ajax-y problems. I'm not sure what django you're working with (I'm around ~1.8) but the following code usually clears this up for me. Just plop this in a script tag in your html page. This auto posts CSRF stuff when you do ajax calls.

```<code>function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
     var cookies = document.cookie.split(';');
    for (var i = 0; i < cookies.length; i++) {
        var cookie = jQuery.trim(cookies[i]);
        // Does this cookie string begin with the name we want?
        if (cookie.substring(0, name.length + 1) == (name + '=')) {
            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
            break;
        }
    }
}
return cookieValue;
}

var csrftoken = getCookie('csrftoken');
   function csrfSafeMethod(method) {
   // these HTTP methods do not require CSRF protection
  return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
        xhr.setRequestHeader("X-CSRFToken", csrftoken);
      }
  }
});
</code>```

This link contains the django docs reference pages that explain these snippets.

Title: Ajax Call Not Returning Data Django

Body:
I want to write a simple ajax method to fire up whenever the document is ready. I have the following JS:

$(document).ready(function()
    {
    $.ajax({
        type:'GET',
        url: '/get_alert',
        sucess: function(data){
            data = JSON.parse(data);
            alert("Hi");
            console.log(data);
            $('#notification_symbol').css('display','inline');
        },
        error: function(){
            console.log("Hello");
        }
    });
 }

I can confirm that the url is working and that the call is being made on ready. However, it is not returning any data. Here is my function in views.py:

def get_alert(request):
    alert = False
    events = EventInvite.objects.filter(Invitee_id=request.user.id, Status= InvitationStatus.objects.filter(Status='Pending')[0]).order_by('-date')
    for event in events:
        if event.seen:
            alert = True
    dict = {
        'alert':alert,
    }
    print(dict) # Tells me the call is being made on ready...
    return JsonResponse(dict)

Any ideas?

Body:
Do you have CSRF token code in place? This is usually the issue for me when having ajax-y problems. I'm not sure what django you're working with (I'm around ~1.8) but the following code usually clears this up for me. Just plop this in a script tag in your html page. This auto posts CSRF stuff when you do ajax calls.

function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
     var cookies = document.cookie.split(';');
    for (var i = 0; i < cookies.length; i++) {
        var cookie = jQuery.trim(cookies[i]);
        // Does this cookie string begin with the name we want?
        if (cookie.substring(0, name.length + 1) == (name + '=')) {
            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
            break;
        }
    }
}
return cookieValue;
}

var csrftoken = getCookie('csrftoken');
   function csrfSafeMethod(method) {
   // these HTTP methods do not require CSRF protection
  return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
        xhr.setRequestHeader("X-CSRFToken", csrftoken);
      }
  }
});

This link contains the django docs reference pages that explain these snippets.


问:
SSRS report column list sort order
Hi for my ssrs report i am using a matrix to display data row as a two column list and
I am using the following expression in order to group the row;

=ceiling(rownumber(nothing) / 2)
  and

the following expression to group column;

=ceiling(rownumber(nothing) mod 2)

similar to https://www.experts-exchange.com/articles/12331/Simple-way-to-show-multi-column-data-in-SSRS-Horizontally-or-Vertically.html

it is working correctly however i would like results to be display alphabetical order going vertical instead of horizontal.

Like.

```<code>Record a    Record d

Record b    Record e

Record c    Record f
</code>```

Instead of

```<code>Record a    Record b

Record c    Record d

Record e    Record f
</code>```

i have order by in my sql query

any suggestions on how to achieve this?

答:
You can modify your sql for this. The hack below could be used if you do not want to use multiple columns.

```<code>DECLARE @T TABLE
(
    TableID INT,
    Value1 NVARCHAR(20),
    ShouldBe INT
)

    INSERT INTO @T (TableID,Value1,ShouldBe)
    VALUES
    (1,'A',1),
    (2,'B',3),
    (3,'C',5),
    (4,'D',2),
    (5,'E',4),
    (6,'F',6),

    (7,'A',1),
    (8,'B',3),
    (9,'C',5),
    (10,'D',2),
    (11,'E',4),
    (12,'F',6),

    (13,'A',1)

    DECLARE @NumberOfRowsPerPage INT = 3
    DECLARE @NumberOfColumns INT = 2

    SELECT PageNumber,Value1
    FROM
    (
        SELECT ColumnOrder=ROW_NUMBER() OVER(PARTITION BY PageNumber,ColumnTile  ORDER BY TableID),*
        FROM
        (
            SELECT ColumnTile=NTILE(@NumberOfColumns) OVER(PARTITION BY PageNumber ORDER BY TableID),*
            FROM
            (
                SELECT PageNumber=( (DataRowNumber -1) / (@NumberOfRowsPerPage * @NumberOfColumns )) + 1, *
                FROM
                (
                    SELECT DataRowNumber=ROW_NUMBER() OVER( ORDER BY TableID) ,*
                    FROM @T
                )AS A
            )AS B
        )AS C
    )AS D
    ORDER BY
        PageNumber,ColumnOrder,DataRowNumber
</code>```

The query will produce the following output based on the RowsPerPage and NumberOfColumns.

```<code>Page   Value
1   A
1   D
1   B
1   E
1   C
1   F
2   A
2   D
2   B
2   E
2   C
2   F
3   A
</code>```

Title: SSRS report column list sort order

Body:
Hi for my ssrs report i am using a matrix to display data row as a two column list and
I am using the following expression in order to group the row;

=ceiling(rownumber(nothing) / 2)
  and

the following expression to group column;

=ceiling(rownumber(nothing) mod 2)

similar to https://www.experts-exchange.com/articles/12331/Simple-way-to-show-multi-column-data-in-SSRS-Horizontally-or-Vertically.html

it is working correctly however i would like results to be display alphabetical order going vertical instead of horizontal.

Like.

Record a    Record d

Record b    Record e

Record c    Record f

Instead of

Record a    Record b

Record c    Record d

Record e    Record f

i have order by in my sql query

any suggestions on how to achieve this?

Body:
You can modify your sql for this. The hack below could be used if you do not want to use multiple columns.

DECLARE @T TABLE
(
    TableID INT,
    Value1 NVARCHAR(20),
    ShouldBe INT
)

    INSERT INTO @T (TableID,Value1,ShouldBe)
    VALUES
    (1,'A',1),
    (2,'B',3),
    (3,'C',5),
    (4,'D',2),
    (5,'E',4),
    (6,'F',6),

    (7,'A',1),
    (8,'B',3),
    (9,'C',5),
    (10,'D',2),
    (11,'E',4),
    (12,'F',6),

    (13,'A',1)

    DECLARE @NumberOfRowsPerPage INT = 3
    DECLARE @NumberOfColumns INT = 2

    SELECT PageNumber,Value1
    FROM
    (
        SELECT ColumnOrder=ROW_NUMBER() OVER(PARTITION BY PageNumber,ColumnTile  ORDER BY TableID),*
        FROM
        (
            SELECT ColumnTile=NTILE(@NumberOfColumns) OVER(PARTITION BY PageNumber ORDER BY TableID),*
            FROM
            (
                SELECT PageNumber=( (DataRowNumber -1) / (@NumberOfRowsPerPage * @NumberOfColumns )) + 1, *
                FROM
                (
                    SELECT DataRowNumber=ROW_NUMBER() OVER( ORDER BY TableID) ,*
                    FROM @T
                )AS A
            )AS B
        )AS C
    )AS D
    ORDER BY
        PageNumber,ColumnOrder,DataRowNumber

The query will produce the following output based on the RowsPerPage and NumberOfColumns.

Page   Value
1   A
1   D
1   B
1   E
1   C
1   F
2   A
2   D
2   B
2   E
2   C
2   F
3   A


问:
NHibernate: Simplest way to return an object with paged children collection?
I want to return one Parent object with the children collection eagerly loaded with the requested page (subset) of children objects.  What's the best way to achieve this?   Filters? Is is possible with an ICriteria query?

I'm using  .SetFirstResult() and .SetMaxResults() to do paging for collections of aggregate root results, but is it possible to utilize this withing the aggregate root to select the page of children results?

Something along these lines:

```<code>public class Parent{
int Id;
IList<Child> Children;
}

public Parent GetWithPagedChildren(int id, int page, int pageSize, out int count)
{
    //Query

    return Parentresult; //With one page of children populated.
}
</code>```

UPDATE:

Actually, the eagerly loading requirement is not so important.  I just want the paged subset of the child objects loaded when I access them.

答:
Just read this bit in the NHibernate Documentation 'Querying tips and tricks' section (13.13):

```<code>//Collections are pageable by using the IQuery interface with a filter:

IQuery q = s.CreateFilter( collection, "" ); // the trivial filter
q.setMaxResults(PageSize);
q.setFirstResult(PageSize * pageNumber);
IList page = q.List();
</code>```

I'm not entirely sure yet how this will work with a child collection but will try it and update this answer.

Body:
I want to return one Parent object with the children collection eagerly loaded with the requested page (subset) of children objects.  What's the best way to achieve this?   Filters? Is is possible with an ICriteria query?

I'm using  .SetFirstResult() and .SetMaxResults() to do paging for collections of aggregate root results, but is it possible to utilize this withing the aggregate root to select the page of children results?

Something along these lines:

public class Parent{
int Id;
IList<Child> Children;
}

public Parent GetWithPagedChildren(int id, int page, int pageSize, out int count)
{
    //Query

    return Parentresult; //With one page of children populated.
}

UPDATE:

Actually, the eagerly loading requirement is not so important.  I just want the paged subset of the child objects loaded when I access them.

Body:
Just read this bit in the NHibernate Documentation 'Querying tips and tricks' section (13.13):

//Collections are pageable by using the IQuery interface with a filter:

IQuery q = s.CreateFilter( collection, "" ); // the trivial filter
q.setMaxResults(PageSize);
q.setFirstResult(PageSize * pageNumber);
IList page = q.List();

I'm not entirely sure yet how this will work with a child collection but will try it and update this answer.


问:
Transaction within a cursor
Is the following the correct way to use transactions within a cursor:</p>

```<code>SET CURSOR_CLOSE_ON_COMMIT ON;

DECLARE cur CURSOR LOCAL FOR
    SELECT * FROM @ordersToProcess;
OPEN cur;

DECLARE @OrderId int;

FETCH NEXT FROM cur INTO @OrderId;
WHILE @@FETCH_STATUS = 0 BEGIN
    BEGIN TRY
        BEGIN TRAN;
        EXEC process_order @OrderId;
        COMMIT TRAN;
        DEALLOCATE cur;
        SET CURSOR_CLOSE_ON_COMMIT OFF;
    END TRY
    BEGIN CATCH
        ROLLBACK TRAN;
        DEALLOCATE cur;
        SET CURSOR_CLOSE_ON_COMMIT OFF;
        THROW;
    END CATCH;

    FETCH NEXT FROM cur INTO @OrderId;
END;
</code>```

答:
No.  You have this code:

```<code>WHILE @@FETCH_STATUS = 0 BEGIN
    BEGIN TRY
        BEGIN TRAN;
        EXEC process_order @OrderId;
        COMMIT TRAN;
        DEALLOCATE cur;
        SET CURSOR_CLOSE_ON_COMMIT OFF;
    END TRY
    . . .
</code>```

This runs one time through the loop, deallocates the cursor and then . . . well, you have a problem on the second time through the loop.

I think you intend to dealloc after the while loop.

Title: Transaction within a cursor

Body:
Is the following the correct way to use transactions within a cursor:

SET CURSOR_CLOSE_ON_COMMIT ON;

DECLARE cur CURSOR LOCAL FOR
    SELECT * FROM @ordersToProcess;
OPEN cur;

DECLARE @OrderId int;

FETCH NEXT FROM cur INTO @OrderId;
WHILE @@FETCH_STATUS = 0 BEGIN
    BEGIN TRY
        BEGIN TRAN;
        EXEC process_order @OrderId;
        COMMIT TRAN;
        DEALLOCATE cur;
        SET CURSOR_CLOSE_ON_COMMIT OFF;
    END TRY
    BEGIN CATCH
        ROLLBACK TRAN;
        DEALLOCATE cur;
        SET CURSOR_CLOSE_ON_COMMIT OFF;
        THROW;
    END CATCH;

    FETCH NEXT FROM cur INTO @OrderId;
END;

Body:
No.  You have this code:

WHILE @@FETCH_STATUS = 0 BEGIN
    BEGIN TRY
        BEGIN TRAN;
        EXEC process_order @OrderId;
        COMMIT TRAN;
        DEALLOCATE cur;
        SET CURSOR_CLOSE_ON_COMMIT OFF;
    END TRY
    . . .

This runs one time through the loop, deallocates the cursor and then . . . well, you have a problem on the second time through the loop.

I think you intend to dealloc after the while loop.


问:
How to draw line not line segment OpenCV 2.4.2
Well the question says it all,

I know the function Line(), which draws line segment between two points.

I need to draw line NOT a line segment, also using the two points of the line segment.

[EN: Edit from what was previously posted as an answer for the question]

I used your solution and it performed good results in horizontal lines, but I still got problems in vertical lines.

For example, follows below an example using the points [306,411] and [304,8] (purple) and the draw line (red), on a image with 600x600 pixels. Do you have some tip?

答:
I had the same problem and found out that there it is a known bug on 2.4.X OpenCV, fixed already for newer versions.

For the 2.4.X versions, the solution is to clip the line before plot it using cv::clipLine()

Here there is a function I did to myself that works fine on the 2.4.13 OpenCV

```<code>void Detector::drawFullImageLine(cv::Mat& img, const std::pair<cv::Point, cv::Point>& points, cv::Scalar color)
{
    //points of line segment
    cv::Point p1 = points.first;
    cv::Point p2 = points.second;

    //points of line segment which extend the segment P1-P2 to
    //the image borders.
    cv::Point p,q;

    //test if line is vertical, otherwise computes line equation
    //y = ax + b
    if (p2.x == p1.x)
    {
        p = cv::Point(p1.x, 0);
        q = cv::Point(p1.x, img.rows);
    }
    else
    {
        double a = (double)(p2.y - p1.y) / (double) (p2.x - p1.x);
        double b =  p1.y - a*p1.x;

        p = cv::Point(0, b);
        q = cv::Point(img.rows, a*img.rows + b);

        //clipline to the image borders. It prevents a known bug on OpenCV
        //versions 2.4.X when drawing
        cv::clipLine(cv::Size(img.rows, img.cols), p, q);
    }

    cv::line(img, p, q, color, 2);
}
</code>```

Body:
I had the same problem and found out that there it is a known bug on 2.4.X OpenCV, fixed already for newer versions.

For the 2.4.X versions, the solution is to clip the line before plot it using cv::clipLine()

Here there is a function I did to myself that works fine on the 2.4.13 OpenCV

void Detector::drawFullImageLine(cv::Mat& img, const std::pair<cv::Point, cv::Point>& points, cv::Scalar color)
{
    //points of line segment
    cv::Point p1 = points.first;
    cv::Point p2 = points.second;

    //points of line segment which extend the segment P1-P2 to
    //the image borders.
    cv::Point p,q;

    //test if line is vertical, otherwise computes line equation
    //y = ax + b
    if (p2.x == p1.x)
    {
        p = cv::Point(p1.x, 0);
        q = cv::Point(p1.x, img.rows);
    }
    else
    {
        double a = (double)(p2.y - p1.y) / (double) (p2.x - p1.x);
        double b =  p1.y - a*p1.x;

        p = cv::Point(0, b);
        q = cv::Point(img.rows, a*img.rows + b);

        //clipline to the image borders. It prevents a known bug on OpenCV
        //versions 2.4.X when drawing
        cv::clipLine(cv::Size(img.rows, img.cols), p, q);
    }

    cv::line(img, p, q, color, 2);
}


问:
Identical values in an array has to be positioned together
```<code>var array1 = ["ddd","aaa","eee","aaa","fff","bbb","ggg","aaa","ccc","fff"]
</code>```

i have to arrange it in a way that  identical values has to be placed together

output array should be

```<code>["ddd","aaa","aaa","aaa","eee","fff","fff","bbb","ggg","ccc"]
</code>```

how to write the logic for this one ??

答:
You could iterate the array and check the position and if not the same as the actual element, splice the value to the earlier position.

var array = ["ddd","aaa","eee","aaa","fff","bbb","ggg","aaa","ccc","fff"],
    i = 0, p;

while (i < array.length) {
    p = array.indexOf(array[i]);
    if (p !== i) {
        array.splice(p, 0, array.splice(i, 1)[0]);
    }
    i++;
}

console.log(array);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
var array1 = ["ddd","aaa","eee","aaa","fff","bbb","ggg","aaa","ccc","fff"]

i have to arrange it in a way that  identical values has to be placed together

output array should be

["ddd","aaa","aaa","aaa","eee","fff","fff","bbb","ggg","ccc"]

how to write the logic for this one ??

Body:
You could iterate the array and check the position and if not the same as the actual element, splice the value to the earlier position.

var array = ["ddd","aaa","eee","aaa","fff","bbb","ggg","aaa","ccc","fff"],
    i = 0, p;

while (i < array.length) {
    p = array.indexOf(array[i]);
    if (p !== i) {
        array.splice(p, 0, array.splice(i, 1)[0]);
    }
    i++;
}

console.log(array);

.as-console-wrapper { max-height: 100% !important; top: 0; }


答:
```<code>sucess: function(data){
</code>```

Noticed that success is misspelled.

Title: Ajax Call Not Returning Data Django

Body:
sucess: function(data){

Noticed that success is misspelled.


问:
for-loop over directory to zip subdirectories
My question is really simple but it's been too long since I last read bash-scripts so I cannot understand bash anymore...

I have a folder (name containing spaces) which has x subfolders. Now I want to zip each subfolder in its own zip archive.

The following script is what I have:

```<code>#!/bin/bash
cd $1
for folder in $1/* do
zip -r "${folder%/}" "${folder%/}"
done
</code>```

every time I try to execute it with ./test.sh . I just get

```<code>./test.sh: line 4: syntax error near unexpected token `zip'
./test.sh: line 4: `zip -r "${folder%/}" "${folder%/}"'
</code>```

what is wrong with my thoughts and why?

if I enter a variable (e.g. file="subfolder i want to zip") in the shell and execute zip -r "${file}" "${file}" it just works fine for the one folder.

I appreciate any help and hope my question can be solved easily (so I'm able to understand it).
Thanks a lot in advance.

答:
If you want to use shell tools, you can use a for loop as illustrated in other answers. If you can afford calling another application like find, here's a one-liner:

```<code>find "${1}" -maxdepth 1 -mindepth 1 -type d -exec zip -r "{}.zip" "{}" \;
</code>```

Body:
My question is really simple but it's been too long since I last read bash-scripts so I cannot understand bash anymore...

I have a folder (name containing spaces) which has x subfolders. Now I want to zip each subfolder in its own zip archive.

The following script is what I have:

#!/bin/bash
cd $1
for folder in $1/* do
zip -r "${folder%/}" "${folder%/}"
done

every time I try to execute it with ./test.sh . I just get

./test.sh: line 4: syntax error near unexpected token `zip'
./test.sh: line 4: `zip -r "${folder%/}" "${folder%/}"'

what is wrong with my thoughts and why?

if I enter a variable (e.g. file="subfolder i want to zip") in the shell and execute zip -r "${file}" "${file}" it just works fine for the one folder.

I appreciate any help and hope my question can be solved easily (so I'm able to understand it).
Thanks a lot in advance.

Body:
If you want to use shell tools, you can use a for loop as illustrated in other answers. If you can afford calling another application like find, here's a one-liner:

find "${1}" -maxdepth 1 -mindepth 1 -type d -exec zip -r "{}.zip" "{}" \;


问:
How to create a list of topics in Apache Kafka using single command
As of now I am creating a topic one by one by using below command.

```<code>sh ./bin/kafka-topics --create --zookeeper localhost:2181  --topic sdelivery --replication-factor 1 --partitions 1
</code>```

Since I have 200+ topics to be created. Is there any way to create a list of topic with a single command?

I am using 0.10.2 version of Apache Kafka.

答:
This seems like more of a unix/bash question than a Kafka one: the xargs utility is specifically designed to run a command repeatedly from a list of arguments. In your specific case you could use:

```<code>cat topic_list.txt | xargs -I % -L1 sh ./bin/kafka-topics --create --zookeeper localhost:2181 --topic % --replication-factor 1 --partitions 1
</code>```

If you want to do a "dry run" and see what commands will be executed you can replace the sh with echo sh.

Alternatively you can just make sure that your config files have default topic settings of --replication-factor 1 and --partitions 1 and just allow those topics to be automatically created the first time you send a message to them.

ContentLicense: CC BY-SA 4.0

Body:
As of now I am creating a topic one by one by using below command.

sh ./bin/kafka-topics --create --zookeeper localhost:2181  --topic sdelivery --replication-factor 1 --partitions 1

Since I have 200+ topics to be created. Is there any way to create a list of topic with a single command?

I am using 0.10.2 version of Apache Kafka.

Body:
This seems like more of a unix/bash question than a Kafka one: the xargs utility is specifically designed to run a command repeatedly from a list of arguments. In your specific case you could use:

cat topic_list.txt | xargs -I % -L1 sh ./bin/kafka-topics --create --zookeeper localhost:2181 --topic % --replication-factor 1 --partitions 1

If you want to do a "dry run" and see what commands will be executed you can replace the sh with echo sh.

Alternatively you can just make sure that your config files have default topic settings of --replication-factor 1 and --partitions 1 and just allow those topics to be automatically created the first time you send a message to them.


问:
How does this float square root approximation work?
I found a rather strange but working square root approximation for floats; I really don't get it. Can someone explain me why this code works?

```<code>float sqrt(float f)
{
    const int result = 0x1fbb4000 + (*(int*)&f >> 1);
    return *(float*)&result;
}
</code>```

I've test it a bit and it outputs values off of std::sqrt() by about 1 to 3%. I know of the Quake III's fast inverse square root and I guess it's something similar here (without the newton iteration) but I'd really appreciate an explanation of how it works.

(nota: I've tagged it both c and c++ since it's both valid-ish (see comments) C and C++ code)

答:
(*(int*)&f >> 1) right-shifts the bitwise representation of f.  This almost divides the exponent by two, which is approximately equivalent to taking the square root.1

Why almost? In IEEE-754, the actual exponent is e - 127.2  To divide this by two, we'd need e/2 - 64, but the above approximation only gives us e/2 - 127.  So we need to add on 63 to the resulting exponent.  This is contributed by bits 30-23 of that magic constant (0x1fbb4000).

I'd imagine the remaining bits of the magic constant have been chosen to minimise the maximum error across the mantissa range, or something like that.  However, it's unclear whether it was determined analytically, iteratively, or heuristically.

It's worth pointing out that this approach is somewhat non-portable. It makes (at least) the following assumptions:

The platform uses single-precision IEEE-754 for float.

The endianness of float representation.

That you will be unaffected by undefined behaviour due to the fact this approach violates C/C++'s strict-aliasing rules.

Thus it should be avoided unless you're certain that it gives predictable behaviour on your platform (and indeed, that it provides a useful speedup vs. sqrtf!).

1. sqrt(a^b) = (a^b)^0.5 = a^(b/2)

2. See e.g. https://en.wikipedia.org/wiki/Single-precision_floating-point_format#Exponent_encoding

Body:
I found a rather strange but working square root approximation for floats; I really don't get it. Can someone explain me why this code works?

float sqrt(float f)
{
    const int result = 0x1fbb4000 + (*(int*)&f >> 1);
    return *(float*)&result;
}

I've test it a bit and it outputs values off of std::sqrt() by about 1 to 3%. I know of the Quake III's fast inverse square root and I guess it's something similar here (without the newton iteration) but I'd really appreciate an explanation of how it works.

(nota: I've tagged it both c and c++ since it's both valid-ish (see comments) C and C++ code)


问:
Android setAuthToken not working for first time
I am saving my application account on Android using AccountManager and want to save authentication token on device.
My app account is added every time when I login and execute addAccountExplicitly but setAuthToken does not work untill I login one more time and setAuthToken again.
Below is my code for adding account and setting authToken

```<code>String accountName = authIntent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
String accountType = authIntent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE);
String accountPass = authIntent.getStringExtra(Constants.ACCOUNT_PASS);
String accntAuthToken = authIntent.getStringExtra(AccountManager.KEY_AUTHTOKEN);

Account resilincAccount = new Account(accountName, Constants.ACCOUNT_TYPE);
AccountManager mAccountManager = AccountManager.get(getApplicationContext());

boolean accountAdded = mAccountManager.addAccountExplicitly(resilincAccount, accountPass, null);
mAccountManager.setAuthToken(resilincAccount, Constants.ACCOUNT_TYPE, accntAuthToken);
mAccountManager.addOnAccountsUpdatedListener(this, null, true);
setAccountAuthenticatorResult(authIntent.getExtras());
setResult(RESULT_OK, authIntent);
</code>```

Any one have any idea why I have to login two times to get my authToken saved in AccountManager?

答:
The Bundle that you pass to setAccountAuthenticatorResult has to contain the following properties:

```<code>res.putExtra(AccountManager.KEY_ACCOUNT_TYPE, <account_type>);
res.putExtra(AccountManager.KEY_ACCOUNT_NAME, <user_id>);
res.putExtra(AccountManager.KEY_AUTHTOKEN, <auth_token>);
</code>```

Body:
I am saving my application account on Android using AccountManager and want to save authentication token on device.
My app account is added every time when I login and execute addAccountExplicitly but setAuthToken does not work untill I login one more time and setAuthToken again.
Below is my code for adding account and setting authToken

String accountName = authIntent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
String accountType = authIntent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE);
String accountPass = authIntent.getStringExtra(Constants.ACCOUNT_PASS);
String accntAuthToken = authIntent.getStringExtra(AccountManager.KEY_AUTHTOKEN);

Account resilincAccount = new Account(accountName, Constants.ACCOUNT_TYPE);
AccountManager mAccountManager = AccountManager.get(getApplicationContext());

boolean accountAdded = mAccountManager.addAccountExplicitly(resilincAccount, accountPass, null);
mAccountManager.setAuthToken(resilincAccount, Constants.ACCOUNT_TYPE, accntAuthToken);
mAccountManager.addOnAccountsUpdatedListener(this, null, true);
setAccountAuthenticatorResult(authIntent.getExtras());
setResult(RESULT_OK, authIntent);

Any one have any idea why I have to login two times to get my authToken saved in AccountManager?

Body:
The Bundle that you pass to setAccountAuthenticatorResult has to contain the following properties:

res.putExtra(AccountManager.KEY_ACCOUNT_TYPE, <account_type>);
res.putExtra(AccountManager.KEY_ACCOUNT_NAME, <user_id>);
res.putExtra(AccountManager.KEY_AUTHTOKEN, <auth_token>);