问:
Selenium Webdriver Java: Checking if a piece of script is present
I have the following piece of HTML code:

```<code><html>
<head>
<script>bladibla</script>
<script>bladibla</script>

<script>

  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-Bla', 'auto');

  ga('send', 'pageview');

</script>

</head>

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

I want to test if "go('send', 'pageview');" is present in that particular piece of code.

I've tried the following, but that doesn't seem to be working:

```<code>String header = driver.findElement(By.xpath("//head[@'script'")).getText();
Assert.assertTrue(header.contains("go('send', 'pageview');"));
</code>```

Does anybody know how I can get Selenium Webdriver to check for the presence of "go('send', 'pageview');" in a Script Tag in the Head of a webpage? GetText doesn't seem to be working as it's a script...

答:
Selenium has the same security restrictions as a browser, and you can't view JavaScript source through the DOM API.

You can see if the page view was sent by using a hitCallback, like:

```<code>window.gaHitSent = false;
ga('send', 'pageview', {
  'hitCallback': function() {
    window.gaHitSent = true;
  }
});
</code>```

You can then check the variable with Selenium.  I'm not a Java developer, so I'm following http://www.guru99.com/execute-javascript-selenium-webdriver.html:

```<code>JavascriptExecutor js = (JavascriptExecutor)driver;
Boolean sent = js.executeScript("return typeof(gaHitSent) !== 'undefined' && gaHitSent");
</code>```

Body:
I have the following piece of HTML code:

I want to test if "go('send', 'pageview');" is present in that particular piece of code.

I've tried the following, but that doesn't seem to be working:

String header = driver.findElement(By.xpath("//head[@'script'")).getText();
Assert.assertTrue(header.contains("go('send', 'pageview');"));

Does anybody know how I can get Selenium Webdriver to check for the presence of "go('send', 'pageview');" in a Script Tag in the Head of a webpage? GetText doesn't seem to be working as it's a script...

Body:
Selenium has the same security restrictions as a browser, and you can't view JavaScript source through the DOM API.

You can see if the page view was sent by using a hitCallback, like:

window.gaHitSent = false;
ga('send', 'pageview', {
  'hitCallback': function() {
    window.gaHitSent = true;
  }
});

You can then check the variable with Selenium.  I'm not a Java developer, so I'm following http://www.guru99.com/execute-javascript-selenium-webdriver.html:

JavascriptExecutor js = (JavascriptExecutor)driver;
Boolean sent = js.executeScript("return typeof(gaHitSent) !== 'undefined' && gaHitSent");


来源: stackexchange

问:
Get int user input in java using delimiters and hasNext?
```<code>public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    in.useDelimiter(", "); // using delimiter ", "

    int i = 1;
    while(in.hasNextInt()){
        i = in.nextInt();
        System.out.println(i);
    }
}
</code>```

I am trying to get the input from console, but this code is
not printing last integer
How can I solve this problem. I don't want to use split and save the result in an array.

答: With Scanner.useDelimiter, the string after your last input integer should match the delimiter pattern, for example with your pattern if you give "1, 3, 5, 6, " you will get 1 3 5 6 as output but if you give "1, 3, 5, 6" you will not get the last integer.

ContentLicense: CC BY-SA 3.0

Body:
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    in.useDelimiter(", "); // using delimiter ", "

    int i = 1;
    while(in.hasNextInt()){
        i = in.nextInt();
        System.out.println(i);
    }
}

I am trying to get the input from console, but this code is
not printing last integer
How can I solve this problem. I don't want to use split and save the result in an array.


问:
Ruby On Rails 4.2 End Of Life
Has an End Of Life date been decided on for Rails 4.2? I am trying to determine when is the deadline for upgrading my product to Rails 5 before there is no more support for the product and thus there will be a security risk if I remain on that version. Thank you.</p>

答:
It appears that the answer regarding Rails 4.2 EOL is already answered on http://rubyonrails.org/maintenance/. The key points are:

"New features are only added to the master branch and will not be made available in patch releases."

"Only the latest release series will receive bug fixes."

"For major security issues, the current release series, the next most recent one, and the last additional major series will receive patches and new versions."

"For minor security issues, the current release series and the next most recent one will receive patches and new versions."

In addition, specifically to Rails 4.2, the release notes for Rails 5.1.0.rc1 states that Rails 4.2 will only receive severe security fixes, otherwise Rails 4.x is unsupported.

Title: Ruby On Rails 4.2 End Of Life


问:
session times out despite activity in an app built with Spring boot and embedded jetty
We have the following:

Java 8 web app developed with Spring Boot and embedded Jetty.

The UI for the app is built using react.

The backend exposes multiple REST APIs via Jersey.

The authentication is done using SAML with Okta as the IDP. We use spring-security-saml-core for SAML authentication.

The Java app is fronted by Nginx for SSL termination but this issue is reproducible without Nginx too.

The issue we have been noticing is that the user session times-out after the session timeout time despite user activity. Following is an excerpt of the application.properties related to session and JSESSIONID cookie:

```<code>    # Session #
    server.session.cookie.domain=domain.example.com
    server.session.cookie.http-only=true
    server.session.cookie.max-age=-1
    server.session.cookie.name=JSESSIONID
    server.session.cookie.path=/
    server.session.cookie.secure=true
    server.session.persistent=false
    server.session.timeout=900
    server.session.tracking-modes=cookie

    # Custom #
    auth.cookie-max-age=900
</code>```

The cookie-mag-age above dictates the lifespan of other cookies we create to store other user details, e.g user id. Following code gets called when Okta sends back the assertion on valid auth. This is a custom class extended from SavedRequestAwareAuthenticationSuccessHandler

```<code>@Override
public void onAuthenticationSuccess(
        final HttpServletRequest request,
        final HttpServletResponse response,
        final Authentication authentication)
                throws ServletException, IOException {

    HttpSession session = request.getSession(true);
    Object credentials = authentication.getCredentials();
    if (credentials instanceof SAMLCredential) {
        SAMLCredential samlCredential = (SAMLCredential) credentials;
        NameID nameId = samlCredential.getNameID();
        if (nameId != null) {
            String nameIdValue = nameId.getValue();
            UserDetail userDetail = userManager.getUserByName(nameIdValue, false);
            if(userDetail != null) {
                session.setAttribute(Constants.SESSION_USERID_FIELD, userDetail.getId());
                String token = csrfTokenManager.getTokenFromSession(request);
                if(token == null) {
                    token = csrfTokenManager.generateAndSaveToken(request, response);
                    response.addHeader(CsrfTokenManager.TOKEN_HEADER_NAME, token);
                }
                Cookie idCookie = AuthUtil.createCookie(
                        Constants.SESSION_USERID_FIELD,
                        userDetail.getId(),
                        appConfig.getCookieMaxAge(), true);
                response.addCookie(idCookie);
            }
        }
    }

    getRedirectStrategy().sendRedirect(request, response,
            appConfig.getAuthSuccessRedirectUrl());
}
</code>```

We call the REST APIs from Javascript using isomorphic fetch as follows:

```<code>export const fetchAllProjects = () => {
    return dispatch => {
        dispatch(requestAllProjects())
        return fetch(`/rest/private/v1/projects`, {
            credentials: 'same-origin'
        })
            .then(errorMessageUtil.handleErrors)
            .then(response => response.json())
            .then(json => dispatch(receiveAllProjects(json)))
            .catch(error => errorMessageUtil.dispatchError(error, dispatch, appActions.displayBadRequestMessage))
    }
}
</code>```

The credentials: 'same-origin', sends all the cookies to the backend including the JESESSIONID and the other cookies set above. We have an authentication filter that checks for valid session and not sends 401

```<code>@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;

    HttpSession session = httpServletRequest.getSession(false);
    if(session == null)  {
        this.sendUnauthorizedResponse(httpServletResponse);
    } else {
        String userIdFromCookie = null;
        Cookie[] cookies = httpServletRequest.getCookies();
        for(Cookie cookie : cookies) {
            if(Constants.SESSION_USERID_FIELD.equals(cookie.getName())) {
                userIdFromCookie = cookie.getValue();
                break;
            }
        }
        String userId = (String)session.getAttribute(Constants.SESSION_USERID_FIELD);
        if(userIdFromCookie != null && userId != null
                && userId.equals(userIdFromCookie)) {
            HeaderMapRequestWrapper requestWrapper = new HeaderMapRequestWrapper(httpServletRequest);
            requestWrapper.addHeader(Constants.USERID_HEADER_NAME, userId);
            chain.doFilter(requestWrapper, httpServletResponse);
        } else {
            this.sendUnauthorizedResponse(httpServletResponse);
        }
    }
}
</code>```

I am sure, we are not doing something right because the timeout time for the session is for the inactivity.

One other question is, do calls to the REST APIs qualify as valid activity for session time-out to extend?

答:
Found the problem with my logic. The code above tries to get the userId from the cookie and the userId from the session and then compare and if not matched, redirect the user to login.

The issue was the timeout time for the session and the cookie expiry time, auth.cookie-max-age=900, were same so even though the session was active because of activity, the cookie was getting expired and userId values didn't match.

My approach is to increase the max age of the cookie to a bigger value, so UI can keep sending the cookies with valid values and if the session really expires due to inactivity, its the userId value from the session that will be null and the user will need to re-login.

Body:
We have the following:

Java 8 web app developed with Spring Boot and embedded Jetty.

The UI for the app is built using react.

The backend exposes multiple REST APIs via Jersey.

The authentication is done using SAML with Okta as the IDP. We use spring-security-saml-core for SAML authentication.

The Java app is fronted by Nginx for SSL termination but this issue is reproducible without Nginx too.

The issue we have been noticing is that the user session times-out after the session timeout time despite user activity. Following is an excerpt of the application.properties related to session and JSESSIONID cookie:

    # Session #
    server.session.cookie.domain=domain.example.com
    server.session.cookie.http-only=true
    server.session.cookie.max-age=-1
    server.session.cookie.name=JSESSIONID
    server.session.cookie.path=/
    server.session.cookie.secure=true
    server.session.persistent=false
    server.session.timeout=900
    server.session.tracking-modes=cookie

    # Custom #
    auth.cookie-max-age=900

The cookie-mag-age above dictates the lifespan of other cookies we create to store other user details, e.g user id. Following code gets called when Okta sends back the assertion on valid auth. This is a custom class extended from SavedRequestAwareAuthenticationSuccessHandler

@Override
public void onAuthenticationSuccess(
        final HttpServletRequest request,
        final HttpServletResponse response,
        final Authentication authentication)
                throws ServletException, IOException {

    HttpSession session = request.getSession(true);
    Object credentials = authentication.getCredentials();
    if (credentials instanceof SAMLCredential) {
        SAMLCredential samlCredential = (SAMLCredential) credentials;
        NameID nameId = samlCredential.getNameID();
        if (nameId != null) {
            String nameIdValue = nameId.getValue();
            UserDetail userDetail = userManager.getUserByName(nameIdValue, false);
            if(userDetail != null) {
                session.setAttribute(Constants.SESSION_USERID_FIELD, userDetail.getId());
                String token = csrfTokenManager.getTokenFromSession(request);
                if(token == null) {
                    token = csrfTokenManager.generateAndSaveToken(request, response);
                    response.addHeader(CsrfTokenManager.TOKEN_HEADER_NAME, token);
                }
                Cookie idCookie = AuthUtil.createCookie(
                        Constants.SESSION_USERID_FIELD,
                        userDetail.getId(),
                        appConfig.getCookieMaxAge(), true);
                response.addCookie(idCookie);
            }
        }
    }

    getRedirectStrategy().sendRedirect(request, response,
            appConfig.getAuthSuccessRedirectUrl());
}

We call the REST APIs from Javascript using isomorphic fetch as follows:

export const fetchAllProjects = () => {
    return dispatch => {
        dispatch(requestAllProjects())
        return fetch(`/rest/private/v1/projects`, {
            credentials: 'same-origin'
        })
            .then(errorMessageUtil.handleErrors)
            .then(response => response.json())
            .then(json => dispatch(receiveAllProjects(json)))
            .catch(error => errorMessageUtil.dispatchError(error, dispatch, appActions.displayBadRequestMessage))
    }
}

The credentials: 'same-origin', sends all the cookies to the backend including the JESESSIONID and the other cookies set above. We have an authentication filter that checks for valid session and not sends 401

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;

    HttpSession session = httpServletRequest.getSession(false);
    if(session == null)  {
        this.sendUnauthorizedResponse(httpServletResponse);
    } else {
        String userIdFromCookie = null;
        Cookie[] cookies = httpServletRequest.getCookies();
        for(Cookie cookie : cookies) {
            if(Constants.SESSION_USERID_FIELD.equals(cookie.getName())) {
                userIdFromCookie = cookie.getValue();
                break;
            }
        }
        String userId = (String)session.getAttribute(Constants.SESSION_USERID_FIELD);
        if(userIdFromCookie != null && userId != null
                && userId.equals(userIdFromCookie)) {
            HeaderMapRequestWrapper requestWrapper = new HeaderMapRequestWrapper(httpServletRequest);
            requestWrapper.addHeader(Constants.USERID_HEADER_NAME, userId);
            chain.doFilter(requestWrapper, httpServletResponse);
        } else {
            this.sendUnauthorizedResponse(httpServletResponse);
        }
    }
}

I am sure, we are not doing something right because the timeout time for the session is for the inactivity.

One other question is, do calls to the REST APIs qualify as valid activity for session time-out to extend?


问:
How to compute a power of a power using recursion?
I've recently been looking into recursion and it's been very confusing. I'm trying to write a java program which uses recursion to generate the result of a base number to a power, which also has a height of how many exponents the base has. For example, a base of two with a power of 3 and a height of 3 will result:

(((2^3)^3)^3)

Here is my (very flawed) code:

```<code>    public static void main(String[] args) {
    System.out.println(exponentWithHeight(2, 2, 3));
}

public static int exponentWithHeight(int base, int power, int height) {
    if (power < 0 || height < 0) {
        throw new IllegalArgumentException("Check input values.");
    }
    if (power == 0) {
        return 1;
    } else {
        return (base * height * exponentWithHeight(base, power - 1, height - 1));
    }
}
</code>```

I'm really not sure how to go about getting my desired output; As I said this is really confusing and new to me. Can someone help explain how to go about doing this?

答:
It is a double recursion, both on height and power.

Note that if it would make sense to have the values cached somewhere, since exponentWithHeight(base, power, 0) will be recalculated multiple times.

The result with this code is 256:

```<code>public static void main(String[] args) {
    System.out.println(exponentWithHeight(2, 2, 3));
}

public static int exponentWithHeight(int base, int power, int height) {
    if (power < 0 || height < 0) {
        throw new IllegalArgumentException("Invalid Input; Check power and/or height value.");
    }
    if (base == 0) {
        return 0;
    }
    if (height == 0) {
        return calcPower(base, power);
    } else {
        return exponentWithHeight(calcPower(base, power), power, height - 1);
    }
}

public static int calcPower(int base, int power) {
    if (power == 0) {
        return 1;
    }
    return base * power(base, power - 1);
}
</code>```

Body:
I've recently been looking into recursion and it's been very confusing. I'm trying to write a java program which uses recursion to generate the result of a base number to a power, which also has a height of how many exponents the base has. For example, a base of two with a power of 3 and a height of 3 will result:

(((2^3)^3)^3)

Here is my (very flawed) code:

    public static void main(String[] args) {
    System.out.println(exponentWithHeight(2, 2, 3));
}

public static int exponentWithHeight(int base, int power, int height) {
    if (power < 0 || height < 0) {
        throw new IllegalArgumentException("Check input values.");
    }
    if (power == 0) {
        return 1;
    } else {
        return (base * height * exponentWithHeight(base, power - 1, height - 1));
    }
}

I'm really not sure how to go about getting my desired output; As I said this is really confusing and new to me. Can someone help explain how to go about doing this?

Body:
It is a double recursion, both on height and power.

Note that if it would make sense to have the values cached somewhere, since exponentWithHeight(base, power, 0) will be recalculated multiple times.

The result with this code is 256:

public static void main(String[] args) {
    System.out.println(exponentWithHeight(2, 2, 3));
}

public static int exponentWithHeight(int base, int power, int height) {
    if (power < 0 || height < 0) {
        throw new IllegalArgumentException("Invalid Input; Check power and/or height value.");
    }
    if (base == 0) {
        return 0;
    }
    if (height == 0) {
        return calcPower(base, power);
    } else {
        return exponentWithHeight(calcPower(base, power), power, height - 1);
    }
}

public static int calcPower(int base, int power) {
    if (power == 0) {
        return 1;
    }
    return base * power(base, power - 1);
}


问:
How to remove link when used to create PDF in laravel dompdf?
I just make a simple html page and write content to it. I created a link when I click on that link the content of the page will converted into PDF file, I have implemented this using laravel dompdf -> https://github.com/barryvdh/laravel-dompdf . Now, My problem is that all things doing good, but the PDF that is generated after click will shows that link in the PDF file. How to remove that button from PDF file.
My code :

My controller : ItemController.php

```<code>class ItemController extends Controller
    {
    public function pdfview(Request $request)
    {

        if($request->has('download')){
            $pdf = \PDF::loadView('pdfview');
            return $pdf->download('pdfview.pdf');
            //return $pdf->stream();
        }

        return view('pdfview');
    }
}
</code>```

My route: web.php

```<code>Route::get('/pdfview',array('as'=>'pdfview','uses'=>'ItemController@pdfview'));
</code>```

My view : pdfview.blade.php

```<code><body>
 <div class="container">
   <div class="rows"><br/>
   <a href="{{ route('pdfview',['download'=>'pdf']) }}"> Click to PDF </a>
      <h2 align="Center"> What is PDF ? </h2><br/><br/>
      <h4> Portable Document Format (PDF) is a file format used to present and exchange documents reliably, independent of software, hardware, or operating system.</h4>
  </div>
 </div>
</body>
</code>```

Help me, If you understand my problem. Thanks

答:
Pass a variable to the view, i.e:

```<code>$pdf = \PDF::loadView('pdfview', array('pdf' => true));
...
return view('pdfview', array('pdf' => false));
</code>```

and check the variable in the template:

```<code>@if(! $pdf )
   <a href="{{ route('pdfview',['download'=>'pdf']) }}"> Click to PDF </a>
@endif
</code>```

Body:
I just make a simple html page and write content to it. I created a link when I click on that link the content of the page will converted into PDF file, I have implemented this using laravel dompdf -> https://github.com/barryvdh/laravel-dompdf . Now, My problem is that all things doing good, but the PDF that is generated after click will shows that link in the PDF file. How to remove that button from PDF file.
My code :

My controller : ItemController.php

class ItemController extends Controller
    {
    public function pdfview(Request $request)
    {

        if($request->has('download')){
            $pdf = \PDF::loadView('pdfview');
            return $pdf->download('pdfview.pdf');
            //return $pdf->stream();
        }

        return view('pdfview');
    }
}

My route: web.php

Route::get('/pdfview',array('as'=>'pdfview','uses'=>'ItemController@pdfview'));

My view : pdfview.blade.php

   'pdf']) }}"> Click to PDF

 What is PDF ?

 Portable Document Format (PDF) is a file format used to present and exchange documents reliably, independent of software, hardware, or operating system.

Help me, If you understand my problem. Thanks

Body:
Pass a variable to the view, i.e:

$pdf = \PDF::loadView('pdfview', array('pdf' => true));
...
return view('pdfview', array('pdf' => false));

and check the variable in the template:

@if(! $pdf )
   <a href="{{ route('pdfview',['download'=>'pdf']) }}"> Click to PDF </a>
@endif


问:
How to check if word exist in a string with php
How can i check if word exist in a string.

I tried strpos but not with good results.

My example
if(strpos($string, 'As ') !== false)

And string is :

"Asthmatic is ruff"

Then it gives me true, as the As is included.

But i need to find word

"As" or "as"

Example:

"As i walked" or "If it was as"

答:
```<code>if (preg_match('/\b(as)\b/i', $string, $matches)) {
    //$string had the word 'as' in it
}
</code>```

Use preg_match to match regular expressions.
\b indicates a word boundary. i at the end indicates the match will be case-insensitive

Body:
if (preg_match('/\b(as)\b/i', $string, $matches)) {
    //$string had the word 'as' in it
}

Use preg_match to match regular expressions.
\b indicates a word boundary. i at the end indicates the match will be case-insensitive


问:
Combining Shapefiles with # of rows based on a matching column
I'm used to working in ArcMap, and am trying to translate an analysis into R.

I have 4 shapefiles that represent 4 assessment parameters. Each shapefile has a unique column called Parameter_Score. Each shapefile also has a column with the Parcel_ID associated with that pixel. Each shapefile has a different number of rows because each parameter affected certain parcels differently, and thus has different Parcels listed.

I would like to create one shapefile that has the Parcel_ID information, as well as each Parameter's unique score. My problem is that the shapefiles all have a different number of elements. I'd like to merge them all together based on the Parcel_ID, and have values of 0 populate the scores for Parcels that are not included in a certain parameter.

For example, I'd like to take these two shapefiles:

and create a new shapefile/merge them into this:

I've looked into merge, join, etc, but none of them allow me to match Parcels that match and add 0 values to parcels that don't match. Instead, rows are either deleted, or all the second parameter's values are turned to 0. Does someone know of a function that can do what I'm asking? Thanks so much!

答:
Was looking at this and just noticed that it might be an R question, even though it is not tagged as such. That seems to be what the text says.

There are lots of ways to do this in R, with powerful flexible packages like data.table or dplyr. But it is easy just using base-R too:

```<code>s1 <- data.frame(Parcel_ID=c(110,112,115,116),Score=c(1,2,3,4))
s2 <- data.frame(Parcel_ID=c(110,112,234,235),Score=c(5,6,7,8))

s3 <- merge(s1,s2,by="Parcel_ID",all=TRUE)
s3[is.na(s3)] <- 0
s3
</code>```

Yielding:

```<code>  Parcel_ID Score.x Score.y
1       110       1       5
2       112       2       6
3       115       3       0
4       116       4       0
5       234       0       7
6       235       0       8
</code>```

Body:
Was looking at this and just noticed that it might be an R question, even though it is not tagged as such. That seems to be what the text says.

There are lots of ways to do this in R, with powerful flexible packages like data.table or dplyr. But it is easy just using base-R too:

s1 <- data.frame(Parcel_ID=c(110,112,115,116),Score=c(1,2,3,4))
s2 <- data.frame(Parcel_ID=c(110,112,234,235),Score=c(5,6,7,8))

s3 <- merge(s1,s2,by="Parcel_ID",all=TRUE)
s3[is.na(s3)] <- 0
s3

Yielding:

  Parcel_ID Score.x Score.y
1       110       1       5
2       112       2       6
3       115       3       0
4       116       4       0
5       234       0       7
6       235       0       8


问:
Is VBA name property is case sensitive
I have observed that below line of code works on one machine but not on other even though both machines have same office 2007 versions.

```<code>strName = folderObj.Name
</code>```

But when I convert property from '.Name' to '.name' then it is observed to be working on machine on which it was not working earlier. Below are some of sample code lines for which I am encountering issues. Per my observation where ever earlier I mentioned .Name is failing on another machine:

```<code>strName = folderObj.Name
Application.ActiveWorkbook.Name
</code>```

Is there any setting which we may need to perform to ignore case for .name.

答:
I remember dealing with a very similar issue a while back, but can't remember the specifics. I want say look for any references in your code to variables, properties, etc that are named 'name' (lower case) and change them to 'Name' (pascal case). I have a vague memory of VBA getting confused when you use different casing for items of the same name. (For the lack of a more technical explanation.) I know this doesn't really address the fact that it runs on one computer but not another, but it's worth a look.

Btw, when you say "it's not working" what error are you getting?

ContentLicense: CC BY-SA 2.5

Title: Is VBA name property is case sensitive

Body:
I have observed that below line of code works on one machine but not on other even though both machines have same office 2007 versions.

strName = folderObj.Name

But when I convert property from '.Name' to '.name' then it is observed to be working on machine on which it was not working earlier. Below are some of sample code lines for which I am encountering issues. Per my observation where ever earlier I mentioned .Name is failing on another machine:

strName = folderObj.Name
Application.ActiveWorkbook.Name

Is there any setting which we may need to perform to ignore case for .name.


问:
Conditional jump or move depends on uninitialised value(s) in C
I have this function that return a parsed_url structure that looks like this

```<code>typedef struct url_parser_url {
    char *protocol;
    char *host;
    int port;
    char *path;
    char *query_string;
    int host_exists;
} url_parser_url_t;

url_parser_url_t *parsed_url;
parsed_url = (url_parser_url_t *) malloc(sizeof(url_parser_url_t));
parse_url(address, true, parsed_url);
printf("parsed_url->path = %s\n", parsed_url->path);
</code>```

The parse_url function looks like

```<code>int parse_url(char *url, bool verify_host, url_parser_url_t *parsed_url) {
    char *local_url = (char *) malloc(sizeof(char) * (strlen(url) + 1));
    char *token;
    char *token_host;
    char *host_port;
    char *token_ptr;
    char *host_token_ptr;

    char *path = NULL;
    strcpy(local_url, url);

    token = strtok_r(local_url, ":", &token_ptr);
    parsed_url->protocol = (char *) malloc(sizeof(char) * strlen(token) + 1);
    strcpy(parsed_url->protocol, token);

    token = strtok_r(NULL, "/", &token_ptr);
    if (token) {
        host_port = (char *) malloc(sizeof(char) * (strlen(token) + 1));
        strcpy(host_port, token);
    } else {
        host_port = (char *) malloc(sizeof(char) * 1);
        strcpy(host_port, "");
    }

    token_host = strtok_r(host_port, ":", &host_token_ptr);
    if (token_host) {
        parsed_url->host = (char *) malloc(
                sizeof(char) * strlen(token_host) + 1);
        strcpy(parsed_url->host, token_host);

        if (verify_host) {
            struct hostent *host;
            host = gethostbyname(parsed_url->host);
            if (host != NULL) {
                parsed_url->host_exists = 1;
            } else {
                parsed_url->host_exists = 0;
            }
        } else {
            parsed_url->host_exists = -1;
        }
    } else {
        parsed_url->host_exists = -1;
        parsed_url->host = NULL;
    }

    token_host = strtok_r(NULL, ":", &host_token_ptr);
    if (token_host)
        parsed_url->port = atoi(token_host);
    else
        parsed_url->port = 0;

    token_host = strtok_r(NULL, ":", &host_token_ptr);
    assert(token_host == NULL);

    token = strtok_r(NULL, "?", &token_ptr);
    parsed_url->path = NULL;
    if (token) {
        path = (char *) realloc(path, sizeof(char) * (strlen(token) + 2));
        strcpy(path, "/");
        strcat(path, token);
        parsed_url->path = (char *) malloc(sizeof(char) * strlen(path) + 1);
        strncpy(parsed_url->path, path, strlen(path));
        free(path);
    } else {
        parsed_url->path = (char *) malloc(sizeof(char) * 2);
        strcpy(parsed_url->path, "/");
    }

    token = strtok_r(NULL, "?", &token_ptr);
    if (token) {
        parsed_url->query_string = (char *) malloc(
                sizeof(char) * (strlen(token) + 1));
        strncpy(parsed_url->query_string, token, strlen(token));
    } else {
        parsed_url->query_string = NULL;
    }

    token = strtok_r(NULL, "?", &token_ptr);
    assert(token == NULL);

    free(local_url);
    free(host_port);
    return 0;
}
</code>```

The problem is when I call the function parse_url and then I use the parsed_url->path member it throws me this segmentation fault

```<code>==16647== Conditional jump or move depends on uninitialised value(s)
</code>```

Can anyone to explain me what is happening and why ? Thank you

答:
And there it is.  Although it is supposed to be a safer alternative to strcpy(), the strncpy() has a nasty wart.  The standard says:

The strncpy function copies not more than n characters (characters that follow a null character are not copied) from the array pointed to by s2 to the array pointed to by s1.

(C2011 7.24.2.4/2), and note 308 clarifies that

Thus, if there is no null character in the first n characters of the array pointed to by s2, the result will not be null-terminated.

The code that is ultimately responsible for your particular valgrind complaint is this:

```<code>    strncpy(parsed_url->path, path, strlen(path));
</code>```

Since by definition there cannot be a null character within the first strlen(path) characters of path, that strncpy() reliably fails to ensure that the copy is null-terminated.  You have at least one other instance of the same problem in your code.

Since you seem to take sufficient care to ensure that enough space is available, one solution would be to switch from strncpy() to strcpy().  That would also be more efficient, because you would avoid duplicate calls to strlen().

As I noted in comments, however, if you're willing to rely on POSIX's strdup(), then that's cleaner than strlen() + malloc() + str[n]cpy(), and has the same semantics (you take responsibility for freeing the memory allocated for the copy).  You wouldn't have even had the opportunity to make these errors if you had made your copies that way.

Body:
I have this function that return a parsed_url structure that looks like this

typedef struct url_parser_url {
    char *protocol;
    char *host;
    int port;
    char *path;
    char *query_string;
    int host_exists;
} url_parser_url_t;

url_parser_url_t *parsed_url;
parsed_url = (url_parser_url_t *) malloc(sizeof(url_parser_url_t));
parse_url(address, true, parsed_url);
printf("parsed_url->path = %s\n", parsed_url->path);

The parse_url function looks like

int parse_url(char *url, bool verify_host, url_parser_url_t *parsed_url) {
    char *local_url = (char *) malloc(sizeof(char) * (strlen(url) + 1));
    char *token;
    char *token_host;
    char *host_port;
    char *token_ptr;
    char *host_token_ptr;

    char *path = NULL;
    strcpy(local_url, url);

    token = strtok_r(local_url, ":", &token_ptr);
    parsed_url->protocol = (char *) malloc(sizeof(char) * strlen(token) + 1);
    strcpy(parsed_url->protocol, token);

    token = strtok_r(NULL, "/", &token_ptr);
    if (token) {
        host_port = (char *) malloc(sizeof(char) * (strlen(token) + 1));
        strcpy(host_port, token);
    } else {
        host_port = (char *) malloc(sizeof(char) * 1);
        strcpy(host_port, "");
    }

    token_host = strtok_r(host_port, ":", &host_token_ptr);
    if (token_host) {
        parsed_url->host = (char *) malloc(
                sizeof(char) * strlen(token_host) + 1);
        strcpy(parsed_url->host, token_host);

        if (verify_host) {
            struct hostent *host;
            host = gethostbyname(parsed_url->host);
            if (host != NULL) {
                parsed_url->host_exists = 1;
            } else {
                parsed_url->host_exists = 0;
            }
        } else {
            parsed_url->host_exists = -1;
        }
    } else {
        parsed_url->host_exists = -1;
        parsed_url->host = NULL;
    }

    token_host = strtok_r(NULL, ":", &host_token_ptr);
    if (token_host)
        parsed_url->port = atoi(token_host);
    else
        parsed_url->port = 0;

    token_host = strtok_r(NULL, ":", &host_token_ptr);
    assert(token_host == NULL);

    token = strtok_r(NULL, "?", &token_ptr);
    parsed_url->path = NULL;
    if (token) {
        path = (char *) realloc(path, sizeof(char) * (strlen(token) + 2));
        strcpy(path, "/");
        strcat(path, token);
        parsed_url->path = (char *) malloc(sizeof(char) * strlen(path) + 1);
        strncpy(parsed_url->path, path, strlen(path));
        free(path);
    } else {
        parsed_url->path = (char *) malloc(sizeof(char) * 2);
        strcpy(parsed_url->path, "/");
    }

    token = strtok_r(NULL, "?", &token_ptr);
    if (token) {
        parsed_url->query_string = (char *) malloc(
                sizeof(char) * (strlen(token) + 1));
        strncpy(parsed_url->query_string, token, strlen(token));
    } else {
        parsed_url->query_string = NULL;
    }

    token = strtok_r(NULL, "?", &token_ptr);
    assert(token == NULL);

    free(local_url);
    free(host_port);
    return 0;
}

The problem is when I call the function parse_url and then I use the parsed_url->path member it throws me this segmentation fault

==16647== Conditional jump or move depends on uninitialised value(s)

Can anyone to explain me what is happening and why ? Thank you

Body:
And there it is.  Although it is supposed to be a safer alternative to strcpy(), the strncpy() has a nasty wart.  The standard says:

The strncpy function copies not more than n characters (characters that follow a null character are not copied) from the array pointed to by s2 to the array pointed to by s1.

(C2011 7.24.2.4/2), and note 308 clarifies that

Thus, if there is no null character in the first n characters of the array pointed to by s2, the result will not be null-terminated.

The code that is ultimately responsible for your particular valgrind complaint is this:

    strncpy(parsed_url->path, path, strlen(path));

Since by definition there cannot be a null character within the first strlen(path) characters of path, that strncpy() reliably fails to ensure that the copy is null-terminated.  You have at least one other instance of the same problem in your code.

Since you seem to take sufficient care to ensure that enough space is available, one solution would be to switch from strncpy() to strcpy().  That would also be more efficient, because you would avoid duplicate calls to strlen().

As I noted in comments, however, if you're willing to rely on POSIX's strdup(), then that's cleaner than strlen() + malloc() + str[n]cpy(), and has the same semantics (you take responsibility for freeing the memory allocated for the copy).  You wouldn't have even had the opportunity to make these errors if you had made your copies that way.


问:
Javascript slider not working when using AJAX to open up the page
I am trying to open a HTML page using ajax on click of a button.

And the HTML page that I am opening has a javascript slider in it, which works fine it I open up the page by itself, but the slider stops working if I open it using my index.html via ajax.

I am putting my the code for both pages for you to see:

The index.html (which is using the ajax to open "SayHello.html") code is below:

```<code>    <script language="JavaScript" type="text/javascript">
        //Gets the browser specific XmlHttpRequest Object
        function getXmlHttpRequestObject() {
            if (window.XMLHttpRequest) {
                return new XMLHttpRequest(); //Not IE
            } else if(window.ActiveXObject) {
                return new ActiveXObject("Microsoft.XMLHTTP"); //IE
            } else {
                //Display your error message here.
                alert("Your browser doesn't support the XmlHttpRequest object.  Better upgrade.");
            }
        }
        //Get our browser specific XmlHttpRequest object.
        var receiveReq = getXmlHttpRequestObject();
        //Initiate the asyncronous request.
        function sayHello(x) {

            //If our XmlHttpRequest object is not in the middle of a request, start the new asyncronous call.
            if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
                //Setup the connection as a GET call to SayHello.html.
                //True explicity sets the request to asyncronous (default).
                if(x==3)
                    receiveReq.open("GET", 'SayHello.html', true);
                else if(x==4)
                    receiveReq.open("GET", 'SayHello2.html', true);
                //Set the function that will be called when the XmlHttpRequest objects state changes.
                receiveReq.onreadystatechange = handleSayHello;
                //Make the actual request.
                receiveReq.send(null);
            }
        }
        //Called every time our XmlHttpRequest objects state changes.
        function handleSayHello() {
            //Check to see if the XmlHttpRequests state is finished.
            if (receiveReq.readyState == 4) {
                //Set the contents of our span element to the result of the asyncronous call.
                document.getElementById('span_result').innerHTML = receiveReq.responseText;
            }
        }
    </script>
<table class="nav">
      <tr><th>sd</th></tr>
      <tr><td><a href="javascript:sayHello(3);">Say Hello</a></td></tr>
      <tr><td><a href="javascript:sayHello(4);">Turvey, Kevin</a></</td></tr>
      <tr><td>Mbogo, Arnold</td></tr>
      <tr><td>Shakespeare, Bill</td></tr>
    </table>
    <br /><br />

    <span id="span_result"></span>
</code>```

And the SayHello.html code is below:

```<code>    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<!-- Mirrored from woorktuts.110mb.com/art_of_reuse_code/index4.html by HTTrack Website Copier/3.x [XR&CO'2010], Tue, 14 Feb 2012 15:07:17 GMT -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Horizontal Carousel</title>
<script type="text/javascript" src="mootools.svn.js"></script>
<script type="text/javascript">
window.addEvent('domready', function(){
      var totIncrement      = 0;
      var increment         = 212;
      var maxRightIncrement = increment*(-6);
      var fx = new Fx.Style('slider-list', 'margin-left', {
                duration: 1000,
                transition: Fx.Transitions.Back.easeInOut,
                wait: true
       });

       //-------------------------------------
      // EVENTS for the button "previous"
      $('previous').addEvents({
          'click' : function(event){
          if(totIncrement<0){
                    totIncrement = totIncrement+increment;
                    fx.stop()
                    fx.start(totIncrement);
                }
            }
      });

       //-------------------------------------
      // EVENTS for the button "next"
      $('next').addEvents({
          'click' : function(event){
             if(totIncrement>maxRightIncrement){
                 totIncrement = totIncrement-increment;
                fx.stop()
                fx.start(totIncrement);
            }
          }
      })

});
    </script>

<style type="text/css">
    body{
        font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif; font-size:11px; color:#333333;
        background-color:#FFFFFF;
    }
    a:link, a:visited, a:hover{color:#0066CC; text-decoration:none;}
    #slider-stage{width:632px; overflow:auto; overflow-x:hidden; overflow-y:hidden; height:200px; margin:0 auto;}
    #slider-buttons{width:632px; margin:0 auto;}
    #slider-list{width:2000px; border:0; margin:0; padding:0; left:400px;}
    #slider-list li{
        list-style:none;
        margin:0;
        padding:0;
        border:0;
        margin-right:4px;
        padding:4px;
        background:#DEDEDE;
        float:left;
        width:200px;
        height:200px;
        }
</style>
</head>

<body>
<h3>More tutorial here: <a href="http://woork.blogspot.com/">http://woork.blogspot.com</a></h3>
<p>Click on Previous or Next Button </p>
<div id="slider-stage">
<ul id="slider-list">
    <li id="l1">Box 1</li>
    <li id="l2">Box 2</li>
    <li id="l3">Box 3</li>
    <li id="l4">Box 4</li>
    <li id="l5">Box 5</li>
    <li id="l6">Box 6</li>
    <li id="l7">Box 7</li>
    <li id="l8">Box 8</li>
    <li id="l9">Box 9</li>
    <li id="l10">Box 10</li>
</ul>
</div>
<div id="slider-buttons">
<a href="#" id="previous">Previous</a> | <a href="#" id="next">Next</a>
</div>
</body>

<!-- Mirrored from woorktuts.110mb.com/art_of_reuse_code/index4.html by HTTrack Website Copier/3.x [XR&CO'2010], Tue, 14 Feb 2012 15:07:20 GMT -->
</html>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "ht$
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga$
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-1497692-16");
pageTracker._trackPageview();
} catch(err) {}</script>
</code>```

Please help.

Regards
Zeeshan

答:
I had a similar problem and solved it with the .ajaxComplete() method. So:

```<code>$(document).ajaxComplete(function(){
    //do something

});
</code>```

Body:
I am trying to open a HTML page using ajax on click of a button.

And the HTML page that I am opening has a javascript slider in it, which works fine it I open up the page by itself, but the slider stops working if I open it using my index.html via ajax.

I am putting my the code for both pages for you to see:

The index.html (which is using the ajax to open "SayHello.html") code is below:

sd

Say Hello

Turvey, Kevin</

Mbogo, Arnold

Shakespeare, Bill

And the SayHello.html code is below:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Horizontal Carousel</title>

More tutorial here: http://woork.blogspot.com

Click on Previous or Next Button

Box 1

Box 2

Box 3

Box 4

Box 5

Box 6

Box 7

Box 8

Box 9

Box 10

Previous | Next

Please help.

Regards
Zeeshan

Body:
I had a similar problem and solved it with the .ajaxComplete() method. So:

$(document).ajaxComplete(function(){
    //do something

});


问:
How can I access this field of a temp table?
I have a complex query that stuffs stuff into temp tables, then reads and combines those temp tables. At the end of this, I have this code:

```<code>    Select distinct CSDirector=r1.CSDirector,
        Category = r1.Category,
        Segment = r1.Segment,
        r1.unit,
        NumUnits=r1.NumUnits,
        NumUnitsLast=r2.NumUnits,
        MonthSales=r1.MonthSales,
        MonthSalesLast=r2.MonthSales,
        MonthPerc = (r1.MonthSales - r2.MonthSales) / case when isnull(r2.MonthSales,0) = 0 then 1 else r2.MonthSales end,
        YTDSales = r1.YTDSales,
        YTDSalesLast = r2.YTDSales,
        YTDPerc= (r1.YTDSales - r2.YTDSales) / case when isnull(r2.YTDSales,0) = 0 then 1 else r2.YTDSales end,
        ProjSales = r1.ProjSales,
        YTDProjSales = r1.YTDProjSales,
        YTDBudgetPerc = r1.YTDBudgetPerc,
        NewBiz = isnull((Select NewBiz from MasterUnitsProjSales where Unit = r1.unit and Cyear=@Cyear),0)
into    #CombinedYears
From #CurrentYear r1 inner join #PriorYear r2 on r1.unit=r2.unit
order by NewBiz,r1.Unit

declare @Unit varchar(30);
declare @paramdate datetime;
set @paramdate = convert(datetime,convert(char(4),@CYear)
                +right('0'+convert(varchar(2),@CMonth),2)
                +'01')

IF OBJECT_ID('tempdb.dbo.#Units', 'U') IS NOT NULL
DROP TABLE #Units

select distinct unit
into #Units
from ReportingMonthlySales;

select
    u.Unit
  , New      = sum(case when ccl.Subcategory = 'New'      then rms.MonthlySales else 0 end)
  , Assumed  = sum(case when ccl.Subcategory = 'Assumed'  then rms.MonthlySales else 0 end)
  , Existing = sum(case when ccl.Subcategory = 'Existing' then rms.MonthlySales else 0 end)
  , Organic  = sum(case when ccl.Subcategory = 'Organic'  then rms.MonthlySales else 0 end)
into    #CategorizedUnits
from #Units u
join CustomerCategoryLog   ccl on u.Unit = ccl.Unit and @paramdate >= ccl.begindate and @paramdate <= ccl.enddate
join ReportingMonthlySales rms on u.Unit = rms.Unit and rms.cyear  = @cyear and rms.cmonth = @cmonth
group by u.unit;

-- Now combine combined years and categorized units
select CY.CSDirector, CY.Category, CY.Segment, CY._Unit,
       CU.New, CU.Assumed, CU.Existing, CU.Organic,
       CY.NumUnits, CY.NumUnitsLast, CY.MonthSales, CY.MonthSalesLast,
       CY.MonthPerc, CY.YTDSales, CY.YTDSalesLast, CY.YTDPerc,
       CY.ProjSales, CY.YTDProjSales, CY.YTDBudgetPerc, CY.NewBiz
from #CombinedYears CY
left join #CategorizedUnits CU on CU.Unit = CY.Unit
</code>```

...but it fails with "Error 207: Invalid column name 'r1'." on this line:

```<code>select CY.CSDirector, CY.Category, CY.Segment, CY.r1.unit,
</code>```

So, I thought perhaps I needed to change this:

```<code>Select distinct CSDirector=r1.CSDirector,
        Category = r1.Category,
        Segment = r1.Segment,
        r1.unit,
</code>```

...to this:

```<code>Select distinct CSDirector=r1.CSDirector,
        Category = r1.Category,
        Segment = r1.Segment,
        _Unit = r1.unit,
</code>```

...along with this:

```<code>select CY.CSDirector, CY.Category, CY.Segment, CY.r1.unit,
</code>```

...to this:

```<code>select CY.CSDirector, CY.Category, CY.Segment, CY._Unit,
</code>```

...but when I try that, I get, "Error 207: Invalid column name '_Unit'." on this line:

```<code>select CY.CSDirector, CY.Category, CY.Segment, CY._Unit,
</code>```

So how can I grab the "Unit" value from the #CombinedYears table?

UPDATE

This also fails:

```<code>--select CY.CSDirector, CY.Category, CY.Segment, CY.r1.unit,
--select CY.CSDirector, CY.Category, CY.Segment, CY._Unit,
select CY.CSDirector, CY.Category, CY.Segment, CY.unit,
</code>```

...with "Error 207: Invalid column name 'unit'."

UPDATE 2

This works:

```<code>--CREATE PROCEDURE [dbo].[sp_ReportMonthlySalesEnhanced]
--  @CYear  int;
--  @CMonth int;
--as

declare @CYear  int = 2017; -- remove before above is uncommented
declare @CMonth int = 3; -- " "

IF OBJECT_ID('tempdb.dbo.#Units', 'U') IS NOT NULL
DROP TABLE #Units

IF OBJECT_ID('tempdb.dbo.#CurrentYear', 'U') IS NOT NULL
DROP TABLE #CurrentYear

IF OBJECT_ID('tempdb.dbo.#PriorYear', 'U') IS NOT NULL
DROP TABLE #PriorYear

IF OBJECT_ID('tempdb.dbo.#CombinedYears', 'U') IS NOT NULL
DROP TABLE #CombinedYears

IF OBJECT_ID('tempdb.dbo.#CategorizedUnits', 'U') IS NOT NULL
Drop Table #CategorizedUnits

Select  CSDirector,
        Category,
        Segment,
        r1.unit,
        NumUnits=isnull((Select sum(NumUnits) from ReportingMonthlySales where unit=r1.unit and
cyear=r1.cyear and cmonth = @Cmonth),0),
        MonthSales=isnull((Select sum(MonthlySales) from ReportingMonthlySales where unit=r1.unit and
cyear=r1.cyear and cmonth = @Cmonth),0.00),
        YTDSales = (Select sum(MonthlySales) From  ReportingMonthlySales where unit=r1.unit and
cyear=r1.cyear and cmonth <= @Cmonth),
        ProjSales =  (Select ProjectedSales from MasterUnitsProjSales where UNit = r1.Unit and
Cyear=r1.cyear),
        YTDProjSales = (Select ProjectedSales from MasterUnitsProjSales where UNit = r1.Unit and
Cyear=r1.cyear) / 12 * @Cmonth,
        YTDBudgetPerc = (Select sum(MonthlySales) From  ReportingMonthlySales where unit=r1.unit and
cyear=r1.cyear and cmonth <= @Cmonth) /
            case when (Select ProjectedSales from MasterUnitsProjSales where UNit = r1.Unit and
Cyear=r1.cyear) = 0 then 1 else ((Select ProjectedSales from MasterUnitsProjSales where UNit = r1.Unit and
Cyear=r1.cyear) / 12 * @Cmonth) end
into    #CurrentYear
From    MasterUnitsProjSales r1
where   r1.Cyear=@CYear
order by r1.NewBiz,r1.Unit

Select  CSDirector,
        Category,
        Segment,
        r1.unit,
        NumUnits=isnull((Select sum(NumUnits) from ReportingMonthlySales where unit=r1.unit and
cyear=r1.cyear - 1 and cmonth = @Cmonth),0),
        MonthSales=isnull((Select sum(MonthlySales) from ReportingMonthlySales where unit=r1.unit and
cyear=r1.cyear - 1 and cmonth = @Cmonth),0.00),
        YTDSales = (Select sum(MonthlySales) From  ReportingMonthlySales where unit=r1.unit and
cyear=r1.cyear - 1 and cmonth <= @Cmonth),
        ProjSales =  (Select ProjectedSales from MasterUnitsProjSales where UNit = r1.Unit and
Cyear=r1.cyear - 1 ),
        YTDProjSales = (Select ProjectedSales from MasterUnitsProjSales where UNit = r1.Unit and
Cyear=r1.cyear - 1) / 12 * @Cmonth,
        YTDBudgetPerc = (Select sum(MonthlySales) From  ReportingMonthlySales where unit=r1.unit and
cyear=r1.cyear - 1 and cmonth <= @Cmonth) /
            case when (Select ProjectedSales from MasterUnitsProjSales where UNit = r1.Unit and
Cyear=r1.cyear - 1 ) = 0 then 1 else ((Select ProjectedSales from MasterUnitsProjSales where UNit = r1.Unit and
Cyear=r1.cyear - 1) / 12 * @CMonth) end
into    #PriorYear
From    MasterUnitsProjSales r1
where r1.Cyear=@CYear
order by r1.NewBiz,r1.Unit

Select distinct CSDirector=r1.CSDirector,
        Category = r1.Category,
        Segment = r1.Segment,
        r1.unit [_Unit],
        NumUnits=r1.NumUnits,
        NumUnitsLast=r2.NumUnits,
        MonthSales=r1.MonthSales,
        MonthSalesLast=r2.MonthSales,
        MonthPerc = (r1.MonthSales - r2.MonthSales) / case when isnull(r2.MonthSales,0) = 0 then 1 else r2.MonthSales end,
        YTDSales = r1.YTDSales,
        YTDSalesLast = r2.YTDSales,
        YTDPerc= (r1.YTDSales - r2.YTDSales) / case when isnull(r2.YTDSales,0) = 0 then 1 else r2.YTDSales end,
        ProjSales = r1.ProjSales,
        YTDProjSales = r1.YTDProjSales,
        YTDBudgetPerc = r1.YTDBudgetPerc,
        NewBiz = isnull((Select NewBiz from MasterUnitsProjSales where Unit = r1.unit and Cyear=@Cyear),0)
into    #CombinedYears
From #CurrentYear r1 inner join #PriorYear r2 on r1.unit=r2.unit
order by NewBiz,r1.Unit

declare @Unit varchar(30);
declare @paramdate datetime;
set @paramdate = convert(datetime,convert(char(4),@CYear)
                +right('0'+convert(varchar(2),@CMonth),2)
                +'01')

select distinct unit
into #Units
from ReportingMonthlySales;

select
    u.Unit
  , New      = sum(case when ccl.Subcategory = 'New'      then rms.MonthlySales else 0 end)
  , Assumed  = sum(case when ccl.Subcategory = 'Assumed'  then rms.MonthlySales else 0 end)
  , Existing = sum(case when ccl.Subcategory = 'Existing' then rms.MonthlySales else 0 end)
  , Organic  = sum(case when ccl.Subcategory = 'Organic'  then rms.MonthlySales else 0 end)
into    #CategorizedUnits
from #Units u
join CustomerCategoryLog   ccl on u.Unit = ccl.Unit and @paramdate >= ccl.begindate and @paramdate <= ccl.enddate
join ReportingMonthlySales rms on u.Unit = rms.Unit and rms.cyear  = @cyear and rms.cmonth = @cmonth
group by u.unit;

-- Now combine combined years and categorized units
select CY.CSDirector, CY.Category, CY.Segment, CY._Unit,
       CU.New, CU.Assumed, CU.Existing, CU.Organic,
       CY.NumUnits, CY.NumUnitsLast, CY.MonthSales, CY.MonthSalesLast,
       CY.MonthPerc, CY.YTDSales, CY.YTDSalesLast, CY.YTDPerc,
       CY.ProjSales, CY.YTDProjSales, CY.YTDBudgetPerc, CY.NewBiz
from #CombinedYears CY
left join #CategorizedUnits CU on CU.Unit = CY._Unit
</code>```

答:
for a start...

```<code>select * from #CombinedYears
</code>```

should be able to identify the field name
or to explicitly name the field... [_Unit] on the query below.

```<code>  Select distinct CSDirector=r1.CSDirector,
        Category = r1.Category,
        Segment = r1.Segment,
        r1.unit [_Unit],   -- here
        NumUnits=r1.NumUnits,
        NumUnitsLast=r2.NumUnits,
        MonthSales=r1.MonthSales,
        MonthSalesLast=r2.MonthSales,
        MonthPerc = (r1.MonthSales - r2.MonthSales) / case when isnull(r2.MonthSales,0) = 0 then 1 else r2.MonthSales end,
        YTDSales = r1.YTDSales,
        YTDSalesLast = r2.YTDSales,
        YTDPerc= (r1.YTDSales - r2.YTDSales) / case when isnull(r2.YTDSales,0) = 0 then 1 else r2.YTDSales end,
        ProjSales = r1.ProjSales,
        YTDProjSales = r1.YTDProjSales,
        YTDBudgetPerc = r1.YTDBudgetPerc,
        NewBiz = isnull((Select NewBiz from MasterUnitsProjSales where Unit = r1.unit and Cyear=@Cyear),0)
into    #CombinedYears
From #CurrentYear r1 inner join #PriorYear r2 on r1.unit=r2.unit
order by NewBiz,r1.Unit
</code>```

Body:
I have a complex query that stuffs stuff into temp tables, then reads and combines those temp tables. At the end of this, I have this code:

    Select distinct CSDirector=r1.CSDirector,
        Category = r1.Category,
        Segment = r1.Segment,
        r1.unit,
        NumUnits=r1.NumUnits,
        NumUnitsLast=r2.NumUnits,
        MonthSales=r1.MonthSales,
        MonthSalesLast=r2.MonthSales,
        MonthPerc = (r1.MonthSales - r2.MonthSales) / case when isnull(r2.MonthSales,0) = 0 then 1 else r2.MonthSales end,
        YTDSales = r1.YTDSales,
        YTDSalesLast = r2.YTDSales,
        YTDPerc= (r1.YTDSales - r2.YTDSales) / case when isnull(r2.YTDSales,0) = 0 then 1 else r2.YTDSales end,
        ProjSales = r1.ProjSales,
        YTDProjSales = r1.YTDProjSales,
        YTDBudgetPerc = r1.YTDBudgetPerc,
        NewBiz = isnull((Select NewBiz from MasterUnitsProjSales where Unit = r1.unit and Cyear=@Cyear),0)
into    #CombinedYears
From #CurrentYear r1 inner join #PriorYear r2 on r1.unit=r2.unit
order by NewBiz,r1.Unit

declare @Unit varchar(30);
declare @paramdate datetime;
set @paramdate = convert(datetime,convert(char(4),@CYear)
                +right('0'+convert(varchar(2),@CMonth),2)
                +'01')

IF OBJECT_ID('tempdb.dbo.#Units', 'U') IS NOT NULL
DROP TABLE #Units

select distinct unit
into #Units
from ReportingMonthlySales;

select
    u.Unit
  , New      = sum(case when ccl.Subcategory = 'New'      then rms.MonthlySales else 0 end)
  , Assumed  = sum(case when ccl.Subcategory = 'Assumed'  then rms.MonthlySales else 0 end)
  , Existing = sum(case when ccl.Subcategory = 'Existing' then rms.MonthlySales else 0 end)
  , Organic  = sum(case when ccl.Subcategory = 'Organic'  then rms.MonthlySales else 0 end)
into    #CategorizedUnits
from #Units u
join CustomerCategoryLog   ccl on u.Unit = ccl.Unit and @paramdate >= ccl.begindate and @paramdate <= ccl.enddate
join ReportingMonthlySales rms on u.Unit = rms.Unit and rms.cyear  = @cyear and rms.cmonth = @cmonth
group by u.unit;

-- Now combine combined years and categorized units
select CY.CSDirector, CY.Category, CY.Segment, CY._Unit,
       CU.New, CU.Assumed, CU.Existing, CU.Organic,
       CY.NumUnits, CY.NumUnitsLast, CY.MonthSales, CY.MonthSalesLast,
       CY.MonthPerc, CY.YTDSales, CY.YTDSalesLast, CY.YTDPerc,
       CY.ProjSales, CY.YTDProjSales, CY.YTDBudgetPerc, CY.NewBiz
from #CombinedYears CY
left join #CategorizedUnits CU on CU.Unit = CY.Unit

...but it fails with "Error 207: Invalid column name 'r1'." on this line:

select CY.CSDirector, CY.Category, CY.Segment, CY.r1.unit,

So, I thought perhaps I needed to change this:

Select distinct CSDirector=r1.CSDirector,
        Category = r1.Category,
        Segment = r1.Segment,
        r1.unit,

...to this:

Select distinct CSDirector=r1.CSDirector,
        Category = r1.Category,
        Segment = r1.Segment,
        _Unit = r1.unit,

...along with this:

select CY.CSDirector, CY.Category, CY.Segment, CY.r1.unit,

...to this:

select CY.CSDirector, CY.Category, CY.Segment, CY._Unit,

...but when I try that, I get, "Error 207: Invalid column name '_Unit'." on this line:

select CY.CSDirector, CY.Category, CY.Segment, CY._Unit,

So how can I grab the "Unit" value from the #CombinedYears table?

UPDATE

This also fails:

--select CY.CSDirector, CY.Category, CY.Segment, CY.r1.unit,
--select CY.CSDirector, CY.Category, CY.Segment, CY._Unit,
select CY.CSDirector, CY.Category, CY.Segment, CY.unit,

...with "Error 207: Invalid column name 'unit'."

UPDATE 2

This works:

--CREATE PROCEDURE [dbo].[sp_ReportMonthlySalesEnhanced]
--  @CYear  int;
--  @CMonth int;
--as

declare @CYear  int = 2017; -- remove before above is uncommented
declare @CMonth int = 3; -- " "

IF OBJECT_ID('tempdb.dbo.#Units', 'U') IS NOT NULL
DROP TABLE #Units

IF OBJECT_ID('tempdb.dbo.#CurrentYear', 'U') IS NOT NULL
DROP TABLE #CurrentYear

IF OBJECT_ID('tempdb.dbo.#PriorYear', 'U') IS NOT NULL
DROP TABLE #PriorYear

IF OBJECT_ID('tempdb.dbo.#CombinedYears', 'U') IS NOT NULL
DROP TABLE #CombinedYears

IF OBJECT_ID('tempdb.dbo.#CategorizedUnits', 'U') IS NOT NULL
Drop Table #CategorizedUnits

Select  CSDirector,
        Category,
        Segment,
        r1.unit,
        NumUnits=isnull((Select sum(NumUnits) from ReportingMonthlySales where unit=r1.unit and
cyear=r1.cyear and cmonth = @Cmonth),0),
        MonthSales=isnull((Select sum(MonthlySales) from ReportingMonthlySales where unit=r1.unit and
cyear=r1.cyear and cmonth = @Cmonth),0.00),
        YTDSales = (Select sum(MonthlySales) From  ReportingMonthlySales where unit=r1.unit and
cyear=r1.cyear and cmonth <= @Cmonth),
        ProjSales =  (Select ProjectedSales from MasterUnitsProjSales where UNit = r1.Unit and
Cyear=r1.cyear),
        YTDProjSales = (Select ProjectedSales from MasterUnitsProjSales where UNit = r1.Unit and
Cyear=r1.cyear) / 12 * @Cmonth,
        YTDBudgetPerc = (Select sum(MonthlySales) From  ReportingMonthlySales where unit=r1.unit and
cyear=r1.cyear and cmonth <= @Cmonth) /
            case when (Select ProjectedSales from MasterUnitsProjSales where UNit = r1.Unit and
Cyear=r1.cyear) = 0 then 1 else ((Select ProjectedSales from MasterUnitsProjSales where UNit = r1.Unit and
Cyear=r1.cyear) / 12 * @Cmonth) end
into    #CurrentYear
From    MasterUnitsProjSales r1
where   r1.Cyear=@CYear
order by r1.NewBiz,r1.Unit

Select  CSDirector,
        Category,
        Segment,
        r1.unit,
        NumUnits=isnull((Select sum(NumUnits) from ReportingMonthlySales where unit=r1.unit and
cyear=r1.cyear - 1 and cmonth = @Cmonth),0),
        MonthSales=isnull((Select sum(MonthlySales) from ReportingMonthlySales where unit=r1.unit and
cyear=r1.cyear - 1 and cmonth = @Cmonth),0.00),
        YTDSales = (Select sum(MonthlySales) From  ReportingMonthlySales where unit=r1.unit and
cyear=r1.cyear - 1 and cmonth <= @Cmonth),
        ProjSales =  (Select ProjectedSales from MasterUnitsProjSales where UNit = r1.Unit and
Cyear=r1.cyear - 1 ),
        YTDProjSales = (Select ProjectedSales from MasterUnitsProjSales where UNit = r1.Unit and
Cyear=r1.cyear - 1) / 12 * @Cmonth,
        YTDBudgetPerc = (Select sum(MonthlySales) From  ReportingMonthlySales where unit=r1.unit and
cyear=r1.cyear - 1 and cmonth <= @Cmonth) /
            case when (Select ProjectedSales from MasterUnitsProjSales where UNit = r1.Unit and
Cyear=r1.cyear - 1 ) = 0 then 1 else ((Select ProjectedSales from MasterUnitsProjSales where UNit = r1.Unit and
Cyear=r1.cyear - 1) / 12 * @CMonth) end
into    #PriorYear
From    MasterUnitsProjSales r1
where r1.Cyear=@CYear
order by r1.NewBiz,r1.Unit

Select distinct CSDirector=r1.CSDirector,
        Category = r1.Category,
        Segment = r1.Segment,
        r1.unit [_Unit],
        NumUnits=r1.NumUnits,
        NumUnitsLast=r2.NumUnits,
        MonthSales=r1.MonthSales,
        MonthSalesLast=r2.MonthSales,
        MonthPerc = (r1.MonthSales - r2.MonthSales) / case when isnull(r2.MonthSales,0) = 0 then 1 else r2.MonthSales end,
        YTDSales = r1.YTDSales,
        YTDSalesLast = r2.YTDSales,
        YTDPerc= (r1.YTDSales - r2.YTDSales) / case when isnull(r2.YTDSales,0) = 0 then 1 else r2.YTDSales end,
        ProjSales = r1.ProjSales,
        YTDProjSales = r1.YTDProjSales,
        YTDBudgetPerc = r1.YTDBudgetPerc,
        NewBiz = isnull((Select NewBiz from MasterUnitsProjSales where Unit = r1.unit and Cyear=@Cyear),0)
into    #CombinedYears
From #CurrentYear r1 inner join #PriorYear r2 on r1.unit=r2.unit
order by NewBiz,r1.Unit

declare @Unit varchar(30);
declare @paramdate datetime;
set @paramdate = convert(datetime,convert(char(4),@CYear)
                +right('0'+convert(varchar(2),@CMonth),2)
                +'01')

select distinct unit
into #Units
from ReportingMonthlySales;

select
    u.Unit
  , New      = sum(case when ccl.Subcategory = 'New'      then rms.MonthlySales else 0 end)
  , Assumed  = sum(case when ccl.Subcategory = 'Assumed'  then rms.MonthlySales else 0 end)
  , Existing = sum(case when ccl.Subcategory = 'Existing' then rms.MonthlySales else 0 end)
  , Organic  = sum(case when ccl.Subcategory = 'Organic'  then rms.MonthlySales else 0 end)
into    #CategorizedUnits
from #Units u
join CustomerCategoryLog   ccl on u.Unit = ccl.Unit and @paramdate >= ccl.begindate and @paramdate <= ccl.enddate
join ReportingMonthlySales rms on u.Unit = rms.Unit and rms.cyear  = @cyear and rms.cmonth = @cmonth
group by u.unit;

-- Now combine combined years and categorized units
select CY.CSDirector, CY.Category, CY.Segment, CY._Unit,
       CU.New, CU.Assumed, CU.Existing, CU.Organic,
       CY.NumUnits, CY.NumUnitsLast, CY.MonthSales, CY.MonthSalesLast,
       CY.MonthPerc, CY.YTDSales, CY.YTDSalesLast, CY.YTDPerc,
       CY.ProjSales, CY.YTDProjSales, CY.YTDBudgetPerc, CY.NewBiz
from #CombinedYears CY
left join #CategorizedUnits CU on CU.Unit = CY._Unit

Body:
for a start...

select * from #CombinedYears

should be able to identify the field name
or to explicitly name the field... [_Unit] on the query below.

  Select distinct CSDirector=r1.CSDirector,
        Category = r1.Category,
        Segment = r1.Segment,
        r1.unit [_Unit],   -- here
        NumUnits=r1.NumUnits,
        NumUnitsLast=r2.NumUnits,
        MonthSales=r1.MonthSales,
        MonthSalesLast=r2.MonthSales,
        MonthPerc = (r1.MonthSales - r2.MonthSales) / case when isnull(r2.MonthSales,0) = 0 then 1 else r2.MonthSales end,
        YTDSales = r1.YTDSales,
        YTDSalesLast = r2.YTDSales,
        YTDPerc= (r1.YTDSales - r2.YTDSales) / case when isnull(r2.YTDSales,0) = 0 then 1 else r2.YTDSales end,
        ProjSales = r1.ProjSales,
        YTDProjSales = r1.YTDProjSales,
        YTDBudgetPerc = r1.YTDBudgetPerc,
        NewBiz = isnull((Select NewBiz from MasterUnitsProjSales where Unit = r1.unit and Cyear=@Cyear),0)
into    #CombinedYears
From #CurrentYear r1 inner join #PriorYear r2 on r1.unit=r2.unit
order by NewBiz,r1.Unit


问:
ng-init assign values conditionally
I found an unexpected behavior of ng-init. According to the doc The ngInit directive allows you to evaluate an expression in the current scope. So I'm trying to assign a value in a variable conditionally. Here is my code

```<code><a ng-href="#" ng-click="flag = !flag;" ng-init="data = (flag == true) ? 'Value For Success' : 'Value for false'; "> {{data}}</a>
</code>```

If in expression I pass false then false value will be assigned to variable and if I pass true, then true value will be assigned. I can achieve it by calling a function but I thought if I could assign value in a single line then why I need to write a function for that. Please suggest what I'm missing ?

Check my fiddle

答:
```<code>ng-bind="{1:'Text One', 2:'Text Two',3:'Text Three'}[variable]"
</code>```

variable, In this case it is numerical, according to the value it contains, it will load the text ...

Title: ng-init assign values conditionally

Body:
I found an unexpected behavior of ng-init. According to the doc The ngInit directive allows you to evaluate an expression in the current scope. So I'm trying to assign a value in a variable conditionally. Here is my code

 {{data}}

If in expression I pass false then false value will be assigned to variable and if I pass true, then true value will be assigned. I can achieve it by calling a function but I thought if I could assign value in a single line then why I need to write a function for that. Please suggest what I'm missing ?

Check my fiddle

Body:
ng-bind="{1:'Text One', 2:'Text Two',3:'Text Three'}[variable]"

variable, In this case it is numerical, according to the value it contains, it will load the text ...


问:
Creating a view creates a table
I have a view that depends on a materialized view.
I have their definitions in a .sql file that cascade drops the materialized view.

```<code>DROP MATERIALIZED VIEW IF EXISTS mat_view_name CASCADE;

CREATE MATERIALIZED VIEW mat_view_name AS ...;

CREATE VIEW view_name AS
    SELECT ... FROM (
        SELECT ... FROM mat_view_name
        UNION
        SELECT ... from another_table
    )
;
</code>```

I changed a SELECT statement inside the materialized view and when I execute the sql script in the migration, it changes my initial view to a table in my structure.sql.

Here's the new code I get in my structure.sql

```<code>CREATE TABLE view_name (
    ...
);

ALTER TABLE ONLY view_name REPLICA IDENTITY NOTHING;

CREATE RULE "_RETURN" AS
ON SELECT TO view_name DO INSTEAD  SELECT .....;
</code>```

If I rollback the migration I get the original code back :

```<code>CREATE VIEW view_name AS...
</code>```

I only added two JOIN statements in a select inside the materialized view.

My database version is 9.6.2.

Do you know why this is happening ?
Is it a performance issue, and PG decides to use this instead of a classic view ?
How to force it to create a view ?

答:
I assume you are getting this script from a dump or a backup of your database.

Materialized views are essentially tables created in a similar fashion to CREATE TABLE AS with the sql being stored in the database so it can be refreshed.

The default behaviour when dumping a materialized view is to dump as a table.

CREATE MATERIALIZED VIEW: documentation

Title: Creating a view creates a table

Body:
I have a view that depends on a materialized view.
I have their definitions in a .sql file that cascade drops the materialized view.

DROP MATERIALIZED VIEW IF EXISTS mat_view_name CASCADE;

CREATE MATERIALIZED VIEW mat_view_name AS ...;

CREATE VIEW view_name AS
    SELECT ... FROM (
        SELECT ... FROM mat_view_name
        UNION
        SELECT ... from another_table
    )
;

I changed a SELECT statement inside the materialized view and when I execute the sql script in the migration, it changes my initial view to a table in my structure.sql.

Here's the new code I get in my structure.sql

CREATE TABLE view_name (
    ...
);

ALTER TABLE ONLY view_name REPLICA IDENTITY NOTHING;

CREATE RULE "_RETURN" AS
ON SELECT TO view_name DO INSTEAD  SELECT .....;

If I rollback the migration I get the original code back :

CREATE VIEW view_name AS...

I only added two JOIN statements in a select inside the materialized view.

My database version is 9.6.2.

Do you know why this is happening ?
Is it a performance issue, and PG decides to use this instead of a classic view ?
How to force it to create a view ?


问:
Get string array from Pymongo query
I need to get an array with the values from the field 'colname'. I can't return a Cursor, just the array of values.

Is there a way to query this array without having to loop the Cursor? I feel this is a waste of processing resources.

Right now I'm doing this:

```<code>from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')
headers = client['headers']

entomo = headers.entomo

entomo_data = entomo.find()
entomo_array = []
for data in entomo_data:
    entomo_array.append(data['colname'])
</code>```

Then I return the entomo_array.

答:
If the 'colname' field has distinct values or if you do not care about duplicate values you can use distinct function. For your example:</p>

```<code>entomo_array = entomo.find().distinct('colname')
</code>```

Title: Get string array from Pymongo query

Body:
I need to get an array with the values from the field 'colname'. I can't return a Cursor, just the array of values.

Is there a way to query this array without having to loop the Cursor? I feel this is a waste of processing resources.

Right now I'm doing this:

from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')
headers = client['headers']

entomo = headers.entomo

entomo_data = entomo.find()
entomo_array = []
for data in entomo_data:
    entomo_array.append(data['colname'])

Then I return the entomo_array.

Body:
If the 'colname' field has distinct values or if you do not care about duplicate values you can use distinct function. For your example:

entomo_array = entomo.find().distinct('colname')


问:
How can I tell which way a scrolling pane is scrolling in javascript?
I have the following jquery to handle scroll events on a particular div and write some content:

```<code>$('#myDiv').scroll(function(eventData) {
  if(eventData.isGoingUp)
    $('#myDiv').prepend('<p>Going up.</p>');
  else
    $('#myDiv').append('<p>Going down.</p>');
});
</code>```

Obviously, evt.isGoingUp doesn't actually exist. Is there anything that does exist that can accomplish this logic?

答:
You could store the previous scroll value and check whether the value has increased or decreased:</p>

```<code>var prev = $('#myDiv').scrollTop();
$('#myDiv').scroll(function(eventData) {
  var cur = $(this).scrollTop();
  if (cur > prev) {
    // scrolled down
  } else {
    // scrolled up
  }
  prev = cur;
});
</code>```

Body:
I have the following jquery to handle scroll events on a particular div and write some content:

$('#myDiv').scroll(function(eventData) {
  if(eventData.isGoingUp)
    $('#myDiv').prepend('
Going up.
');
  else
    $('#myDiv').append('
Going down.
');
});

Obviously, evt.isGoingUp doesn't actually exist. Is there anything that does exist that can accomplish this logic?

Body:
You could store the previous scroll value and check whether the value has increased or decreased:

var prev = $('#myDiv').scrollTop();
$('#myDiv').scroll(function(eventData) {
  var cur = $(this).scrollTop();
  if (cur > prev) {
    // scrolled down
  } else {
    // scrolled up
  }
  prev = cur;
});


答: Try stripos instead (the case insensitive version of strpos)

Title: How to check if word exist in a string with php

Body:
How can i check if word exist in a string.

I tried strpos but not with good results.

My example
if(strpos($string, 'As ') !== false)

And string is :

"Asthmatic is ruff"

Then it gives me true, as the As is included.

But i need to find word

"As" or "as"

Example:

"As i walked" or "If it was as"


问:
Google App Engine KeyProperty
what's the benefits of KeyProperty ? if i can connect  two entity using user_id and id </p>

```<code>   class User(ndb.Model):

        name = ndb.StringProperty()

   class Attend(ndb.Model):
        user_id = ndb.IntegerProperty()
        date = ndb.DateProperty()

User(id=1,name="xyz)
Attend(user_id = 1, date = "xyz")
</code>```

答:
There are a couple of minor benefits of storing a KeyProperty over an ID:

It is easier to do x.user_key.get() than ndb.Key(Attend, x.user_id).get()

The key is fully specified so there is no doubt about the entity it refers to but for the ID you also need to know the entity type.

These are both really minor so you can do either one.  I sometimes store keys and sometimes store IDs based on other factors.

Title: Google App Engine KeyProperty

Body:
what's the benefits of KeyProperty ? if i can connect  two entity using user_id and id

   class User(ndb.Model):

        name = ndb.StringProperty()

   class Attend(ndb.Model):
        user_id = ndb.IntegerProperty()
        date = ndb.DateProperty()

User(id=1,name="xyz)
Attend(user_id = 1, date = "xyz")


问:
How do I use a local macro referencing a variable?
I am trying to create a macro in Stata that will set a variable name for me to reference later on in my do file. Essentially, I am trying to replace a variable name with a local macro.

An example dataset is the following:

```<code>ID   Indicator1 Indicator2    Amount
1    1            0             10
2    0            1             2
3    0            0             3
4    1            0             5
5    1            1             20
</code>```

My data has a number of indicators but I only have to work with only one indicator at a time. I want to put the indicator that I'm currently working with into a macro, so that I have to change only one thing in my entire code.

My code is:

```<code>local myvar = "Indicator"
</code>```

What I want is to be able to use something like this:

```<code>sum Amount if "`myvar'" == 1
</code>```

However, I keep getting an error that says "type mismatch" even though myvar has been defined.

答:
By typing any of these

```<code>local myvar "Indicator"
</code>```

or

```<code>local myvar = "Indicator"
</code>```

or

```<code>local myvar Indicator
</code>```

you place the literal text Indicator inside a local macro with the name myvar. The " " in this example are delimiters and, as the last example shows, dispensable in this case. So far, so good.

However, the use of " " in your summarize statement indicates to Stata that you intend the result of evaluating (dereferencing) the local macro to be treated as a  literal string; and a literal string can only be compared with another literal string or the contents of a string variable, indicated by its name. Hence the error message type mismatch.

So, this would be legal:

```<code>sum Amount if "`myvar'" == "1"
</code>```

Nothing would happen, because "indicator" is not equal to "1", so the statement would be false (in every observation for which it was tried). But
Stata would have no problem with the syntax.

But it is not what you want. You want the local macro contents to be treated as a variable name, which means writing

```<code>sum Amount if `myvar' == 1
</code>```

The fact that the local macro has been defined is immaterial here; it is being used improperly.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create a macro in Stata that will set a variable name for me to reference later on in my do file. Essentially, I am trying to replace a variable name with a local macro.

An example dataset is the following:

ID   Indicator1 Indicator2    Amount
1    1            0             10
2    0            1             2
3    0            0             3
4    1            0             5
5    1            1             20

My data has a number of indicators but I only have to work with only one indicator at a time. I want to put the indicator that I'm currently working with into a macro, so that I have to change only one thing in my entire code.

My code is:

local myvar = "Indicator"

What I want is to be able to use something like this:

sum Amount if "`myvar'" == 1

However, I keep getting an error that says "type mismatch" even though myvar has been defined.

Body:
By typing any of these

local myvar "Indicator"

or

local myvar = "Indicator"

or

local myvar Indicator

you place the literal text Indicator inside a local macro with the name myvar. The " " in this example are delimiters and, as the last example shows, dispensable in this case. So far, so good.

However, the use of " " in your summarize statement indicates to Stata that you intend the result of evaluating (dereferencing) the local macro to be treated as a  literal string; and a literal string can only be compared with another literal string or the contents of a string variable, indicated by its name. Hence the error message type mismatch.

So, this would be legal:

sum Amount if "`myvar'" == "1"

Nothing would happen, because "indicator" is not equal to "1", so the statement would be false (in every observation for which it was tried). But
Stata would have no problem with the syntax.

But it is not what you want. You want the local macro contents to be treated as a variable name, which means writing

sum Amount if `myvar' == 1

The fact that the local macro has been defined is immaterial here; it is being used improperly.


问:
Assistance with SqlConnection
I am working on trying to connect my project to a database, which I am fairly new when it comes to working with databases. When I run the program I get a server error stating that login failed for user. I am working on a sign up form that when filled out will populate the fields in the database after clicking create account.

This is my back end code:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class SignUp : System.Web.UI.Page
{

    SqlConnection conn = new SqlConnection();

    protected void Page_Load(object sender, EventArgs e)
    {
        conn.ConnectionString = @"Data Source=184.168.47.13;Initial Catalog=portfoliobrown;User ID=crossfire19;Password=***********";
    //error occurs here    conn.Open();
    }

    public void ExecuteConnection()
    {

        SqlCommand Command = new SqlCommand("Insert into SignUp" + "(FirstName, LastName, Password, Email)values(@FirsName, @LastName, #Password, @Email)",conn);

        Command.Parameters.AddWithValue("@FirstName", FirstName.Text);
        Command.Parameters.AddWithValue("@LastName", LastName.Text);
        Command.Parameters.AddWithValue("@Password", Email.Text);
        Command.Parameters.AddWithValue("@Email", Password.Text);
        Command.ExecuteNonQuery();

        conn.Close();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        ExecuteConnection();
    }
}
</code>```

I have a table in the database. FirstName, LastName, Password, Email, Etc
Also my password and user name for the database should be correct, as when I test the connection it works just fine

Thanks for any help I would appreciate it.

答:
This is the connection string format I use, it was coded with VS 2010 and has been in production for 8 years now. First coded with VS 2008 upgraded to VS 2010 a few years ago.

```<code>connectionString="server=192.168.1.1;database=MyDb;uid=sa; pwd=Password" providerName="System.Data.SqlClient"
</code>```

Hope this helps.

R/
Prescott ....

Title: Assistance with SqlConnection

Body:
I am working on trying to connect my project to a database, which I am fairly new when it comes to working with databases. When I run the program I get a server error stating that login failed for user. I am working on a sign up form that when filled out will populate the fields in the database after clicking create account.

This is my back end code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class SignUp : System.Web.UI.Page
{

    SqlConnection conn = new SqlConnection();

    protected void Page_Load(object sender, EventArgs e)
    {
        conn.ConnectionString = @"Data Source=184.168.47.13;Initial Catalog=portfoliobrown;User ID=crossfire19;Password=***********";
    //error occurs here    conn.Open();
    }

    public void ExecuteConnection()
    {

        SqlCommand Command = new SqlCommand("Insert into SignUp" + "(FirstName, LastName, Password, Email)values(@FirsName, @LastName, #Password, @Email)",conn);

        Command.Parameters.AddWithValue("@FirstName", FirstName.Text);
        Command.Parameters.AddWithValue("@LastName", LastName.Text);
        Command.Parameters.AddWithValue("@Password", Email.Text);
        Command.Parameters.AddWithValue("@Email", Password.Text);
        Command.ExecuteNonQuery();

        conn.Close();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        ExecuteConnection();
    }
}

I have a table in the database. FirstName, LastName, Password, Email, Etc
Also my password and user name for the database should be correct, as when I test the connection it works just fine

Thanks for any help I would appreciate it.

Body:
This is the connection string format I use, it was coded with VS 2010 and has been in production for 8 years now. First coded with VS 2008 upgraded to VS 2010 a few years ago.

connectionString="server=192.168.1.1;database=MyDb;uid=sa; pwd=Password" providerName="System.Data.SqlClient"

Hope this helps.

R/
Prescott ....


问:
W/OpenGLRenderer: Points are too far apart
When constructing a vector that is an ellipse, I am getting this warning message in LogCat:

```<code>W/OpenGLRenderer: Points are too far apart 4.000000
</code>```

I am interested in knowing what exactly this means.  I noticed in the AOSP that there is a drawArc Method that throws this warning, however, it does not give a clear representation of what exactly is meant. Do I need to adjust my vector drawables?  Will I see any future errors or drawing mistakes from these warnings?  How can I get these warnings to subside?

AOSP Reference file

答:
The warning "Points are too far apart" means the "A" path command specifies an ellipse that's too small to form an arc between the endpoints. To handle this, the drawArc method enlarges the ellipse's size so that it can adequately form an arc between the endpoints.  To avoid the warning, you have to avoid such problematic "A" commands.

For example, the following path (specifying a 1x1 ellipse that's too small to go through the endpoints) will trigger this warning:

```<code>M10 10 A 1 1 0 1 1 5 5
</code>```

While the following path (specifying a 10x10 ellipse with the same endpoints) will not:

```<code>M10 10 A 10 10 0 1 1 5 5
</code>```

Body:
When constructing a vector that is an ellipse, I am getting this warning message in LogCat:

W/OpenGLRenderer: Points are too far apart 4.000000

I am interested in knowing what exactly this means.  I noticed in the AOSP that there is a drawArc Method that throws this warning, however, it does not give a clear representation of what exactly is meant. Do I need to adjust my vector drawables?  Will I see any future errors or drawing mistakes from these warnings?  How can I get these warnings to subside?

AOSP Reference file

Body:
The warning "Points are too far apart" means the "A" path command specifies an ellipse that's too small to form an arc between the endpoints. To handle this, the drawArc method enlarges the ellipse's size so that it can adequately form an arc between the endpoints.  To avoid the warning, you have to avoid such problematic "A" commands.

For example, the following path (specifying a 1x1 ellipse that's too small to go through the endpoints) will trigger this warning:

M10 10 A 1 1 0 1 1 5 5

While the following path (specifying a 10x10 ellipse with the same endpoints) will not:

M10 10 A 10 10 0 1 1 5 5


问:
Jackson JSON XML - different names when serializing to XML
I'd like to have different name for my element when it's serialized to XML (for example "fooXml") and different for JSON (for example "fooJson"). Is it possible?

I'm using XML annotations like:

```<code>@XmlElements({
    @XmlElement(type = Foo.class, name = "fooXml"),
    })
    private SortedSet<Foo> fooSet;
</code>```

I've tried already @JsonProperty, with without any luck.

I've also tried exporting it to getter method, like:

```<code>@XmlElement(type = Foo.class, name = "fooXml")
@JsonProperty(value = "fooJson")
public List<Foo> getFooList() {
    return new ArrayList<>(fooSet);
}
</code>```

But it's always ignoring JSON annotations and serializing to XML form (fooXml name).

How shall I do it?

edit: I'm using Jersey-json.

答:
Alright, I had a need for this same functionality and found a solution that works for this:

```<code>import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;

@JsonProperty("MyJsonName")
@JacksonXmlProperty(localName = "MyXmlName")
private MyProperty myProperty;
</code>```

Works for me, and myProperty will be in the 'MyJsonName' field in Json and the 'MyXmlName' in XML.

Body:
I'd like to have different name for my element when it's serialized to XML (for example "fooXml") and different for JSON (for example "fooJson"). Is it possible?

I'm using XML annotations like:

@XmlElements({
    @XmlElement(type = Foo.class, name = "fooXml"),
    })
    private SortedSet<Foo> fooSet;

I've tried already @JsonProperty, with without any luck.

I've also tried exporting it to getter method, like:

@XmlElement(type = Foo.class, name = "fooXml")
@JsonProperty(value = "fooJson")
public List<Foo> getFooList() {
    return new ArrayList<>(fooSet);
}

But it's always ignoring JSON annotations and serializing to XML form (fooXml name).

How shall I do it?

edit: I'm using Jersey-json.

Body:
Alright, I had a need for this same functionality and found a solution that works for this:

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;

@JsonProperty("MyJsonName")
@JacksonXmlProperty(localName = "MyXmlName")
private MyProperty myProperty;

Works for me, and myProperty will be in the 'MyJsonName' field in Json and the 'MyXmlName' in XML.


问:
Postgresql gem install pg 0.18.4 passes, bundle install fails
Mac OS El Capitan

Bundle install fails with:

```<code>compiling pg_connection.c
pg_connection.c:2394:3: warning: implicit declaration of function 'gettimeofday' is invalid in C99 [-Wimplicit-function-declaration]
                gettimeofday(&currtime, NULL);
                ^
1 warning generated.
compiling pg_copy_coder.c
compiling pg_errors.c
compiling pg_result.c
compiling pg_text_decoder.c
compiling pg_text_encoder.c
compiling pg_type_map.c
compiling pg_type_map_all_strings.c
compiling pg_type_map_by_class.c
compiling pg_type_map_by_column.c
compiling pg_type_map_by_mri_type.c
compiling pg_type_map_by_oid.c
compiling pg_type_map_in_ruby.c
compiling util.c
linking shared-object pg_ext.bundle
ld: file not found: dynamic_lookup
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [pg_ext.bundle] Error 1

make failed, exit code 2

Gem files will remain installed in /Users/jmintz/Documents/LaunchAngels/radar/vendor/bundle/gems/pg-0.18.4 for inspection.
Results logged to /Users/jmintz/Documents/LaunchAngels/radar/vendor/bundle/extensions/x86_64-darwin-15/2.2.0-static/pg-0.18.4/gem_make.out
</code>```

...
...

```<code>An error occurred while installing pg (0.18.4), and Bundler cannot continue.

Make sure that `gem install pg -v '0.18.4'` succeeds before bundling.
</code>```

Running 'gem install pg -v '0.18.4' results in:

```<code>Building native extensions.  This could take a while...
Successfully installed pg-0.18.4
Parsing documentation for pg-0.18.4
Done installing documentation for pg after 4 seconds
1 gem installed
</code>```

Yet running 'bundle install' again fails. Any suggestions? I've tried uninstalling and reinstalling postgresql with homebrew with no luck

答:
this worked for me on sierra:</p>

```<code>gem install pg -v '0.18.3' -- --with-pg-config=/Applications/Postgres.app/Contents/Versions/latest/bin/pg_config
</code>```

Body:
Mac OS El Capitan

Bundle install fails with:

compiling pg_connection.c
pg_connection.c:2394:3: warning: implicit declaration of function 'gettimeofday' is invalid in C99 [-Wimplicit-function-declaration]
                gettimeofday(&currtime, NULL);
                ^
1 warning generated.
compiling pg_copy_coder.c
compiling pg_errors.c
compiling pg_result.c
compiling pg_text_decoder.c
compiling pg_text_encoder.c
compiling pg_type_map.c
compiling pg_type_map_all_strings.c
compiling pg_type_map_by_class.c
compiling pg_type_map_by_column.c
compiling pg_type_map_by_mri_type.c
compiling pg_type_map_by_oid.c
compiling pg_type_map_in_ruby.c
compiling util.c
linking shared-object pg_ext.bundle
ld: file not found: dynamic_lookup
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [pg_ext.bundle] Error 1

make failed, exit code 2

Gem files will remain installed in /Users/jmintz/Documents/LaunchAngels/radar/vendor/bundle/gems/pg-0.18.4 for inspection.
Results logged to /Users/jmintz/Documents/LaunchAngels/radar/vendor/bundle/extensions/x86_64-darwin-15/2.2.0-static/pg-0.18.4/gem_make.out

...
...

An error occurred while installing pg (0.18.4), and Bundler cannot continue.

Make sure that `gem install pg -v '0.18.4'` succeeds before bundling.

Running 'gem install pg -v '0.18.4' results in:

Building native extensions.  This could take a while...
Successfully installed pg-0.18.4
Parsing documentation for pg-0.18.4
Done installing documentation for pg after 4 seconds
1 gem installed

Yet running 'bundle install' again fails. Any suggestions? I've tried uninstalling and reinstalling postgresql with homebrew with no luck

Body:
this worked for me on sierra:

gem install pg -v '0.18.3' -- --with-pg-config=/Applications/Postgres.app/Contents/Versions/latest/bin/pg_config


问:
ElasticSearch - Filter stop words from Top words
I have a list of documents I am indexing like this:

```<code>        ElasticIndex.CreateIndex(IndexName, _ => _
            .Mappings(__ => __
                .Map<AlbumMetadata>(
                    M => M.AutoMap()
                   .Properties(P => P.Text(T => T.Name(N => N.Keywords)
                       .Analyzer("stop")
                       .Fields(F => F.Keyword(K => K.Name("keywords"))))))));
</code>```

In my class AlbumMetaData, the field Keywords is a list:

```<code>    [Keyword]
    public List<string> Keywords            { get; set; }
</code>```

When I want to retrieve the top terms, I do the following query (you can ignore Category and Type, they're not relevant to the problem):

```<code>        var Match = Driver.Search<AlbumMetadata>(_ => _
            .Query(Q => Q
                .Term(P => P.Category, (int)Category) && Q
                .Term(P => P.Type, (int)Type))
            .Source(F => F.Includes(S => S.Fields(L => L.Keywords)))
            .Aggregations(A => A
                .Terms("Tags", T => T
                    .Field(E => E.Keywords)
                    .Size(Limit)
            )
        ));

        var Tags = Match.Aggs.Terms("Tags").Buckets.ToDictionary(K => K.Key, V => V.DocCount);
</code>```

The problem is that in the output, I get some stop words as well as some symbols, like / - & |

What am I doing wrong?

Edit:
In order to clarify the question, here is what I am trying to achieve:

I have documents that have titles (full English sentences) and tags (list of single words, sometimes a tag is a two word tag).

I need to be able to perform a search that will find documents based on the title and tags (and ideally using word stems, ignoring plurals, etc).
I also need to extract the list of top words. The Keywords list is a concatenation of all words from the title and all the entries from the tags list.

Is the way I create the index appropriate in this context? Also, is the way I do the aggregation the right way?

答:
There's a few things:

When you create the index, .AutoMap() on the mapping will infer Elasticsearch field datatypes from the POCO property types and the attributes applied to them. Then, .Properties() overrides any of these inferred mappings. So, the end result of your mapping for Keywords is a text datatype field with the stop analyzer applied, and a multi-field sub field of "keywords" (queryable via "keywords.keywords"), set as a keyword datatype.

The aggregation is running on the "keywords" text field with the stop analyzer applied. The stop analyzer uses English stop words by default, but you can configure the stop analyzer with other stop words by defining a custom stop analyzer in the index. The stop analyzer will not remove symbols like /, -, & and |.

With a terms aggregation, you generally want to get back aggregations on the verbatim terms for a field, which you can get with your mapping by using the "keywords.keywords" field in the aggregation. You can apply a normalizer to a keyword field which is similar to an analyzer, except it produces only one token. This is because a keyword field uses doc_values, an on-disk columnar data structure that is suited for well performing, large scale aggregations.

You can run the aggregation on a text field too as you're doing, but you also need to enable fielddata and be aware of how it works. text fields can't use doc_values.

Body:
I have a list of documents I am indexing like this:

        ElasticIndex.CreateIndex(IndexName, _ => _
            .Mappings(__ => __
                .Map<AlbumMetadata>(
                    M => M.AutoMap()
                   .Properties(P => P.Text(T => T.Name(N => N.Keywords)
                       .Analyzer("stop")
                       .Fields(F => F.Keyword(K => K.Name("keywords"))))))));

In my class AlbumMetaData, the field Keywords is a list:

    [Keyword]
    public List<string> Keywords            { get; set; }

When I want to retrieve the top terms, I do the following query (you can ignore Category and Type, they're not relevant to the problem):

        var Match = Driver.Search<AlbumMetadata>(_ => _
            .Query(Q => Q
                .Term(P => P.Category, (int)Category) && Q
                .Term(P => P.Type, (int)Type))
            .Source(F => F.Includes(S => S.Fields(L => L.Keywords)))
            .Aggregations(A => A
                .Terms("Tags", T => T
                    .Field(E => E.Keywords)
                    .Size(Limit)
            )
        ));

        var Tags = Match.Aggs.Terms("Tags").Buckets.ToDictionary(K => K.Key, V => V.DocCount);

The problem is that in the output, I get some stop words as well as some symbols, like / - & |

What am I doing wrong?

Edit:
In order to clarify the question, here is what I am trying to achieve:

I have documents that have titles (full English sentences) and tags (list of single words, sometimes a tag is a two word tag).

I need to be able to perform a search that will find documents based on the title and tags (and ideally using word stems, ignoring plurals, etc).
I also need to extract the list of top words. The Keywords list is a concatenation of all words from the title and all the entries from the tags list.

Is the way I create the index appropriate in this context? Also, is the way I do the aggregation the right way?