问:
Using set_facts and with_items together in Ansible
I'm currently using Ansible 1.7.2.  I have the following test playbook:

```<code>---
- hosts: localhost
  tasks:
  - name: set fact 1
    set_fact: foo="[ 'zero' ]"

  - name: set fact 2
    set_fact: foo="{{ foo }} + [ 'one' ]"

  - name: set fact 3
    set_fact: foo="{{ foo }} + [ 'two', 'three' ]"

  - name: set fact 4
    set_fact: foo="{{ foo }} + [ '{{ item }}' ]"
    with_items:
      - four
      - five
      - six

  - debug: var=foo
</code>```

The first task sets a fact that's a list with one item in it.  The subsequent tasks append to that list with more values.  The first three tasks work as expected, but the last one doesn't.  Here's the output when I run this:

```<code>PLAY [localhost] **************************************************************

GATHERING FACTS ***************************************************************
ok: [localhost]

TASK: [set fact 1] ************************************************************
ok: [localhost]

TASK: [set fact 2] ************************************************************
ok: [localhost]

TASK: [set fact 3] ************************************************************
ok: [localhost]

TASK: [set fact 4] ************************************************************
ok: [localhost] => (item=four)
ok: [localhost] => (item=five)
ok: [localhost] => (item=six)

TASK: [debug var=foo] *********************************************************
ok: [localhost] => {
    "foo": [
        "zero",
        "one",
        "two",
        "three",
        "six"
    ]
}

PLAY RECAP ********************************************************************
localhost                  : ok=6    changed=0    unreachable=0    failed=0
</code>```

Given the with_items in task 4 and the fact that the output shows the task properly iterated over the items in that list, I would have expected the result to contain all the numbers zero through six. But that last task seems to only be evaluating set_fact with the last item in the list.  Is this possibly a bug in Ansible?

Edit: I also just tested this on ansible 1.8 and the output was identical.

答:
As mentioned in other people's comments, the top solution given here was not working for me in Ansible 2.2, particularly when also using with_items.

It appears that OP's intended approach does work now with a slight change to the quoting of item.

```<code>- set_fact: something="{{ something + [ item ] }}"
  with_items:
    - one
    - two
    - three
</code>```

And a longer example where I've handled the initial case of the list being undefined and added an optional when because that was also causing me grief:

```<code>- set_fact: something="{{ something|default([]) + [ item ] }}"
  with_items:
    - one
    - two
    - three
  when: item.name in allowed_things.item_list
</code>```

Body:
I'm currently using Ansible 1.7.2.  I have the following test playbook:

---
- hosts: localhost
  tasks:
  - name: set fact 1
    set_fact: foo="[ 'zero' ]"

  - name: set fact 2
    set_fact: foo="{{ foo }} + [ 'one' ]"

  - name: set fact 3
    set_fact: foo="{{ foo }} + [ 'two', 'three' ]"

  - name: set fact 4
    set_fact: foo="{{ foo }} + [ '{{ item }}' ]"
    with_items:
      - four
      - five
      - six

  - debug: var=foo

The first task sets a fact that's a list with one item in it.  The subsequent tasks append to that list with more values.  The first three tasks work as expected, but the last one doesn't.  Here's the output when I run this:

PLAY [localhost] **************************************************************

GATHERING FACTS ***************************************************************
ok: [localhost]

TASK: [set fact 1] ************************************************************
ok: [localhost]

TASK: [set fact 2] ************************************************************
ok: [localhost]

TASK: [set fact 3] ************************************************************
ok: [localhost]

TASK: [set fact 4] ************************************************************
ok: [localhost] => (item=four)
ok: [localhost] => (item=five)
ok: [localhost] => (item=six)

TASK: [debug var=foo] *********************************************************
ok: [localhost] => {
    "foo": [
        "zero",
        "one",
        "two",
        "three",
        "six"
    ]
}

PLAY RECAP ********************************************************************
localhost                  : ok=6    changed=0    unreachable=0    failed=0

Given the with_items in task 4 and the fact that the output shows the task properly iterated over the items in that list, I would have expected the result to contain all the numbers zero through six. But that last task seems to only be evaluating set_fact with the last item in the list.  Is this possibly a bug in Ansible?

Edit: I also just tested this on ansible 1.8 and the output was identical.

Body:
As mentioned in other people's comments, the top solution given here was not working for me in Ansible 2.2, particularly when also using with_items.

It appears that OP's intended approach does work now with a slight change to the quoting of item.

- set_fact: something="{{ something + [ item ] }}"
  with_items:
    - one
    - two
    - three

And a longer example where I've handled the initial case of the list being undefined and added an optional when because that was also causing me grief:

- set_fact: something="{{ something|default([]) + [ item ] }}"
  with_items:
    - one
    - two
    - three
  when: item.name in allowed_things.item_list


来源: stackexchange

问:
NPM Script for "node-sass" and "postcss" to autoprefix
I need to compile my scss to css files with autoprefixing the attributes. My npm script looks like this:

{
  "scripts": {
    "build:css": "node-sass --output-style 'compressed' src/scss/ -o public_html/css/map/ && postcss --use autoprefixer public_html/css/map/ -d public_html/css/",
    "watch:css": "node-sass --watch --recursive --output-style 'compressed' src/scss/ -o public_html/css/"
  },
  "devDependencies": {
    "bootstrap-sass": "^3.3.7",
    "node-sass": "^4.5.0",
    "postcss": "^6.0.13",
    "postcss-cli": "^4.1.1"
  }
}
```

But I get a error message:

Plugin Error: Cannot find module 'autoprefixer'

At last i think that my code is dirty. I try to generate with node-sass the css files, and place them on filetree in "map" directory. Then i try to grab them with postcss and copy the autoprefixed css files in the css folder. Is there any cleaner way without creating the files in the map directory?

答:
You need to install the npm module: autoprefixer</p>

```<code>npm install autoprefixer --save-dev
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to compile my scss to css files with autoprefixing the attributes. My npm script looks like this:

{
  "scripts": {
    "build:css": "node-sass --output-style 'compressed' src/scss/ -o public_html/css/map/ && postcss --use autoprefixer public_html/css/map/ -d public_html/css/",
    "watch:css": "node-sass --watch --recursive --output-style 'compressed' src/scss/ -o public_html/css/"
  },
  "devDependencies": {
    "bootstrap-sass": "^3.3.7",
    "node-sass": "^4.5.0",
    "postcss": "^6.0.13",
    "postcss-cli": "^4.1.1"
  }
}

But I get a error message:

Plugin Error: Cannot find module 'autoprefixer'

At last i think that my code is dirty. I try to generate with node-sass the css files, and place them on filetree in "map" directory. Then i try to grab them with postcss and copy the autoprefixed css files in the css folder. Is there any cleaner way without creating the files in the map directory?

Body:
You need to install the npm module: autoprefixer

npm install autoprefixer --save-dev

ContentLicense: CC BY-SA 3.0


问:
curly braces in es6 arrow function for each
We create presentational component or stateless component like this

```<code>const MyComponent = () => {
   return(<div>my component</div>)
}
</code>```

but I'd seen this

```<code>const MyComponent = () =>
   <div>
     <h1>head</h1>
     my component
   </div>
</code>```

so now I'm confused when the braces is needed when using es6's arrow function.

This confused me on when rendering a list using map

shorter version

```<code><div>
{map(o =>
   <div>{o.name}</div>
)}
</div>
</code>```

longer version

```<code><div>
    {map(o => {
     return(<div>{o.name}</div>)
     })}
</div>
</code>```

Both are correct, but why write longer?

答:
Arrow functions work both way to provide you with a bit of versatility. Say you need to perform some logic inside your function before you return, in this case you would need to add curly braces, i.e say you need to extract the name of a list of users, but you want to append their title.

```<code>let users = [new User(), ... ];
//...

let withTitle = users.map(p => {
   const title = getTitle(p); // automagically returns Mr, Mrs, etc
   return `${title} ${p.fullName}`
});

// withTitle => ['Mr Ricky Bobby', 'Mr Ron Burgundy']
</code>```

Now, you can declare a function that does the work for you, and use the shorthand version of the arrow function. like so.

```<code>const extractWithTitle: (user) => {
   const title = getTitle(p); // automagically returns Mr, Mrs, etc
   return `${title} ${p.fullName}`
}

let withTitle = users.map(p => extractWithTitle(p));
// withTitle => ['Mr Ricky Bobby', 'Mr Ron Burgundy']
</code>```

Now, an even shorter way to approach this would be to pass a reference to the function.

```<code>users.map(extractWithTitle);
</code>```

Body:
We create presentational component or stateless component like this

const MyComponent = () => {
   return(
my component
)
}

but I'd seen this

const MyComponent = () =>

head

     my component

so now I'm confused when the braces is needed when using es6's arrow function.

This confused me on when rendering a list using map

shorter version

{map(o =>

{o.name}

)}

longer version

    {map(o => {
     return(
{o.name}
)
     })}

Both are correct, but why write longer?

Body:
Arrow functions work both way to provide you with a bit of versatility. Say you need to perform some logic inside your function before you return, in this case you would need to add curly braces, i.e say you need to extract the name of a list of users, but you want to append their title.

let users = [new User(), ... ];
//...

let withTitle = users.map(p => {
   const title = getTitle(p); // automagically returns Mr, Mrs, etc
   return `${title} ${p.fullName}`
});

// withTitle => ['Mr Ricky Bobby', 'Mr Ron Burgundy']

Now, you can declare a function that does the work for you, and use the shorthand version of the arrow function. like so.

const extractWithTitle: (user) => {
   const title = getTitle(p); // automagically returns Mr, Mrs, etc
   return `${title} ${p.fullName}`
}

let withTitle = users.map(p => extractWithTitle(p));
// withTitle => ['Mr Ricky Bobby', 'Mr Ron Burgundy']

Now, an even shorter way to approach this would be to pass a reference to the function.

users.map(extractWithTitle);


问:
populate listView with specific data
I'm working on an app consists of

three Buttons to enter three different Fragments, each of them contains a List. when you press on the toggle Button next to any ListItem it is added to a SQLite database.

Button for Summary contains three lists to populate saved data from each Fragment.
My problem is (for example how can I retrieve saved data from fragment_one ONLY to the listView_one in the Summary activity) ?

N.B. all the data are of the same type (from the same model) and the saved ones got saved in the same database.

I've searched and found that I should use Fragment tag during FragmentTransaction..

What should I do after I set a tag for each Fragment?
When should I check the tag to populate the data correctly?

Sorry for that long question but i'm little overwhelmed and got stuck at this point.

答:
If I understand correctly your problem, we have 2 ways to do this:

add a tag column in your db, then you can retrieve saved value from each fragment with your desired tag.

create a singleton manage each fragment saved data, etc:

public class DataManager {

// singleton implementation

...

private List mFragmentOneSavedData; // just save db row id to query later

...

}

Thanks.

Title: populate listView with specific data


问:
How to convert XML to Dict
I want to find some great solution to convert XML to dict and vice versa in python</p>

答:
I might suggest taking a look at declxml to see if it fits your use case (full disclosure: I am the author). With declxml, you create objects called processors which declaratively define the structure of your XML document. Processors are used to both parse and serialize between XML and Python values including objects, dictionaries, and namedtuples.

```<code>import declxml as xml

some_xml = """
<mydocument has="an attribute">
  <and>
    <many>elements</many>
    <many>more elements</many>
  </and>
  <plus a="complex">
    element as well
  </plus>
</mydocument>
"""

processor = xml.dictionary('mydocument', [
    xml.string('.', attribute='has'),
    xml.array(xml.string('many'), nested='and'),
    xml.dictionary('plus', [
        xml.string('.', attribute='a'),
        xml.string('.', alias='plus')
    ])
])

xml.parse_from_string(processor, some_xml)
</code>```

Which produces the following output

```<code>{'has': 'an attribute',
 'and': ['elements', 'more elements'],
 'plus': {'a': 'complex', 'plus': 'element as well'}}
</code>```

Title: How to convert XML to Dict

Body:
I might suggest taking a look at declxml to see if it fits your use case (full disclosure: I am the author). With declxml, you create objects called processors which declaratively define the structure of your XML document. Processors are used to both parse and serialize between XML and Python values including objects, dictionaries, and namedtuples.

import declxml as xml

some_xml = """
<mydocument has="an attribute">
  <and>
    <many>elements</many>
    <many>more elements</many>
  </and>
  <plus a="complex">
    element as well
  </plus>
</mydocument>
"""

processor = xml.dictionary('mydocument', [
    xml.string('.', attribute='has'),
    xml.array(xml.string('many'), nested='and'),
    xml.dictionary('plus', [
        xml.string('.', attribute='a'),
        xml.string('.', alias='plus')
    ])
])

xml.parse_from_string(processor, some_xml)

Which produces the following output

{'has': 'an attribute',
 'and': ['elements', 'more elements'],
 'plus': {'a': 'complex', 'plus': 'element as well'}}


问:
Simple Python: about structure of code
```<code>print ("This program reads an unsigned binary number of arbitrary length
\nand tries to compute the decimal equivalent. The program reports an error
\nif the input number contains characters other than 0 and 1.")
dec = 0
bin = 0
factor = 1

print ("Enter the binary number: ")
bin = int(input())

while(bin > 0):

    if((bin % 10) == True):
        dec += factor
        bin //= 10
        factor = factor * 2

    else:
        print("unrecognized bit:")

print ("I think your binary number in decimal form is: " ,dec)
</code>```

This is my code for a program that is supposed to convert a binary number from the user into a decimal number. It works fine, but I'm trying to add an "else" statement that will print "unrecognized bit" if the user enters a number other than 0 or 1. It kinds works, however the program prints "Unrecognized bit" even if the user has only entered 0 and 1's. This shouldn't happen. Also, see picture related. I've entered 12343 to test the program, and it says Unrecognized bit which is good but it also takes the "1" in that number and converts it to 16 which shouldn't happen, it should just say unrecognized bit. I think these two problems are simple to fix but I'm just not sure. Thank you!

picture

答:
You need to test your input to be sure it is legal. You can do this using regular expressions. Replace bin = int(input()) with:

```<code>import re
inp = input()
if re.match('.*[^01]+.*', inp) is not None:
    print("illegal character in input, must be ones and/or zeros")
    exit()

bin = int(inp)
</code>```

This will print the illegal character message if the input contains anything but ones or zeros.

Title: Simple Python: about structure of code

Body:
print ("This program reads an unsigned binary number of arbitrary length
\nand tries to compute the decimal equivalent. The program reports an error
\nif the input number contains characters other than 0 and 1.")
dec = 0
bin = 0
factor = 1

print ("Enter the binary number: ")
bin = int(input())

while(bin > 0):

    if((bin % 10) == True):
        dec += factor
        bin //= 10
        factor = factor * 2

    else:
        print("unrecognized bit:")

print ("I think your binary number in decimal form is: " ,dec)

This is my code for a program that is supposed to convert a binary number from the user into a decimal number. It works fine, but I'm trying to add an "else" statement that will print "unrecognized bit" if the user enters a number other than 0 or 1. It kinds works, however the program prints "Unrecognized bit" even if the user has only entered 0 and 1's. This shouldn't happen. Also, see picture related. I've entered 12343 to test the program, and it says Unrecognized bit which is good but it also takes the "1" in that number and converts it to 16 which shouldn't happen, it should just say unrecognized bit. I think these two problems are simple to fix but I'm just not sure. Thank you!

picture

Body:
You need to test your input to be sure it is legal. You can do this using regular expressions. Replace bin = int(input()) with:

import re
inp = input()
if re.match('.*[^01]+.*', inp) is not None:
    print("illegal character in input, must be ones and/or zeros")
    exit()

bin = int(inp)

This will print the illegal character message if the input contains anything but ones or zeros.


问:
-libcurl linker "cannot find"
I'm following this quasi-tutorial here on making curl work:
Using LibCURL C++

I'm at the point now where I've downloaded and linked the necessary file paths to my compiler and linker. However, when I run the program I get this error:

"cannot find -lcurldll"

This appears to be a linker command malfunction. In the tutorial, its instructed to put "curldll" in the link library.  I've been working on this for hours without success. What should I do? (Using Windows 10, Code :: Blocks)

答: The answer was to put the command without the -l in the linker. </p>

Title: -libcurl linker "cannot find"


问:
Casting from NSString to "const std::string&"
I'm really rusty with my C++ and ObjectiveC, but I have linked a C++ library into my iOS project.   I am having trouble calling the method in my C++ library from my iOS App.

Ultimately, I'm having a hard time grokking the type conversion, and getting it right.

Can someone help point out what I am doing wrong, and offer the solution?

// In my C++ Library

```<code>std::string Foo::bar(const std::string& src)
{
    //...
}
</code>```

// In my iOS Project:

```<code>NSString *input = @"Foo";
NSString *output = [NSString stringWithCString: Foo::bar(std::string([input UTF8String])).c_str() encoding: [NSString defaultCStringEncoding]];
</code>```

The error I get in Xcode is:

```<code>Undefined symbols for architecture x86_64:
Foo::bar(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)", referenced from...
</code>```

From what I understand, it's the casting of input which is problemmatic.

I've already scoured StackOverflow, but can't seem to find the specific casting from NSString to const std::string&

Thanks!

答:
To convert from NSString to const std::string&, you just need to use [input UTF8String]. Try my code below

```<code>NSString *input = @"Foo";
std::string str = [input UTF8String];
NSString *output = [NSString stringWithUTF8String:Foo::bar(str).c_str()];
</code>```

Body:
I'm really rusty with my C++ and ObjectiveC, but I have linked a C++ library into my iOS project.   I am having trouble calling the method in my C++ library from my iOS App.

Ultimately, I'm having a hard time grokking the type conversion, and getting it right.

Can someone help point out what I am doing wrong, and offer the solution?

// In my C++ Library

std::string Foo::bar(const std::string& src)
{
    //...
}

// In my iOS Project:

NSString *input = @"Foo";
NSString *output = [NSString stringWithCString: Foo::bar(std::string([input UTF8String])).c_str() encoding: [NSString defaultCStringEncoding]];

The error I get in Xcode is:

Undefined symbols for architecture x86_64:
Foo::bar(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)", referenced from...

From what I understand, it's the casting of input which is problemmatic.

I've already scoured StackOverflow, but can't seem to find the specific casting from NSString to const std::string&

Thanks!

Body:
To convert from NSString to const std::string&, you just need to use [input UTF8String]. Try my code below

NSString *input = @"Foo";
std::string str = [input UTF8String];
NSString *output = [NSString stringWithUTF8String:Foo::bar(str).c_str()];


问:
Akavache or Sqlite is crashing When Calling in OnStart method
When I use the code below in my xamarin.forms project to check if User object exist in akavache cache, I am getting the exception below. the same code or any akavache query works somewhere else but crashes in onStart method only. I believe that I am initializing akavache in constructor already. I tried exact same code using mobile center to query locally (local sqlite) user data and I get the same exception. I think that this should be something to do with the sqlite as both akavache and mobile center uses similar sqlite libraries. Does anybody know why it doesnt work in OnStart method?

```<code> public App()
        {
            Microsoft.Azure.Mobile.MobileCenter.Start("android=key" +
                   "uwp=key",
                   typeof(Microsoft.Azure.Mobile.Analytics.Analytics), typeof(Microsoft.Azure.Mobile.Crashes.Crashes));

            Akavache.BlobCache.ApplicationName = "myApp";
            Akavache.BlobCache.EnsureInitialized();

            ServiceLocator.Add<ICloudService, AzureCloudService>();

            InitializeComponent();

            }

  protected async override void OnStart()
        {

            try
            {
               var User= await BlobCache.UserAccount.GetObject<User>("User");

                if (User != null)
                    Helpers.Settings.IsLoggedIn = true;
                else
                    Helpers.Settings.IsLoggedIn = false;
            }
            catch (Exception)
            {
                Helpers.Settings.IsLoggedIn = false;
            }
           ShowMainPageOrLoginPage();
        }
</code>```

11-13 02:08:14.761 E/MobileCenterCrashes( 6308): Unhandled Exception:
  11-13 02:08:14.761 E/MobileCenterCrashes( 6308):
  System.NullReferenceException: Object reference not set to an instance
  of an object. 11-13 02:08:14.761 E/MobileCenterCrashes( 6308):   at
  Xamarin.Forms.Platform.Android.AppCompat.Platform.LayoutRootPage
  (Xamarin.Forms.Page page, System.Int32 width, System.Int32 height)
  [0x0000c] in
  D:\agent_work\1\s\Xamarin.Forms.Platform.Android\AppCompat\Platform.cs:291
  11-13 02:08:14.761 E/MobileCenterCrashes( 6308):   at
  Xamarin.Forms.Platform.Android.AppCompat.Platform.Xamarin.Forms.Platform.Android.IPlatformLayout.OnLayout
  (System.Boolean changed, System.Int32 l, System.Int32 t, System.Int32
  r, System.Int32 b) [0x00003] in
  D:\agent_work\1\s\Xamarin.Forms.Platform.Android\AppCompat\Platform.cs:199
  11-13 02:08:14.761 E/MobileCenterCrashes( 6308):   at
  Xamarin.Forms.Platform.Android.PlatformRenderer.OnLayout
  (System.Boolean changed, System.Int32 l, System.Int32 t, System.Int32
  r, System.Int32 b) [0x0000e] in
  D:\agent_work\1\s\Xamarin.Forms.Platform.Android\PlatformRenderer.cs:73
  11-13 02:08:14.761 E/MobileCenterCrashes( 6308):   at
  Android.Views.ViewGroup.n_OnLayout_ZIIII (System.IntPtr jnienv,
  System.IntPtr native__this, System.Boolean changed, System.Int32 l,
  System.Int32 t, System.Int32 r, System.Int32 b) [0x00008] in
  :0

EDIT:
This issue is definetly caused by akavache. Message is really strange. it looks like that akavache has some relation with LayoutRootPage.

See my code above, I get User object from akavache cache and user object defines if I should show Login Page or Main Page. If I move ShowMainPageOrLoginPage();function above akavache call, it works just fine. So it seems that you cant make any query with akavache before the rootlayoutpage - Main page is set or loaded.

答:
I had the same problem once before, for some reason if you initialize using the static method it doesn't work all the time.

Doesn't work

```<code>IBlobCache _cache = BlobCache.LocalMachine;
</code>```

Does Work

```<code>IBlobCache _cache = new SQLitePersistentBlobCache(systemPath + "/CacheUtils.db");
</code>```

If you want to find the systemPath you can use this in either your Android or iOS

```<code>systemPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
</code>```

Body:
When I use the code below in my xamarin.forms project to check if User object exist in akavache cache, I am getting the exception below. the same code or any akavache query works somewhere else but crashes in onStart method only. I believe that I am initializing akavache in constructor already. I tried exact same code using mobile center to query locally (local sqlite) user data and I get the same exception. I think that this should be something to do with the sqlite as both akavache and mobile center uses similar sqlite libraries. Does anybody know why it doesnt work in OnStart method?

 public App()
        {
            Microsoft.Azure.Mobile.MobileCenter.Start("android=key" +
                   "uwp=key",
                   typeof(Microsoft.Azure.Mobile.Analytics.Analytics), typeof(Microsoft.Azure.Mobile.Crashes.Crashes));

            Akavache.BlobCache.ApplicationName = "myApp";
            Akavache.BlobCache.EnsureInitialized();

            ServiceLocator.Add<ICloudService, AzureCloudService>();

            InitializeComponent();

            }

  protected async override void OnStart()
        {

            try
            {
               var User= await BlobCache.UserAccount.GetObject<User>("User");

                if (User != null)
                    Helpers.Settings.IsLoggedIn = true;
                else
                    Helpers.Settings.IsLoggedIn = false;
            }
            catch (Exception)
            {
                Helpers.Settings.IsLoggedIn = false;
            }
           ShowMainPageOrLoginPage();
        }

11-13 02:08:14.761 E/MobileCenterCrashes( 6308): Unhandled Exception:
  11-13 02:08:14.761 E/MobileCenterCrashes( 6308):
  System.NullReferenceException: Object reference not set to an instance
  of an object. 11-13 02:08:14.761 E/MobileCenterCrashes( 6308):   at
  Xamarin.Forms.Platform.Android.AppCompat.Platform.LayoutRootPage
  (Xamarin.Forms.Page page, System.Int32 width, System.Int32 height)
  [0x0000c] in
  D:\agent_work\1\s\Xamarin.Forms.Platform.Android\AppCompat\Platform.cs:291
  11-13 02:08:14.761 E/MobileCenterCrashes( 6308):   at
  Xamarin.Forms.Platform.Android.AppCompat.Platform.Xamarin.Forms.Platform.Android.IPlatformLayout.OnLayout
  (System.Boolean changed, System.Int32 l, System.Int32 t, System.Int32
  r, System.Int32 b) [0x00003] in
  D:\agent_work\1\s\Xamarin.Forms.Platform.Android\AppCompat\Platform.cs:199
  11-13 02:08:14.761 E/MobileCenterCrashes( 6308):   at
  Xamarin.Forms.Platform.Android.PlatformRenderer.OnLayout
  (System.Boolean changed, System.Int32 l, System.Int32 t, System.Int32
  r, System.Int32 b) [0x0000e] in
  D:\agent_work\1\s\Xamarin.Forms.Platform.Android\PlatformRenderer.cs:73
  11-13 02:08:14.761 E/MobileCenterCrashes( 6308):   at
  Android.Views.ViewGroup.n_OnLayout_ZIIII (System.IntPtr jnienv,
  System.IntPtr native__this, System.Boolean changed, System.Int32 l,
  System.Int32 t, System.Int32 r, System.Int32 b) [0x00008] in
  :0

EDIT:
This issue is definetly caused by akavache. Message is really strange. it looks like that akavache has some relation with LayoutRootPage.

See my code above, I get User object from akavache cache and user object defines if I should show Login Page or Main Page. If I move ShowMainPageOrLoginPage();function above akavache call, it works just fine. So it seems that you cant make any query with akavache before the rootlayoutpage - Main page is set or loaded.

Body:
I had the same problem once before, for some reason if you initialize using the static method it doesn't work all the time.

Doesn't work

IBlobCache _cache = BlobCache.LocalMachine;

Does Work

IBlobCache _cache = new SQLitePersistentBlobCache(systemPath + "/CacheUtils.db");

If you want to find the systemPath you can use this in either your Android or iOS

systemPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);


问:
How to internationalize metas such as title in view.yml?
I'd like to internationalize the strings of my view.yml, I can't find how to do this.

I have a solution that is bad, in my opinion:

```<code>metas:
  title: <?php echo sfContext::getInstance()->getI18n()->__('TITLE'); ?>
</code>```

I'd like to find a way to do it without calling "sfConfig::getInstance()". Is it possible?

答:
Since include_title() does not translate what it finds in view.yml, I made this very simple function in my custom helper:

```<code>function include_translated_title($context)
{
  $title = $context->getI18N()->__($context->getResponse()->getTitle());

  echo content_tag('title', $title)."\n";
}
</code>```

Then I use it in my layout.php files:

```<code><head>
<?php include_http_metas() ?>
<?php include_metas() ?>
<?php include_translated_title($sf_context) ?>
</code>```

This way, I can use translation keys in my view.yml

ContentLicense: CC BY-SA 2.5

Body:
I'd like to internationalize the strings of my view.yml, I can't find how to do this.

I have a solution that is bad, in my opinion:

metas:
  title: <?php echo sfContext::getInstance()->getI18n()->__('TITLE'); ?>

I'd like to find a way to do it without calling "sfConfig::getInstance()". Is it possible?

Body:
Since include_title() does not translate what it finds in view.yml, I made this very simple function in my custom helper:

function include_translated_title($context)
{
  $title = $context->getI18N()->__($context->getResponse()->getTitle());

  echo content_tag('title', $title)."\n";
}

Then I use it in my layout.php files:

<head>
<?php include_http_metas() ?>
<?php include_metas() ?>
<?php include_translated_title($sf_context) ?>

This way, I can use translation keys in my view.yml


问:
Finding the query execution path?
I have a legacy java web application where I have employee hibernate entity. Somehow in a particular flow, a query(HQL) is getting fired by hibernate to
 fetch employee entity. I tried my best to find out where/why exactly that query is firing but did not find why.

Is there a way hibernate can tell me where and why that query is executing ? Is there any kind of configuration/setting like  auditing which can help
 here ?

I am using hibernate version 5.1

答: You can use use_sql_comments or create empty constructor and put debug point there as suggested at finding origin of query

Title: Finding the query execution path?


问:
Multi-level Categories in Wagtail
I always make sure I have tried every possible avenue before coming on here for advice.

That said, here is what I am currently struggling with; creating multi-level/nested categories. As an aside, it will be nice if the wagtail core developers can implement an easy way for multi-level category creation, without us having to write some vanilla-django hack for it.

I have been working on this application for a few weeks, everything runs smoothly, except now, there's a business decision for a nested category to be implemented.

My initial M.O was to create a ServiceCategoryIndex Page, a ServiceCategoryPage then make the ServiceIndex Page a descendant or orderable to the ServiceCategoryIndex Page as ServiceCategoryPage, Which just doesn't seem right.

After a couple of iteration, I went back to my default model, then tried the url of the category using views and url like vanilla-django, the problem with is, I am not able to query the foreign key with a through relationship on the template, so I still can't get the content of the service page as a list queryset rendered out.

Here're my model codes below, any suggestion or work around on this will be absolutely helpful. P.S: I am almost at the point of re-writing the whole project in vanilla-django, giving I don't find a solution within the next few days.

```<code>def get_service_context(context):
    context['all_categories'] = ServiceCategory.objects.all()
    context['root_categories'] = ServiceCategory.objects.filter(
    parent=None,
    ).prefetch_related(
    'children',
    ).annotate(
    service_count=Count('servicepage'),
    )
    return context

class ServiceIndexPage(Page):
    header_image = models.ForeignKey(
        'wagtailimages.Image',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+'
    )
    heading = models.CharField(max_length=500, null=True, blank=True)
    sub_heading = models.CharField(max_length=500, null=True, blank=True)
    body = RichTextField(null=True, blank=True)

    def get_context(self, request, category=None, *args, **kwargs):
        context = super(ServiceIndexPage, self).get_context(request, *args, **kwargs)

        services = ServicePage.objects.child_of(self).live().order_by('-first_published_at').prefetch_related('categories', 'categories__category')
        if category is None:
            if request.GET.get('category'):
                category = get_object_or_404(ServiceCategory, slug=request.GET.get('category'))
        if category:
            if not request.GET.get('category'):
                category = get_object_or_404(ServiceCategory, slug=category)
            services = services.filter(categories__category__name=category)

        # Pagination
        page = request.GET.get('page')
        page_size = 10
        if hasattr(settings, 'SERVICE_PAGINATION_PER_PAGE'):
            page_size = settings.SERVICE_PAGINATION_PER_PAGE

        if page_size is not None:
            paginator = Paginator(services, page_size)  # Show 10 services per page
            try:
                services = paginator.page(page)
            except PageNotAnInteger:
                services = paginator.page(1)
            except EmptyPage:
                services = paginator.page(paginator.num_pages)

        context['services'] = services
        context['category'] = category
        context = get_service_context(context)

        return context

@register_snippet
class ServiceCategory(models.Model):
    name = models.CharField(max_length=250, unique=True, verbose_name=_('Category Name'))
    slug = models.SlugField(unique=True, max_length=250)
    parent = models.ForeignKey('self', blank=True, null=True, related_name="children")
    date = models.DateField(auto_now_add=True, auto_now=False, null=True, blank=True)
    description = RichTextField(blank=True)

    class Meta:
        ordering = ['-date']
        verbose_name = _("Service Category")
        verbose_name_plural = _("Service Categories")

    panels = [
        FieldPanel('name'),
        FieldPanel('parent'),
        FieldPanel('description'),
    ]

    def __str__(self):
        return self.name

    def clean(self):
        if self.parent:
            parent = self.parent
            if self.parent == self:
                raise ValidationError('Parent category cannot be self.')
            if parent.parent and parent.parent == self:
                raise ValidationError('Cannot have circular Parents.')

    def save(self, *args, **kwargs):
        if not self.slug:
            slug = slugify(self.name)
            count = ServiceCategory.objects.filter(slug=slug).count()
            if count > 0:
                slug = '{}-{}'.format(slug, count)
            self.slug = slug
        return super(ServiceCategory, self).save(*args, **kwargs)

class ServiceCategoryServicePage(models.Model):
    category = models.ForeignKey(ServiceCategory, related_name="+", verbose_name=_('Category'))
    page = ParentalKey('ServicePage', related_name='categories')
    panels = [
        FieldPanel('category'),
    ]

class ServicePage(Page):
     header_image = models.ForeignKey(
        'wagtailimages.Image',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+',
        verbose_name=_('Header image')
    )
    service_title = models.CharField(max_length=300, null=True, blank=True)
    body = StreamField([
        ('h1', CharBlock(icon="title", classanme="title")),
        ('h2', CharBlock(icon="title", classanme="title")),
        ('h3', CharBlock(icon="title", classanme="title")),
        ('h4', CharBlock(icon="title", classanme="title")),
        ('h5', CharBlock(icon="title", classanme="title")),
        ('h6', CharBlock(icon="title", classanme="title")),
        ('paragraph', RichTextBlock(icon="pilcrow")),
        ('aligned_image', ImageBlock(label="Aligned image", icon="image")),
        ('pullquote', PullQuoteBlock()),
        ('raw_html', RawHTMLBlock(label='Raw HTML', icon="code")),
        ('embed', EmbedBlock(icon="code")),
])
    date = models.DateField("Post date")
    service_categories = models.ManyToManyField(ServiceCategory, through=ServiceCategoryServicePage, blank=True)

    feed_image = models.ForeignKey(
        'wagtailimages.Image',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+',
        verbose_name=_('Feed image')
    )

    search_fields = Page.search_fields + [
        index.SearchField('body'),
        index.SearchField('service_title'),
        index.SearchField('title'),]

    def get_absolute_url(self):
        return self.url

    def get_service_index(self):
        # Find closest ancestor which is a service index
        return self.get_ancestors().type(ServiceIndexPage).last()

    def get_context(self, request, *args, **kwargs):
        context = super(ServicePage, self).get_context(request, *args, **kwargs)
        context['services'] = self.get_service_index().serviceindexpage
        context = get_service_context(context)
        return context

    class Meta:
        verbose_name = _('Service page')
        verbose_name_plural = _('Services pages')

    parent_page_types = ['services.ServiceIndexPage']

ServicePage.content_panels = [
    FieldPanel('title', classname="full title"),
    FieldPanel('service_title'),
    ImageChooserPanel('header_image'),
    FieldPanel('date'),
    InlinePanel('categories', label=_("Categories")),
    StreamFieldPanel('body'),
    ImageChooserPanel('feed_image'),
</code>```

]

答:
I have been working on a similar issue - except we are calling them Topic instead of Category but hopefully this helps you out.

Summary of Solution

Use the Django-Treebeard library to manage your trees, they can be nested up to 63 levels deep and will give you full access to the api for things like get_children or is_root.

You will need to override some behaviour for creating and 'moving' nodes, this is best done by the base_form_class override.

I have used ModelAdmin for this but it should work just as well if the are snippets, but ModelAdmin gives you more control for the future if you wanted to add more complex editing.

Finally, you can then link these topics/categories to your pages with a ForeignKey or some other relational link.

Caveats: No reordering of child nodes other than alphabetical in this example, this can be added but it is a bit more complicated as you need a UI for it - hence using ModelAdmin. Also, you should never let the user delete the root, it will delete all nodes.

Django Treebeard Caveats - worth reading

1 - Building the Model

I have a dedicated Topics app, but you can put this in any models.py. See comments throughout that explain the code.

```<code>from __future__ import unicode_literals

from django import forms
from django.core.exceptions import PermissionDenied
from django.db import models

from treebeard.mp_tree import MP_Node

from wagtail.contrib.modeladmin.options import ModelAdmin
from wagtail.wagtailadmin.edit_handlers import FieldPanel
from wagtail.wagtailadmin.forms import WagtailAdminModelForm

# This is your main 'node' model, it inherits mp_node
# mp_node is short for materialized path, it means the tree has a clear path
class Topic(MP_Node):
    """
        Topics can be nested and ordered.
        Root (id 1) cannot be deleted, can be edited.
        User should not edit path, depth, numchild directly.
    """

    name = models.CharField(max_length=30)
    is_selectable = models.BooleanField(default=True)  # means selectable by pages
    # any other fields for the Topic/Category can go here
    # eg. slug, date, description

    # may need to rework node_order_by to be orderable
    # careful - cannot change after initial data is set up
    node_order_by = ['name']

    # just like any model in wagtail, you will need to set up panels for editing fields
    panels = [
        FieldPanel('parent'),  # parent is not a field on the model, it is built in the TopicForm form class
        FieldPanel('name', classname='full'),
        FieldPanel('is_selectable'),
    ]

    # this is just a convenience function to make the names appear with lines
    # eg root | - first child
    def name_with_depth(self):
        depth = '— ' * (self.get_depth() - 1)
        return depth + self.name
    name_with_depth.short_description = 'Name'

    # another convenience function/property - just for use in modeladmin index
    @property
    def parent_name(self):
        if not self.is_root():
            return self.get_parent().name
        return None

    # a bit of a hacky way to stop users from deleting root
    def delete(self):
        if self.is_root():
            raise PermissionDenied('Cannot delete root topic.')
        else:
            super(Topic, self).delete()

    # pick your python string representation
    def __unicode__(self):
        return self.name_with_depth()

    def __str__(self):
        return self.name_with_depth()

    class Meta:
        verbose_name = 'Topic'
        verbose_name_plural = 'Topics'

# this class is the form class override for Topic
# it handles the logic to ensure that pages can be moved
# root pages need to be treated specially
# including the first created item always being the root
class TopicForm(WagtailAdminModelForm):

    # build a parent field that will show the available topics
    parent = forms.ModelChoiceField(
        required=True,
        empty_label=None,
        queryset=Topic.objects.none(),
    )

    def __init__(self, *args, **kwargs):
        super(TopicForm, self).__init__(*args, **kwargs)
        instance = kwargs['instance']
        all = Topic.objects.all()
        is_root = False

        if len(all) == 0 or instance.is_root():
            # no nodes, first created must be root or is editing root
            is_root = True

        if is_root:
            # disable the parent field, rename name label
            self.fields['parent'].empty_label = 'N/A - Root Node'
            self.fields['parent'].disabled = True
            self.fields['parent'].required = False
            self.fields['parent'].help_text = 'Root Node has no Parent'
            self.fields['name'].label += ' (Root)'
        else:
            # sets the queryset on the parent field
            # ensure that they cannot select the existing topic as parent
            self.fields['parent'].queryset = Topic.objects.exclude(
                pk=instance.pk)
            self.fields['parent'].initial = instance.get_parent()

    def save(self, commit=True):
        parent = self.cleaned_data['parent']
        instance = super(TopicForm, self).save(commit=False)
        all = Topic.objects.all()

        is_new = instance.id is None
        is_root = False
        if is_new and len(all) == 0:
            is_root = True
        elif not is_new and instance.is_root():
            is_root = True

        # saving / creating
        if is_root and is_new and commit:
            # adding the root
            instance = Topic.add_root(instance=instance)
        elif is_new and commit:
            # adding a new child under the seleced parent
            instance = parent.add_child(instance=instance)
        elif not is_new and instance.get_parent() != parent and commit:
            # moving the instance to under a new parent, editing existing node
            # must use 'sorted-child' - will base sorting on node_order_by
            instance.move(parent, pos='sorted-child')
        elif commit:
            # no moving required, just save
            instance.save()

        return instance

# tell Wagtail to use our form class override
Topic.base_form_class = TopicForm

class TopicAdmin(ModelAdmin):
    model = Topic
    menu_icon = 'radio-empty'
    menu_order = 200
    add_to_settings_menu = False
    list_display = ['name_with_depth', 'parent_name']
    search_fields = ['name']
</code>```

2 - Register the modeladmin function in wagtail_hooks.py

This ensures that the TopicAdmin in the previous code is used in Wagtail Admin. You will know it works as it will appear on the left admin sidebar modeladmin register docs.

```<code>from wagtail.contrib.modeladmin.options import modeladmin_register
from .models import TopicAdmin

modeladmin_register(TopicAdmin)
</code>```

3 - Migrate & Create First Topic

Now would be a good time to make migrations and run your migrate, remember that node_order_by is not easy to change after you have built your model. If you want to add custom ordering of children eg. reordering capacity or ordering by some other field, do this before you migrate.

Then go into admin and create the first root node.

4 - Link to your Pages

Here is a quick and nasty example, letting you link one topic to a page without anything fancy. Note that we are limiting choices here, this can be extended to do more complicated limiting based on the fields you have set in Topic.

```<code>topic = models.ForeignKey(
    'topics.Topic',
    on_delete=models.SET_NULL,
    blank=True,
    null=True,
    limit_choices_to={'is_selectable': True},
    related_name='blog_page_topic',
)
</code>```

5 - Room for Improvement

The topic string representation always contains the dashes to show its 'depth', this is a bit ugly when seen elsewhere. It would be better to use an extended field type and build this representation only when needed.

As mentioned, no ability to reorder child nodes manually, you can create custom buttons in model admin so it would be possible to add buttons to move up/ move down and work through that way.

Example code, so probably a few rough edges but should be enough to get you started. I have tested this on Wagtail 1.13 in the demo application and it works.

Title: Multi-level Categories in Wagtail

Body:
I always make sure I have tried every possible avenue before coming on here for advice.

That said, here is what I am currently struggling with; creating multi-level/nested categories. As an aside, it will be nice if the wagtail core developers can implement an easy way for multi-level category creation, without us having to write some vanilla-django hack for it.

I have been working on this application for a few weeks, everything runs smoothly, except now, there's a business decision for a nested category to be implemented.

My initial M.O was to create a ServiceCategoryIndex Page, a ServiceCategoryPage then make the ServiceIndex Page a descendant or orderable to the ServiceCategoryIndex Page as ServiceCategoryPage, Which just doesn't seem right.

After a couple of iteration, I went back to my default model, then tried the url of the category using views and url like vanilla-django, the problem with is, I am not able to query the foreign key with a through relationship on the template, so I still can't get the content of the service page as a list queryset rendered out.

Here're my model codes below, any suggestion or work around on this will be absolutely helpful. P.S: I am almost at the point of re-writing the whole project in vanilla-django, giving I don't find a solution within the next few days.

def get_service_context(context):
    context['all_categories'] = ServiceCategory.objects.all()
    context['root_categories'] = ServiceCategory.objects.filter(
    parent=None,
    ).prefetch_related(
    'children',
    ).annotate(
    service_count=Count('servicepage'),
    )
    return context

class ServiceIndexPage(Page):
    header_image = models.ForeignKey(
        'wagtailimages.Image',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+'
    )
    heading = models.CharField(max_length=500, null=True, blank=True)
    sub_heading = models.CharField(max_length=500, null=True, blank=True)
    body = RichTextField(null=True, blank=True)

    def get_context(self, request, category=None, *args, **kwargs):
        context = super(ServiceIndexPage, self).get_context(request, *args, **kwargs)

        services = ServicePage.objects.child_of(self).live().order_by('-first_published_at').prefetch_related('categories', 'categories__category')
        if category is None:
            if request.GET.get('category'):
                category = get_object_or_404(ServiceCategory, slug=request.GET.get('category'))
        if category:
            if not request.GET.get('category'):
                category = get_object_or_404(ServiceCategory, slug=category)
            services = services.filter(categories__category__name=category)

        # Pagination
        page = request.GET.get('page')
        page_size = 10
        if hasattr(settings, 'SERVICE_PAGINATION_PER_PAGE'):
            page_size = settings.SERVICE_PAGINATION_PER_PAGE

        if page_size is not None:
            paginator = Paginator(services, page_size)  # Show 10 services per page
            try:
                services = paginator.page(page)
            except PageNotAnInteger:
                services = paginator.page(1)
            except EmptyPage:
                services = paginator.page(paginator.num_pages)

        context['services'] = services
        context['category'] = category
        context = get_service_context(context)

        return context

@register_snippet
class ServiceCategory(models.Model):
    name = models.CharField(max_length=250, unique=True, verbose_name=_('Category Name'))
    slug = models.SlugField(unique=True, max_length=250)
    parent = models.ForeignKey('self', blank=True, null=True, related_name="children")
    date = models.DateField(auto_now_add=True, auto_now=False, null=True, blank=True)
    description = RichTextField(blank=True)

    class Meta:
        ordering = ['-date']
        verbose_name = _("Service Category")
        verbose_name_plural = _("Service Categories")

    panels = [
        FieldPanel('name'),
        FieldPanel('parent'),
        FieldPanel('description'),
    ]

    def __str__(self):
        return self.name

    def clean(self):
        if self.parent:
            parent = self.parent
            if self.parent == self:
                raise ValidationError('Parent category cannot be self.')
            if parent.parent and parent.parent == self:
                raise ValidationError('Cannot have circular Parents.')

    def save(self, *args, **kwargs):
        if not self.slug:
            slug = slugify(self.name)
            count = ServiceCategory.objects.filter(slug=slug).count()
            if count > 0:
                slug = '{}-{}'.format(slug, count)
            self.slug = slug
        return super(ServiceCategory, self).save(*args, **kwargs)

class ServiceCategoryServicePage(models.Model):
    category = models.ForeignKey(ServiceCategory, related_name="+", verbose_name=_('Category'))
    page = ParentalKey('ServicePage', related_name='categories')
    panels = [
        FieldPanel('category'),
    ]

class ServicePage(Page):
     header_image = models.ForeignKey(
        'wagtailimages.Image',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+',
        verbose_name=_('Header image')
    )
    service_title = models.CharField(max_length=300, null=True, blank=True)
    body = StreamField([
        ('h1', CharBlock(icon="title", classanme="title")),
        ('h2', CharBlock(icon="title", classanme="title")),
        ('h3', CharBlock(icon="title", classanme="title")),
        ('h4', CharBlock(icon="title", classanme="title")),
        ('h5', CharBlock(icon="title", classanme="title")),
        ('h6', CharBlock(icon="title", classanme="title")),
        ('paragraph', RichTextBlock(icon="pilcrow")),
        ('aligned_image', ImageBlock(label="Aligned image", icon="image")),
        ('pullquote', PullQuoteBlock()),
        ('raw_html', RawHTMLBlock(label='Raw HTML', icon="code")),
        ('embed', EmbedBlock(icon="code")),
])
    date = models.DateField("Post date")
    service_categories = models.ManyToManyField(ServiceCategory, through=ServiceCategoryServicePage, blank=True)

    feed_image = models.ForeignKey(
        'wagtailimages.Image',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+',
        verbose_name=_('Feed image')
    )

    search_fields = Page.search_fields + [
        index.SearchField('body'),
        index.SearchField('service_title'),
        index.SearchField('title'),]

    def get_absolute_url(self):
        return self.url

    def get_service_index(self):
        # Find closest ancestor which is a service index
        return self.get_ancestors().type(ServiceIndexPage).last()

    def get_context(self, request, *args, **kwargs):
        context = super(ServicePage, self).get_context(request, *args, **kwargs)
        context['services'] = self.get_service_index().serviceindexpage
        context = get_service_context(context)
        return context

    class Meta:
        verbose_name = _('Service page')
        verbose_name_plural = _('Services pages')

    parent_page_types = ['services.ServiceIndexPage']

ServicePage.content_panels = [
    FieldPanel('title', classname="full title"),
    FieldPanel('service_title'),
    ImageChooserPanel('header_image'),
    FieldPanel('date'),
    InlinePanel('categories', label=_("Categories")),
    StreamFieldPanel('body'),
    ImageChooserPanel('feed_image'),

]

Body:
I have been working on a similar issue - except we are calling them Topic instead of Category but hopefully this helps you out.

Summary of Solution

Use the Django-Treebeard library to manage your trees, they can be nested up to 63 levels deep and will give you full access to the api for things like get_children or is_root.

You will need to override some behaviour for creating and 'moving' nodes, this is best done by the base_form_class override.

I have used ModelAdmin for this but it should work just as well if the are snippets, but ModelAdmin gives you more control for the future if you wanted to add more complex editing.

Finally, you can then link these topics/categories to your pages with a ForeignKey or some other relational link.

Caveats: No reordering of child nodes other than alphabetical in this example, this can be added but it is a bit more complicated as you need a UI for it - hence using ModelAdmin. Also, you should never let the user delete the root, it will delete all nodes.

Django Treebeard Caveats - worth reading

1 - Building the Model

I have a dedicated Topics app, but you can put this in any models.py. See comments throughout that explain the code.

from __future__ import unicode_literals

from django import forms
from django.core.exceptions import PermissionDenied
from django.db import models

from treebeard.mp_tree import MP_Node

from wagtail.contrib.modeladmin.options import ModelAdmin
from wagtail.wagtailadmin.edit_handlers import FieldPanel
from wagtail.wagtailadmin.forms import WagtailAdminModelForm

# This is your main 'node' model, it inherits mp_node
# mp_node is short for materialized path, it means the tree has a clear path
class Topic(MP_Node):
    """
        Topics can be nested and ordered.
        Root (id 1) cannot be deleted, can be edited.
        User should not edit path, depth, numchild directly.
    """

    name = models.CharField(max_length=30)
    is_selectable = models.BooleanField(default=True)  # means selectable by pages
    # any other fields for the Topic/Category can go here
    # eg. slug, date, description

    # may need to rework node_order_by to be orderable
    # careful - cannot change after initial data is set up
    node_order_by = ['name']

    # just like any model in wagtail, you will need to set up panels for editing fields
    panels = [
        FieldPanel('parent'),  # parent is not a field on the model, it is built in the TopicForm form class
        FieldPanel('name', classname='full'),
        FieldPanel('is_selectable'),
    ]

    # this is just a convenience function to make the names appear with lines
    # eg root | - first child
    def name_with_depth(self):
        depth = '— ' * (self.get_depth() - 1)
        return depth + self.name
    name_with_depth.short_description = 'Name'

    # another convenience function/property - just for use in modeladmin index
    @property
    def parent_name(self):
        if not self.is_root():
            return self.get_parent().name
        return None

    # a bit of a hacky way to stop users from deleting root
    def delete(self):
        if self.is_root():
            raise PermissionDenied('Cannot delete root topic.')
        else:
            super(Topic, self).delete()

    # pick your python string representation
    def __unicode__(self):
        return self.name_with_depth()

    def __str__(self):
        return self.name_with_depth()

    class Meta:
        verbose_name = 'Topic'
        verbose_name_plural = 'Topics'

# this class is the form class override for Topic
# it handles the logic to ensure that pages can be moved
# root pages need to be treated specially
# including the first created item always being the root
class TopicForm(WagtailAdminModelForm):

    # build a parent field that will show the available topics
    parent = forms.ModelChoiceField(
        required=True,
        empty_label=None,
        queryset=Topic.objects.none(),
    )

    def __init__(self, *args, **kwargs):
        super(TopicForm, self).__init__(*args, **kwargs)
        instance = kwargs['instance']
        all = Topic.objects.all()
        is_root = False

        if len(all) == 0 or instance.is_root():
            # no nodes, first created must be root or is editing root
            is_root = True

        if is_root:
            # disable the parent field, rename name label
            self.fields['parent'].empty_label = 'N/A - Root Node'
            self.fields['parent'].disabled = True
            self.fields['parent'].required = False
            self.fields['parent'].help_text = 'Root Node has no Parent'
            self.fields['name'].label += ' (Root)'
        else:
            # sets the queryset on the parent field
            # ensure that they cannot select the existing topic as parent
            self.fields['parent'].queryset = Topic.objects.exclude(
                pk=instance.pk)
            self.fields['parent'].initial = instance.get_parent()

    def save(self, commit=True):
        parent = self.cleaned_data['parent']
        instance = super(TopicForm, self).save(commit=False)
        all = Topic.objects.all()

        is_new = instance.id is None
        is_root = False
        if is_new and len(all) == 0:
            is_root = True
        elif not is_new and instance.is_root():
            is_root = True

        # saving / creating
        if is_root and is_new and commit:
            # adding the root
            instance = Topic.add_root(instance=instance)
        elif is_new and commit:
            # adding a new child under the seleced parent
            instance = parent.add_child(instance=instance)
        elif not is_new and instance.get_parent() != parent and commit:
            # moving the instance to under a new parent, editing existing node
            # must use 'sorted-child' - will base sorting on node_order_by
            instance.move(parent, pos='sorted-child')
        elif commit:
            # no moving required, just save
            instance.save()

        return instance

# tell Wagtail to use our form class override
Topic.base_form_class = TopicForm

class TopicAdmin(ModelAdmin):
    model = Topic
    menu_icon = 'radio-empty'
    menu_order = 200
    add_to_settings_menu = False
    list_display = ['name_with_depth', 'parent_name']
    search_fields = ['name']

2 - Register the modeladmin function in wagtail_hooks.py

This ensures that the TopicAdmin in the previous code is used in Wagtail Admin. You will know it works as it will appear on the left admin sidebar modeladmin register docs.

from wagtail.contrib.modeladmin.options import modeladmin_register
from .models import TopicAdmin

modeladmin_register(TopicAdmin)

3 - Migrate & Create First Topic

Now would be a good time to make migrations and run your migrate, remember that node_order_by is not easy to change after you have built your model. If you want to add custom ordering of children eg. reordering capacity or ordering by some other field, do this before you migrate.

Then go into admin and create the first root node.

4 - Link to your Pages

Here is a quick and nasty example, letting you link one topic to a page without anything fancy. Note that we are limiting choices here, this can be extended to do more complicated limiting based on the fields you have set in Topic.

topic = models.ForeignKey(
    'topics.Topic',
    on_delete=models.SET_NULL,
    blank=True,
    null=True,
    limit_choices_to={'is_selectable': True},
    related_name='blog_page_topic',
)

5 - Room for Improvement

The topic string representation always contains the dashes to show its 'depth', this is a bit ugly when seen elsewhere. It would be better to use an extended field type and build this representation only when needed.

As mentioned, no ability to reorder child nodes manually, you can create custom buttons in model admin so it would be possible to add buttons to move up/ move down and work through that way.

Example code, so probably a few rough edges but should be enough to get you started. I have tested this on Wagtail 1.13 in the demo application and it works.


问:
How to compare elements in array in the same document?
I've found ways to compare values between arrays in diff documents that are in the same MongoDB collection, but how would you compare elements, by index, in the same array, in one document? Here's the entry in question:

```<code>{ "_id" : ObjectId("1"), "arr" : [ { "int" : 100 }, { "int" : 10 } ] }
</code>```

I've got a collection with a ton of these entries (simplified here of course), and I'd like to query the collection, check each entry, and if arr[0].int > arr[1].int return those documents. Even better would be having the logic for determining what percent the element at index 1 is diff from the element at index 0. So in this case here, for example, index 1 is 10 times less than index 0

The following works for querying if an element in a mongoDoc is greater than a given value:

```<code>db.collection.find( { "arr.0.int" : { $gt: 10 }})
</code>```

I've played with this - but nothing has proved useful.
Since the dataset is large - performance considerations would be awesome!

Thanks!

答:
The basic case here is to simply apply a condition with $redact and $arrayElemAt in order to examine at each index:

```<code>db.collection.aggregate([
  { "$redact": {
    "$cond": {
      "if": {
        "$gt": [
          { "$arrayElemAt": ["$arr.int", 0] },
          { "$arrayElemAt": ["$arr.int", 1] }
        ]
      },
      "then": "$$KEEP",
      "else": "$$PRUNE"
    }
  }}
])
</code>```

This is a special pipeline stage that employs $cond in a way where the "if" condition is met "then" we "$$KEEP" the document in results, otherwise "else" we "$$PRUNE" it from the results.

This uses native operators and is as "performant" as such a query dependent on calculation is ever going to get.

MongoDB 3.6 allows a little shorter syntax on this using $expr:

```<code>db.collection.aggregate([
  { "$match": {
    "$expr": {
      "$gt": [
        { "$arrayElemAt": ["$arr.int", 0] },
        { "$arrayElemAt": ["$arr.int", 1] }
      ]
    }
  }}
])
</code>```

Which can even actually be used in a .find():

```<code>db.collection.find({
  "$expr": {
    "$gt": [
      { "$arrayElemAt": ["$arr.int", 0] },
      { "$arrayElemAt": ["$arr.int", 1] }
    ]
  }
})
</code>```

And all versions since release have supported JavaScript evaluation via $where:

```<code>db.collection.find({
  "$where": "return this.arr[0].int > this.arr[1].int"
})
</code>```

But since that requires the evaluation of a JavaScript expression for each document then it's not as performant as using the native operators.

Also the only way you get your "ratio" response is by using an aggregation pipeline which can actually "alter" the results returned, which a .find() query cannot do:

```<code>db.collection.aggregate([
  { "$redact": {
    "$cond": {
      "if": {
        "$gt": [
          { "$arrayElemAt": ["$arr.int", 0] },
          { "$arrayElemAt": ["$arr.int", 1] }
        ]
      },
      "then": "$$KEEP",
      "else": "$$PRUNE"
    }
  }},
  { "$addFields": {
    "ratio": {
      "$divide": [
        { "$arrayElemAt": ["$arr.int", 1] },
        { "$arrayElemAt": ["$arr.int", 0] }
      ]
    }
  }}
])
</code>```

There's nothing great about "calculations as a condition" at any rate, since there simply is no other option other than to run through every document in the collection and see if it matches conditions.

So if this is "common logic" then you would be better storing that in your document instead. i.e:

```<code>{ "arr": [{ "int": 100 },{ "int": 10 }], "firstIsGreater": true }
</code>```

Then you actually "can" use an index for selection in an efficient way. So it would be up to your application logic to write this condition as you altered the content in the document, and thus allowing you not to need such a calculation.

If you cannot model and store in such a way, then calculation in either form is all you have. So it's generally better to put some thought into why you think you need such a calculated condition in the first place.

Body:
I've found ways to compare values between arrays in diff documents that are in the same MongoDB collection, but how would you compare elements, by index, in the same array, in one document? Here's the entry in question:

{ "_id" : ObjectId("1"), "arr" : [ { "int" : 100 }, { "int" : 10 } ] }

I've got a collection with a ton of these entries (simplified here of course), and I'd like to query the collection, check each entry, and if arr[0].int > arr[1].int return those documents. Even better would be having the logic for determining what percent the element at index 1 is diff from the element at index 0. So in this case here, for example, index 1 is 10 times less than index 0

The following works for querying if an element in a mongoDoc is greater than a given value:

db.collection.find( { "arr.0.int" : { $gt: 10 }})

I've played with this - but nothing has proved useful.
Since the dataset is large - performance considerations would be awesome!

Thanks!

Body:
The basic case here is to simply apply a condition with $redact and $arrayElemAt in order to examine at each index:

db.collection.aggregate([
  { "$redact": {
    "$cond": {
      "if": {
        "$gt": [
          { "$arrayElemAt": ["$arr.int", 0] },
          { "$arrayElemAt": ["$arr.int", 1] }
        ]
      },
      "then": "$$KEEP",
      "else": "$$PRUNE"
    }
  }}
])

This is a special pipeline stage that employs $cond in a way where the "if" condition is met "then" we "$$KEEP" the document in results, otherwise "else" we "$$PRUNE" it from the results.

This uses native operators and is as "performant" as such a query dependent on calculation is ever going to get.

MongoDB 3.6 allows a little shorter syntax on this using $expr:

db.collection.aggregate([
  { "$match": {
    "$expr": {
      "$gt": [
        { "$arrayElemAt": ["$arr.int", 0] },
        { "$arrayElemAt": ["$arr.int", 1] }
      ]
    }
  }}
])

Which can even actually be used in a .find():

db.collection.find({
  "$expr": {
    "$gt": [
      { "$arrayElemAt": ["$arr.int", 0] },
      { "$arrayElemAt": ["$arr.int", 1] }
    ]
  }
})

And all versions since release have supported JavaScript evaluation via $where:

db.collection.find({
  "$where": "return this.arr[0].int > this.arr[1].int"
})

But since that requires the evaluation of a JavaScript expression for each document then it's not as performant as using the native operators.

Also the only way you get your "ratio" response is by using an aggregation pipeline which can actually "alter" the results returned, which a .find() query cannot do:

db.collection.aggregate([
  { "$redact": {
    "$cond": {
      "if": {
        "$gt": [
          { "$arrayElemAt": ["$arr.int", 0] },
          { "$arrayElemAt": ["$arr.int", 1] }
        ]
      },
      "then": "$$KEEP",
      "else": "$$PRUNE"
    }
  }},
  { "$addFields": {
    "ratio": {
      "$divide": [
        { "$arrayElemAt": ["$arr.int", 1] },
        { "$arrayElemAt": ["$arr.int", 0] }
      ]
    }
  }}
])

There's nothing great about "calculations as a condition" at any rate, since there simply is no other option other than to run through every document in the collection and see if it matches conditions.

So if this is "common logic" then you would be better storing that in your document instead. i.e:

{ "arr": [{ "int": 100 },{ "int": 10 }], "firstIsGreater": true }

Then you actually "can" use an index for selection in an efficient way. So it would be up to your application logic to write this condition as you altered the content in the document, and thus allowing you not to need such a calculation.

If you cannot model and store in such a way, then calculation in either form is all you have. So it's generally better to put some thought into why you think you need such a calculated condition in the first place.


问:
build xml with multiple elements c#
i want to create a xml file with the data pushed by sql server and i want build the xml like this:

```<code><Items Class="1" Grade="20" Score="150">
    <Item ID="1" TemplateID="11233" StrengthLevel="0" AttackCompose="0" DefendCompose="0" LuckCompose="0" AgilityCompose="0" IsBind="true" ValidDate="0" Count="1" />
    <Item ID="2" TemplateID="200216" StrengthLevel="0" AttackCompose="0" DefendCompose="0" LuckCompose="0" AgilityCompose="0" IsBind="true" ValidDate="0" Count="1" />
    <Item ID="3" TemplateID="11408" StrengthLevel="0" AttackCompose="0" DefendCompose="0" LuckCompose="0" AgilityCompose="0" IsBind="true" ValidDate="0" Count="2" />
  </Items>
</code>```

And here's the most important part of my code to create it in c#:

```<code>Dictionary<int, Dictionary<int, DailyLeagueAwardList>> dictionary1 = new Dictionary<int, Dictionary<int, DailyLeagueAwardList>>();
      DailyLeagueAwardList[] allDailyLeagueAwardList = produceBussiness.GetAllDailyLeagueAwardList();
      DailyLeagueAwardItems[] allDailyLeagueAwardItems = produceBussiness.GetAllDailyLeagueAwardItems();
      foreach (DailyLeagueAwardList DailyLeagueAwardList in allDailyLeagueAwardList)
      {
        DailyLeagueAwardList.AwardLists = new List<DailyLeagueAwardItems>();
        if (!dictionary1.ContainsKey(DailyLeagueAwardList.Class))
          dictionary1.Add(DailyLeagueAwardList.Class, new Dictionary<int, DailyLeagueAwardList>()
          {
            {
              DailyLeagueAwardList.Grade,
              DailyLeagueAwardList
            }
          });
        else if (!dictionary1[DailyLeagueAwardList.Class].ContainsKey(DailyLeagueAwardList.Grade))
          dictionary1[DailyLeagueAwardList.Class].Add(DailyLeagueAwardList.Grade, DailyLeagueAwardList);
      }
      foreach (DailyLeagueAwardItems DailyLeagueAwardItems in allDailyLeagueAwardItems)
      {
        if (dictionary1.ContainsKey(DailyLeagueAwardItems.ID) && dictionary1[DailyLeagueAwardItems.ID].ContainsKey(DailyLeagueAwardItems.Class))
          dictionary1[DailyLeagueAwardItems.ID][DailyLeagueAwardItems.Class].AwardLists.Add(DailyLeagueAwardItems);
      }
      XElement xelement1 = (XElement) null;
      foreach (Dictionary<int, DailyLeagueAwardList> dictionary2 in dictionary1.Values)
      {
        foreach (DailyLeagueAwardList DailyLeagueAwardList in dictionary2.Values)
        {
          if (xelement1 == null)
            xelement1 = new XElement((XName) "Items", (object) new XAttribute((XName) "Class",
                (object) DailyLeagueAwardList.Class), (object)new XAttribute((XName)"Grade",
                (object)DailyLeagueAwardList.Grade),
                (object)new XAttribute((XName)"Score",
                (object)DailyLeagueAwardList.Score),
                (object)new XAttribute((XName)"Rank",
                (object)DailyLeagueAwardList.Rank));
          foreach (DailyLeagueAwardItems awardList in DailyLeagueAwardList.AwardLists)
          {
            XElement xelement3 = new XElement((XName) "Item", new object[10]
            {
              (object) new XAttribute((XName) "ID", (object) awardList.ID),
              (object) new XAttribute((XName) "TemplateID", (object) awardList.TemplateID),
              (object) new XAttribute((XName) "StrengthLevel", (object) awardList.StrengthLevel),
              (object) new XAttribute((XName) "AttackCompose", (object) awardList.AttackCompose),
              (object) new XAttribute((XName) "DefendCompose", (object) awardList.DefendCompose),
              (object) new XAttribute((XName) "LuckCompose", (object) awardList.LuckCompose),
              (object) new XAttribute((XName) "AgilityCompose", (object) awardList.AgilityCompose),
              (object) new XAttribute((XName) "IsBind", (object) awardList.IsBind),
              (object) new XAttribute((XName) "ValidDate", (object) awardList.ValidDate),
              (object) new XAttribute((XName) "Count", (object) awardList.Count)
            });
            xelement1.Add((object) xelement3);
          }
          //xelement1.Add((object) xelement3);
        }
        result.Add((object) xelement1);
        xelement1 = (XElement) null;
      }
</code>```

I'm using XElement on C#, i think the problem is on ↓

```<code>foreach (DailyLeagueAwardItems DailyLeagueAwardItems in allDailyLeagueAwardItems)
      {
        if (dictionary1.ContainsKey(DailyLeagueAwardItems.ID) && dictionary1[DailyLeagueAwardItems.ID].ContainsKey(DailyLeagueAwardItems.Class))
          dictionary1[DailyLeagueAwardItems.ID][DailyLeagueAwardItems.Class].AwardLists.Add(DailyLeagueAwardItems);
      }
</code>```

And above i think is the error, how i can fix it?

Thanks and sorry for the bad english!

*EDIT
Is only returning this:

```<code><Items Class="1" Grade="20" Score="150" Rank="0" />
  <Items Class="2" Grade="20" Score="200" Rank="0" />
  <Items Class="3" Grade="20" Score="250" Rank="0" />
  <Items Class="4" Grade="20" Score="300" Rank="0" />
  <Items Class="5" Grade="20" Score="400" Rank="0" />
  <Items Class="6" Grade="20" Score="550" Rank="0" />
  <Items Class="7" Grade="20" Score="700" Rank="0" />
  <Items Class="8" Grade="20" Score="850" Rank="0" />
  <Items Class="9" Grade="20" Score="900" Rank="0" />
  <Items Class="10" Grade="30" Score="150" Rank="0" />
  <Items Class="11" Grade="30" Score="200" Rank="0" />
  <Items Class="12" Grade="30" Score="250" Rank="0" />
  <Items Class="13" Grade="30" Score="300" Rank="0" />
  <Items Class="14" Grade="30" Score="400" Rank="0" />
  <Items Class="15" Grade="30" Score="550" Rank="0" />
  <Items Class="16" Grade="30" Score="700" Rank="0" />
  <Items Class="17" Grade="30" Score="850" Rank="0" />
  <Items Class="18" Grade="30" Score="900" Rank="0" />
  <Items Class="19" Grade="40" Score="150" Rank="0" />
  <Items Class="20" Grade="40" Score="200" Rank="0" />
  <Items Class="21" Grade="40" Score="250" Rank="0" />
  <Items Class="22" Grade="40" Score="300" Rank="0" />
  <Items Class="23" Grade="40" Score="400" Rank="0" />
  <Items Class="24" Grade="40" Score="550" Rank="0" />
  <Items Class="25" Grade="40" Score="700" Rank="0" />
  <Items Class="26" Grade="40" Score="850" Rank="0" />
  <Items Class="27" Grade="40" Score="900" Rank="0" />
  <Items Class="28" Grade="100" Score="0" Rank="1" />
  <Items Class="29" Grade="100" Score="0" Rank="2" />
  <Items Class="30" Grade="100" Score="0" Rank="3" />
</code>```

答:
After reading your question, your comment, I still don't understand, and I'm afraid, the more I ask, the more confusing I get.

If I was you, instead of doing this, I will go by 2 approach:

If you have a string build in like this:
(note: i simplify from your xml)

string str = "<Items Class=\"1\" Grade=\"20\" Score=\"150\"><Item ID=\"1\" TemplateID=\"11233\" /></Items>

Then what need to be done is :

```<code>XmlDocument doc = new XmlDocument();
doc.LoadXml(str);
doc.Save("myFile.xml"); //Save XML to a physical file if needed
</code>```

Using Serialize:

From database, you should have following classes:

I believe your awardList belongs to Items class below

```<code>public class Items
{
    [XmlAttribute()]
    public int Class{get;set;}

    [XmlAttribute()]
    public int Grade{get;set;}

    [XmlAttribute()]
    public double Score{get;set;}

    [XmlElement("Item")]
    public List<Item> Item { get; set; }

}

public class Item
{
    [XmlAttribute()]
    public int ID{get;set;}

    [XmlAttribute()]
    public int TemplateID{get;set;}

    [XmlAttribute()]
    public int StrengthLevel{get;set;}

    [XmlAttribute()]
    public int AttackCompose{get;set;}

    [XmlAttribute()]
    public int DefendCompose{get;set;}

    [XmlAttribute()]
    public int LuckCompose{get;set;}

    [XmlAttribute()]
    public int AgilityCompose{get;set;}

    [XmlAttribute()]
    public bool IsBind{get;set;}

    [XmlAttribute()]
    public int ValidDate{get;set;}

    [XmlAttribute()]
    public int Count{get;set;}

}
</code>```

Then at the end: (I copy from here, too lazy to re-type

```<code>XmlSerializer xsSubmit = new XmlSerializer(typeof(MyObject));
 var subReq = new MyObject();
 var xml = "";

 using(var sww = new StringWriter())
 {
     using(XmlWriter writer = XmlWriter.Create(sww))
     {
         xsSubmit.Serialize(writer, subReq);
         xml = sww.ToString(); // Your XML
     }
 }
</code>```

Title: build xml with multiple elements c#

Body:
i want to create a xml file with the data pushed by sql server and i want build the xml like this:

<Items Class="1" Grade="20" Score="150">
    <Item ID="1" TemplateID="11233" StrengthLevel="0" AttackCompose="0" DefendCompose="0" LuckCompose="0" AgilityCompose="0" IsBind="true" ValidDate="0" Count="1" />
    <Item ID="2" TemplateID="200216" StrengthLevel="0" AttackCompose="0" DefendCompose="0" LuckCompose="0" AgilityCompose="0" IsBind="true" ValidDate="0" Count="1" />
    <Item ID="3" TemplateID="11408" StrengthLevel="0" AttackCompose="0" DefendCompose="0" LuckCompose="0" AgilityCompose="0" IsBind="true" ValidDate="0" Count="2" />
  </Items>

And here's the most important part of my code to create it in c#:

Dictionary<int, Dictionary<int, DailyLeagueAwardList>> dictionary1 = new Dictionary<int, Dictionary<int, DailyLeagueAwardList>>();
      DailyLeagueAwardList[] allDailyLeagueAwardList = produceBussiness.GetAllDailyLeagueAwardList();
      DailyLeagueAwardItems[] allDailyLeagueAwardItems = produceBussiness.GetAllDailyLeagueAwardItems();
      foreach (DailyLeagueAwardList DailyLeagueAwardList in allDailyLeagueAwardList)
      {
        DailyLeagueAwardList.AwardLists = new List<DailyLeagueAwardItems>();
        if (!dictionary1.ContainsKey(DailyLeagueAwardList.Class))
          dictionary1.Add(DailyLeagueAwardList.Class, new Dictionary<int, DailyLeagueAwardList>()
          {
            {
              DailyLeagueAwardList.Grade,
              DailyLeagueAwardList
            }
          });
        else if (!dictionary1[DailyLeagueAwardList.Class].ContainsKey(DailyLeagueAwardList.Grade))
          dictionary1[DailyLeagueAwardList.Class].Add(DailyLeagueAwardList.Grade, DailyLeagueAwardList);
      }
      foreach (DailyLeagueAwardItems DailyLeagueAwardItems in allDailyLeagueAwardItems)
      {
        if (dictionary1.ContainsKey(DailyLeagueAwardItems.ID) && dictionary1[DailyLeagueAwardItems.ID].ContainsKey(DailyLeagueAwardItems.Class))
          dictionary1[DailyLeagueAwardItems.ID][DailyLeagueAwardItems.Class].AwardLists.Add(DailyLeagueAwardItems);
      }
      XElement xelement1 = (XElement) null;
      foreach (Dictionary<int, DailyLeagueAwardList> dictionary2 in dictionary1.Values)
      {
        foreach (DailyLeagueAwardList DailyLeagueAwardList in dictionary2.Values)
        {
          if (xelement1 == null)
            xelement1 = new XElement((XName) "Items", (object) new XAttribute((XName) "Class",
                (object) DailyLeagueAwardList.Class), (object)new XAttribute((XName)"Grade",
                (object)DailyLeagueAwardList.Grade),
                (object)new XAttribute((XName)"Score",
                (object)DailyLeagueAwardList.Score),
                (object)new XAttribute((XName)"Rank",
                (object)DailyLeagueAwardList.Rank));
          foreach (DailyLeagueAwardItems awardList in DailyLeagueAwardList.AwardLists)
          {
            XElement xelement3 = new XElement((XName) "Item", new object[10]
            {
              (object) new XAttribute((XName) "ID", (object) awardList.ID),
              (object) new XAttribute((XName) "TemplateID", (object) awardList.TemplateID),
              (object) new XAttribute((XName) "StrengthLevel", (object) awardList.StrengthLevel),
              (object) new XAttribute((XName) "AttackCompose", (object) awardList.AttackCompose),
              (object) new XAttribute((XName) "DefendCompose", (object) awardList.DefendCompose),
              (object) new XAttribute((XName) "LuckCompose", (object) awardList.LuckCompose),
              (object) new XAttribute((XName) "AgilityCompose", (object) awardList.AgilityCompose),
              (object) new XAttribute((XName) "IsBind", (object) awardList.IsBind),
              (object) new XAttribute((XName) "ValidDate", (object) awardList.ValidDate),
              (object) new XAttribute((XName) "Count", (object) awardList.Count)
            });
            xelement1.Add((object) xelement3);
          }
          //xelement1.Add((object) xelement3);
        }
        result.Add((object) xelement1);
        xelement1 = (XElement) null;
      }

I'm using XElement on C#, i think the problem is on ↓

foreach (DailyLeagueAwardItems DailyLeagueAwardItems in allDailyLeagueAwardItems)
      {
        if (dictionary1.ContainsKey(DailyLeagueAwardItems.ID) && dictionary1[DailyLeagueAwardItems.ID].ContainsKey(DailyLeagueAwardItems.Class))
          dictionary1[DailyLeagueAwardItems.ID][DailyLeagueAwardItems.Class].AwardLists.Add(DailyLeagueAwardItems);
      }

And above i think is the error, how i can fix it?

Thanks and sorry for the bad english!

*EDIT
Is only returning this:

<Items Class="1" Grade="20" Score="150" Rank="0" />
  <Items Class="2" Grade="20" Score="200" Rank="0" />
  <Items Class="3" Grade="20" Score="250" Rank="0" />
  <Items Class="4" Grade="20" Score="300" Rank="0" />
  <Items Class="5" Grade="20" Score="400" Rank="0" />
  <Items Class="6" Grade="20" Score="550" Rank="0" />
  <Items Class="7" Grade="20" Score="700" Rank="0" />
  <Items Class="8" Grade="20" Score="850" Rank="0" />
  <Items Class="9" Grade="20" Score="900" Rank="0" />
  <Items Class="10" Grade="30" Score="150" Rank="0" />
  <Items Class="11" Grade="30" Score="200" Rank="0" />
  <Items Class="12" Grade="30" Score="250" Rank="0" />
  <Items Class="13" Grade="30" Score="300" Rank="0" />
  <Items Class="14" Grade="30" Score="400" Rank="0" />
  <Items Class="15" Grade="30" Score="550" Rank="0" />
  <Items Class="16" Grade="30" Score="700" Rank="0" />
  <Items Class="17" Grade="30" Score="850" Rank="0" />
  <Items Class="18" Grade="30" Score="900" Rank="0" />
  <Items Class="19" Grade="40" Score="150" Rank="0" />
  <Items Class="20" Grade="40" Score="200" Rank="0" />
  <Items Class="21" Grade="40" Score="250" Rank="0" />
  <Items Class="22" Grade="40" Score="300" Rank="0" />
  <Items Class="23" Grade="40" Score="400" Rank="0" />
  <Items Class="24" Grade="40" Score="550" Rank="0" />
  <Items Class="25" Grade="40" Score="700" Rank="0" />
  <Items Class="26" Grade="40" Score="850" Rank="0" />
  <Items Class="27" Grade="40" Score="900" Rank="0" />
  <Items Class="28" Grade="100" Score="0" Rank="1" />
  <Items Class="29" Grade="100" Score="0" Rank="2" />
  <Items Class="30" Grade="100" Score="0" Rank="3" />

Body:
After reading your question, your comment, I still don't understand, and I'm afraid, the more I ask, the more confusing I get.

If I was you, instead of doing this, I will go by 2 approach:

If you have a string build in like this:
(note: i simplify from your xml)

string str = "<Items Class=\"1\" Grade=\"20\" Score=\"150\"><Item ID=\"1\" TemplateID=\"11233\" /></Items>

Then what need to be done is :

XmlDocument doc = new XmlDocument();
doc.LoadXml(str);
doc.Save("myFile.xml"); //Save XML to a physical file if needed

Using Serialize:

From database, you should have following classes:

I believe your awardList belongs to Items class below

public class Items
{
    [XmlAttribute()]
    public int Class{get;set;}

    [XmlAttribute()]
    public int Grade{get;set;}

    [XmlAttribute()]
    public double Score{get;set;}

    [XmlElement("Item")]
    public List<Item> Item { get; set; }

}

public class Item
{
    [XmlAttribute()]
    public int ID{get;set;}

    [XmlAttribute()]
    public int TemplateID{get;set;}

    [XmlAttribute()]
    public int StrengthLevel{get;set;}

    [XmlAttribute()]
    public int AttackCompose{get;set;}

    [XmlAttribute()]
    public int DefendCompose{get;set;}

    [XmlAttribute()]
    public int LuckCompose{get;set;}

    [XmlAttribute()]
    public int AgilityCompose{get;set;}

    [XmlAttribute()]
    public bool IsBind{get;set;}

    [XmlAttribute()]
    public int ValidDate{get;set;}

    [XmlAttribute()]
    public int Count{get;set;}

}

Then at the end: (I copy from here, too lazy to re-type

XmlSerializer xsSubmit = new XmlSerializer(typeof(MyObject));
 var subReq = new MyObject();
 var xml = "";

 using(var sww = new StringWriter())
 {
     using(XmlWriter writer = XmlWriter.Create(sww))
     {
         xsSubmit.Serialize(writer, subReq);
         xml = sww.ToString(); // Your XML
     }
 }


问:
Listbox Values calculate
This resets the text box for quantity and amount to zero when i test, how do i make this calculate?</p>

```<code>Dim Number As Integer

txtNumber.Text = Number

Dim orchestra As Integer = 40
Dim mezz As Integer = 27.5
Dim general As Integer = 15
Dim balcony As Integer = 10

If lstSection.SelectedItem = "Orchestra" Then
  txtAmount.Text = (Number * 40)
ElseIf lstSection.SelectedItem = "Mezzanine" Then
  txtAmount.Text = (Number * 27.5)
ElseIf lstSection.SelectedItem = "General" Then
  txtAmount.Text = (Number * 15)
ElseIf lstSection.SelectedItem = "Balcony" Then
  txtAmount.Text = (Number * 10)
End If
</code>```

答:
Assuming my edit is correct, and you intend to declare your Number variable within the same method, the problem you're seeing is occurring because you're not assigning a value to Number.

Integer value types always initialize with the default value of 0.

Thus: txtAmount.Text = (0 * 40), which of course will always be 0.

Title: Listbox Values calculate

Body:
This resets the text box for quantity and amount to zero when i test, how do i make this calculate?

Dim Number As Integer

txtNumber.Text = Number

Dim orchestra As Integer = 40
Dim mezz As Integer = 27.5
Dim general As Integer = 15
Dim balcony As Integer = 10

If lstSection.SelectedItem = "Orchestra" Then
  txtAmount.Text = (Number * 40)
ElseIf lstSection.SelectedItem = "Mezzanine" Then
  txtAmount.Text = (Number * 27.5)
ElseIf lstSection.SelectedItem = "General" Then
  txtAmount.Text = (Number * 15)
ElseIf lstSection.SelectedItem = "Balcony" Then
  txtAmount.Text = (Number * 10)
End If


问:
is unobstrusive javascript style slower than the usual?
At the moment I'm doing jquery like this

```<code><input id='aa' ... >
<script>
makeIt('aa', 2,'home/getitems',10)
</script>
</code>```

I can also do it like this

```<code><input class='theOne' ae-minLen='3' ae-url='home/getitems' ae-maxRes='10' ... >
</code>```

and the makeIt is called on document.ready for
$(document).find('.theOne').each ...

and it gets the values using

$(this).attr('ae-minLen') etc.

but, I'm wondering whether the unobtrusive way is slower than the usual ?

EDIT:
ppl say it's slower, how much slower is it, should I have a 5MB html to actually notice it ?

答: Do it the right way (unobtrusive).  Then, if you notice it is not fast enough, try it the other way and measure to see if it solves your problem.</p>

Body:
At the moment I'm doing jquery like this

<input id='aa' ... >

I can also do it like this

<input class='theOne' ae-minLen='3' ae-url='home/getitems' ae-maxRes='10' ... >

and the makeIt is called on document.ready for
$(document).find('.theOne').each ...

and it gets the values using

$(this).attr('ae-minLen') etc.

but, I'm wondering whether the unobtrusive way is slower than the usual ?

EDIT:
ppl say it's slower, how much slower is it, should I have a 5MB html to actually notice it ?


答:
It might be worth putting a note that there is ongoing work for a Collection hierarchy but this would be more for Images/Documents.

It has been flagged for the 2.0 release.

https://github.com/wagtail/wagtail/pull/3407

Title: Multi-level Categories in Wagtail


问:
Disable Twilio Scaler to send SMS
I have a several Twilio phone numbers to send SMS messages to users (2-way sms).

And I want to try Copilot and Messaging service features, but I have my own logic around how I chose the number to send SMS from.
So I need to be able to choose a "from" number by myself.

If I will provide "from" number and MessagingServiceSid at the same time, will this disable Messaging Service Scaler logic?

Sorry, but I can't just test it on my account right now. But I see Twilio Java SDK want me to provide "from" number OR "MessagingServiceSid" but not both. Many thanks.

答:
Twilio developer evangelist here.

You can't set both a MessagingServiceSid and a From number when sending a message. You can either let the messaging service decide which number to use to send your messages (using it's Geomatching, fallback and scaling features) or you need to send the messages using the From number of your choice using the regular API.

Title: Disable Twilio Scaler to send SMS


问:
Where can I pass the Id_token using openid connect
Using the implicit flow my response_type can be "id_token token" or "id_token", both tokens are then saved on the client.

I know what to do with the access_token on the client:

To call the user profile endpoint you use the access_token.

To call the Api/Resource server you use the access_token

Where should/can I pass the id_token to get what?

答: You should not need to pass the token anywhere, it should contain the user's claims.  Primarily you might be interested in the user id, but the claims can be just about anything.  Once you verify and decode the token (which is JWT) you should be able to read this info and act accordingly.  See this link for more info on ID tokens: https://auth0.com/docs/tokens/id-token</p>


问:
How to get input field value using PHP
I have a input field as follows:

```<code><input type="text" name="subject" id="subject" value="Car Loan">
</code>```

I would like to get the input fields value Car Loan and assign it to a session. How do I do this using PHP or jQuery?

答:
```<code><form action="" method="post">
<input type="text" name="subject" id="subject" value="Car Loan">
<button type="submit" name="ok">OK</button>
</form>
<?php
if(isset($_POST['ok'])){
echo $_POST['subject'];
}
?>
</code>```

Title: How to get input field value using PHP

Body:
I have a input field as follows:

<input type="text" name="subject" id="subject" value="Car Loan">

I would like to get the input fields value Car Loan and assign it to a session. How do I do this using PHP or jQuery?


问:
Distribution certificate / private key not installed
Using Xcode 9.1, after building an iOS app, I want to archive it and upload it to the appStore for beta-testing.
But I get the following issue after clicking the button Upload to the App Store... and choosing Automatically manage signing:

"My Name" has one iOS Distribution certificate but its private key is
not installed. Contact the creator of this certificate to get a copy of the private key.

I do not know why this "private key is not installed", but the Distribution certificate may have been created on a different computer or something. In any case:

What is the simplest way to retrieve the missing private key and install it? In order to make things work.

答:
You can only have one distribution certificate. It unites a public key, known to Apple, with a private key, which lives in the keychain of some computer. If this distribution certificate was created on another computer, then the private key is on the keychain of that computer. And this distribution certificate does not work without it.

So to use this distribution certificate on this computer, you must find that computer, open Keychain Access, locate and export the private key, mail it or otherwise get it to this computer, and import it into the keychain of this computer.

If you go into the Accounts pref pane in Xcode and double-click your Team, you'll see a dialog that gives you help with this. If you see your distribution certificate and it says Not In Keychain, you can control-click that certificate to get a menu item that lets you email whoever created the certificate and ask them to send it to you. That person can use this same import to choose Export Certificate and can email you exported certificate.

Either way, the private key or exported certificate will be passworded. You'll need to know the password in order to use it.


问:
How to iterate web service response object in Katalon Studio script?
I am getting the response object via web service call using Katalon Studio and now I want to check whether the given user values are present in response object or not. How can I do that? Please help.
Code::</p>

```<code>ResponseObject getUsersResponse = WS.callTestCase(findTestCase("getResponse"),
    ["serviceName":"insertUserRequest"])
</code>```

答: They have a dedicated documentation page regard to your current concern. Here is the link, it might worth to look at it and use appropriate keywords.</p>

Body:
I am getting the response object via web service call using Katalon Studio and now I want to check whether the given user values are present in response object or not. How can I do that? Please help.
Code::

ResponseObject getUsersResponse = WS.callTestCase(findTestCase("getResponse"),
    ["serviceName":"insertUserRequest"])


问:
Remove tiny scroll bar - Ionic 3
You can see that there is a tiny scroll bar as shown below.Can you tell me how to remove that? This is Ionic 3 app. I have tried many ways.But no luck yet.

Please see how bad it is on the device :(

This on the browser:

.sass

```<code> .height-70 {
        height: 70px;
        overflow: hidden;
    }
</code>```

.html

```<code><ion-content padding>
  <ion-grid>
    <ion-row>
      <ion-col class="height-70" col-12>
        <ion-content>
          <button ion-button icon-left full (click)="loginWithLinkedin()" class="background-color-linkedin"><ion-icon name="logo-linkedin" class="margin-top-minus-4"></ion-icon><span>Continue with Linkedin</span></button>
        </ion-content>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>
</code>```

Chrome css(run time): below padding:16px is the problem.But how can I remove it? Because I need padding too.Any workaround?

答:
```<code>.scroll-content {
    overflow-y: hidden;
}
</code>```

Title: Remove tiny scroll bar - Ionic 3

Body:
You can see that there is a tiny scroll bar as shown below.Can you tell me how to remove that? This is Ionic 3 app. I have tried many ways.But no luck yet.

Please see how bad it is on the device :(

This on the browser:

.sass

 .height-70 {
        height: 70px;
        overflow: hidden;
    }

.html

<ion-content padding>
  <ion-grid>
    <ion-row>
      <ion-col class="height-70" col-12>
        <ion-content>
          <button ion-button icon-left full (click)="loginWithLinkedin()" class="background-color-linkedin"><ion-icon name="logo-linkedin" class="margin-top-minus-4"></ion-icon>Continue with Linkedin</button>
        </ion-content>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>

Chrome css(run time): below padding:16px is the problem.But how can I remove it? Because I need padding too.Any workaround?

Body:
.scroll-content {
    overflow-y: hidden;
}


问:
curly braces in es6 arrow function for each
We create presentational component or stateless component like this

```<code>const MyComponent = () => {
   return(<div>my component</div>)
}
</code>```

but I'd seen this

```<code>const MyComponent = () =>
   <div>
     <h1>head</h1>
     my component
   </div>
</code>```

so now I'm confused when the braces is needed when using es6's arrow function.

This confused me on when rendering a list using map

shorter version

```<code><div>
{map(o =>
   <div>{o.name}</div>
)}
</div>
</code>```

longer version

```<code><div>
    {map(o => {
     return(<div>{o.name}</div>)
     })}
</div>
</code>```

Both are correct, but why write longer?

答:
Both are correct, but why write longer?

You basically need to use the longer version if you need to add more sentences in you arrow function other than the jsx component.

E.g.

```<code><div>
    {map(o => {
       const name = "My name is: " + o.name;
       return(<div>{name}</div>)
     })}
</div>
</code>```

Otherwise, you may use the short version.

Body:
We create presentational component or stateless component like this

const MyComponent = () => {
   return(
my component
)
}

but I'd seen this

const MyComponent = () =>

head

     my component

so now I'm confused when the braces is needed when using es6's arrow function.

This confused me on when rendering a list using map

shorter version

{map(o =>

{o.name}

)}

longer version

    {map(o => {
     return(
{o.name}
)
     })}

Both are correct, but why write longer?

Body:
Both are correct, but why write longer?

You basically need to use the longer version if you need to add more sentences in you arrow function other than the jsx component.

E.g.

<div>
    {map(o => {
       const name = "My name is: " + o.name;
       return(<div>{name}</div>)
     })}
</div>

Otherwise, you may use the short version.