问:
Did the author make a mistake in explaining stack and heap in C++ or am I misreading something?
Here is the code:

```<code>int main()
{
    using namespace std;
    int nights = 1001;
    int * pt = new int; // allocate space for an int
    *pt = 1001;         // store a value there

    cout << "nights value = ";
    cout << nights << ": location " << &nights << endl;
    cout << "int ";
    cout << "value = " << *pt << ": location = " << pt << endl;

    double * pd = new double; // allocate space for a double
    *pd = 10000001.0; // store a double there

    cout << "double ";
    cout << "value = " << *pd << ": location = " << pd << endl;
    cout << "location of pointer pd: " << &pd << endl;
    cout << "size of pt = " << sizeof(pt);
    cout << ": size of *pt = " << sizeof(*pt) << endl;
    cout << "size of pd = " << sizeof pd;
    cout << ": size of *pd = " << sizeof(*pd) << endl;

    return 0;
}
</code>```

Now here is the author's note about the code:

Another point to note is that typically new uses a different block of memory than do the ordinary variable definitions that we have been using. Both the variable nights and pd have their values stored in a memory region called the stack, whereas the memory allocated by the new is in a region called the heap or free store.

Initial Question:

Now my concern is this: the variable pd was create by the keyword new, so it should be stored in the region called heap just like the variable pt, since they were both created by the keyword new.

Am I missing something here? Thank you very much in advance for your inputs.

Revised Question/Follow-up based on the hold:

This question was put on hold by 5 people because they couldn't understand what I was asking. I believe that my question has already been answered but for those who are still not sure about what I was initially asking please read along:

I was unclear about the author's explanation about where the variables and their values were stored in memory. Up to the author explanation, I had a belief that any memory created dynamically (or should I say during runtime after compiling) by using the keyword new gets stored in the heap not the stack.

So, it confused me when he wrote that the variable pd has is value
  stored in the stack, but again how is that possible if the variable
  was create during "runtime" with the keyword new, so it should be
  in the heap, not the stack.

Please try to use the code above as the reference and in particular the **variables (nights, pd, and pt) in your answer so that I can understand it from that code's perspective.

答:
Now my concern is this: the variable pd was create by the keyword new, so it should be stored in the region called heap just like the variable pt, since they were both created by the keyword new.

No, it was not. The code is:

```<code> double * pd = new double; // allocate space for a double
</code>```

This is no different from:

```<code>double * pd;
pd = new double;
</code>```

So clearly, pd itself is not created by the new operator, only the value it holds is. But he's talking about pd, not its value.

Body:
Here is the code:

int main()
{
    using namespace std;
    int nights = 1001;
    int * pt = new int; // allocate space for an int
    *pt = 1001;         // store a value there

    cout << "nights value = ";
    cout << nights << ": location " << &nights << endl;
    cout << "int ";
    cout << "value = " << *pt << ": location = " << pt << endl;

    double * pd = new double; // allocate space for a double
    *pd = 10000001.0; // store a double there

    cout << "double ";
    cout << "value = " << *pd << ": location = " << pd << endl;
    cout << "location of pointer pd: " << &pd << endl;
    cout << "size of pt = " << sizeof(pt);
    cout << ": size of *pt = " << sizeof(*pt) << endl;
    cout << "size of pd = " << sizeof pd;
    cout << ": size of *pd = " << sizeof(*pd) << endl;

    return 0;
}

Now here is the author's note about the code:

Another point to note is that typically new uses a different block of memory than do the ordinary variable definitions that we have been using. Both the variable nights and pd have their values stored in a memory region called the stack, whereas the memory allocated by the new is in a region called the heap or free store.

Initial Question:

Now my concern is this: the variable pd was create by the keyword new, so it should be stored in the region called heap just like the variable pt, since they were both created by the keyword new.

Am I missing something here? Thank you very much in advance for your inputs.

Revised Question/Follow-up based on the hold:

This question was put on hold by 5 people because they couldn't understand what I was asking. I believe that my question has already been answered but for those who are still not sure about what I was initially asking please read along:

I was unclear about the author's explanation about where the variables and their values were stored in memory. Up to the author explanation, I had a belief that any memory created dynamically (or should I say during runtime after compiling) by using the keyword new gets stored in the heap not the stack.

So, it confused me when he wrote that the variable pd has is value
  stored in the stack, but again how is that possible if the variable
  was create during "runtime" with the keyword new, so it should be
  in the heap, not the stack.

Please try to use the code above as the reference and in particular the **variables (nights, pd, and pt) in your answer so that I can understand it from that code's perspective.

Body:
Now my concern is this: the variable pd was create by the keyword new, so it should be stored in the region called heap just like the variable pt, since they were both created by the keyword new.

No, it was not. The code is:

 double * pd = new double; // allocate space for a double

This is no different from:

double * pd;
pd = new double;

So clearly, pd itself is not created by the new operator, only the value it holds is. But he's talking about pd, not its value.


来源: stackexchange

问:
How to resolve typescript Redux connect error ActionCreatorsMapObject
Have error with typescript

```<code>ERROR in [at-loader] ./src/app/components/profile/userProfile/_userMain.tsx:130:37
    TS2345: Argument of type 'typeof "/usr/src/app/src/js/src/app/redux/actions/sessionActions"' is not assignable to parameter of type 'ActionCreatorsMapObject'.

ERROR in [at-loader] ./src/app/components/profile/userProfile/_userMain.tsx:133:124
    TS2345: Argument of type 'typeof UserProfileMain' is not assignable to parameter of type 'ComponentClass<(state: any) => any> | StatelessComponent<(state: any) => any>'.
  Type 'typeof UserProfileMain' is not assignable to type 'StatelessComponent<(state: any) => any>'.
    Type 'typeof UserProfileMain' provides no match for the signature '(props: ((state: any) => any) & { children?: ReactNode; }, context?: any): ReactElement<any>'
</code>```

Is it possible to fix this without decorators? ( @connect )

```<code>interface IActions {
    avatarUpload: (file:any) => void;
}

export interface IMainProps {
    auth: number,
    actions: IActions
}

class UserProfileMain extends React.Component<IMainProps, any> {
    constructor(props:any){
        super(props);
        this.state ={
            files: [],
        }
    }

    render(){
        return(<div />)
    }
}

const mapStateToProps = (state:any):any => {
    return {
        auth: state.authStatus.data.user.id,
    };
};

const mapDispatchToProps = (dispatch:any):any => {
    return {
        actions: bindActionCreators(sessionActions, dispatch) //First error (130:37)
    };
}
export default connect<typeof mapStateToProps, typeof mapDispatchToProps, IMainProps>(mapStateToProps, mapDispatchToProps)(UserProfileMain); //second error (133:124)
</code>```

Already tried with UserProfileMain as any but got other bunch of errors

Maybe you know some best practice for that

Hope your support

答:
You need to change your

```<code>actions: bindActionCreators(sessionActions, dispatch)
</code>```

line to

```<code>actions: bindActionCreators<any>(sessionActions, dispatch)
</code>```

or something more specific because the redux typescript definitions are using generics.

See the redux typescript definitions here.

The generic type in the <> should be the same type of sessionActions, which is also the return value of the bindActionCreators() function call.

ContentLicense: CC BY-SA 3.0

Body:
Have error with typescript

ERROR in [at-loader] ./src/app/components/profile/userProfile/_userMain.tsx:130:37
    TS2345: Argument of type 'typeof "/usr/src/app/src/js/src/app/redux/actions/sessionActions"' is not assignable to parameter of type 'ActionCreatorsMapObject'.

ERROR in [at-loader] ./src/app/components/profile/userProfile/_userMain.tsx:133:124
    TS2345: Argument of type 'typeof UserProfileMain' is not assignable to parameter of type 'ComponentClass<(state: any) => any> | StatelessComponent<(state: any) => any>'.
  Type 'typeof UserProfileMain' is not assignable to type 'StatelessComponent<(state: any) => any>'.
    Type 'typeof UserProfileMain' provides no match for the signature '(props: ((state: any) => any) & { children?: ReactNode; }, context?: any): ReactElement<any>'

Is it possible to fix this without decorators? ( @connect )

interface IActions {
    avatarUpload: (file:any) => void;
}

export interface IMainProps {
    auth: number,
    actions: IActions
}

class UserProfileMain extends React.Component<IMainProps, any> {
    constructor(props:any){
        super(props);
        this.state ={
            files: [],
        }
    }

    render(){
        return(
)
    }
}

const mapStateToProps = (state:any):any => {
    return {
        auth: state.authStatus.data.user.id,
    };
};

const mapDispatchToProps = (dispatch:any):any => {
    return {
        actions: bindActionCreators(sessionActions, dispatch) //First error (130:37)
    };
}
export default connect<typeof mapStateToProps, typeof mapDispatchToProps, IMainProps>(mapStateToProps, mapDispatchToProps)(UserProfileMain); //second error (133:124)

Already tried with UserProfileMain as any but got other bunch of errors

Maybe you know some best practice for that

Hope your support

Body:
You need to change your

actions: bindActionCreators(sessionActions, dispatch)

line to

actions: bindActionCreators<any>(sessionActions, dispatch)

or something more specific because the redux typescript definitions are using generics.

See the redux typescript definitions here.

The generic type in the <> should be the same type of sessionActions, which is also the return value of the bindActionCreators() function call.


问:
What should I increase Xmx setting to for IntelliJ 9.04?
I'm getting out of memory issues when I'm running IntelliJ IDEA 9.0.4, build IU-95.627.

My Macbook Pro has 4GB of Memory

I've heard one recommendation clearing out the ~/Library/Caches/IntelliJ90 folder is an answer..
Is that something others would recommend?

What should I set it to?
I saw this post and tried setting EXE4J_JAVA_HOME in my ~/.profile but that did't make a difference.

I've heard others say setting this too high is not a good idea as well..

Any ideas?
IntelliJ Contents/info.plist VMOptions setting:
-Xms64m -Xmx512m -XX:MaxPermSize=128m -ea -Xbootclasspath/a:../lib/boot.jar

PS: Just in case this has any bearing on things, I've been trying to use Sqlprofiler at the same time with a Grails app using the p6spy plugin in my IDE.

答:
I figured out this was down to looking up a huge stacktrace.log file in the target folder.
I didn't realise how huge it was until I looked at it in the Finder window....</p>

ContentLicense: CC BY-SA 2.5


问:
C program recursive call to main() with and without parameters
Why does it give an error of segmentation fault(core dumped) and gives no output in 1st case ?Can anyone explain how program is program callls main recursively with parameters?

```<code>#include <stdio.h>
int main()
{
    static int i = 2;
    if (i<7)
    {
        main();
        printf("%d ", i);
        i++;
        //main(10);
    }
}
</code>```

-

```<code>#include <stdio.h>
int main()
{
    static int i = 5;
    if (--i)
    {
     //main();
     printf("%d ", i);
     main(10);
    }
}
</code>```

答:
1st case the i++ after the call of main(), that means the program has no chance to add the i, and into infinity loop, and stackoverflow! haha....

but the 2nd case, it's reduce the i before you call the main.

Body:
Why does it give an error of segmentation fault(core dumped) and gives no output in 1st case ?Can anyone explain how program is program callls main recursively with parameters?

#include <stdio.h>
int main()
{
    static int i = 2;
    if (i<7)
    {
        main();
        printf("%d ", i);
        i++;
        //main(10);
    }
}

-

#include <stdio.h>
int main()
{
    static int i = 5;
    if (--i)
    {
     //main();
     printf("%d ", i);
     main(10);
    }
}


问:
How to make list-menu display when it have class active?

jQuery(document).ready(function() {
  $(".list-menu").hide();
  $(".head-list a").click(function() {
    $(".list-menu:visible").slideUp('slow');
    $(".head-list").removeClass('active-menu');
    $(this).parent().addClass('active-menu').next().slideDown('slow');
    return false;
  });
  if ($(".list-menu ul li").hasClass('active')) {
    $(".list-menu").show();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="head-list">Puchase</div>
<div class="list-menu">
  <ul>
    <li class="<?php if($page == 'home'){ echo 'active';} ?>">Purchase</li>
    <li>Purchase List</li>
    <li>Purchase3</li>
    <li>Purchase4</li>
    <li>Purchase5</li>
  </ul>
</div></code>```

I Wanna it to display the .list-menu that have ul li class active only.

Thank You for your answers.

答:
You need to add each loop for multiple li.
in your code its only consider last li.
Last li don't have active class.
below is reference code for each loop with li.</p>

```<code>$( "list-menu ul li" ).each(function( index ) {
 if($(index).hasClass('active'))
 {
   $("index").show();
 }
 else
 {
 $("index").hide();
 }
});
</code>```

Body:
jQuery(document).ready(function() {
  $(".list-menu").hide();
  $(".head-list a").click(function() {
    $(".list-menu:visible").slideUp('slow');
    $(".head-list").removeClass('active-menu');
    $(this).parent().addClass('active-menu').next().slideDown('slow');
    return false;
  });
  if ($(".list-menu ul li").hasClass('active')) {
    $(".list-menu").show();
  }
});

Puchase

    <li class="<?php if($page == 'home'){ echo 'active';} ?>">Purchase

Purchase List

Purchase3

Purchase4

Purchase5

I Wanna it to display the .list-menu that have ul li class active only.

Thank You for your answers.

Body:
You need to add each loop for multiple li.
in your code its only consider last li.
Last li don't have active class.
below is reference code for each loop with li.

$( "list-menu ul li" ).each(function( index ) {
 if($(index).hasClass('active'))
 {
   $("index").show();
 }
 else
 {
 $("index").hide();
 }
});


答:
The only mistakes the author have made are

Not calling delete once use of the pointers is finished.

The repeated use of endl is questionable. Use \n instead.

using namespace std;, whilst often used in tutorials to achieve brevity is ill-advised in production code, particularly in headers.

Using int * pt = new int; *pt = 1001; in place of int* pt = new int(1001); is questionable since the way the author has it, *pt is in an unnecessarily uninitialised state between two statements. That makes your code vulnerable to instabilities to creep in.

(Minor). You should always think about the possibility that new can throw a std::bad_alloc exception if the allocation fails.

I wouldn't worry about the terms stack and heap too much; they are language implementation concepts not part of the language itself. Prefer the terms automatic and dynamic storage duration. That's what the C++ standard uses, so why invent a whole load of alternative terminology?

Really I'd burn the book and get yourself a copy of Stroustrup.

ContentLicense: CC BY-SA 4.0

Title: Did the author make a mistake in explaining stack and heap in C++ or am I misreading something?


问:
Acceleo file tags
I'm new to Acceleo and I'm trying to figure out some things about the file tags I can use.
The format I see most commonly is something like that:

```<code>[file (someElement.anotherElement.concat('SomeText.java'), false, 'UTF-8')]
</code>```

1st Question: How can I write some text first and then the text from some element? e.g. Create a file named "SomeTextElement1.java". Where Element1 is a property(or something) from an .ecore file)

2nd Question: How can I take values from 2 different elements?
e.g. Create a file named "Element1-Element2.java". Where Element1 and Element2 taken from an .ecore file.

and 3rd Question: How can I put a file statement inside an [if] statement???
e.g.

```<code>[if (condition) /]
[file (Element1.concat('.java'),false, 'UTF-8')]
[else if (condition)]
[file (Element1.concat('.java'),false, 'UTF-8')]
[if/]
</code>```

I get an error saying file tag is not terminated. But i don't want to terminate it inside the if statement because then i would have to write the same code twice... all i want is to change the filename if a condition is true.. is that possible or not?

Thanks in advance.

答:
You generally don't want to have external "if"s for this. The file name itself is an expression, not a simple string, so you can achieve what you're trying to get with the following:

```<code>[file (if (condition) then 'somename.java' else 'someothername.java' endif, false, 'UTF-8')]
</code>```

Note that in this case, the "if" structure you'll be using is the OCL "if", so you have to properly use the "if then else endif" structure. if you want multiple conditions, this will then become

```<code>if (condition) then 'somename' else
    if (otherCondition) then 'someothername' else 'yetanothername' endif
endif
</code>```

Title: Acceleo file tags

Body:
I'm new to Acceleo and I'm trying to figure out some things about the file tags I can use.
The format I see most commonly is something like that:

[file (someElement.anotherElement.concat('SomeText.java'), false, 'UTF-8')]

1st Question: How can I write some text first and then the text from some element? e.g. Create a file named "SomeTextElement1.java". Where Element1 is a property(or something) from an .ecore file)

2nd Question: How can I take values from 2 different elements?
e.g. Create a file named "Element1-Element2.java". Where Element1 and Element2 taken from an .ecore file.

and 3rd Question: How can I put a file statement inside an [if] statement???
e.g.

[if (condition) /]
[file (Element1.concat('.java'),false, 'UTF-8')]
[else if (condition)]
[file (Element1.concat('.java'),false, 'UTF-8')]
[if/]

I get an error saying file tag is not terminated. But i don't want to terminate it inside the if statement because then i would have to write the same code twice... all i want is to change the filename if a condition is true.. is that possible or not?

Thanks in advance.

Body:
You generally don't want to have external "if"s for this. The file name itself is an expression, not a simple string, so you can achieve what you're trying to get with the following:

[file (if (condition) then 'somename.java' else 'someothername.java' endif, false, 'UTF-8')]

Note that in this case, the "if" structure you'll be using is the OCL "if", so you have to properly use the "if then else endif" structure. if you want multiple conditions, this will then become

if (condition) then 'somename' else
    if (otherCondition) then 'someothername' else 'yetanothername' endif
endif


问:
Need help Translating PHP to Python
I am using a REST library whose development team only supports PHP. Pretty much everything are finished except translating this part of their PHP code to my Python codebase. the "preg_match" is tough for me, please help.

Their PHP:

```<code>function strippadding($string) {
  $slast  = ord(substr($string, -1));
  $slastc = chr($slast);
  $pcheck = substr($string, -$slast);
  if (preg_match("/$slastc{" . $slast . "}/", $string)) {
    $string = substr($string, 0, strlen($string) - $slast);
    return $string;
  } else {
    return false;
  }
}
</code>```

My Python:

```<code>def strip_padding_pay2go(string):
  last_string = string[-1]
  slast       = ord(last_string)
  slastc      = chr(slast)
  pcheck      = last_string[:-slast]

  if re.search("/" + str(slastc) + "{" + str(slast) + "}/", string):
      last_char =  len(string) - slast
      new_string = string[0: last_char]
      return new_string
  else:
      return False
</code>```

But i keep failing ( returns False ).

答:
I got it</p>

```<code>def strip_padding_pay2go(string):
  last_string = string[-1]
  slast       = ord(last_string)
  slastc      = chr(slast)
  pcheck      = last_string[:-slast]

  if re.search(str(slastc) + "{" + str(slast) + "}", string):
      last_char =  len(string) - slast
      new_string = string[0: last_char]
      return new_string
  else:
      return False
</code>```

Title: Need help Translating PHP to Python

Body:
I am using a REST library whose development team only supports PHP. Pretty much everything are finished except translating this part of their PHP code to my Python codebase. the "preg_match" is tough for me, please help.

Their PHP:

function strippadding($string) {
  $slast  = ord(substr($string, -1));
  $slastc = chr($slast);
  $pcheck = substr($string, -$slast);
  if (preg_match("/$slastc{" . $slast . "}/", $string)) {
    $string = substr($string, 0, strlen($string) - $slast);
    return $string;
  } else {
    return false;
  }
}

My Python:

def strip_padding_pay2go(string):
  last_string = string[-1]
  slast       = ord(last_string)
  slastc      = chr(slast)
  pcheck      = last_string[:-slast]

  if re.search("/" + str(slastc) + "{" + str(slast) + "}/", string):
      last_char =  len(string) - slast
      new_string = string[0: last_char]
      return new_string
  else:
      return False

But i keep failing ( returns False ).

Body:
I got it

def strip_padding_pay2go(string):
  last_string = string[-1]
  slast       = ord(last_string)
  slastc      = chr(slast)
  pcheck      = last_string[:-slast]

  if re.search(str(slastc) + "{" + str(slast) + "}", string):
      last_char =  len(string) - slast
      new_string = string[0: last_char]
      return new_string
  else:
      return False


问:
How can I convince OS X to open txmt:// URLs in MacVim?
I guess there's not much else to the question.  OS X 10.5.</p>

答: I do not know whether plugin for this «protocol» already exists, but if you want to write your own, you should take a look at BufReadCmd event (and also BufWriteCmd). If you don't want to start from scratch, some such events are defined in $VIMRUNTIME/plugin/netrwPlugin.vim (for example, for ftp:// protocol) file which should come with your vim installation.


问:
tomcat8.0 and tomcat8.5.6 WebappClassLoaderBase
We update tomcat to 8.5.6 from 8.0.32 recently, and we meet a AccessControlException when try to load /opt/apache-tomcat-8.5.6_1/webapps/example/WEB-INF/classes/com/sun/xml/internal/ws/runtime/config/jaxb.properties, and I debug the source code between tomcat 8.5.6 and 8.0.32, it's different in org.apache.catalina.loader.WebappClassLoaderBase.findResource

Tomcat8.0

```<code>public URL findResource(final String name) {

    if (log.isDebugEnabled())
        log.debug("    findResource(" + name + ")");

    checkStateForResourceLoading(name);

    URL url = null;

    String path = nameToPath(name);

    ResourceEntry entry = resourceEntries.get(path);
    if (entry == null) {
        if (securityManager != null) {
            PrivilegedAction<ResourceEntry> dp =
                new PrivilegedFindResourceByName(name, path);
            entry = AccessController.doPrivileged(dp);
        } else {
            entry = findResourceInternal(name, path);
        }
    }
    if (entry != null) {
        url = entry.source;
        entry.webResource = null;
    }

    if ((url == null) && hasExternalRepositories) {
        url = super.findResource(name);
    }

    if (log.isDebugEnabled()) {
        if (url != null)
            log.debug("    --> Returning '" + url.toString() + "'");
        else
            log.debug("    --> Resource not found, returning null");
    }
    return url;
}
</code>```

Tomcat8.5.6

```<code>public URL findResource(final String name) {

    if (log.isDebugEnabled())
        log.debug("    findResource(" + name + ")");

    checkStateForResourceLoading(name);

    URL url = null;

    String path = nameToPath(name);

    WebResource resource = resources.getClassLoaderResource(path);
    if (resource.exists()) {
        url = resource.getURL();
        trackLastModified(path, resource);
    }

    if ((url == null) && hasExternalRepositories) {
        url = super.findResource(name);
    }

    if (log.isDebugEnabled()) {
        if (url != null)
            log.debug("    --> Returning '" + url.toString() + "'");
        else
            log.debug("    --> Resource not found, returning null");
    }
    return url;
}
</code>```

As you can see, tomcat8.0 load resource by AccessController.doPrivileged, but in tomcat8.5.6, it load the resource directly, I think that's why I got a Exception

```<code>java.security.AccessControlException: access denied
("java.io.FilePermission"
"/opt/apache-tomcat-8.5.6_1/webapps/example/WEB-INF/classes/com/sun/xml/internal/ws/runtime/config/jaxb.properties"
"read")

java.lang.IllegalStateException: MASM0003: Default [ jaxws-tubes-default.xml ] configuration file was not loaded
        at com.sun.xml.internal.ws.assembler.MetroConfigLoader.init(MetroConfigLoader.java:133)
        at com.sun.xml.internal.ws.assembler.MetroConfigLoader.<init>(MetroConfigLoader.java:104)
</code>```

this file is loaded by MetroConfigLoader,

```<code>private static JAXBContext createJAXBContext() throws Exception {
        return isJDKInternal()?(JAXBContext)AccessController.doPrivileged(new PrivilegedExceptionAction<JAXBContext>() {
            public JAXBContext run() throws Exception {
                return JAXBContext.newInstance(MetroConfig.class.getPackage().getName());
            }
        }, createSecurityContext()):JAXBContext.newInstance(MetroConfig.class.getPackage().getName());
    }

    private static AccessControlContext createSecurityContext() {
        PermissionCollection perms = new Permissions();
        perms.add(new RuntimePermission("accessClassInPackage.com.sun.xml.internal.ws.runtime.config"));
        perms.add(new ReflectPermission("suppressAccessChecks"));
        return new AccessControlContext(new ProtectionDomain[]{new ProtectionDomain((CodeSource)null, perms)});
    }
</code>```

Does anyone meet same issue? or there is some other issues. thanks.

答:
After three days researching, now I use jaxws-rt instead of default implementation in JDK, and as you can read from the code in JDK:

```<code>private static JAXBContext createJAXBContext() throws Exception {
        return isJDKInternal()?(JAXBContext)AccessController.doPrivileged(new PrivilegedExceptionAction<JAXBContext>() {
            public JAXBContext run() throws Exception {
                return JAXBContext.newInstance(MetroConfig.class.getPackage().getName());
            }
        }, createSecurityContext()):JAXBContext.newInstance(MetroConfig.class.getPackage().getName());
}
</code>```

If it's JDK internal, it will create the instance with specific privilege, and tomcat get resource by doPrivileged in tomcat8.0, but it's different in tomcat8.5, So it can't get the resource without privilege

```<code>java.security.AccessControlException: access denied ("java.io.FilePermission"
"/opt/apache-tomcat-8.5.6_1/webapps/example/WEB-INF/classes/com/sun/xml/internal/ws/runtime/config/jaxb.properties"
"read")
</code>```

So I changed to external jaxws-rt, and it will create the instance directly. I just add jaxws-rt  to pom.

```<code> <dependency>
        <groupId>com.sun.xml.ws</groupId>
        <artifactId>jaxws-rt</artifactId>
        <version>2.2.10</version>
 </dependency>
</code>```

Body:
We update tomcat to 8.5.6 from 8.0.32 recently, and we meet a AccessControlException when try to load /opt/apache-tomcat-8.5.6_1/webapps/example/WEB-INF/classes/com/sun/xml/internal/ws/runtime/config/jaxb.properties, and I debug the source code between tomcat 8.5.6 and 8.0.32, it's different in org.apache.catalina.loader.WebappClassLoaderBase.findResource

Tomcat8.0

public URL findResource(final String name) {

    if (log.isDebugEnabled())
        log.debug("    findResource(" + name + ")");

    checkStateForResourceLoading(name);

    URL url = null;

    String path = nameToPath(name);

    ResourceEntry entry = resourceEntries.get(path);
    if (entry == null) {
        if (securityManager != null) {
            PrivilegedAction<ResourceEntry> dp =
                new PrivilegedFindResourceByName(name, path);
            entry = AccessController.doPrivileged(dp);
        } else {
            entry = findResourceInternal(name, path);
        }
    }
    if (entry != null) {
        url = entry.source;
        entry.webResource = null;
    }

    if ((url == null) && hasExternalRepositories) {
        url = super.findResource(name);
    }

    if (log.isDebugEnabled()) {
        if (url != null)
            log.debug("    --> Returning '" + url.toString() + "'");
        else
            log.debug("    --> Resource not found, returning null");
    }
    return url;
}

Tomcat8.5.6

public URL findResource(final String name) {

    if (log.isDebugEnabled())
        log.debug("    findResource(" + name + ")");

    checkStateForResourceLoading(name);

    URL url = null;

    String path = nameToPath(name);

    WebResource resource = resources.getClassLoaderResource(path);
    if (resource.exists()) {
        url = resource.getURL();
        trackLastModified(path, resource);
    }

    if ((url == null) && hasExternalRepositories) {
        url = super.findResource(name);
    }

    if (log.isDebugEnabled()) {
        if (url != null)
            log.debug("    --> Returning '" + url.toString() + "'");
        else
            log.debug("    --> Resource not found, returning null");
    }
    return url;
}

As you can see, tomcat8.0 load resource by AccessController.doPrivileged, but in tomcat8.5.6, it load the resource directly, I think that's why I got a Exception

java.security.AccessControlException: access denied
("java.io.FilePermission"
"/opt/apache-tomcat-8.5.6_1/webapps/example/WEB-INF/classes/com/sun/xml/internal/ws/runtime/config/jaxb.properties"
"read")

java.lang.IllegalStateException: MASM0003: Default [ jaxws-tubes-default.xml ] configuration file was not loaded
        at com.sun.xml.internal.ws.assembler.MetroConfigLoader.init(MetroConfigLoader.java:133)
        at com.sun.xml.internal.ws.assembler.MetroConfigLoader.<init>(MetroConfigLoader.java:104)

this file is loaded by MetroConfigLoader,

private static JAXBContext createJAXBContext() throws Exception {
        return isJDKInternal()?(JAXBContext)AccessController.doPrivileged(new PrivilegedExceptionAction<JAXBContext>() {
            public JAXBContext run() throws Exception {
                return JAXBContext.newInstance(MetroConfig.class.getPackage().getName());
            }
        }, createSecurityContext()):JAXBContext.newInstance(MetroConfig.class.getPackage().getName());
    }

    private static AccessControlContext createSecurityContext() {
        PermissionCollection perms = new Permissions();
        perms.add(new RuntimePermission("accessClassInPackage.com.sun.xml.internal.ws.runtime.config"));
        perms.add(new ReflectPermission("suppressAccessChecks"));
        return new AccessControlContext(new ProtectionDomain[]{new ProtectionDomain((CodeSource)null, perms)});
    }

Does anyone meet same issue? or there is some other issues. thanks.

Body:
After three days researching, now I use jaxws-rt instead of default implementation in JDK, and as you can read from the code in JDK:

private static JAXBContext createJAXBContext() throws Exception {
        return isJDKInternal()?(JAXBContext)AccessController.doPrivileged(new PrivilegedExceptionAction<JAXBContext>() {
            public JAXBContext run() throws Exception {
                return JAXBContext.newInstance(MetroConfig.class.getPackage().getName());
            }
        }, createSecurityContext()):JAXBContext.newInstance(MetroConfig.class.getPackage().getName());
}

If it's JDK internal, it will create the instance with specific privilege, and tomcat get resource by doPrivileged in tomcat8.0, but it's different in tomcat8.5, So it can't get the resource without privilege

java.security.AccessControlException: access denied ("java.io.FilePermission"
"/opt/apache-tomcat-8.5.6_1/webapps/example/WEB-INF/classes/com/sun/xml/internal/ws/runtime/config/jaxb.properties"
"read")

So I changed to external jaxws-rt, and it will create the instance directly. I just add jaxws-rt  to pom.

 <dependency>
        <groupId>com.sun.xml.ws</groupId>
        <artifactId>jaxws-rt</artifactId>
        <version>2.2.10</version>
 </dependency>


问:
Preserve order when indexing a multilevel with a list
Using Pandas 0.20.2 with Python 3.6.1:

When you index a single-level DataFrame with a list, the returned DataFrame respects the order of the list, for example consider this DataFrame:

```<code>df = pd.DataFrame({'col1': [0,1,2],
                   'col2': ['foo', 'bar', 'baz']},
                  index=list('ABD'))
</code>```

Which, when indexed with a list in a different order as the index, returns:

```<code>df.loc[['D','B'],:]
</code>```

I would like to have exactly this behavior when i use a multi-index DataFrame. But if i add one of the columns to the index, and index again, the order is like the original DataFrame, instead of the list used for indexing:

```<code>df = df.set_index('col2', append=True)
df.loc[['D','B'],:]
</code>```

Since the level contains strings, sorting the DataFrame before indexing is not as simple. A workaround could be to convert the index to Categorical, where the categories are mapped according to my preferred order, then a normal sort could work. But that seems really far-fetched, especially if you want different 'orders' all the time.

edit:

@EdChum's answer works for the 2-level example i posted, but doesn't with a 3-level, so caution is needed!

Consider this DataFrame:

```<code>df = pd.DataFrame({'col1': ['foo', 'bar', 'baz'],
                   'col2': ['green', 'blue', 'red'],
                   'col3': [0,1,2], },
                   index=list('ABD'))

df.index.names = ['col0']
df = df.set_index(['col1','col2'], append=True)
</code>```

```<code>df.reindex(index=['baz', 'bar'], level='col1')
</code>```

edit2:

Trying @piRSquared's answer on the 3-level index, if you sort for the same level as the one your indexing with, it seems to be a solution.

```<code>df = df.sort_index(level='col1')
df.iloc[df.index.get_level_values('col1').searchsorted(['baz', 'bar'])]
</code>```

答:
You could use reindex to force the order of the rows in the order you desire, it seems that using loc it's not possible to do this with multi-indexes as sortedness is enforced always:

```<code>In[13]:
df.reindex(['D','B'], level=0)
Out[13]:
        col1
  col2
D baz      2
B bar      1
</code>```

Body:
Using Pandas 0.20.2 with Python 3.6.1:

When you index a single-level DataFrame with a list, the returned DataFrame respects the order of the list, for example consider this DataFrame:

df = pd.DataFrame({'col1': [0,1,2],
                   'col2': ['foo', 'bar', 'baz']},
                  index=list('ABD'))

Which, when indexed with a list in a different order as the index, returns:

df.loc[['D','B'],:]

I would like to have exactly this behavior when i use a multi-index DataFrame. But if i add one of the columns to the index, and index again, the order is like the original DataFrame, instead of the list used for indexing:

df = df.set_index('col2', append=True)
df.loc[['D','B'],:]

Since the level contains strings, sorting the DataFrame before indexing is not as simple. A workaround could be to convert the index to Categorical, where the categories are mapped according to my preferred order, then a normal sort could work. But that seems really far-fetched, especially if you want different 'orders' all the time.

edit:

@EdChum's answer works for the 2-level example i posted, but doesn't with a 3-level, so caution is needed!

Consider this DataFrame:

df = pd.DataFrame({'col1': ['foo', 'bar', 'baz'],
                   'col2': ['green', 'blue', 'red'],
                   'col3': [0,1,2], },
                   index=list('ABD'))

df.index.names = ['col0']
df = df.set_index(['col1','col2'], append=True)

df.reindex(index=['baz', 'bar'], level='col1')

edit2:

Trying @piRSquared's answer on the 3-level index, if you sort for the same level as the one your indexing with, it seems to be a solution.

df = df.sort_index(level='col1')
df.iloc[df.index.get_level_values('col1').searchsorted(['baz', 'bar'])]

Body:
You could use reindex to force the order of the rows in the order you desire, it seems that using loc it's not possible to do this with multi-indexes as sortedness is enforced always:

In[13]:
df.reindex(['D','B'], level=0)
Out[13]:
        col1
  col2
D baz      2
B bar      1


问:
What is the minimum version of Xcode required to test the app in test device (iOS 10.3.2)?
I am new to the iOS development world. I have an app in the app store and there is one issue in the app. The app was developed long ago (around 5 years ago) and some features of the app stopped running in the latest update (10.3.2). I need to fix the issue but I don't know what is the minimum Xcode and OS I have to install in my MacBook to move ahead. I expect some suggestions from you.</p>

答:
Firstly you've to convert that code on to the latest version of language (Swift/Objective-C). And only then you can debug/run that latest code for iOS 10.3.2 on Xcode 8.3.2

Otherwise one more option is there to debug the issues on iOS 10.3.2 with converting the code, you can make an .ipa file of the old code and install it on iOS 10.3.2 and debug the issue with the help of Device logs.
Device logs you can find in Go to Xcode > Window from menu > Devices > Choose your device and click on the "View Device Logs" button.


问:
How to repeat a query in postgreSQL, and add the results to a table
I need to run a query 1000 times, and add the results to a table. I have the following code which is what I would like to be repeated:

```<code>Select max_gridco, count(max_gridco) as TaxLots, sum(population) as pop_sum
from
(
    Select tlid, max_gridco, population
    from (
        select tlid, max_gridco, population, st_intersects(tle.geom, acres025.geom)
        from tle, acres025
        where max_gridco not in (0, 1)
        order by RANDOM()
        limit 1000
    ) as count
    where st_intersects = 't'
    order by max_gridco
) as gridcode_count
group by max_gridco;
</code>```

Is there a way that I can run this 1000 times automatically, and in the output table have a column that includes the run number? So my table would look like the following:

Run number | max_gridco | TaxLots | pop_sum

I am trying to do a Loop command in PgAdmin3, but cannot seem to get the syntax correct.

答:
use DO block or create a function, eg:

```<code>DO
$$
begin
for i in 1..1000 loop
    insert into save_to_table (Run number,max_gridco,TaxLots,pop_sum)
    Select i, max_gridco, count(max_gridco) as TaxLots, sum(population) as pop_sum
    from
    (
        Select tlid, max_gridco, population
        from (
            select tlid, max_gridco, population, st_intersects(tle.geom, acres025.geom)
            from tle, acres025
            where max_gridco not in (0, 1)
            order by RANDOM()
            limit 1000
        ) as count
        where st_intersects = 't'
        order by max_gridco
    ) as gridcode_count
    group by max_gridco;
end loop;
end;
$$
;
</code>```

Body:
I need to run a query 1000 times, and add the results to a table. I have the following code which is what I would like to be repeated:

Select max_gridco, count(max_gridco) as TaxLots, sum(population) as pop_sum
from
(
    Select tlid, max_gridco, population
    from (
        select tlid, max_gridco, population, st_intersects(tle.geom, acres025.geom)
        from tle, acres025
        where max_gridco not in (0, 1)
        order by RANDOM()
        limit 1000
    ) as count
    where st_intersects = 't'
    order by max_gridco
) as gridcode_count
group by max_gridco;

Is there a way that I can run this 1000 times automatically, and in the output table have a column that includes the run number? So my table would look like the following:

Run number | max_gridco | TaxLots | pop_sum

I am trying to do a Loop command in PgAdmin3, but cannot seem to get the syntax correct.

Body:
use DO block or create a function, eg:

DO
$$
begin
for i in 1..1000 loop
    insert into save_to_table (Run number,max_gridco,TaxLots,pop_sum)
    Select i, max_gridco, count(max_gridco) as TaxLots, sum(population) as pop_sum
    from
    (
        Select tlid, max_gridco, population
        from (
            select tlid, max_gridco, population, st_intersects(tle.geom, acres025.geom)
            from tle, acres025
            where max_gridco not in (0, 1)
            order by RANDOM()
            limit 1000
        ) as count
        where st_intersects = 't'
        order by max_gridco
    ) as gridcode_count
    group by max_gridco;
end loop;
end;
$$
;


问:
How to convert comma separated string values into a List<string> using asp.net mvc5
want to convert comma separated string values into a List

have tried

```<code>public List<string> GetColumnNamesByReportname(string Reportname)
{
    using (var Context = new MCPEntities())
    {
        var ColumnNames = Context.Reports.Where(c => c.ReportName == Reportname).Select(c => c.ColumnNames).ToList();
        return ColumnNames;
    }
}
</code>```

答:
So lets say we have a class called "Report" that has a name and a list of column names in CSV form.

```<code>public class Report
{
    public string ReportName { get; set; }
    public string ColumnNames { get; set; }
}
</code>```

Then we have a class called "Context" that holds a list of reports.

```<code>public class ContextClass
{
    public List<Report> Reports { get; set; }
}
</code>```

Then we initialize the Context class with a new report called "Report1" that has 3 columns and add it to the list

```<code> var Context = new ContextClass();
 Context.Reports = new List<Report>();
 Context.Reports.Add(new Report()
 {
      ReportName = "Report1",
      ColumnNames = "Col1,Col2,Col3"
 });
</code>```

Then in the context of your method, a "ReportName" is passed in called "Report1"

```<code> var ReportName = "Report1";
</code>```

We can then return the values as a list of string as per your original posted code"

```<code> var ColumnNames = Context.Reports.Where(c => c.ReportName == ReportName).Select(c => c.ColumnNames.Split(',')).ToList();
 return ColumnNames
</code>```

I've tested this locally and it works fine.

Thanks

Body:
want to convert comma separated string values into a List

have tried

public List<string> GetColumnNamesByReportname(string Reportname)
{
    using (var Context = new MCPEntities())
    {
        var ColumnNames = Context.Reports.Where(c => c.ReportName == Reportname).Select(c => c.ColumnNames).ToList();
        return ColumnNames;
    }
}

Body:
So lets say we have a class called "Report" that has a name and a list of column names in CSV form.

public class Report
{
    public string ReportName { get; set; }
    public string ColumnNames { get; set; }
}

Then we have a class called "Context" that holds a list of reports.

public class ContextClass
{
    public List<Report> Reports { get; set; }
}

Then we initialize the Context class with a new report called "Report1" that has 3 columns and add it to the list

 var Context = new ContextClass();
 Context.Reports = new List<Report>();
 Context.Reports.Add(new Report()
 {
      ReportName = "Report1",
      ColumnNames = "Col1,Col2,Col3"
 });

Then in the context of your method, a "ReportName" is passed in called "Report1"

 var ReportName = "Report1";

We can then return the values as a list of string as per your original posted code"

 var ColumnNames = Context.Reports.Where(c => c.ReportName == ReportName).Select(c => c.ColumnNames.Split(',')).ToList();
 return ColumnNames

I've tested this locally and it works fine.

Thanks


问:
React Native: How to make Listview with with local images
I made an album that looks sort of like this:

```<code><ScrollView>
  <Image1
     <Text1>
        smth
     </Text1>    />

  <Image2
     <Text2>
        smthElse
     </Text2>    />' ... and so on 20 times.
</code>```

I have 5 albums, which I access with tabs on top.
The problem is that sometimes when I switch between the tabs, some images are blank and don't load. The images are all required like this:

```<code>source={require('../assets/Image1.png')}
</code>```

I want them to be required from the app and not via uri.

I thought the problem is because of the memory and on weaker phones it's possible that they don't always load, because I use a ScrollView and it loads all the images at once. I read that a ListView quite solve my problem, but I can't figure out how to make a ListView that renders 20 specific images with a specific text for each one.

If anyone can give me some clues it would be much appreciated.

Thank you !

答:
In response to your question how to use a ListView to render 20 images. We are using a SectionList for rendering multiple photos. I will share the snippets below to get you started.

SectionList

```<code><SectionList
    contentContainerStyle={styles.sectionListContainer}
    renderItem={this.renderItem}
    renderSectionHeader={this.renderHeader}
    sections={this.state.ImageData}
/>
</code>```

this.renderItem

```<code>renderItem(data) {
    return (
        <View key={data.item.key} style={{ flex: 1 }}>
            <View style={{ flex: 1, flexDirection: "row", flexWrap: "wrap" }}>
                <Image
                    style={styles.foodPhoto}
                    source={{ uri: `data:image/jpg;base64,${data.item.photo}`}}
                />
            </View>
        </View>
    )

}
</code>```

To format the this.state.ImageData it took us a bit of fiddling to get the formatting/schema right for the SectionList. The format itself is documented at RN documentation. Hope that this helps!

Body:
I made an album that looks sort of like this:

<ScrollView>
  <Image1
     <Text1>
        smth
     </Text1>    />

  <Image2
     <Text2>
        smthElse
     </Text2>    />' ... and so on 20 times.

I have 5 albums, which I access with tabs on top.
The problem is that sometimes when I switch between the tabs, some images are blank and don't load. The images are all required like this:

source={require('../assets/Image1.png')}

I want them to be required from the app and not via uri.

I thought the problem is because of the memory and on weaker phones it's possible that they don't always load, because I use a ScrollView and it loads all the images at once. I read that a ListView quite solve my problem, but I can't figure out how to make a ListView that renders 20 specific images with a specific text for each one.

If anyone can give me some clues it would be much appreciated.

Thank you !

Body:
In response to your question how to use a ListView to render 20 images. We are using a SectionList for rendering multiple photos. I will share the snippets below to get you started.

SectionList

<SectionList
    contentContainerStyle={styles.sectionListContainer}
    renderItem={this.renderItem}
    renderSectionHeader={this.renderHeader}
    sections={this.state.ImageData}
/>

this.renderItem

renderItem(data) {
    return (
        <View key={data.item.key} style={{ flex: 1 }}>
            <View style={{ flex: 1, flexDirection: "row", flexWrap: "wrap" }}>
                <Image
                    style={styles.foodPhoto}
                    source={{ uri: `data:image/jpg;base64,${data.item.photo}`}}
                />
            </View>
        </View>
    )

}

To format the this.state.ImageData it took us a bit of fiddling to get the formatting/schema right for the SectionList. The format itself is documented at RN documentation. Hope that this helps!


问:
"Requested URI is invalid" during upload with FtpWebRequest
I trying upload file to a directory on a FTP server. I used this method with FtpWebRequest.
I would like to upload one file to a home directory for this user, but I always get the following error message:

The requested URI is invalid for this FTP command.

What can be problem? I tried use passive mode off, but it still the same.

```<code>static void FtpUpload()
{

    // Get the object used to communicate with the server.
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://12.22.44.45");
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.UsePassive = false;

    // This example assumes the FTP site uses anonymous logon.
    request.Credentials = new NetworkCredential("pokus", "password");

    // Copy the contents of the file to the request stream.
    StreamReader sourceStream = new StreamReader(path);
    byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
    sourceStream.Close();
    request.ContentLength = fileContents.Length;

    Stream requestStream = request.GetRequestStream();
    requestStream.Write(fileContents, 0, fileContents.Length);
    requestStream.Close();

    FtpWebResponse response = (FtpWebResponse)request.GetResponse();

    Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);

    response.Close();

}
</code>```

答:
I suggest you use WebClient which is a higher level abstraction and works with HTTP and FTP and has much simpler API and performance-wise pretty the same (uses the same API).

Here is upload data.

Body:
I trying upload file to a directory on a FTP server. I used this method with FtpWebRequest.
I would like to upload one file to a home directory for this user, but I always get the following error message:

The requested URI is invalid for this FTP command.

What can be problem? I tried use passive mode off, but it still the same.

static void FtpUpload()
{

    // Get the object used to communicate with the server.
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://12.22.44.45");
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.UsePassive = false;

    // This example assumes the FTP site uses anonymous logon.
    request.Credentials = new NetworkCredential("pokus", "password");

    // Copy the contents of the file to the request stream.
    StreamReader sourceStream = new StreamReader(path);
    byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
    sourceStream.Close();
    request.ContentLength = fileContents.Length;

    Stream requestStream = request.GetRequestStream();
    requestStream.Write(fileContents, 0, fileContents.Length);
    requestStream.Close();

    FtpWebResponse response = (FtpWebResponse)request.GetResponse();

    Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);

    response.Close();

}


问:
Validating multiple messages on the same JMS endpoint in Citrus Framework
I'm sending a single message that produces multiple messages, two of which arrive on the same JMS endpoint.

```<code>runner.send(sendMessageBuilder -> sendMessageBuilder.endpoint(inputMessage.getEndpoint())
    .messageType(MessageType.XML)
    .payload(inputMessage.getPayload())
    .header(JMSOUTPUTCORRELATIONID, correlationId));

for(OutputMessage outputMessage : inputMessage.getOutputMessages()) {
     runner.receive(receiveMessageBuilder -> receiveMessageBuilder.endpoint(outputMessage.getEndpoint())
        .schemaValidation(false)
        .payload(outputMessage.getPayload())
        .header(JMSOUTPUTCORRELATIONID, correlationId));
}
</code>```

When validating two messages on the same endpoint I'm having trouble finding a way to match them to their respective expected outputs.
I was wondering if Citrus has a built in way to do this or if I could build in a condition that checks the other expected outputs if the first one fails.

答:
I've added a custom validator. </p>

```<code>List<OutputMessage> outputMessages = inputMessage.getOutputMessages();
while(outputMessages.size() > 0) {
    OutputMessage outputMessage = outputMessages.get(0);
    runner.receive(receiveMessageBuilder -> receiveMessageBuilder.endpoint(outputMessage.getEndpoint())
        .schemaValidation(true)
        .validator(new MultipleOutputMessageValidator(outputMessages))
        .header(JMSOUTPUTCORRELATIONID, correlationId));
}
</code>```

<p>The validator is provided with the the list of expected outputs that have not yet been validated. It will then try to validate each of the expected outputs in the list against the received message and if the validation is succesful removes that expected output from the list. </p>

```<code>public class MultipleOutputMessageValidator extends DomXmlMessageValidator {
    private static Logger log = LoggerFactory.getLogger(MultipleOutputMessageValidator.class);
    private List<OutputMessage> controlMessages;

    public MultipleOutputMessageValidator(List<OutputMessage> controlMessages) {
        this.controlMessages = controlMessages;
    }

    @Override
    public void validateMessagePayload(Message receivedMessage, Message controlMessage, XmlMessageValidationContext validationContext, TestContext context) throws ValidationException {
        Boolean isValidated = false;
        for (OutputMessage message : this.controlMessages) {
            try {
                super.validateMessagePayload(receivedMessage, message, validationContext, context);
                isValidated = true;
                controlMessages.remove(message);
                break;
            } catch (ValidationException e) {
                // Do nothing for now
            }
        }
        if (!isValidated) {
            throw new ValidationException("None of the messages validated");
        }
    }
}
</code>```

Body:
I'm sending a single message that produces multiple messages, two of which arrive on the same JMS endpoint.

runner.send(sendMessageBuilder -> sendMessageBuilder.endpoint(inputMessage.getEndpoint())
    .messageType(MessageType.XML)
    .payload(inputMessage.getPayload())
    .header(JMSOUTPUTCORRELATIONID, correlationId));

for(OutputMessage outputMessage : inputMessage.getOutputMessages()) {
     runner.receive(receiveMessageBuilder -> receiveMessageBuilder.endpoint(outputMessage.getEndpoint())
        .schemaValidation(false)
        .payload(outputMessage.getPayload())
        .header(JMSOUTPUTCORRELATIONID, correlationId));
}

When validating two messages on the same endpoint I'm having trouble finding a way to match them to their respective expected outputs.
I was wondering if Citrus has a built in way to do this or if I could build in a condition that checks the other expected outputs if the first one fails.

Body:
I've added a custom validator.

List<OutputMessage> outputMessages = inputMessage.getOutputMessages();
while(outputMessages.size() > 0) {
    OutputMessage outputMessage = outputMessages.get(0);
    runner.receive(receiveMessageBuilder -> receiveMessageBuilder.endpoint(outputMessage.getEndpoint())
        .schemaValidation(true)
        .validator(new MultipleOutputMessageValidator(outputMessages))
        .header(JMSOUTPUTCORRELATIONID, correlationId));
}

The validator is provided with the the list of expected outputs that have not yet been validated. It will then try to validate each of the expected outputs in the list against the received message and if the validation is succesful removes that expected output from the list.

public class MultipleOutputMessageValidator extends DomXmlMessageValidator {
    private static Logger log = LoggerFactory.getLogger(MultipleOutputMessageValidator.class);
    private List<OutputMessage> controlMessages;

    public MultipleOutputMessageValidator(List<OutputMessage> controlMessages) {
        this.controlMessages = controlMessages;
    }

    @Override
    public void validateMessagePayload(Message receivedMessage, Message controlMessage, XmlMessageValidationContext validationContext, TestContext context) throws ValidationException {
        Boolean isValidated = false;
        for (OutputMessage message : this.controlMessages) {
            try {
                super.validateMessagePayload(receivedMessage, message, validationContext, context);
                isValidated = true;
                controlMessages.remove(message);
                break;
            } catch (ValidationException e) {
                // Do nothing for now
            }
        }
        if (!isValidated) {
            throw new ValidationException("None of the messages validated");
        }
    }
}


问:
Illegal Configuration: Compiling IB documents for earlier than iOS 7 is no longer supported
I recently updated to XCode 9. When I build the app it says "illegal configuration" for some storyboards in my pod files. I tried to recreate the storyboard files but it doesn't help.

答:
XCode 9 will not support storyboards that are built for iOS version less than 7.

Try changing the Builds for in File Inspector to a higher version then Clean and Build.

See screenshot

Edit: Important info from @user435779 below: Restart XCode if the errors don't go away.


问:
hiding the Select button in gridview
I currently have a gridview that allows you to select the row by clicking anywhere on that row.  however, there is a problem.  The AutoGenerateSelectButton must be set to true.  This means that the select button is now visible and part of the grid view.  I wanted to know if there was a way to hide it without disrupting the grid size?</p>

答:
```<code>                <asp:GridView ID="gv" runat="server" Width="100%" AutoGenerateColumns="False"
                    DataKeyNames="BillingAccountNo" OnRowDataBound="gv_RowDataBound"
                    OnSelectedIndexChanged="dgBillingInformation_SelectedIndexChanged">
                    <Columns>

                        <asp:BoundField DataField="field" HeaderText="field" />
                        <asp:BoundField DataField="field" HeaderText="field" />
                        <asp:CommandField ShowSelectButton="true" ButtonType="Button" ControlStyle-CssClass="hidden" ItemStyle-CssClass="hidden" HeaderStyle-CssClass="hidden" FooterStyle-CssClass="hidden" />
                    </Columns>
                </asp:GridView>
</code>```

Title: hiding the Select button in gridview


答:
First case:

i++ is positionned after the call to main. So i will always be equal to 2, as you never reach this part of the code. You are then calling your main function everytime, leading to an infinite recursion, and thus to the segmentation fault. The fix for this case would be to increase i before calling the main function.

```<code>if (i<7)
{
    i++; // Increment before calling the main function, so i value is changed
    main();
    printf("%d ", i);
}
</code>```

Do note that it will lead to something which looks like your second case, except that you will print several "7".

Seconde case:

In the second case, you are decreasing the value of i everytime you enter your if condition. When you finally can't enter your if condition anymore, it means i is equal to 0 (as if(0) is equivalent to if(false)). Everytime you will return to the previous called main function, i will still be equal to 0, explaining why you are displaying "0" everytime. If you want to print the different values, you can place your printf before the call to the main function for instance.

Title: C program recursive call to main() with and without parameters

Body:
Why does it give an error of segmentation fault(core dumped) and gives no output in 1st case ?Can anyone explain how program is program callls main recursively with parameters?

#include <stdio.h>
int main()
{
    static int i = 2;
    if (i<7)
    {
        main();
        printf("%d ", i);
        i++;
        //main(10);
    }
}

-

#include <stdio.h>
int main()
{
    static int i = 5;
    if (--i)
    {
     //main();
     printf("%d ", i);
     main(10);
    }
}

Body:
First case:

i++ is positionned after the call to main. So i will always be equal to 2, as you never reach this part of the code. You are then calling your main function everytime, leading to an infinite recursion, and thus to the segmentation fault. The fix for this case would be to increase i before calling the main function.

if (i<7)
{
    i++; // Increment before calling the main function, so i value is changed
    main();
    printf("%d ", i);
}

Do note that it will lead to something which looks like your second case, except that you will print several "7".

Seconde case:

In the second case, you are decreasing the value of i everytime you enter your if condition. When you finally can't enter your if condition anymore, it means i is equal to 0 (as if(0) is equivalent to if(false)). Everytime you will return to the previous called main function, i will still be equal to 0, explaining why you are displaying "0" everytime. If you want to print the different values, you can place your printf before the call to the main function for instance.


问:
How to fetch WorkItem links with the TFS Java API
We use the TFS Java API to fetch WorkItems from a TFS server:

```<code>    TFSTeamProjectCollection collection = TFSTeamProjectCollectionUtils
            .openTeamProjectCollection(serverUrl, credentials,
                    new DefaultConnectionAdvisor(Locale.getDefault(),
                            TimeZone.getDefault()));
    WorkItemClient client = collection.getWorkItemClient();

    List<WorkItem> result = new ArrayList<>();
    try {
        WorkItemCollection workItems = client.query(wiqlQuery, null, false);
        for (int i = 0; i < workItems.size(); i++) {
            WorkItem item = workItems.getWorkItem(i);
            result.add(item);
        }
        return result;
    } catch (TECoreException e) {
        throw new ConQATException("Failed to fetch work items from TFS", e);
    }
</code>```

If I run the query select * from workitems I get all workitems on the server with all fields and all links. Since I'm only interested in some of the fields, I would like to restrict the query to only those and save some bandwidth/time: select ID, Title from workitems

This works fine, but now the links of the items are missing (i.e. item.getLinks() always returns an empty collection).

Is there a way to select the links other than select * from workitems?

答:
The solution using WorkItemLinkInfo is correct.
Just as remark: Using a WIQL Query you only receive the attributes you were querying - which cannot be the set of links of a work item (therefore always empty). If you query a single workitem using

```<code>WorkItemClient client = TFSConnection.getClient();
WorkItem firstWorkItem = client.getWorkItemByID(id);
</code>```

then you also get the LinkCollection using (containing RelatedLinks, ExternalLinks or HyperLinks)

```<code>LinkCollection linkcoll = firstWorkItem.getLinks()
</code>```

Body:
We use the TFS Java API to fetch WorkItems from a TFS server:

    TFSTeamProjectCollection collection = TFSTeamProjectCollectionUtils
            .openTeamProjectCollection(serverUrl, credentials,
                    new DefaultConnectionAdvisor(Locale.getDefault(),
                            TimeZone.getDefault()));
    WorkItemClient client = collection.getWorkItemClient();

    List<WorkItem> result = new ArrayList<>();
    try {
        WorkItemCollection workItems = client.query(wiqlQuery, null, false);
        for (int i = 0; i < workItems.size(); i++) {
            WorkItem item = workItems.getWorkItem(i);
            result.add(item);
        }
        return result;
    } catch (TECoreException e) {
        throw new ConQATException("Failed to fetch work items from TFS", e);
    }

If I run the query select * from workitems I get all workitems on the server with all fields and all links. Since I'm only interested in some of the fields, I would like to restrict the query to only those and save some bandwidth/time: select ID, Title from workitems

This works fine, but now the links of the items are missing (i.e. item.getLinks() always returns an empty collection).

Is there a way to select the links other than select * from workitems?

Body:
The solution using WorkItemLinkInfo is correct.
Just as remark: Using a WIQL Query you only receive the attributes you were querying - which cannot be the set of links of a work item (therefore always empty). If you query a single workitem using

WorkItemClient client = TFSConnection.getClient();
WorkItem firstWorkItem = client.getWorkItemByID(id);

then you also get the LinkCollection using (containing RelatedLinks, ExternalLinks or HyperLinks)

LinkCollection linkcoll = firstWorkItem.getLinks()


问:
How to create an iPhone app that interacts with my website?
What I want to do is to make an iPhone application for my website similar to the photofunia. The users will be able to select an effect from a list, and then upload their own photo. Then the result will be shown in the browser where the user can save the image and/or publish to website like facebook, etc.

What software can I use to do that? Phonegap, appcelerator, etc? Can some of these help?

Thanks.

答:
First of all, you may be able to make an iPhone app using Adobe Flash and the Adobe Packager for iPhone.

The other option is to get a Mac and Learn Objective-C.

There is no "easy" solution here.


问:
groovyc seems to not compile, class not runnable
I am not able to compile and run Groovy-scripts. I take a very first example Gold.groovy . I can compile it with
groovyc Gold.groovy

when I try to start it thereafter with:
java Gold

I get the error message

"Fehler: Hauptklasse Gold konnte nicht gefunden oder geladen werden" -
  which means in english ~ "Main class not found"

Has anybody a hint what I could try or where to find the error?

Thanks in forehand

source

List fibo = [1, 1]                          //#A
List gold = [1, 2]                          //#B

while ( ! isGolden( gold[-1] ) ) {          //#C
    fibo.add( fibo[-1] + fibo[-2] )         //#D
    gold.add( fibo[-1] / fibo[-2] )         //#E
}

println "found golden ratio with fibo(${ fibo.size-1 }) as"
println fibo[-1] + " / " + fibo[-2] + " = " + gold[-1]
println "_" * 10 +  "|"  + "_" * (10 * gold[-1])

def isGolden(candidate) {                   //#F
    def small = 1                           //#G
    def big = small * candidate             //#H
    return isCloseEnough( (small+big)/big, big/small)
}

def isCloseEnough(a,b) { return (a-b).abs() < 1.0e-9 }
//#A Initial Fibonacci numbers
//#B Golden ration candidates
//#C Last gold candidate
//#D Next fibo number
//#E Next golden candidate
//#F Candidate satisfies golden rule
//#G Smaller section
//#H Bigger section```
</div>
</div>
</p>

<p><strong>for request: screen output</strong></p>

```D:\work\groovy\GroovyInAction-master\listings\chap01>set CLASSPATH
CLASSPATH=.;D:\DevTools\groovy-2.4.7\embeddable\groovy-all-2.4.7.jar

D:\work\groovy\GroovyInAction-master\listings\chap01>type HelloWorld.groovy
println "Hello World"

D:\work\groovy\GroovyInAction-master\listings\chap01>groovyc HelloWorld.groovy

D:\work\groovy\GroovyInAction-master\listings\chap01>java WelloWorld
Fehler: Hauptklasse WelloWorld konnte nicht gefunden oder geladen werden

D:\work\groovy\GroovyInAction-master\listings\chap01>javac -cp .;D:\DevTools\gro
ovy-2.4.7\embeddable\groovy-all-2.4.7.jar HelloWorld
error: Class names, 'HelloWorld', are only accepted if annotation processing is
explicitly requested
1 error
```

答:
Gold.groovy:

```<code>def name = 'world'
println "hello $name!"
</code>```

compile:

```<code>groovyc Gold.groovy
</code>```

produces Gold.class

run (for unix use : instead of ; in the classpath):

```<code>java -cp embeddable\groovy-all-2.4.11.jar;. Gold
</code>```

output:

```<code>hello world!
</code>```

Body:
I am not able to compile and run Groovy-scripts. I take a very first example Gold.groovy . I can compile it with
groovyc Gold.groovy

when I try to start it thereafter with:
java Gold

I get the error message

"Fehler: Hauptklasse Gold konnte nicht gefunden oder geladen werden" -
  which means in english ~ "Main class not found"

Has anybody a hint what I could try or where to find the error?

Thanks in forehand

source

List fibo = [1, 1]                          //#A
List gold = [1, 2]                          //#B

while ( ! isGolden( gold[-1] ) ) {          //#C
    fibo.add( fibo[-1] + fibo[-2] )         //#D
    gold.add( fibo[-1] / fibo[-2] )         //#E
}

println "found golden ratio with fibo(${ fibo.size-1 }) as"
println fibo[-1] + " / " + fibo[-2] + " = " + gold[-1]
println "_" * 10 +  "|"  + "_" * (10 * gold[-1])

def isGolden(candidate) {                   //#F
    def small = 1                           //#G
    def big = small * candidate             //#H
    return isCloseEnough( (small+big)/big, big/small)
}

def isCloseEnough(a,b) { return (a-b).abs() < 1.0e-9 }
//#A Initial Fibonacci numbers
//#B Golden ration candidates
//#C Last gold candidate
//#D Next fibo number
//#E Next golden candidate
//#F Candidate satisfies golden rule
//#G Smaller section
//#H Bigger section

for request: screen output

D:\work\groovy\GroovyInAction-master\listings\chap01>set CLASSPATH
CLASSPATH=.;D:\DevTools\groovy-2.4.7\embeddable\groovy-all-2.4.7.jar

D:\work\groovy\GroovyInAction-master\listings\chap01>type HelloWorld.groovy
println "Hello World"

D:\work\groovy\GroovyInAction-master\listings\chap01>groovyc HelloWorld.groovy

D:\work\groovy\GroovyInAction-master\listings\chap01>java WelloWorld
Fehler: Hauptklasse WelloWorld konnte nicht gefunden oder geladen werden

D:\work\groovy\GroovyInAction-master\listings\chap01>javac -cp .;D:\DevTools\gro
ovy-2.4.7\embeddable\groovy-all-2.4.7.jar HelloWorld
error: Class names, 'HelloWorld', are only accepted if annotation processing is
explicitly requested
1 error

Body:
Gold.groovy:

def name = 'world'
println "hello $name!"

compile:

groovyc Gold.groovy

produces Gold.class

run (for unix use : instead of ; in the classpath):

java -cp embeddable\groovy-all-2.4.11.jar;. Gold

output:

hello world!


问:
Django ORM distinct query where order is done by annotated field and you need distinct('id')
Merchant has places. Places have a location coordinates. I need to return a list of UNIQUE merchants through API call (DRF) filtered by distances of proximity to any place they have associated and return back distance value from the closest place. Right now I get duplicates (i.e. merchant gets returned multiple times if there are several places of the merchant in proximity).

If I try to have annotate(distance=...).distinct('pk') I get error message

```<code>django.db.utils.ProgrammingError:
    SELECT DISTINCT ON expressions must match initial ORDER BY expressions
    LINE 1: SELECT COUNT(*) FROM (SELECT DISTINCT ON ("merchants_merchan
</code>```

If I add .order_by('pk') I can then use .distinct('pk'), but then I can't sort returning queryset by distance.

Here is what I have done so far:

Queryset

```<code>class MerchantQuerySet(models.QuerySet):
    def nearby(self, latitude, longitude, proximity=None):
        """Get nearby Merchants.

        Custom queryset method for getting merchants associated with
        nearby places.

        Returns:
            A queryset of ``Merchant`` objects.

        """
        point = Point(latitude, longitude)

        # we query for location nearby for places first and then
        # annotate with distance to the same place
        return self.filter(
            places__location__distance_lte=(point, D(ft=proximity))).\
            annotate(distance=Distance(
                'places__location', point)).distinct()
</code>```

Models

```<code>class Merchant(TimeStampedModel):

    name = models.CharField(max_length=255, verbose_name=_('Name'))
    description = models.TextField(
        blank=True,
        verbose_name=_('Description'),
    )
    logo = imagekitmodels.ProcessedImageField(
        max_length=512,
        upload_to=get_upload_path_for_model,
        processors=[ResizeToFill(300, 300)],
        format='PNG',
        options={'quality': 100},
        editable=True,
        null=True,
        blank=True,
        verbose_name=_('Company logo'),
        help_text=_('Image will be resized to 300x300px.')
    )
    categories = models.ManyToManyField(
        'categories.Category',
        blank=True,
        related_name='merchants',
        verbose_name=_('Categories'),
    )
    address = models.TextField(blank=True, verbose_name=_('Address'))
    contact = models.CharField(
        max_length=32,
        blank=True,
        verbose_name=_('Contact phone'),
    )
    url = models.URLField(blank=True, verbose_name=_('Site URL'))
    social_urls = ArrayField(
        models.URLField(blank=True),
        blank=True,
        null=True,
        verbose_name=_('Social URLs'),
    )
    budget_tips = models.TextField(
        blank=True,
        verbose_name=_('Budget tips'),
        help_text=_('Recommendations to determine merchant budget.'),
    )

    objects = query.MerchantQuerySet.as_manager()

    class Meta:
        verbose_name = _('Merchant')
        verbose_name_plural = _('Merchants')

class Place(TimeStampedModel):

    id = models.CharField(
        max_length=32,
        primary_key=True,
        unique=True,
        verbose_name=_('ID'),
        help_text=_('Forsquare ID of the venue.'),
    )
    merchant = models.ForeignKey(
        'merchants.Merchant',
        related_name='places',
        verbose_name=_('Merchant'),
        help_text=_('Merchant, business owner.'),
    )
    categories = models.ManyToManyField(
        'categories.Category',
        blank=True,
        related_name='places',
        verbose_name=_('Categories'),
    )
    name = models.CharField(
        max_length=255,
        blank=True,
        verbose_name=_('Name')
    )
    address = models.TextField(blank=True, verbose_name=_('Address'))
    contact = models.CharField(
        max_length=32,
        blank=True,
        verbose_name=_('Contact phone')
    )
    location = PointField(blank=True, null=True, verbose_name=_('Location'))

    objects = PlaceQuerySet.as_manager()

    class Meta:
        verbose_name = _('Place')
        verbose_name_plural = _('Places')
</code>```

DRF View

```<code>class MerchantViewSet(

            mixins.ListModelMixin,
            mixins.RetrieveModelMixin,
            favorites_api_mixins.UserFavoritesMixin,
            viewsets.GenericViewSet,
    ):

        queryset = models.Merchant.objects.all()
        serializer_class = serializers.MerchantSerializer
        filter_backends = (MerchantOrderingFilter,
                           filters.DjangoFilterBackend,
                           filters.SearchFilter,
                           utils_filters.LocationDistanceFilter)

        ordering_fields = ('name', 'created', 'distance')
        ordering = ('-created')
        search_fields = ('name',)
</code>```

utils_filters.LocationDistanceFilter

```<code>class LocationDistanceFilter(BaseFilterBackend):
    """Location distance filter.

    Class for filtering objects by distance. Takes three GET params ``lat``,
    ``long`` and ``dist``:

        .../?dist=300&lat=55.56&long=98.01

    """
    dist_param = 'dist'

    def get_filter_point(self, request):
        """Get filter point.

        Get point for filtering by distance to this point.

        Args:
            request (Request): A ``Request`` object.

        Returns:
            A ``Point`` object or None.

        Raises:
            Parse error if point is invalid.

        """
        latitude = request.query_params.get('lat')
        longitude = request.query_params.get('long')

        if latitude and longitude:
            try:
                latitude = float(latitude)
                longitude = float(longitude)
            except ValueError:
                raise ParseError(
                    'Invalid geometry string supplied for '
                    'latitude or longitude'
                )

            return Point(latitude, longitude)

        else:
            return None

    def filter_queryset(self, request, queryset, view):
        """Filter queryset.

        Filter queryset by ``lat``, ``long`` and ``dist` params. Queryset
        should have method ``nearby``.

        Args:
            request (Request): A ``Request`` object.
            queryset (QuerySet): A ``QuerySet`` object.
            view (ViewSet): Current API view instance.

        Returns:
            A query set of objects filtered by latitude, longitude
            and distance.

        """
        distance = request.query_params.get(self.dist_param)
        point = self.get_filter_point(request)

        if not point:
            return queryset

        return queryset.nearby(
            latitude=point.x,
            longitude=point.y,
            proximity=distance,
        )
</code>```

Any ideas?

答:
If you take a look at the distinct() documentation (as @Todor suggests), you will find this:

Any fields used in an order_by() call are included in the SQL SELECT columns. This can sometimes lead to unexpected results when used in conjunction with distinct(). If you order by fields from a related model, those fields will be added to the selected columns and they may make otherwise duplicate rows appear to be distinct. Since the extra columns don’t appear in the returned results (they are only there to support ordering), it sometimes looks like non-distinct results are being returned.

So whatever you do, do it with that in mind.

Let's try to work around that:

annotate(distance=...) creates a column named distance which you can use to sort your query. You need distinct merchants which can be assured by distinct pks:

```<code>...annotate(distance=...).order_by('pk', 'distance').distinct('pk')
</code>```

This will order your queryset first by pk then by distance and finally it will return only merchants with distinct pk.

Body:
Merchant has places. Places have a location coordinates. I need to return a list of UNIQUE merchants through API call (DRF) filtered by distances of proximity to any place they have associated and return back distance value from the closest place. Right now I get duplicates (i.e. merchant gets returned multiple times if there are several places of the merchant in proximity).

If I try to have annotate(distance=...).distinct('pk') I get error message

django.db.utils.ProgrammingError:
    SELECT DISTINCT ON expressions must match initial ORDER BY expressions
    LINE 1: SELECT COUNT(*) FROM (SELECT DISTINCT ON ("merchants_merchan

If I add .order_by('pk') I can then use .distinct('pk'), but then I can't sort returning queryset by distance.

Here is what I have done so far:

Queryset

class MerchantQuerySet(models.QuerySet):
    def nearby(self, latitude, longitude, proximity=None):
        """Get nearby Merchants.

        Custom queryset method for getting merchants associated with
        nearby places.

        Returns:
            A queryset of ``Merchant`` objects.

        """
        point = Point(latitude, longitude)

        # we query for location nearby for places first and then
        # annotate with distance to the same place
        return self.filter(
            places__location__distance_lte=(point, D(ft=proximity))).\
            annotate(distance=Distance(
                'places__location', point)).distinct()

Models

class Merchant(TimeStampedModel):

    name = models.CharField(max_length=255, verbose_name=_('Name'))
    description = models.TextField(
        blank=True,
        verbose_name=_('Description'),
    )
    logo = imagekitmodels.ProcessedImageField(
        max_length=512,
        upload_to=get_upload_path_for_model,
        processors=[ResizeToFill(300, 300)],
        format='PNG',
        options={'quality': 100},
        editable=True,
        null=True,
        blank=True,
        verbose_name=_('Company logo'),
        help_text=_('Image will be resized to 300x300px.')
    )
    categories = models.ManyToManyField(
        'categories.Category',
        blank=True,
        related_name='merchants',
        verbose_name=_('Categories'),
    )
    address = models.TextField(blank=True, verbose_name=_('Address'))
    contact = models.CharField(
        max_length=32,
        blank=True,
        verbose_name=_('Contact phone'),
    )
    url = models.URLField(blank=True, verbose_name=_('Site URL'))
    social_urls = ArrayField(
        models.URLField(blank=True),
        blank=True,
        null=True,
        verbose_name=_('Social URLs'),
    )
    budget_tips = models.TextField(
        blank=True,
        verbose_name=_('Budget tips'),
        help_text=_('Recommendations to determine merchant budget.'),
    )

    objects = query.MerchantQuerySet.as_manager()

    class Meta:
        verbose_name = _('Merchant')
        verbose_name_plural = _('Merchants')

class Place(TimeStampedModel):

    id = models.CharField(
        max_length=32,
        primary_key=True,
        unique=True,
        verbose_name=_('ID'),
        help_text=_('Forsquare ID of the venue.'),
    )
    merchant = models.ForeignKey(
        'merchants.Merchant',
        related_name='places',
        verbose_name=_('Merchant'),
        help_text=_('Merchant, business owner.'),
    )
    categories = models.ManyToManyField(
        'categories.Category',
        blank=True,
        related_name='places',
        verbose_name=_('Categories'),
    )
    name = models.CharField(
        max_length=255,
        blank=True,
        verbose_name=_('Name')
    )
    address = models.TextField(blank=True, verbose_name=_('Address'))
    contact = models.CharField(
        max_length=32,
        blank=True,
        verbose_name=_('Contact phone')
    )
    location = PointField(blank=True, null=True, verbose_name=_('Location'))

    objects = PlaceQuerySet.as_manager()

    class Meta:
        verbose_name = _('Place')
        verbose_name_plural = _('Places')

DRF View

class MerchantViewSet(

            mixins.ListModelMixin,
            mixins.RetrieveModelMixin,
            favorites_api_mixins.UserFavoritesMixin,
            viewsets.GenericViewSet,
    ):

        queryset = models.Merchant.objects.all()
        serializer_class = serializers.MerchantSerializer
        filter_backends = (MerchantOrderingFilter,
                           filters.DjangoFilterBackend,
                           filters.SearchFilter,
                           utils_filters.LocationDistanceFilter)

        ordering_fields = ('name', 'created', 'distance')
        ordering = ('-created')
        search_fields = ('name',)

utils_filters.LocationDistanceFilter

class LocationDistanceFilter(BaseFilterBackend):
    """Location distance filter.

    Class for filtering objects by distance. Takes three GET params ``lat``,
    ``long`` and ``dist``:

        .../?dist=300&lat=55.56&long=98.01

    """
    dist_param = 'dist'

    def get_filter_point(self, request):
        """Get filter point.

        Get point for filtering by distance to this point.

        Args:
            request (Request): A ``Request`` object.

        Returns:
            A ``Point`` object or None.

        Raises:
            Parse error if point is invalid.

        """
        latitude = request.query_params.get('lat')
        longitude = request.query_params.get('long')

        if latitude and longitude:
            try:
                latitude = float(latitude)
                longitude = float(longitude)
            except ValueError:
                raise ParseError(
                    'Invalid geometry string supplied for '
                    'latitude or longitude'
                )

            return Point(latitude, longitude)

        else:
            return None

    def filter_queryset(self, request, queryset, view):
        """Filter queryset.

        Filter queryset by ``lat``, ``long`` and ``dist` params. Queryset
        should have method ``nearby``.

        Args:
            request (Request): A ``Request`` object.
            queryset (QuerySet): A ``QuerySet`` object.
            view (ViewSet): Current API view instance.

        Returns:
            A query set of objects filtered by latitude, longitude
            and distance.

        """
        distance = request.query_params.get(self.dist_param)
        point = self.get_filter_point(request)

        if not point:
            return queryset

        return queryset.nearby(
            latitude=point.x,
            longitude=point.y,
            proximity=distance,
        )

Any ideas?

Body:
If you take a look at the distinct() documentation (as @Todor suggests), you will find this:

Any fields used in an order_by() call are included in the SQL SELECT columns. This can sometimes lead to unexpected results when used in conjunction with distinct(). If you order by fields from a related model, those fields will be added to the selected columns and they may make otherwise duplicate rows appear to be distinct. Since the extra columns don’t appear in the returned results (they are only there to support ordering), it sometimes looks like non-distinct results are being returned.

So whatever you do, do it with that in mind.

Let's try to work around that:

annotate(distance=...) creates a column named distance which you can use to sort your query. You need distinct merchants which can be assured by distinct pks:

...annotate(distance=...).order_by('pk', 'distance').distinct('pk')

This will order your queryset first by pk then by distance and finally it will return only merchants with distinct pk.


问:
django oauth request with bearer token returns "relative imports require the 'package' argument" error
I am trying to implement the django oauth toolkit by following this tutorial:

https://django-oauth-toolkit.readthedocs.io/en/latest/tutorial/tutorial_03.html

But I can't get past this step as the curl get request at the bottom of the page returns the error

```<code>relative imports require the 'package' argument
</code>```

I've completed the first part of the tutorial exactly as instructed and it is all working fine up to this point.
I'm using django 1.8.

Has anyone else encountered this problem?

答: Turns out I was using the wrong version of django-auth-toolkit, the latest version 1.0.0 only supports Django 1.10, 1.11. Reverting back to 0.12.0 solved the problem for me.</p>

Body:
I am trying to implement the django oauth toolkit by following this tutorial:

https://django-oauth-toolkit.readthedocs.io/en/latest/tutorial/tutorial_03.html

But I can't get past this step as the curl get request at the bottom of the page returns the error

relative imports require the 'package' argument

I've completed the first part of the tutorial exactly as instructed and it is all working fine up to this point.
I'm using django 1.8.

Has anyone else encountered this problem?


问:
access textfield text from another viewController
I try to access a textfield content in my view profileView from my first view viewController but it doesn't work.
I read that I have to use override func prepare(for segue: UIStoryboardSegue, sender: Any?) {} so I did but it still not working and I don't understand why.

Here is my viewController code:

// This code is the code generated by xCode, only the loginField was added.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var loginField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
```

<p>and here is my <code>profileController</code> prepare func:</p>

<pre class="lang-swift prettyprint-override"><code>    var login: String!
    @IBOutlet weak var myLabel: UILabel!

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        print("prepare")
        if (segue.identifier == "mainMenu")
        {
            let svc = segue.source as! ViewController
            login = svc.loginField.text
            self.myLabel.text = login
            print(login)
        }
    }
</code>```

Actually, the thing i really read was "prepareForSegue" func but when I try to override it, xCode won't compile the code...

Thanks for your help.

答:
You cannot set the text of the UITextField and any other components of UIKit in the prepare for segue, because all View components of the recently allocated controller are not initialised yet they are all nil in prepareForSegue. they allocated only be when the viewController is presented.

You set Text for current ViewController TextField at prepareForSegue. Instead of this you should set text at viewWillAppear method while pop or dismiss the presented ViewController by using Notification, Delegate or userDefaults etc...

Body:
I try to access a textfield content in my view profileView from my first view viewController but it doesn't work.
I read that I have to use override func prepare(for segue: UIStoryboardSegue, sender: Any?) {} so I did but it still not working and I don't understand why.

Here is my viewController code:

// This code is the code generated by xCode, only the loginField was added.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var loginField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

and here is my profileController prepare func:

    var login: String!
    @IBOutlet weak var myLabel: UILabel!

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        print("prepare")
        if (segue.identifier == "mainMenu")
        {
            let svc = segue.source as! ViewController
            login = svc.loginField.text
            self.myLabel.text = login
            print(login)
        }
    }

Actually, the thing i really read was "prepareForSegue" func but when I try to override it, xCode won't compile the code...

Thanks for your help.


问:
Convert String in Host byte order (Little endian) to Network byte order (Big endian)
I have a Hex String which reads 18000000 this String is in Host byte order (Little endian) and I need to convert it to Network byte order (Big endian). The resultant Hex String will be 00000018.

To summarize I need to convert
18000000 to 00000018

How do I achieve this in PHP?

答:
I just stumbled on this answer while searching for something, but I ended up doing something a lot simpler (since I knew my string was always going to have a leading zero if necessary to align to a two character boundary):

```<code>$littlendian = join(array_reverse(str_split($bigendian), 2)));
</code>```

Obviously if your bigendian input isn't well formatted like that, this trick isn't going to work directly :)

Body:
I just stumbled on this answer while searching for something, but I ended up doing something a lot simpler (since I knew my string was always going to have a leading zero if necessary to align to a two character boundary):

$littlendian = join(array_reverse(str_split($bigendian), 2)));

Obviously if your bigendian input isn't well formatted like that, this trick isn't going to work directly :)


问:
How are these two XPath expressions different?
I'm parsing a website using XPath. I've got two queries, one which finds the node I'm looking for:

```<code>//td[.//text()[contains(., "Date Filed:")]]
</code>```

And one which doesn't:

```<code>//td[contains(.//text(), "Date Filed:")]
</code>```

I don't understand how these are different. I'd read them both to mean, "Find td nodes which have a descendant text node containing Date Filed."

Can anybody explain how these are different?

Here's the HTML, though I don't think it's relevant to the question:

```<code><td width="40%" valign="top">
    <br><br><br><br><br>
    <b>Date Filed:</b> 11/13/2008<br>
    <b>Jury Demand: </b> No<br><br>
    <br><b>Date Terminated: </b><br>
    <br><b>Date Reopened: </b><br>
    <br><b>Does this action raise an issue of constitutionality?: </b>Y<br>
</td>
</code>```

(Don't look at me that way. I didn't make the website, the U.S. Gov't did.)

答:
In XPath 1.0, if you supply a node-set to a function like contains() that expects a string, it uses the string-value of the first node in the node-set (in document order).

In XPath 2.0 and later versions, if you supply a node-set to a function like contains() that expects a string, the node-set is atomized, and if the result contains more than one string (which will normally be the case when more than one node is selected), then you get a type error XPTY0004.

When you ask questions about XSLT or XPath on StackOverflow, please always say which version you are talking about.

Body:
I'm parsing a website using XPath. I've got two queries, one which finds the node I'm looking for:

//td[.//text()[contains(., "Date Filed:")]]

And one which doesn't:

//td[contains(.//text(), "Date Filed:")]

I don't understand how these are different. I'd read them both to mean, "Find td nodes which have a descendant text node containing Date Filed."

Can anybody explain how these are different?

Here's the HTML, though I don't think it's relevant to the question:

    Date Filed: 11/13/2008

    Jury Demand:  No

Date Terminated:

Date Reopened:

Does this action raise an issue of constitutionality?: Y

(Don't look at me that way. I didn't make the website, the U.S. Gov't did.)