问:
Does Nexus accept Groovy strings in script?
After running a groovy script as task to create a role with:

security.addRole(// id
                 roleDeveloper,
                 // name
                 roleDeveloper,
                 // description
                 "A developer on ${repoCap} group",
                 // privileges
                 ["nx-repository-view-maven2-${repo}-dependencies-browse",
                  "nx-repository-view-maven2-${repo}-dependencies-read"],
                 // roles
                 ["dw-all-public-repos"])
```

<p>I can't access to the <em>roles</em> menu. I get the following error:</p>

```com.orientechnologies.orient.core.exception.ODatabaseException: Error on deserialization of Serializable DB name="security"
[...]
Caused by: java.lang.ClassNotFoundException: org.codehaus.groovy.runtime.GStringImpl
  at java.net.URLClassLoader.findClass(URLClassLoader.java:381) [na:1.8.0_91]
  at java.lang.ClassLoader.loadClass(ClassLoader.java:424) [na:1.8.0_91]
  at java.lang.ClassLoader.loadClass(ClassLoader.java:357) [na:1.8.0_91]
  at org.apache.felix.framework.BundleWiringImpl.doImplicitBootDelegation(BundleWiringImpl.java:1782) [na:na]
  at org.apache.felix.framework.BundleWiringImpl.searchDynamicImports(BundleWiringImpl.java:1717) [na:na]
  at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1552) [na:na]
  at org.apache.felix.framework.BundleWiringImpl.access$400(BundleWiringImpl.java:79) [na:na]
  at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:2018) [na:na]
```

After running several tests (with and without String interpolations) on several version of Nexus (3.x) it looks like String interpolations are supported for some parameters but not for privileges parameter.

Is it a known issue ?

Now that my Roles menu is inaccessible due to this above error is there a way to fix it ? (I tried to remove it with a script but it failed because delete perform a load first)

答:
Sorry for the problems Alexandre. It looks like you'll have to connect to the database directly in order to fix the problematic records. Instructions for how to do this with Nexus offline are here: https://support.sonatype.com/hc/en-us/articles/115002930827-Accessing-the-OrientDB-Console

In particular the database you're looking to connect to is 'security':

```<code>connect plocal:data/db/security admin admin
</code>```

And the tables you will need to inspect/delete from are 'privilege' and 'role'.
I'll keep an eye out here in case you run into problems or have any followup questions.

Body:
After running a groovy script as task to create a role with:

security.addRole(// id
                 roleDeveloper,
                 // name
                 roleDeveloper,
                 // description
                 "A developer on ${repoCap} group",
                 // privileges
                 ["nx-repository-view-maven2-${repo}-dependencies-browse",
                  "nx-repository-view-maven2-${repo}-dependencies-read"],
                 // roles
                 ["dw-all-public-repos"])

I can't access to the roles menu. I get the following error:

com.orientechnologies.orient.core.exception.ODatabaseException: Error on deserialization of Serializable DB name="security"
[...]
Caused by: java.lang.ClassNotFoundException: org.codehaus.groovy.runtime.GStringImpl
  at java.net.URLClassLoader.findClass(URLClassLoader.java:381) [na:1.8.0_91]
  at java.lang.ClassLoader.loadClass(ClassLoader.java:424) [na:1.8.0_91]
  at java.lang.ClassLoader.loadClass(ClassLoader.java:357) [na:1.8.0_91]
  at org.apache.felix.framework.BundleWiringImpl.doImplicitBootDelegation(BundleWiringImpl.java:1782) [na:na]
  at org.apache.felix.framework.BundleWiringImpl.searchDynamicImports(BundleWiringImpl.java:1717) [na:na]
  at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1552) [na:na]
  at org.apache.felix.framework.BundleWiringImpl.access$400(BundleWiringImpl.java:79) [na:na]
  at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:2018) [na:na]

After running several tests (with and without String interpolations) on several version of Nexus (3.x) it looks like String interpolations are supported for some parameters but not for privileges parameter.

Is it a known issue ?

Now that my Roles menu is inaccessible due to this above error is there a way to fix it ? (I tried to remove it with a script but it failed because delete perform a load first)

Body:
Sorry for the problems Alexandre. It looks like you'll have to connect to the database directly in order to fix the problematic records. Instructions for how to do this with Nexus offline are here: https://support.sonatype.com/hc/en-us/articles/115002930827-Accessing-the-OrientDB-Console

In particular the database you're looking to connect to is 'security':

connect plocal:data/db/security admin admin

And the tables you will need to inspect/delete from are 'privilege' and 'role'.
I'll keep an eye out here in case you run into problems or have any followup questions.


来源: stackexchange

问:
How to copy column data from one sheet and then copy that to another sheet in vba excel
I need help with this small project. What I need to accomplished this task is the following:

I have a excel file where my macro button once clicked will read the data from a sheet1 only in column A then should throw the data to another sheet2 and move every data from the sheet1 to sheet2 and display all the data to each separate column.

here is a image of the data example. in the image every circle needs to be in its own column to the new sheet2 that is only part of the data the total of the column rows is around 900.

if need more information please let me know.

here is the code I have it copy the sheet from sheet1 to sheet2 but I need the rest to work

```<code>Sub ExportFile()
Dim strValue As String
Dim strCellNum As String
Dim x As String
x = 1

For i = 1 To 700 Step 7
    strCellNum = "A" & i
    strValue = Worksheets("data").Range(strCellNum).Value
    Debug.Print strValue
    Worksheets("NewData").Range("A" & x).Value = strValue
    x = x + 1
Next
End Sub
</code>```

答:
Give this a try:</p>

```<code>Sub DataReorganizer()
    Dim s1 As Worksheet, s2 As Worksheet, N As Long, i As Long, j As Long, k As Long
    Dim v As Variant

    Set s1 = Sheets("Data")
    Set s2 = Sheets("NewData")

    N = s1.Cells(Rows.Count, "A").End(xlUp).Row
    For i = N To 2 Step -1
        If s1.Cells(i, "A").Value = "" And s1.Cells(i - 1, "A").Value = "" Then s1.Cells(i, "A").Delete shift:=xlUp
    Next i

    j = 1
    k = 1
    N = s1.Cells(Rows.Count, "A").End(xlUp).Row
    For i = 1 To N
        v = s1.Cells(i, "A").Value
        If v = "" Then
            j = 1
            k = k + 1
        Else
            s2.Cells(j, k).Value = v
            j = j + 1
        End If
    Next i

End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need help with this small project. What I need to accomplished this task is the following:

I have a excel file where my macro button once clicked will read the data from a sheet1 only in column A then should throw the data to another sheet2 and move every data from the sheet1 to sheet2 and display all the data to each separate column.

here is a image of the data example. in the image every circle needs to be in its own column to the new sheet2 that is only part of the data the total of the column rows is around 900.

if need more information please let me know.

here is the code I have it copy the sheet from sheet1 to sheet2 but I need the rest to work

Sub ExportFile()
Dim strValue As String
Dim strCellNum As String
Dim x As String
x = 1

For i = 1 To 700 Step 7
    strCellNum = "A" & i
    strValue = Worksheets("data").Range(strCellNum).Value
    Debug.Print strValue
    Worksheets("NewData").Range("A" & x).Value = strValue
    x = x + 1
Next
End Sub

Body:
Give this a try:

Sub DataReorganizer()
    Dim s1 As Worksheet, s2 As Worksheet, N As Long, i As Long, j As Long, k As Long
    Dim v As Variant

    Set s1 = Sheets("Data")
    Set s2 = Sheets("NewData")

    N = s1.Cells(Rows.Count, "A").End(xlUp).Row
    For i = N To 2 Step -1
        If s1.Cells(i, "A").Value = "" And s1.Cells(i - 1, "A").Value = "" Then s1.Cells(i, "A").Delete shift:=xlUp
    Next i

    j = 1
    k = 1
    N = s1.Cells(Rows.Count, "A").End(xlUp).Row
    For i = 1 To N
        v = s1.Cells(i, "A").Value
        If v = "" Then
            j = 1
            k = k + 1
        Else
            s2.Cells(j, k).Value = v
            j = j + 1
        End If
    Next i

End Sub


问:
Trying to get property on non-object with Laravel 5.1 and Vue 2
I have a url loading with data passed on from Laravel.  I place the data in the vue data using blade syntax like this:

```<code>data: {
    id: "{!! ($header->id) !!}",
    vendor: '{!! $header->vendor_name !!}',
    orderDate: '{!! $header->orderDate !!}',
    list: [],
}
</code>```

So far so good. The data is set properly.

Then there is a method that triggers when a row in the table is clicked:

```<code>methods: {
   findInventoryItem: function(rowId) {
       var header = this.id;
       url = '{!! url('part-order/find-inventory') !!}' + '?headerId=' + header + '&rowId=' + rowId;
       window.location.href = url;
   }
</code>```

The url is setup properly.

The error happens when I click the table row.  This error pops up.

```<code>Trying to get property of non-object (View: /code/zone/resources/views/parts/part-order.blade.php)
</code>```

Notice that the error is not with the requested url but with the existing url.

The error is triggered by this line:

```<code>id: "{!! ($header->id) !!}",
</code>```

Any ideas as to what is going on here?

答:
This error says that $header is null. You need to check it for null. Something like:

```<code>{!! is_null($header) ? 0 : $header->id !!}
</code>```

Or:

```<code>@if (!is_null($header))
    {!! $header->id !!}
@endif
</code>```

Body:
I have a url loading with data passed on from Laravel.  I place the data in the vue data using blade syntax like this:

data: {
    id: "{!! ($header->id) !!}",
    vendor: '{!! $header->vendor_name !!}',
    orderDate: '{!! $header->orderDate !!}',
    list: [],
}

So far so good. The data is set properly.

Then there is a method that triggers when a row in the table is clicked:

methods: {
   findInventoryItem: function(rowId) {
       var header = this.id;
       url = '{!! url('part-order/find-inventory') !!}' + '?headerId=' + header + '&rowId=' + rowId;
       window.location.href = url;
   }

The url is setup properly.

The error happens when I click the table row.  This error pops up.

Trying to get property of non-object (View: /code/zone/resources/views/parts/part-order.blade.php)

Notice that the error is not with the requested url but with the existing url.

The error is triggered by this line:

id: "{!! ($header->id) !!}",

Any ideas as to what is going on here?

Body:
This error says that $header is null. You need to check it for null. Something like:

{!! is_null($header) ? 0 : $header->id !!}

Or:

@if (!is_null($header))
    {!! $header->id !!}
@endif


问:
Python3 appending key value pair alters previous entry
I am trying to build the following JSON:

```<code>{'Keys-1': [{'Key1': 'Value1'}, {'Key1': 'Value2'}]}
</code>```

Here is the code I am using to build this JSON:

```<code>existingFile = {}
importobjs = []
importobj = {}
objkey = 'Key1'
objvalue = 'Value1'
importobj[objkey] = objvalue
importobjs.append(importobj)
objvalue = 'Value2'
importobj[objkey] = objvalue
importobjs.append(importobj)
existingFile['Keys-1'] = importobjs
</code>```

Works almost perfectly, except the value of the first key-value pair is updated to 'Value2'

```<code>{'Keys-1': [{'Key1': 'Value2'}, {'Key1': 'Value2'}]}
</code>```

答:
The problem with your code (as mentioned in the comments) is that the objects are being passed by reference instead of by value. What your existingFile actually looks like is

```<code>{'Keys-1': [object@importobj_address, object@importobj_address]}
</code>```

So your array contains two of the exact same objects. If you change importobj again and add it to importobjs, then you will have 3 of the exact same objects in the array.

Here is an example of how you can implement this correctly:

```<code>existingFile = {}
importobjs = []
first_key = 'Key1'
importobjs.append({first_key:'Value1'})
importobjs.append({first_key:'Value2'})
existingFile['Keys-1'] = importobjs
</code>```

To expand the example:

```<code>existingFile = {}
first_objs = []
first_key = 'Key1'
first_objs.append({first_key:'Value1'})
first_objs.append({first_key:'Value2'})
existingFile['Keys-1'] = first_objs
second_objs = []
second_key = 'Key2'
second_objs.append({second_key:'Value3'})
second_objs.append({second_key:'Value4'})
existingFile['Keys-2'] = second_objs
</code>```

However, much of these issues would be avoided by looping through lists rather than variables for each string.

Body:
I am trying to build the following JSON:

{'Keys-1': [{'Key1': 'Value1'}, {'Key1': 'Value2'}]}

Here is the code I am using to build this JSON:

existingFile = {}
importobjs = []
importobj = {}
objkey = 'Key1'
objvalue = 'Value1'
importobj[objkey] = objvalue
importobjs.append(importobj)
objvalue = 'Value2'
importobj[objkey] = objvalue
importobjs.append(importobj)
existingFile['Keys-1'] = importobjs

Works almost perfectly, except the value of the first key-value pair is updated to 'Value2'

{'Keys-1': [{'Key1': 'Value2'}, {'Key1': 'Value2'}]}

Body:
The problem with your code (as mentioned in the comments) is that the objects are being passed by reference instead of by value. What your existingFile actually looks like is

{'Keys-1': [object@importobj_address, object@importobj_address]}

So your array contains two of the exact same objects. If you change importobj again and add it to importobjs, then you will have 3 of the exact same objects in the array.

Here is an example of how you can implement this correctly:

existingFile = {}
importobjs = []
first_key = 'Key1'
importobjs.append({first_key:'Value1'})
importobjs.append({first_key:'Value2'})
existingFile['Keys-1'] = importobjs

To expand the example:

existingFile = {}
first_objs = []
first_key = 'Key1'
first_objs.append({first_key:'Value1'})
first_objs.append({first_key:'Value2'})
existingFile['Keys-1'] = first_objs
second_objs = []
second_key = 'Key2'
second_objs.append({second_key:'Value3'})
second_objs.append({second_key:'Value4'})
existingFile['Keys-2'] = second_objs

However, much of these issues would be avoided by looping through lists rather than variables for each string.


问:
How to use Flow with async/await, promises and thenables?
Flow can do clever stuff like this:

```<code>type MyMap = WeakMap<number, string>;
const obj: MyMap = new WeakMap();
obj.set(123, 'bar'); // ok
obj.set('not', 'bar'); // flow error!
</code>```

But what about promises, thenables, and async/await?

I was hoping it might be possible to do this kind of thing:

```<code>type AsyncMultiplier = (number) => Thenable<number>;

const myTransform: AsyncMultiplier = async input => input * 2;

(async () => {
  (await myTransform(2)) * 5; // should be ok

  // forgetting to await the result:
  myTransform(2) * 5; // should give a type error
})();
</code>```

Is there some way to get Flow to understand the semantics of await, thenables, etc?

答:
Flow understands async/await and Promises. There is no built-in type for Thenable though you may be able to define your own.

Anyway, in your example just replace Thenable with Promise and you get the expected error. Note that if you try to typecheck your example you get the following error:

```<code>1: type AsyncMultiplier = (number) => Thenable<number>;
                                      ^ identifier `Thenable`. Could not resolve name
</code>```

Body:
Flow can do clever stuff like this:

type MyMap = WeakMap<number, string>;
const obj: MyMap = new WeakMap();
obj.set(123, 'bar'); // ok
obj.set('not', 'bar'); // flow error!

But what about promises, thenables, and async/await?

I was hoping it might be possible to do this kind of thing:

type AsyncMultiplier = (number) => Thenable<number>;

const myTransform: AsyncMultiplier = async input => input * 2;

(async () => {
  (await myTransform(2)) * 5; // should be ok

  // forgetting to await the result:
  myTransform(2) * 5; // should give a type error
})();

Is there some way to get Flow to understand the semantics of await, thenables, etc?

Body:
Flow understands async/await and Promises. There is no built-in type for Thenable though you may be able to define your own.

Anyway, in your example just replace Thenable with Promise and you get the expected error. Note that if you try to typecheck your example you get the following error:

1: type AsyncMultiplier = (number) => Thenable<number>;
                                      ^ identifier `Thenable`. Could not resolve name


问:
Today Extension Failed to inherit CoreMedia permissions from
I am trying to add a Today Extension in Swift to my Objective-C app. I keep getting this message in my debugger log: Failed to inherit CoreMedia permissions from 3005: (null). The number ex. 3005 is different every time. I am reading from NSUserDefaults from within the widget but I am reading/writing in the app itself. The only code in my TodayViewController is this the following:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    let formatter = NSNumberFormatter()
    formatter.numberStyle = .CurrencyStyle
    totalLabel.text = formatter.stringFromNumber(0)
    coinsLabel.text = formatter.stringFromNumber(0)

    formatter.maximumFractionDigits = 0
    billsLabel.text = formatter.stringFromNumber(0)

}

func widgetMarginInsetsForProposedMarginInsets(defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets {
    return UIEdgeInsetsMake(8.0, 16.0, 8.0, 16.0)
}

func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)!) {
    // Perform any setup necessary in order to update the view.

    // If an error is encountered, use NCUpdateResult.Failed
    // If there's no update required, use NCUpdateResult.NoData
    // If there's an update, use NCUpdateResult.NewData

    completionHandler(NCUpdateResult.NewData)
}
</code>```

答:
Here's my experience with this error message. I had a storyboard with 4 ViewControllers in it. I did a refactor extract on all of them, so now I have 5 storyboards, 4 of which had view controllers and the original, "main," one only had storyboard references in it.

Well... that's bad. Don't do that.

Everything worked when I kept the initial storyboard in the original storyboard file, so I didn't refactor just one of them.

Body:
I am trying to add a Today Extension in Swift to my Objective-C app. I keep getting this message in my debugger log: Failed to inherit CoreMedia permissions from 3005: (null). The number ex. 3005 is different every time. I am reading from NSUserDefaults from within the widget but I am reading/writing in the app itself. The only code in my TodayViewController is this the following:

override func viewDidLoad() {
    super.viewDidLoad()

    let formatter = NSNumberFormatter()
    formatter.numberStyle = .CurrencyStyle
    totalLabel.text = formatter.stringFromNumber(0)
    coinsLabel.text = formatter.stringFromNumber(0)

    formatter.maximumFractionDigits = 0
    billsLabel.text = formatter.stringFromNumber(0)

}

func widgetMarginInsetsForProposedMarginInsets(defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets {
    return UIEdgeInsetsMake(8.0, 16.0, 8.0, 16.0)
}

func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)!) {
    // Perform any setup necessary in order to update the view.

    // If an error is encountered, use NCUpdateResult.Failed
    // If there's no update required, use NCUpdateResult.NoData
    // If there's an update, use NCUpdateResult.NewData

    completionHandler(NCUpdateResult.NewData)
}


问:
Nil value in virtual attribute not caught by Rails validation?
I have this Rails model:

```<code>class Profile < ActiveRecord::Base

  validates :number_format, :inclusion => { :in => ["1,000.00", "1.000,00"] }

  def number_format=(format)
    self.currency_delimiter = format[1]
    self.currency_separator = format[5]
  end

  def number_format
    "1#{currency_delimiter}000#{currency_separator}00"
  end

end
</code>```

The problem is that when I test it with RSpec...

```<code>it "is invalid without a number_format" do
  expect(FactoryGirl.build(:profile, :number_format => nil).errors_on(:number_format).size).to eq(1)
end
</code>```

...I get this error:

1) Profile number_format is invalid without a number_format
       Failure/Error: expect(FactoryGirl.build(:profile, :number_format => nil).errors_on(:number_format).size).to eq(1)

```<code>   expected: 1
        got: 0
</code>```

How is this possible?

I thought nil won't get validated due to the validation method I put in place.

答:
FactoryGirl.build just initializes a record, it doesn't try to save the record to the database and therefore doesn't call valid? on the record. Without calling valid? the instances errors will always be empty.

Try this instead:

```<code>it "is invalid without a number_format" do
  profile = FactoryGirl.build(:profile, :number_format => nil)

  expect(profile).to_not be_valid # `be_valid` actually calls `valid?`
  expect(profile.errors_on(:number_format).size).to eq(1)
end
</code>```

Body:
I have this Rails model:

class Profile < ActiveRecord::Base

  validates :number_format, :inclusion => { :in => ["1,000.00", "1.000,00"] }

  def number_format=(format)
    self.currency_delimiter = format[1]
    self.currency_separator = format[5]
  end

  def number_format
    "1#{currency_delimiter}000#{currency_separator}00"
  end

end

The problem is that when I test it with RSpec...

it "is invalid without a number_format" do
  expect(FactoryGirl.build(:profile, :number_format => nil).errors_on(:number_format).size).to eq(1)
end

...I get this error:

1) Profile number_format is invalid without a number_format
       Failure/Error: expect(FactoryGirl.build(:profile, :number_format => nil).errors_on(:number_format).size).to eq(1)

   expected: 1
        got: 0

How is this possible?

I thought nil won't get validated due to the validation method I put in place.

Body:
FactoryGirl.build just initializes a record, it doesn't try to save the record to the database and therefore doesn't call valid? on the record. Without calling valid? the instances errors will always be empty.

Try this instead:

it "is invalid without a number_format" do
  profile = FactoryGirl.build(:profile, :number_format => nil)

  expect(profile).to_not be_valid # `be_valid` actually calls `valid?`
  expect(profile.errors_on(:number_format).size).to eq(1)
end


问:
Change the font color of generated word cloud
I am currently using this library to generate a word cloud. Currently, the generated picture looks like this:

However, I will only be able to print this out using the black-white printer, therefore the font color will be to shallow and I want to change them into black. Unfortunately, this is the only example that I can found, where the code reads:

```<code>def grey_color_func(word, font_size, position, orientation, random_state=None,**kwargs):
    return "hsl(0, 0%%, %d%%)" % random.randint(60, 100)
wc = WordCloud(max_words=1000, mask=mask, stopwords=stopwords, margin=10,random_state=1).generate(text)
# store default colored image
default_colors = wc.to_array()
plt.title("Custom colors")
plt.imshow(wc.recolor(color_func=grey_color_func, random_state=3),
interpolation="bilinear")
</code>```

I have no idea what does grey_color_func do in this case, or how to change it to generate a black color.

Any suggestion is welcomed.

答:
This has a lot to do with what HSL(A) represent on this scale.  Since both hue and saturation are set to zero, the luminosity is what is controlling the gray scale portion.  That is, this particular random value is determining the gray scale:

```<code>random.randint(60, 100)
</code>```

Practically, you need to change the bounds of this random int to a value between 0 and 30, or between 0 and whatever value you feel is appropriately "dark" enough to work with your printer.

ContentLicense: CC BY-SA 4.0

Body:
I am currently using this library to generate a word cloud. Currently, the generated picture looks like this:

However, I will only be able to print this out using the black-white printer, therefore the font color will be to shallow and I want to change them into black. Unfortunately, this is the only example that I can found, where the code reads:

def grey_color_func(word, font_size, position, orientation, random_state=None,**kwargs):
    return "hsl(0, 0%%, %d%%)" % random.randint(60, 100)
wc = WordCloud(max_words=1000, mask=mask, stopwords=stopwords, margin=10,random_state=1).generate(text)
# store default colored image
default_colors = wc.to_array()
plt.title("Custom colors")
plt.imshow(wc.recolor(color_func=grey_color_func, random_state=3),
interpolation="bilinear")

I have no idea what does grey_color_func do in this case, or how to change it to generate a black color.

Any suggestion is welcomed.

Body:
This has a lot to do with what HSL(A) represent on this scale.  Since both hue and saturation are set to zero, the luminosity is what is controlling the gray scale portion.  That is, this particular random value is determining the gray scale:

random.randint(60, 100)

Practically, you need to change the bounds of this random int to a value between 0 and 30, or between 0 and whatever value you feel is appropriately "dark" enough to work with your printer.


问:
RecyclerView scrolls to top on notifyDataSetChanged in chat screen
I am trying to create messaging kind of screen using recyclerView which will start from bottom and will loadMore data when user reached top end of chat. But I am facing this weird issue.

My recyclerView scrolls to top on calling notifyDataSetChanged. Due to this onLoadMore gets called multiple times.

Here is my code:

```<code>LinearLayoutManager llm = new LinearLayoutManager(context);
llm.setOrientation(LinearLayoutManager.VERTICAL);
llm.setStackFromEnd(true);
recyclerView.setLayoutManager(llm);
</code>```

** In Adapter

```<code> @Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    if (messages.size() > 8 && position == 0 && null != mLoadMoreCallbacks) {
        mLoadMoreCallbacks.onLoadMore();
    }
</code>```

** In Activity

```<code>@Override
public void onLoadMore() {
    // Get data from database and add into arrayList
      chatMessagesAdapter.notifyDataSetChanged();
}
</code>```

It's just that recyclerView scrolls to top. If scrolling to top stops, this issue will be resolved. Please help me to figure out the cause of this issue. Thanks in advance.

答:
I do not rely on onBindViewHolder for these kind of things. It can be called multiple times for a position. For the lists which has load more option maybe you should use something like this after your recyclerview inflated.

```<code>    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if ((((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstCompletelyVisibleItemPosition() == 0)) {
                if (args.listModel.hasMore && null != mLoadMoreCallback && !loadMoreStarted) {
                    mLoadMoreCallbacks.onLoadMore();
                }
            }
        }
    });
</code>```

Hope it helps.

Body:
I am trying to create messaging kind of screen using recyclerView which will start from bottom and will loadMore data when user reached top end of chat. But I am facing this weird issue.

My recyclerView scrolls to top on calling notifyDataSetChanged. Due to this onLoadMore gets called multiple times.

Here is my code:

LinearLayoutManager llm = new LinearLayoutManager(context);
llm.setOrientation(LinearLayoutManager.VERTICAL);
llm.setStackFromEnd(true);
recyclerView.setLayoutManager(llm);

** In Adapter

 @Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    if (messages.size() > 8 && position == 0 && null != mLoadMoreCallbacks) {
        mLoadMoreCallbacks.onLoadMore();
    }

** In Activity

@Override
public void onLoadMore() {
    // Get data from database and add into arrayList
      chatMessagesAdapter.notifyDataSetChanged();
}

It's just that recyclerView scrolls to top. If scrolling to top stops, this issue will be resolved. Please help me to figure out the cause of this issue. Thanks in advance.

Body:
I do not rely on onBindViewHolder for these kind of things. It can be called multiple times for a position. For the lists which has load more option maybe you should use something like this after your recyclerview inflated.

    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if ((((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstCompletelyVisibleItemPosition() == 0)) {
                if (args.listModel.hasMore && null != mLoadMoreCallback && !loadMoreStarted) {
                    mLoadMoreCallbacks.onLoadMore();
                }
            }
        }
    });

Hope it helps.


问:
Issues with setGame
I'm trying to force my bot to change it's "Game" when it startes to "!help for help" but cannot seem to get it work.

Currently my code is...

```<code>const Commando = require('discord.js-commando');
const Request = require('request');
const Bot = new Commando.Client();

Bot.client.setGame("!help for help");
</code>```

I've also tried...

```<code>Bot.client.setStatus("!help for help");
Bot.user.setGame("!help for help");
Bot.user.setStatus("!help for help");
</code>```

I use can't seem to understand how you call to this to make it work.

答:
Try this:</p>

```<code>bot.on('ready', () => {
  bot.user.setGame("use !help");
});
</code>```

Title: Issues with setGame

Body:
I'm trying to force my bot to change it's "Game" when it startes to "!help for help" but cannot seem to get it work.

Currently my code is...

const Commando = require('discord.js-commando');
const Request = require('request');
const Bot = new Commando.Client();

Bot.client.setGame("!help for help");

I've also tried...

Bot.client.setStatus("!help for help");
Bot.user.setGame("!help for help");
Bot.user.setStatus("!help for help");

I use can't seem to understand how you call to this to make it work.

Body:
Try this:

bot.on('ready', () => {
  bot.user.setGame("use !help");
});


问:
Consume soap Service in Apache Camel
i want to consume soap web serivce in apache camel using Java DSL.Any way without CXF.i have already try using CXF with spring.</p>

答:
Here is a simple example that used only camel http without cxf. If you need to perform some modifications of SOAP request string you can just change "constant" to something like "spel".

```<code><setBody><constant><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header/>
<soapenv:Body>
  <MyAction>
     <myparam>ABC</myparam>
  </MyAction>
</soapenv:Body>
</soapenv:Envelope>]]></constant></setBody>
<setHeader headerName="SOAPAction"><constant>MySOAPAction</constant></setHeader>
<setHeader headerName="CamelHttpMethod"><constant>POST</constant></setHeader>
<setHeader headerName="Content-Type"><constant>text/xml;charset=UTF-8</constant></setHeader>
<to uri="http://myserver:1234" />
</code>```

Same with Java DSL

```<code>public class MyRouteBuilder extends RouteBuilder {
  public void configure() {
    from("direct:start")
      .setBody(constant("")) // String SOAP content from XML example
      .setHeader("SOAPAction", constant("MySOAPAction"))
      .setHeader("CamelHttpMethod", constant("POST"))
      .setHeader("Content-Type", constant("text/xml;charset=UTF-8"))
      .to("http://myserver:1234")
      .log("SOAP service called"); // Here you can process service response
    }
}
</code>```

Title: Consume soap Service in Apache Camel

Body:
Here is a simple example that used only camel http without cxf. If you need to perform some modifications of SOAP request string you can just change "constant" to something like "spel".

<setBody><constant><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header/>
<soapenv:Body>
  <MyAction>
     <myparam>ABC</myparam>
  </MyAction>
</soapenv:Body>
</soapenv:Envelope>]]></constant></setBody>
<setHeader headerName="SOAPAction"><constant>MySOAPAction</constant></setHeader>
<setHeader headerName="CamelHttpMethod"><constant>POST</constant></setHeader>
<setHeader headerName="Content-Type"><constant>text/xml;charset=UTF-8</constant></setHeader>
<to uri="http://myserver:1234" />

Same with Java DSL

public class MyRouteBuilder extends RouteBuilder {
  public void configure() {
    from("direct:start")
      .setBody(constant("")) // String SOAP content from XML example
      .setHeader("SOAPAction", constant("MySOAPAction"))
      .setHeader("CamelHttpMethod", constant("POST"))
      .setHeader("Content-Type", constant("text/xml;charset=UTF-8"))
      .to("http://myserver:1234")
      .log("SOAP service called"); // Here you can process service response
    }
}


问:
Conditionally display results by key
Given the following sample data, I need to display the results by type:

```<code>{
    "count": 50,
    "data": [{
        "id": "title",
        "image": "https://url-to-image.jpg",
        "permalink": "/folder/bob/",
        "text": "lots of text",
        "title": "Bob",
        "type": "User"
    }, {
        "id": "title2",
        "image": "https://url-to-image2.jpg",
        "permalink": "/folder/joe/",
        "text": "lots of text here",
        "title": "Joe",
        "type": "Article"
    }, {
        "id": "title3",
        "image": "https://url-to-image3.jpg",
        "permalink": "/attorneys/jim/",
        "text": "lots of text here",
        "title": "Jim",
        "type": "Blog"
    }]
}
</code>```

I'm trying to run a condition that if the type is a certain one, to display those posts:

```<code>$("#searchterm").keyup(function(e) {
   var q = $("#searchterm").val();
   //Only begin search with at least 3 characters.
   if(q.length > 3){
      ajax_search();
   }
   //Send search query
   function ajax_search(){
   $.getJSON("http://url-to-search?q=" + q, {
            dataType:'jsonp'
     },
     //Get results and make 'em look good
     function(data) {
       console.log(data);
       $(".results").empty();
      //  $(".results").append("Results for <b> " + q + "</b>");
         $.each(data.data, function(i, data) {
                     if(data.type === 'Article'){
             $(".articles").append("<li><a href=localhost:4000" + data.permalink + ">" + data.title + "</a></li>");
                     } else if(data.type === 'Blog'){
                         $(".blog").append("<li><a href=localhost:4000" + data.permalink + ">" + data.title + "</a></li>");
                     }
         });
      });
    }
});
</code>```

However, the results come up empty, although there are results without the conditional statements.

In the end, the results should look like this:

Article

Joe

Blog

Jim

答: Turns out, the issue is with an overflow I have set to be able to scroll through results was set to the wrong class.</p>

Title: Conditionally display results by key

Body:
Given the following sample data, I need to display the results by type:

{
    "count": 50,
    "data": [{
        "id": "title",
        "image": "https://url-to-image.jpg",
        "permalink": "/folder/bob/",
        "text": "lots of text",
        "title": "Bob",
        "type": "User"
    }, {
        "id": "title2",
        "image": "https://url-to-image2.jpg",
        "permalink": "/folder/joe/",
        "text": "lots of text here",
        "title": "Joe",
        "type": "Article"
    }, {
        "id": "title3",
        "image": "https://url-to-image3.jpg",
        "permalink": "/attorneys/jim/",
        "text": "lots of text here",
        "title": "Jim",
        "type": "Blog"
    }]
}

I'm trying to run a condition that if the type is a certain one, to display those posts:

$("#searchterm").keyup(function(e) {
   var q = $("#searchterm").val();
   //Only begin search with at least 3 characters.
   if(q.length > 3){
      ajax_search();
   }
   //Send search query
   function ajax_search(){
   $.getJSON("http://url-to-search?q=" + q, {
            dataType:'jsonp'
     },
     //Get results and make 'em look good
     function(data) {
       console.log(data);
       $(".results").empty();
      //  $(".results").append("Results for  " + q + "");
         $.each(data.data, function(i, data) {
                     if(data.type === 'Article'){
             $(".articles").append("
" + data.title + "
");
                     } else if(data.type === 'Blog'){
                         $(".blog").append("
" + data.title + "
");
                     }
         });
      });
    }
});

However, the results come up empty, although there are results without the conditional statements.

In the end, the results should look like this:

Article

Joe

Blog

Jim


问:
Sqlite Database and Broadcast Receiver
Is it a good idea to access SQLite Database inside the Broadcast Receiver and perform operations (say reading from it and displaying a toast or changing the UI etc) on it.

Can Android kill my Receiver while performing these operations? (if those operations are lengthy)

What's the right way of doing the above operations?

答:
A broadcast receiver (receiver) is an Android component which allows you to register for system or application events. All registered receivers for an event are notified by the Android runtime once this event happens.
So  BroadcastReceiver is not recommended for doing this kind of lengthy process. You can start a Service from that BroadcastReceiver to access your Database.</p>

Title: Sqlite Database and Broadcast Receiver


问:
Execute mac command from Python
Im trying to execute a MAC command from Python but get the following error:-

Command

```<code>from subprocess import call
call(["""osascript -e 'tell app "System Events" to display dialog "Hello World" ' """])
</code>```

Error

```<code>Traceback (most recent call last):
  File "/Users/premanandlakshmanan/Documents/psilon/quantopian/mac_popup.py", line 2, in <module>
    call(["""osascript -e 'tell app "System Events" to display dialog "Hello World" ' """])
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 522, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory
[Finished in 0.3s with exit code 1]
</code>```

答:
According to the documentation, subprocess.call() takes a list of arguments. You need to break up your command into its individual parts.

```<code>from subprocess import call

args = ['osascript',
        '-e',
        'tell app "System Events" to display dialog "Hello World"'
       ]
call(args)
</code>```

Title: Execute mac command from Python

Body:
Im trying to execute a MAC command from Python but get the following error:-

Command

from subprocess import call
call(["""osascript -e 'tell app "System Events" to display dialog "Hello World" ' """])

Error

Traceback (most recent call last):
  File "/Users/premanandlakshmanan/Documents/psilon/quantopian/mac_popup.py", line 2, in <module>
    call(["""osascript -e 'tell app "System Events" to display dialog "Hello World" ' """])
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 522, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory
[Finished in 0.3s with exit code 1]

Body:
According to the documentation, subprocess.call() takes a list of arguments. You need to break up your command into its individual parts.

from subprocess import call

args = ['osascript',
        '-e',
        'tell app "System Events" to display dialog "Hello World"'
       ]
call(args)


问:
Added component-scan to a legacy Spring application
I have a legacy Spring application whether the context is configured entirely with XML. I would like to add a new controller to the application using the @Controller annotation so I begin to migrate to using annotations.

As a test I have added the following controller to the application

```<code>package uk.co.onevisionconsulting.engineermanager.webapp.controller2;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {

     @RequestMapping("/hello")
     public String hello(){
          return "Hello";
     }
}
</code>```

I have also added the context:component-scan tag to my spring context

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans” xmlns:context="http://www.springframework.org/schema/context"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance”
             xsi:schemaLocation="http://www.springframework.org/schema/beans
             http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
             http://www.springframework.org/schema/context
             http://www.springframework.org/schema/context/spring-context-2.5.xsd">

     <context:component-scan base-package="uk.co.onevisionconsulting.engineermanager" />

     <bean name="jsonView"
          class="uk.co.onevisionconsulting.engineermanager.webapp.view.JsonView" />

     <bean name="csvView"
          class="uk.co.onevisionconsulting.engineermanager.webapp.view.CsvView" />

     <bean name="ajaxView"
          class="uk.co.onevisionconsulting.engineermanager.webapp.view.AjaxView" />

     <bean name="dataTablesView"
          class="uk.co.onevisionconsulting.engineermanager.webapp.view.DataTablesView" />

     <bean id="exceptionResolver"
          class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
          <property name="exceptionMappings">
               <props>
                    <prop key="org.springframework.dao.DataAccessException">
                         dataAccessFailure
                    </prop>
               </props>
          </property>
     </bean>

     <bean id=“someController"
          class="uk.co.onevisionconsulting.engineermanager.webapp.controller.SomeController" >
          <property name=“someManager" ref=“someManager" />
     </bean>

     <!-- Loads more controllers -->

     <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
          <property name="maxUploadSize" value="2097152" />
     </bean>

     <bean id="messageSource"
          class="org.springframework.context.support.ResourceBundleMessageSource">
          <property name="basename" value="ApplicationResources" />
          <property name="useCodeAsDefaultMessage" value="true" />
     </bean>

     <bean id="urlMapping"
          class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
          <property name="mappings">
               <value>
                    <!— Some URLs —>
               </value>
          </property>
          <property name="order" value="0" />
     </bean>

     <bean
          class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
          <property name="order" value="1" />
     </bean>

     <bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
          <property name="order" value="2" />
     </bean>

     <!-- View Resolver for JSPs -->
     <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
          <property name="requestContextAttribute" value="rc" />
          <property name="viewClass"
               value="org.springframework.web.servlet.view.JstlView" />
          <property name="prefix" value="/WEB-INF/pages/" />
          <property name="suffix" value=".jsp" />
     </bean>
</beans>
</code>```

All though the classpath scanner (ClassPathScanningCandidateComponentProvider) picks up the HelloController I get a 404 when I try and navigate to localhost:8080/hello

Can anyone see what else I need to do? Here is my web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">

    <display-name>Engineer Manager</display-name>

    <!-- Define the default CSS Theme -->
    <context-param>
        <param-name>csstheme</param-name>
        <param-value>engineermanager</param-value>
    </context-param>

    <!-- Define the basename for a resource bundle for I18N -->
    <context-param>
        <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
        <param-value>ApplicationResources</param-value>
    </context-param>

    <!-- Fallback locale if no bundles found for browser's preferred locale -->
    <!-- Force a single locale using param-name 'javax.servlet.jsp.jstl.fmt.locale' -->
    <context-param>
        <param-name>javax.servlet.jsp.jstl.fmt.fallbackLocale</param-name>
        <param-value>en</param-value>
    </context-param>

    <!-- Context Configuration locations for Spring XML files -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:/applicationContext-resources.xml
            classpath:/applicationContext-dao.xml
            classpath:/applicationContext-service.xml
            classpath*:/applicationContext.xml
            /WEB-INF/applicationContext*.xml
            /WEB-INF/security.xml
        </param-value>
    </context-param>

    <filter>
        <filter-name>localeFilter</filter-name>
        <filter-class>org.appfuse.webapp.filter.LocaleFilter</filter-class>
    </filter>
    <filter>
        <filter-name>securityFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <init-param>
            <param-name>targetBeanName</param-name>
            <param-value>springSecurityFilterChain</param-value>
        </init-param>
    </filter>
    <filter>
        <filter-name>sitemesh</filter-name>
        <filter-class>com.opensymphony.module.sitemesh.filter.PageFilter</filter-class>
    </filter>
    <filter>
        <filter-name>staticFilter</filter-name>
        <filter-class>org.appfuse.webapp.filter.StaticFilter</filter-class>
        <init-param>
            <param-name>servletName</param-name>
            <param-value>dispatcher</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>securityFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>localeFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>sitemesh</filter-name>
        <url-pattern>*.html</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>
    <filter-mapping>
        <filter-name>sitemesh</filter-name>
        <url-pattern>*.jsp</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>
    <filter-mapping>
        <filter-name>staticFilter</filter-name>
        <url-pattern>*.html</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.appfuse.webapp.listener.StartupListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.appfuse.webapp.listener.UserCounterListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.json</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>3600</session-timeout>
    </session-config>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <error-page>
        <error-code>500</error-code>
        <location>/error.jsp</location>
    </error-page>
    <error-page>
        <error-code>400</error-code>
        <location>/index.jsp</location>
    </error-page>
    <error-page>
        <error-code>403</error-code>
        <location>/403.jsp</location>
    </error-page>
    <error-page>
        <error-code>404</error-code>
        <location>/404.jsp</location>
    </error-page>
</web-app>
</code>```

答:
Your DispatcherServlet doesn't pick the /hello url-pattern.

So change the web.xml configuration as shown below to pick the multiple url-pattern values:

```<code><servlet-mapping>
     <servlet-name>dispatcher</servlet-name>
      <url-pattern>*.json</url-pattern> <!-- serves all .json requests -->
      <url-pattern>/hello</url-pattern> <!-- serves /hello request -->
</servlet-mapping>
</code>```

Body:
I have a legacy Spring application whether the context is configured entirely with XML. I would like to add a new controller to the application using the @Controller annotation so I begin to migrate to using annotations.

As a test I have added the following controller to the application

package uk.co.onevisionconsulting.engineermanager.webapp.controller2;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {

     @RequestMapping("/hello")
     public String hello(){
          return "Hello";
     }
}

I have also added the context:component-scan tag to my spring context

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans” xmlns:context="http://www.springframework.org/schema/context"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance”
             xsi:schemaLocation="http://www.springframework.org/schema/beans
             http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
             http://www.springframework.org/schema/context
             http://www.springframework.org/schema/context/spring-context-2.5.xsd">

     <context:component-scan base-package="uk.co.onevisionconsulting.engineermanager" />

     <bean name="jsonView"
          class="uk.co.onevisionconsulting.engineermanager.webapp.view.JsonView" />

     <bean name="csvView"
          class="uk.co.onevisionconsulting.engineermanager.webapp.view.CsvView" />

     <bean name="ajaxView"
          class="uk.co.onevisionconsulting.engineermanager.webapp.view.AjaxView" />

     <bean name="dataTablesView"
          class="uk.co.onevisionconsulting.engineermanager.webapp.view.DataTablesView" />

     <bean id="exceptionResolver"
          class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
          <property name="exceptionMappings">
               <props>
                    <prop key="org.springframework.dao.DataAccessException">
                         dataAccessFailure
                    </prop>
               </props>
          </property>
     </bean>

     <bean id=“someController"
          class="uk.co.onevisionconsulting.engineermanager.webapp.controller.SomeController" >
          <property name=“someManager" ref=“someManager" />
     </bean>

     <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
          <property name="maxUploadSize" value="2097152" />
     </bean>

     <bean id="messageSource"
          class="org.springframework.context.support.ResourceBundleMessageSource">
          <property name="basename" value="ApplicationResources" />
          <property name="useCodeAsDefaultMessage" value="true" />
     </bean>

     <bean id="urlMapping"
          class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
          <property name="mappings">
               <value>
                    <!— Some URLs —>
               </value>
          </property>
          <property name="order" value="0" />
     </bean>

     <bean
          class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
          <property name="order" value="1" />
     </bean>

     <bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
          <property name="order" value="2" />
     </bean>

     <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
          <property name="requestContextAttribute" value="rc" />
          <property name="viewClass"
               value="org.springframework.web.servlet.view.JstlView" />
          <property name="prefix" value="/WEB-INF/pages/" />
          <property name="suffix" value=".jsp" />
     </bean>
</beans>

All though the classpath scanner (ClassPathScanningCandidateComponentProvider) picks up the HelloController I get a 404 when I try and navigate to localhost:8080/hello

Can anyone see what else I need to do? Here is my web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">

    <display-name>Engineer Manager</display-name>

    <context-param>
        <param-name>csstheme</param-name>
        <param-value>engineermanager</param-value>
    </context-param>

    <context-param>
        <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
        <param-value>ApplicationResources</param-value>
    </context-param>

    <context-param>
        <param-name>javax.servlet.jsp.jstl.fmt.fallbackLocale</param-name>
        <param-value>en</param-value>
    </context-param>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:/applicationContext-resources.xml
            classpath:/applicationContext-dao.xml
            classpath:/applicationContext-service.xml
            classpath*:/applicationContext.xml
            /WEB-INF/applicationContext*.xml
            /WEB-INF/security.xml
        </param-value>
    </context-param>

    <filter>
        <filter-name>localeFilter</filter-name>
        <filter-class>org.appfuse.webapp.filter.LocaleFilter</filter-class>
    </filter>
    <filter>
        <filter-name>securityFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <init-param>
            <param-name>targetBeanName</param-name>
            <param-value>springSecurityFilterChain</param-value>
        </init-param>
    </filter>
    <filter>
        <filter-name>sitemesh</filter-name>
        <filter-class>com.opensymphony.module.sitemesh.filter.PageFilter</filter-class>
    </filter>
    <filter>
        <filter-name>staticFilter</filter-name>
        <filter-class>org.appfuse.webapp.filter.StaticFilter</filter-class>
        <init-param>
            <param-name>servletName</param-name>
            <param-value>dispatcher</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>securityFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>localeFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>sitemesh</filter-name>
        <url-pattern>*.html</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>
    <filter-mapping>
        <filter-name>sitemesh</filter-name>
        <url-pattern>*.jsp</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>
    <filter-mapping>
        <filter-name>staticFilter</filter-name>
        <url-pattern>*.html</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.appfuse.webapp.listener.StartupListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.appfuse.webapp.listener.UserCounterListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.json</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>3600</session-timeout>
    </session-config>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <error-page>
        <error-code>500</error-code>
        <location>/error.jsp</location>
    </error-page>
    <error-page>
        <error-code>400</error-code>
        <location>/index.jsp</location>
    </error-page>
    <error-page>
        <error-code>403</error-code>
        <location>/403.jsp</location>
    </error-page>
    <error-page>
        <error-code>404</error-code>
        <location>/404.jsp</location>
    </error-page>
</web-app>

Body:
Your DispatcherServlet doesn't pick the /hello url-pattern.

So change the web.xml configuration as shown below to pick the multiple url-pattern values:

<servlet-mapping>
     <servlet-name>dispatcher</servlet-name>
      <url-pattern>*.json</url-pattern> <!-- serves all .json requests -->
      <url-pattern>/hello</url-pattern> <!-- serves /hello request -->
</servlet-mapping>


问:
How do I create a button who will fetch the user's location without listeners
I'm trying to use the user's gps location in my app. The idea is to have a button that will fetch his current location and display it on a map. I don't want to have a real time update of his position. His location will be updated ONLY when he presses the button. Here is a sample of my fragment.

```<code>public class HomeFragment extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener, View.OnClickListener {

private static final int MY_PERMISSION_ACCESS_COARSE_LOCATION = 11;
private static final int MY_PERMISSION_ACCESS_FINE_LOCATION = 12;
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private LocationManager mLocationManager;
private String mLatitudeText;
private String mLongitudeText;
private View view;
private MarkerOptions mMarker = new MarkerOptions();

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    if (view != null) {
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null)
            parent.removeView(view);
    }
    try {
        Log.d("debug", "inside TRy");
        view = inflater.inflate(R.layout.fragment_homepage, container, false);

    } catch (Exception e) {
        Log.d("debug", "error inside try:"+e.toString());
    } finally {
        SupportMapFragment mMap = (SupportMapFragment) this.getChildFragmentManager()
                .findFragmentById(R.id.map);
        ImageButton mGpsUpdate = (ImageButton) view.findViewById(R.id.update_gps);
        Log.d("debug", "after inflater");
        mGpsUpdate.setOnClickListener(this);

        createGoogleMapClient(); // <- moi

        mMap.getMapAsync(this);
        return view;
    }
}

public void onStart() {
    mGoogleApiClient.connect();
    super.onStart();
}

public void onStop() {
    mGoogleApiClient.disconnect();
    super.onStop();
}

private void createGoogleMapClient(){

    mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

@Override
public void onMapReady(GoogleMap googleMap) {
    Log.d("debug", "in");
    mMap = googleMap;

    // Add a marker in Sydney and move the camera
    LatLng champlain = new LatLng(45.5164522,-73.52062409999996);

    mMap.addMarker(new MarkerOptions().position(champlain).title("Champlain College"));

    mMap.moveCamera(CameraUpdateFactory.newLatLng(champlain));//Move camera to Champlain
    CameraPosition oldPos = mMap.getCameraPosition();

    CameraPosition pos = CameraPosition.builder(oldPos).bearing(-103).build(); //rotate map
    mMap.moveCamera(CameraUpdateFactory.newCameraPosition(pos));

    //Debug
    updateLocation();

    mMap.setMinZoomPreference((float)17.3);
    mMap.setMaxZoomPreference(20);
    mMap.getUiSettings().setRotateGesturesEnabled(false);
    mMap.getUiSettings().setCompassEnabled(false);
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    updateLocation();

}

private void checkPermission(){
    if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions( getActivity(), new String[] {  android.Manifest.permission.ACCESS_COARSE_LOCATION  },
                MY_PERMISSION_ACCESS_COARSE_LOCATION );
        ActivityCompat.requestPermissions( getActivity(), new String[] {  android.Manifest.permission.ACCESS_FINE_LOCATION  },
                MY_PERMISSION_ACCESS_FINE_LOCATION );
    }
}

@Override
public void onConnectionSuspended(int i) {
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

@Override
public void onDestroyView() {

    FragmentManager fm = getFragmentManager();

    Fragment xmlFragment = fm.findFragmentById(R.id.map);
    if (xmlFragment != null) {
        fm.beginTransaction().remove(xmlFragment).commit();
    }

    super.onDestroyView();
}

public void updateLocation(){
    checkPermission();
    Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
        mGoogleApiClient);

    if (mLastLocation != null) {

        mLatitudeText = String.valueOf(mLastLocation.getLatitude());
        mLongitudeText = String.valueOf(mLastLocation.getLongitude());

        Log.d("Coordinates",(mLatitudeText + ", " + mLongitudeText));

        LatLng me = new LatLng(Double.parseDouble(mLatitudeText), Double.parseDouble(mLongitudeText));

        mMap.addMarker(mMarker.position(me).title("me"));

    }
}

@Override
public void onClick(View v) {
    Log.d("debug", "inside Button Listener");
    switch(v.getId()){
        case R.id.update_gps:
            Log.d("debug", "inside good case");
            mMap.clear();
            updateLocation();
            break;
    }
  }
}
</code>```

Any ideas?

答:
The device doesn't determine its location on its own, but only when some application request the location. So your app is now dependent on other applications requesting location updates. That's why you are stuck with the same location even if moving around.

Also the "last known location" here means exactly that: It may not be up-to-date. Locations do come with a time stamp which could be used to asses if the location might still be relevant.

I don't see a call to requestLocationUpdates() anywhere in your code. You could add that to onConnected(). That would request up-to-date location updates at an interval which you can specify. You could then access this up-to-date "latest location" with getLastLocation() just as you already do.

And you should then call removeLocationUpdates() when you no longer need to track the user.

This approach would keep updating the location all the time and depending on your settings could affect the battery consumption.

But the other option would be to request updates only when the button is pressed and cancel them after the first result and that would have a delay between the button press and receiving the location.

Body:
I'm trying to use the user's gps location in my app. The idea is to have a button that will fetch his current location and display it on a map. I don't want to have a real time update of his position. His location will be updated ONLY when he presses the button. Here is a sample of my fragment.

public class HomeFragment extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener, View.OnClickListener {

private static final int MY_PERMISSION_ACCESS_COARSE_LOCATION = 11;
private static final int MY_PERMISSION_ACCESS_FINE_LOCATION = 12;
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private LocationManager mLocationManager;
private String mLatitudeText;
private String mLongitudeText;
private View view;
private MarkerOptions mMarker = new MarkerOptions();

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    if (view != null) {
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null)
            parent.removeView(view);
    }
    try {
        Log.d("debug", "inside TRy");
        view = inflater.inflate(R.layout.fragment_homepage, container, false);

    } catch (Exception e) {
        Log.d("debug", "error inside try:"+e.toString());
    } finally {
        SupportMapFragment mMap = (SupportMapFragment) this.getChildFragmentManager()
                .findFragmentById(R.id.map);
        ImageButton mGpsUpdate = (ImageButton) view.findViewById(R.id.update_gps);
        Log.d("debug", "after inflater");
        mGpsUpdate.setOnClickListener(this);

        createGoogleMapClient(); // <- moi

        mMap.getMapAsync(this);
        return view;
    }
}

public void onStart() {
    mGoogleApiClient.connect();
    super.onStart();
}

public void onStop() {
    mGoogleApiClient.disconnect();
    super.onStop();
}

private void createGoogleMapClient(){

    mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

@Override
public void onMapReady(GoogleMap googleMap) {
    Log.d("debug", "in");
    mMap = googleMap;

    // Add a marker in Sydney and move the camera
    LatLng champlain = new LatLng(45.5164522,-73.52062409999996);

    mMap.addMarker(new MarkerOptions().position(champlain).title("Champlain College"));

    mMap.moveCamera(CameraUpdateFactory.newLatLng(champlain));//Move camera to Champlain
    CameraPosition oldPos = mMap.getCameraPosition();

    CameraPosition pos = CameraPosition.builder(oldPos).bearing(-103).build(); //rotate map
    mMap.moveCamera(CameraUpdateFactory.newCameraPosition(pos));

    //Debug
    updateLocation();

    mMap.setMinZoomPreference((float)17.3);
    mMap.setMaxZoomPreference(20);
    mMap.getUiSettings().setRotateGesturesEnabled(false);
    mMap.getUiSettings().setCompassEnabled(false);
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    updateLocation();

}

private void checkPermission(){
    if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions( getActivity(), new String[] {  android.Manifest.permission.ACCESS_COARSE_LOCATION  },
                MY_PERMISSION_ACCESS_COARSE_LOCATION );
        ActivityCompat.requestPermissions( getActivity(), new String[] {  android.Manifest.permission.ACCESS_FINE_LOCATION  },
                MY_PERMISSION_ACCESS_FINE_LOCATION );
    }
}

@Override
public void onConnectionSuspended(int i) {
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

@Override
public void onDestroyView() {

    FragmentManager fm = getFragmentManager();

    Fragment xmlFragment = fm.findFragmentById(R.id.map);
    if (xmlFragment != null) {
        fm.beginTransaction().remove(xmlFragment).commit();
    }

    super.onDestroyView();
}

public void updateLocation(){
    checkPermission();
    Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
        mGoogleApiClient);

    if (mLastLocation != null) {

        mLatitudeText = String.valueOf(mLastLocation.getLatitude());
        mLongitudeText = String.valueOf(mLastLocation.getLongitude());

        Log.d("Coordinates",(mLatitudeText + ", " + mLongitudeText));

        LatLng me = new LatLng(Double.parseDouble(mLatitudeText), Double.parseDouble(mLongitudeText));

        mMap.addMarker(mMarker.position(me).title("me"));

    }
}

@Override
public void onClick(View v) {
    Log.d("debug", "inside Button Listener");
    switch(v.getId()){
        case R.id.update_gps:
            Log.d("debug", "inside good case");
            mMap.clear();
            updateLocation();
            break;
    }
  }
}

Any ideas?


问:
Octave dsolve SymPy Error: Python exception: AttributeError: 'list' object has no attribute 'subs'
(I tried posting this in Scientific Computing but they said to post it here; sorry if this is again off-topic.)

I'm using dsolve on Octave for the first time (Thanks so much for including this feature, BTW; this SimPy connection is just great), and it works fine with most of the ODEs and IVPs I've tried, but this one gives me an error:

```<code>>> pkg load symbolic
>> syms x(t)
>> ode1 = diff(x,t) == -t/x
>> cond1 = x(0) == 5
>> dsolve(ode1, cond1)
error: Python exception: AttributeError: 'list' object has no attribute 'subs'
    occurred at line 15 of the Python code block error: called from
    python_cmd at line 176 column 5
    dsolve at line 200 column 10
</code>```

Just solving the ODE worked fine; it only crashes with the IVP:

```<code>>> dsolve(ode1)
ans =
{
(sym)

             _________
            ╱       2
  x(t) = -╲╱  C₁ - t

(sym)

            _________
           ╱       2
  x(t) = ╲╱  C₁ - t
</code>```

I tried other initial conditions, but got the same error:

```<code>>> cond2 = x(-3) == 0.1
warning: Using rat() heuristics for double-precision input (is this what you wanted?)
warning: called from
    sym at line 225 column 7
    binop_helper at line 60 column 5
    ineq_helper at line 35 column 5
    eq at line 91 column 5
cond2 = (sym) x(-3) = 1/10
>> dsolve(ode1, cond2)
error: Python exception: AttributeError: 'list' object has no attribute 'subs'
    occurred at line 15 of the Python code block
error: called from
    python_cmd at line 176 column 5
    dsolve at line 200 column 10
</code>```

Can anyone help with this? I'd really like to use Octave to solve ODEs and IVPs explicitly

答:
The Short Answer:

Unfortunately, it is not yet supported.

The Longer Answer:

I came across the same problem, and had a look inside the script to see what was going wrong.

On line 174 of the dsolve.m function, you will find the following:

```<code>% FIXME: it is not currently supported a list of boundary/initial conditions
</code>```

What you can do:

If you really need it, I would suggest contacting the authors of the package, and let them know that there are actually people wanting this functionality. Visit the Forge page to see the details of the author of the package.

https://octave.sourceforge.io/symbolic/index.html

Body:
(I tried posting this in Scientific Computing but they said to post it here; sorry if this is again off-topic.)

I'm using dsolve on Octave for the first time (Thanks so much for including this feature, BTW; this SimPy connection is just great), and it works fine with most of the ODEs and IVPs I've tried, but this one gives me an error:

>> pkg load symbolic
>> syms x(t)
>> ode1 = diff(x,t) == -t/x
>> cond1 = x(0) == 5
>> dsolve(ode1, cond1)
error: Python exception: AttributeError: 'list' object has no attribute 'subs'
    occurred at line 15 of the Python code block error: called from
    python_cmd at line 176 column 5
    dsolve at line 200 column 10

Just solving the ODE worked fine; it only crashes with the IVP:

>> dsolve(ode1)
ans =
{
(sym)

             _________
            ╱       2
  x(t) = -╲╱  C₁ - t

(sym)

            _________
           ╱       2
  x(t) = ╲╱  C₁ - t

I tried other initial conditions, but got the same error:

>> cond2 = x(-3) == 0.1
warning: Using rat() heuristics for double-precision input (is this what you wanted?)
warning: called from
    sym at line 225 column 7
    binop_helper at line 60 column 5
    ineq_helper at line 35 column 5
    eq at line 91 column 5
cond2 = (sym) x(-3) = 1/10
>> dsolve(ode1, cond2)
error: Python exception: AttributeError: 'list' object has no attribute 'subs'
    occurred at line 15 of the Python code block
error: called from
    python_cmd at line 176 column 5
    dsolve at line 200 column 10

Can anyone help with this? I'd really like to use Octave to solve ODEs and IVPs explicitly

Body:
The Short Answer:

Unfortunately, it is not yet supported.

The Longer Answer:

I came across the same problem, and had a look inside the script to see what was going wrong.

On line 174 of the dsolve.m function, you will find the following:

% FIXME: it is not currently supported a list of boundary/initial conditions

What you can do:

If you really need it, I would suggest contacting the authors of the package, and let them know that there are actually people wanting this functionality. Visit the Forge page to see the details of the author of the package.

https://octave.sourceforge.io/symbolic/index.html


问:
Validate that input is in this time format - "HH:MM"
I'm trying to use preg_match to validate that a time input is in this format - "HH:MM"

答:
Corrected answer for @Toskan if you only want to validate HH:MM string</p>

```<code>     protected function isValidTime($timeStr){

    $dateObj = DateTime::createFromFormat('d.m.Y H:i', "10.10.2010 " . $timeStr);
    $dateObjOffset = DateTime::createFromFormat('d.m.Y H:i', "10.10.2010 " . '24:00');

    if($dateObjOffset <= $dateObj){
        return false;
    }
    if ($dateObj !== false) {
       return true;
    }
    else{
       return false;
    }
}
</code>```

Body:
Corrected answer for @Toskan if you only want to validate HH:MM string

     protected function isValidTime($timeStr){

    $dateObj = DateTime::createFromFormat('d.m.Y H:i', "10.10.2010 " . $timeStr);
    $dateObjOffset = DateTime::createFromFormat('d.m.Y H:i', "10.10.2010 " . '24:00');

    if($dateObjOffset <= $dateObj){
        return false;
    }
    if ($dateObj !== false) {
       return true;
    }
    else{
       return false;
    }
}


问:
Issues using Oracle case function
i'm trying to find the create a query that will return a set of staff's last name with their attached grade level (which is in another table with no foreign key relationship available with the staff one).

So far i have this but it is returning a "missing keyword" error on it. What is wrong with it?/ have i got my logic very wrong?

The last name and salary are in the staff/employee table.
The grade level is in a Job grades table.

```<code>    select last_name, salary,
CASE grade_level
WHEN  lowest_sal >= 1000 THEN 'A'
WHEN lowest_sal >= 3000  THEN 'B'
WHEN lowest_sal >= 6000 THEN 'C'
WHEN lowest_sal >= 10000 THEN 'D'
WHEN lowest_sal >= 15000  THEN 'E'
ELSE 'F'
END
FROM employees, job_grades
WHERE department_id > 50;
</code>```

答:
There is syntax error in the CASE statement

Important thing - you are missing the JOIN conditions

```<code>SELECT LAST_NAME
    , SALARY
    , CASE
        WHEN LOWEST_SAL >= 1000 THEN 'A'
        WHEN LOWEST_SAL >= 3000 THEN 'B'
        WHEN LOWEST_SAL >= 6000 THEN 'C'
        WHEN LOWEST_SAL >= 10000 THEN 'D'
        WHEN LOWEST_SAL >= 15000 THEN 'E'
        ELSE 'F'
    END AS GRADE_LEVEL
FROM EMPLOYEES
    JOIN JOB_GRADES
        ON EMPLOYEES.ID = JOB_GRADES.EMP_ID
WHERE DEPARTMENT_ID > 50;
</code>```

Title: Issues using Oracle case function

Body:
i'm trying to find the create a query that will return a set of staff's last name with their attached grade level (which is in another table with no foreign key relationship available with the staff one).

So far i have this but it is returning a "missing keyword" error on it. What is wrong with it?/ have i got my logic very wrong?

The last name and salary are in the staff/employee table.
The grade level is in a Job grades table.

    select last_name, salary,
CASE grade_level
WHEN  lowest_sal >= 1000 THEN 'A'
WHEN lowest_sal >= 3000  THEN 'B'
WHEN lowest_sal >= 6000 THEN 'C'
WHEN lowest_sal >= 10000 THEN 'D'
WHEN lowest_sal >= 15000  THEN 'E'
ELSE 'F'
END
FROM employees, job_grades
WHERE department_id > 50;

Body:
There is syntax error in the CASE statement

Important thing - you are missing the JOIN conditions

SELECT LAST_NAME
    , SALARY
    , CASE
        WHEN LOWEST_SAL >= 1000 THEN 'A'
        WHEN LOWEST_SAL >= 3000 THEN 'B'
        WHEN LOWEST_SAL >= 6000 THEN 'C'
        WHEN LOWEST_SAL >= 10000 THEN 'D'
        WHEN LOWEST_SAL >= 15000 THEN 'E'
        ELSE 'F'
    END AS GRADE_LEVEL
FROM EMPLOYEES
    JOIN JOB_GRADES
        ON EMPLOYEES.ID = JOB_GRADES.EMP_ID
WHERE DEPARTMENT_ID > 50;


问:
XPath to select all elements between two headings?
```<code><h2>Headline 1</h2>
<p>some text</p>
<p>some more text</p>
<ul>
<li>list item 1</li>
<li>list item 2</li>
</ul>
<p>more text</p>
<h2>Headline 2</h2>
</code>```

I have the above in a webpage and I want to be able to target all elements following the first h2 that contains the text 'Headline 1' up to but NOT including the element h2 that contains the text 'Headline 2'.

I can target the elements like this:

```<code>//*[count(preceding-sibling::hr)=1]
</code>```

but this is not specific to the text contained and so if the page ever changed then the xpath could be pointing to something totally different.

What I would like in sudo code terms is this:

give me all the elements between the header 'Headline 1' and the
  header 'Headline 2' including 'Headline 1'

Is this at all possible?

答:
This XPath,

```<code>//*[    preceding-sibling::h2[. = 'Headline 1']
    and following-sibling::h2[. = 'Headline 2']]
</code>```

will select all elements between h2s with string values of 'Headline 1' and 'Headline 2':

```<code><p>some text</p>
<p>some more text</p>
<ul>
<li>list item 1</li>
<li>list item 2</li>
</ul>
<p>more text</p>
</code>```

Andersson points out in the comments that OP wants the first h2 included in the selection.

Andersson's initial thought would work:

```<code>//h2[. = 'Headline 1'] |
//*[    preceding-sibling::h2[. = 'Headline 1']
    and following-sibling::h2[. = 'Headline 2']]
</code>```

Here's another way:

```<code>//*[self::h2[. = 'Headline 1']
    or (    preceding-sibling::h2[. = 'Headline 1']
        and following-sibling::h2[. = 'Headline 2']]
</code>```

Or, probably the ideal way:

```<code>//h2[. = 'Headline 2']
    /preceding-sibling::*[not(following-sibling::h2[. = 'Heading 1'])]
</code>```

because it avoids having to specify 'Heading 1' twice.

Body:
Headline 1

some text

some more text

list item 1

list item 2

more text

Headline 2

I have the above in a webpage and I want to be able to target all elements following the first h2 that contains the text 'Headline 1' up to but NOT including the element h2 that contains the text 'Headline 2'.

I can target the elements like this:

//*[count(preceding-sibling::hr)=1]

but this is not specific to the text contained and so if the page ever changed then the xpath could be pointing to something totally different.

What I would like in sudo code terms is this:

give me all the elements between the header 'Headline 1' and the
  header 'Headline 2' including 'Headline 1'

Is this at all possible?

Body:
This XPath,

//*[    preceding-sibling::h2[. = 'Headline 1']
    and following-sibling::h2[. = 'Headline 2']]

will select all elements between h2s with string values of 'Headline 1' and 'Headline 2':

<p>some text</p>
<p>some more text</p>
<ul>
<li>list item 1</li>
<li>list item 2</li>
</ul>
<p>more text</p>

Andersson points out in the comments that OP wants the first h2 included in the selection.

Andersson's initial thought would work:

//h2[. = 'Headline 1'] |
//*[    preceding-sibling::h2[. = 'Headline 1']
    and following-sibling::h2[. = 'Headline 2']]

Here's another way:

//*[self::h2[. = 'Headline 1']
    or (    preceding-sibling::h2[. = 'Headline 1']
        and following-sibling::h2[. = 'Headline 2']]

Or, probably the ideal way:

//h2[. = 'Headline 2']
    /preceding-sibling::*[not(following-sibling::h2[. = 'Heading 1'])]

because it avoids having to specify 'Heading 1' twice.


问:
ERR_CONTENT_LENGTH_MISMATCH node express angular
I am getting this error ERR_CONTENT_LENGTH_MISMATCH when i am calling my api.
Client side Angular
Backend Express (nodejs)</p>

答:
It seems that you are setting the Content-length header in Express but sending a body that doesn't match the declared size.

Avoid setting the Content-length in Express and use chunked encoding instead - that way you won't need to know the size up front and it will be impossible to declare the wrong size because you wouldn't declare any.

Errors like that can also sometimes be caused by the problems with proxy misconfiguration or permissions.

Of course it's impossible to tell for sure what you're doing wrong in a code that you didn't show.


问:
Arithmetic operation resulted in an overflow
When i send:

```<code>Result = CInt(NetApiBufferFree(pBuffer))
</code>```

I receive (SOME TIMES) this error:

```<code>Arithmetic operation resulted in an overflow.
</code>```

What exactly means that? and how i can resolve it?

答:
It means that CInt argument is out of range of Integer, -0x80000000 to 0x7FFFFFFF
And it happens when NetApiBufferFree returns an error: error codes are bigger than 0x80000000.

There is no unsigned int32 type, so use CLng instead of CInt.

About source of error.  You should find out code of error which you get: call MsgBox or log it to file, or use breakpoint. Next find its description. If it won't help you (for example error would be E_FAIL), add code to check that pBuffer value is valid - that it wasn't modified by something, and wasn't already freed. Add logging for NetApiBuffer* calls.

ContentLicense: CC BY-SA 2.5

Body:
When i send:

Result = CInt(NetApiBufferFree(pBuffer))

I receive (SOME TIMES) this error:

Arithmetic operation resulted in an overflow.

What exactly means that? and how i can resolve it?


问:
mongodb save in a nested object (node.js) application
I get "bookid not found" from my code.
I can add author and titles separately using postman but I can't seem to get the reviewsCreate function to to work, am I missing something? PLS help

my schema

```<code>    var mongoose = require('mongoose');

    var reviewSchema = new mongoose.Schema({
        author: {
            type: String,
            required: true
        },
        rating: {
            type: Number,
            required: true,
            min: 0,
            max: 5
        },
        reviewText: { type: String, required: true },
        createdOn: {
            type: Date,
            "default": Date.now
        }
    });

    var titleSchema = new mongoose.Schema({
        title: {
            type: String,
            required: true
        },
        favouredBy: {
            type:[String],
            required: false
        },
        reviews: [reviewSchema]

    });
    var bookSchema = new mongoose.Schema({
        bookAuthor: {
            type: String,
            required: true
        },
        titles: [titleSchema]
    });
    mongoose.model('Book', bookSchema);
</code>```

```<code>   router.post('/books/:bookid/titles/:titleid/reviews',ctrlReviews.reviewsCreate);
</code>```

```<code>    module.exports.reviewsCreate = function(req, res) {
        if (req.params.bookid) {
            Bok
                .findById(req.params.titleid)
                .select('titles')
                .exec(
                    function(err, book) {
                        if (err) {
                            sendJSONresponse(res, 400, err);
                        } else {
                            doAddReview(req, res, book);
                        }
                    }
                );
        } else {
            sendJSONresponse(res, 404, {
                "message": "Not found, bookid required"
            });
        }

    };

    var doAddReview = function(req, res, book, author) {
        if (!book) {
            sendJSONresponse(res, 404, "bookid not found");
        } else {
            book.reviews.push({
                author: author,
                rating: req.query.rating,
                reviewText: req.query.reviewText
            });
            book.save(function(err, book) {
                var thisReview;
                if (err) {
                    sendJSONresponse(res, 400, err);
                } else {
                    updateAverageRating(book._id);
                    thisReview = book.reviews[book.reviews.length - 1];
                    sendJSONresponse(res, 201, thisReview);
                }
            });
        }
    };
</code>```

this is what i get when i used your recommendation
error :

TypeError: Cannot read property 'push' of undefined

when i put console.log(book); right under the doAddrivew function.

```<code>    { _id: 58dd21c3cb77090b930b6063,
      titles:
       [ { title: 'this is title',
           _id: 58dd3f2701cc081056135dae,
           reviews: [],
           favouredBy: [Object] },
         { title: 'this is the second tittle',
           _id: 58dd42a59f12f110d1756f08,
           reviews: [],
           favouredBy: [Object] } ]
    }
</code>```

答:
your book schema have the titles property which further have the reviews

do

```<code>var doAddReview = function(req, res, book, author) {
    if (!book) {
        sendJSONresponse(res, 404, "bookid not found");
    } else {
       /* book.titles.reviews.push({
            author: author,
            rating: req.query.rating,
            reviewText: req.query.reviewText
        }); */
        book.titles[0].reviews.push({ // to push in first element
            author: author,
            rating: req.query.rating,
            reviewText: req.query.reviewText
        });
        book.save(function(err, book) {
            var thisReview;
            if (err) {
                sendJSONresponse(res, 400, err);
            } else {
                updateAverageRating(book._id);
                // -----------------------------
                thisReview = book.reviews[book.reviews.length - 1];
               // thisReview = book.titles.reviews[book.titles.reviews.length - 1];
                // here also you may have to modify
                sendJSONresponse(res, 201, thisReview);
            }
        });
    }
}
</code>```

▼ UPDATE ▼

First of All the book should be an instance of your Book Model.

The titles property defined inside bookSchema is an array, So when you want to add the data in bookSchema, bookAuthor property will have just a string, but the titles field would contain objects like [{}, {}, {}], so you have to select the index of titles like titles[0] or titles[1] and then push onto which title you want to review

Note: as reviews of [reviewSchema] is also an array you have use index and select the required element from that array, to perform operations like update, delete like book.titles[0].reviews[1]

Suppose if i want to Push in titles array first element

```<code>book.titles[0].reviews.push({
    author: author,
    rating: req.query.rating,
    reviewText: req.query.reviewText
});
</code>```

```<code>    { _id: 58dd21c3cb77090b930b6063,
      titles:
       [ { title: 'this is title',
           _id: 58dd3f2701cc081056135dae,
           reviews: [],
           favouredBy: [Object] },
         { title: 'this is the second tittle',
           _id: 58dd42a59f12f110d1756f08,
           reviews: [],
           favouredBy: [Object] } ]
    }
</code>```

Here as you have 2 objects inside the titles you have to select in which you want to push,

if you want to push the reviews in first object of _id: 58dd3f2701cc081056135dae, then select titles[0]

and for _id: 58dd42a59f12f110d1756f08, titles[1]

as your array will have multiple objects, so you have to match the object in which you want to perform the operation like update, so to filter the document you can make the use of $ positional operator

https://docs.mongodb.com/v3.2/reference/operator/update/position/

Please have a look at dot notation also
https://docs.mongodb.com/manual/core/document/#dot-notation

Body:
I get "bookid not found" from my code.
I can add author and titles separately using postman but I can't seem to get the reviewsCreate function to to work, am I missing something? PLS help

my schema

    var mongoose = require('mongoose');

    var reviewSchema = new mongoose.Schema({
        author: {
            type: String,
            required: true
        },
        rating: {
            type: Number,
            required: true,
            min: 0,
            max: 5
        },
        reviewText: { type: String, required: true },
        createdOn: {
            type: Date,
            "default": Date.now
        }
    });

    var titleSchema = new mongoose.Schema({
        title: {
            type: String,
            required: true
        },
        favouredBy: {
            type:[String],
            required: false
        },
        reviews: [reviewSchema]

    });
    var bookSchema = new mongoose.Schema({
        bookAuthor: {
            type: String,
            required: true
        },
        titles: [titleSchema]
    });
    mongoose.model('Book', bookSchema);

   router.post('/books/:bookid/titles/:titleid/reviews',ctrlReviews.reviewsCreate);

    module.exports.reviewsCreate = function(req, res) {
        if (req.params.bookid) {
            Bok
                .findById(req.params.titleid)
                .select('titles')
                .exec(
                    function(err, book) {
                        if (err) {
                            sendJSONresponse(res, 400, err);
                        } else {
                            doAddReview(req, res, book);
                        }
                    }
                );
        } else {
            sendJSONresponse(res, 404, {
                "message": "Not found, bookid required"
            });
        }

    };

    var doAddReview = function(req, res, book, author) {
        if (!book) {
            sendJSONresponse(res, 404, "bookid not found");
        } else {
            book.reviews.push({
                author: author,
                rating: req.query.rating,
                reviewText: req.query.reviewText
            });
            book.save(function(err, book) {
                var thisReview;
                if (err) {
                    sendJSONresponse(res, 400, err);
                } else {
                    updateAverageRating(book._id);
                    thisReview = book.reviews[book.reviews.length - 1];
                    sendJSONresponse(res, 201, thisReview);
                }
            });
        }
    };

this is what i get when i used your recommendation
error :

TypeError: Cannot read property 'push' of undefined

when i put console.log(book); right under the doAddrivew function.

    { _id: 58dd21c3cb77090b930b6063,
      titles:
       [ { title: 'this is title',
           _id: 58dd3f2701cc081056135dae,
           reviews: [],
           favouredBy: [Object] },
         { title: 'this is the second tittle',
           _id: 58dd42a59f12f110d1756f08,
           reviews: [],
           favouredBy: [Object] } ]
    }

Body:
your book schema have the titles property which further have the reviews

do

var doAddReview = function(req, res, book, author) {
    if (!book) {
        sendJSONresponse(res, 404, "bookid not found");
    } else {
       /* book.titles.reviews.push({
            author: author,
            rating: req.query.rating,
            reviewText: req.query.reviewText
        }); */
        book.titles[0].reviews.push({ // to push in first element
            author: author,
            rating: req.query.rating,
            reviewText: req.query.reviewText
        });
        book.save(function(err, book) {
            var thisReview;
            if (err) {
                sendJSONresponse(res, 400, err);
            } else {
                updateAverageRating(book._id);
                // -----------------------------
                thisReview = book.reviews[book.reviews.length - 1];
               // thisReview = book.titles.reviews[book.titles.reviews.length - 1];
                // here also you may have to modify
                sendJSONresponse(res, 201, thisReview);
            }
        });
    }
}

▼ UPDATE ▼

First of All the book should be an instance of your Book Model.

The titles property defined inside bookSchema is an array, So when you want to add the data in bookSchema, bookAuthor property will have just a string, but the titles field would contain objects like [{}, {}, {}], so you have to select the index of titles like titles[0] or titles[1] and then push onto which title you want to review

Note: as reviews of [reviewSchema] is also an array you have use index and select the required element from that array, to perform operations like update, delete like book.titles[0].reviews[1]

Suppose if i want to Push in titles array first element

book.titles[0].reviews.push({
    author: author,
    rating: req.query.rating,
    reviewText: req.query.reviewText
});

    { _id: 58dd21c3cb77090b930b6063,
      titles:
       [ { title: 'this is title',
           _id: 58dd3f2701cc081056135dae,
           reviews: [],
           favouredBy: [Object] },
         { title: 'this is the second tittle',
           _id: 58dd42a59f12f110d1756f08,
           reviews: [],
           favouredBy: [Object] } ]
    }

Here as you have 2 objects inside the titles you have to select in which you want to push,

if you want to push the reviews in first object of _id: 58dd3f2701cc081056135dae, then select titles[0]

and for _id: 58dd42a59f12f110d1756f08, titles[1]

as your array will have multiple objects, so you have to match the object in which you want to perform the operation like update, so to filter the document you can make the use of $ positional operator

https://docs.mongodb.com/v3.2/reference/operator/update/position/

Please have a look at dot notation also
https://docs.mongodb.com/manual/core/document/#dot-notation