问:
How can I split the string elements into disjoint groups in java?
The lines are as follows

```<code>A1;B1;C1
A2;B2;C2
</code>```

How to find a set of unique strings and break it into non-intersecting groups by the following criterion: if two lines have coincidences of non-empty values in one or more columns, they belong to the same group. For example, lines

```<code>1,2,3
4,5,6
1,5,7
</code>```

belong to one group.
Initially I thought to make through a three of HashSet (for each column) to quickly see if the string is included in the list of unique values, then adding either to the list of already grouped rows or to the list of unique rows. But the algorithm in this case has a performance bottleneck: if you want to merge groups, you must go through each group in the list. Algorithm on a large amount of data (> 1 million records), with a large number of mergers, works slowly. If the mergers are small (about thousands), it works quickly. I caught the stuck in this place and do not know how to optimize this bottleneck or whether it is necessary to use other data structures and algorithms. Can someone tell me which direction to dig. I will be grateful for any thoughts on this matter.

答:
I'd suggest the following approach:

Create a Set<String> ungroupedLines, initially containing all the lines. You'll remove the lines as you assign them to groups.

Build three Map<String, Collection<String>>-s, as you've suggested, one per column.

Initialize an empty Collection<Collection<String>> result.

While ungroupedLines is not empty:

Create a new Collection<String> group.

Remove an element, add it to group.

Perform "depth-first search" from that element, using your three maps.

Ignore (skip) any elements that have already been removed from your ungroupedLines.

For the rest, remove them from ungroupedLines and add them to group before recursing on them.

Alternatively, you can use breadth-first search.

Add group to result.

Body:
The lines are as follows

A1;B1;C1
A2;B2;C2

How to find a set of unique strings and break it into non-intersecting groups by the following criterion: if two lines have coincidences of non-empty values in one or more columns, they belong to the same group. For example, lines

1,2,3
4,5,6
1,5,7

belong to one group.
Initially I thought to make through a three of HashSet (for each column) to quickly see if the string is included in the list of unique values, then adding either to the list of already grouped rows or to the list of unique rows. But the algorithm in this case has a performance bottleneck: if you want to merge groups, you must go through each group in the list. Algorithm on a large amount of data (> 1 million records), with a large number of mergers, works slowly. If the mergers are small (about thousands), it works quickly. I caught the stuck in this place and do not know how to optimize this bottleneck or whether it is necessary to use other data structures and algorithms. Can someone tell me which direction to dig. I will be grateful for any thoughts on this matter.


来源: stackexchange

问:
Cannot Deploy Pyramid Application on Heroku
I am having issues deploying my Pyramid app on Heroku. It runs fine locally but as soon as I try to launch it I receive this error "pkg_resources.DistributionNotFound: mymedaproject". mymedaproject is the name of my project and is not a python library which is why I am confused. I followed the instructions from this recipe to get to this point:

http://pyramid-cookbook.readthedocs.org/en/latest/deployment/heroku.html

Any ideas?

答:
Check your .gitignore file that it isn't blocking any egg or egg-info information.

If it is, Heroku won't be receiving the egg for your application.

ContentLicense: CC BY-SA 3.0


问:
(HTML & CSS) Transparent Nav Bar on homepage only. Black background-color in other views
I am fairly new to CSS and have run into a problem. I have a horizontal (Bourbon Refills) navigation bar in my application. On my homepage the navbar is semi-transparent with the background image showing through. I would like for the navbar to be a different color in all of the other views (for example the backgound color should be black in all views except for the homepage) but am unsure how to do this aside from having two separate navbars.  Surely there is a better solution.  (Right now I am placing the navbar in my index.html.erb file as a partial <%= render 'partials/navbar' %>.) Any help would be appreciated!

navbar.scss:

```<code>  header.navigation {
  $base-border-color: gainsboro !default;
  $base-border-radius: 3px !default;
  $action-color: #477DCA !default;
  $dark-gray: #333 !default;
  $large-screen: 53.75em !default;
  $navigation-padding: 1em;
  $navigation-background: transparent;
  $navigation-color: white;
  $navigation-color-hover: transparentize(white, 0.2);
  $navigation-height: 70px;
  $navigation-nav-button-background: $action-color;
  $navigation-nav-button-background-hover: lighten($navigation-background, 10%);
  $navigation-nav-button-border: 1px solid lighten($navigation-nav-button-background, 20%);
  $navigation-active-link-color: transparentize(white, 0.5);
  $horizontal-bar-mode: $large-screen;

  background-color: $navigation-background;
  min-height: $navigation-height;
  width: 100%;
  z-index: 999;

  .navigation-wrapper {
    @include clearfix;
    position: relative;
    z-index: 9999;
    background-color: rgba(0,0,0,0.06);
  }
</code>```

_navbar.html.erb:

```<code>  <header class="navigation" role="banner">
    <div class="navigation-wrapper">
      <a href="javascript:void(0)" class="logo">
      <!--<img src="https://raw.githubusercontent.com/thoughtbot/refills/master/source/images/placeholder_square.png" alt="Logo Image">
      </a>-->
      <a href="javascript:void(0)" class="navigation-menu-button" id="js-mobile-menu">MENU</a>
      <nav role="navigation">
        <ul id="js-navigation-menu" class="navigation-menu">
          <li class="nav-link"><%= link_to 'Camelot Chess', root_path %></li>
          <% if user_signed_in? %>
          <li class="nav-link"><%= link_to 'Create Game', new_game_path %></li>
          <li class="nav-link"><%= link_to 'Join Game', games_path %></li>
          <li class="nav-link right"><%= link_to 'Sign out', destroy_user_session_path, :method => :delete %></li>
          <li class="nav-link right">Hello, <%= current_user.email %></li>
          <% else %>
          <li class="nav-link right"><%= link_to 'Sign Up', new_user_registration_path %></li>
          <li class="nav-link right"><%= link_to 'Sign In', new_user_session_path %></li>
          <% end %>
        </ul>
      </nav>
    </div>
  </header>
</code>```

答:
You can add a class on the .navigation-wrapper and change the background color only when that class is on the nav.

```<code>.navigation-wrapper.black {
    background-color: black;
}
</code>```

You can use some conditional to add the class on the nav only if you aren't on the homepage.

Edit:

In the controller as instance variable such as @black_header = true and then in your .erb file do

```<code><header class="navigation-wrapper <%= @black_header? + 'black' : '' %>" " role="banner"
</code>```

If all of your pages will have the black header except the homepage, then you actually might want to do the opposite here.  (Use the instance variable for when you don't want a black header, and default it to black)

Body:
I am fairly new to CSS and have run into a problem. I have a horizontal (Bourbon Refills) navigation bar in my application. On my homepage the navbar is semi-transparent with the background image showing through. I would like for the navbar to be a different color in all of the other views (for example the backgound color should be black in all views except for the homepage) but am unsure how to do this aside from having two separate navbars.  Surely there is a better solution.  (Right now I am placing the navbar in my index.html.erb file as a partial <%= render 'partials/navbar' %>.) Any help would be appreciated!

navbar.scss:

  header.navigation {
  $base-border-color: gainsboro !default;
  $base-border-radius: 3px !default;
  $action-color: #477DCA !default;
  $dark-gray: #333 !default;
  $large-screen: 53.75em !default;
  $navigation-padding: 1em;
  $navigation-background: transparent;
  $navigation-color: white;
  $navigation-color-hover: transparentize(white, 0.2);
  $navigation-height: 70px;
  $navigation-nav-button-background: $action-color;
  $navigation-nav-button-background-hover: lighten($navigation-background, 10%);
  $navigation-nav-button-border: 1px solid lighten($navigation-nav-button-background, 20%);
  $navigation-active-link-color: transparentize(white, 0.5);
  $horizontal-bar-mode: $large-screen;

  background-color: $navigation-background;
  min-height: $navigation-height;
  width: 100%;
  z-index: 999;

  .navigation-wrapper {
    @include clearfix;
    position: relative;
    z-index: 9999;
    background-color: rgba(0,0,0,0.06);
  }

_navbar.html.erb:

      MENU

<%= link_to 'Camelot Chess', root_path %>

          <% if user_signed_in? %>

<%= link_to 'Create Game', new_game_path %>

<%= link_to 'Join Game', games_path %>

<%= link_to 'Sign out', destroy_user_session_path, :method => :delete %>

Hello, <%= current_user.email %>

          <% else %>

<%= link_to 'Sign Up', new_user_registration_path %>

<%= link_to 'Sign In', new_user_session_path %>

          <% end %>

Body:
You can add a class on the .navigation-wrapper and change the background color only when that class is on the nav.

.navigation-wrapper.black {
    background-color: black;
}

You can use some conditional to add the class on the nav only if you aren't on the homepage.

Edit:

In the controller as instance variable such as @black_header = true and then in your .erb file do

<header class="navigation-wrapper <%= @black_header? + 'black' : '' %>" " role="banner"

If all of your pages will have the black header except the homepage, then you actually might want to do the opposite here.  (Use the instance variable for when you don't want a black header, and default it to black)


问:
How to get the html of an input checkbox with jquery or javascript?
This is what I have in html file

 <input type="checkbox" id="abc-news-au" /> ABC News (AU)

    <input type="checkbox" id="ars-technica" /> Ars Technica

    <input type="checkbox" id="associated-press" /> Associated Press
```
</div>
</div>
</p>

<p>I want to get the text between labels Ex. ABC NEWs (AU)</p>

<p>I use the following code but didnt work *(v is the id of the element)</p>

```console.log("get text: "+ $("#"+v).text()) //(empty)
console.log("get text: "+ $("#"+v).html()) //undefined
```

<p>The only code that shows something is </p>

```console.log("get text: "+ v) //abc-news-au
```

which is obviously the id of the element...
How do I get the text of the element?

答:
<input /> does not have any html() or text(). It's a self closing tag. You want to get the .text() of it's wrapping .

Using jQuery:

$('body').on('click','input', function(e){
  console.log($(e.target).closest('label').text());
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type="checkbox" id="abc-news-au" /> ABC News (AU)</label><br />
<label><input type="checkbox" id="ars-technica" /> Ars Technica</label><br />
<label><input type="checkbox" id="associated-press" /> Associated Press</label><br /></code>```

Body:
This is what I have in html file

 <input type="checkbox" id="abc-news-au" /> ABC News (AU)

    <input type="checkbox" id="ars-technica" /> Ars Technica

    <input type="checkbox" id="associated-press" /> Associated Press

I want to get the text between labels Ex. ABC NEWs (AU)

I use the following code but didnt work *(v is the id of the element)

console.log("get text: "+ $("#"+v).text()) //(empty)
console.log("get text: "+ $("#"+v).html()) //undefined

The only code that shows something is

console.log("get text: "+ v) //abc-news-au

which is obviously the id of the element...
How do I get the text of the element?

Body:
<input /> does not have any html() or text(). It's a self closing tag. You want to get the .text() of it's wrapping <label>.

Using jQuery:

$('body').on('click','input', function(e){
  console.log($(e.target).closest('label').text());
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type="checkbox" id="abc-news-au" /> ABC News (AU)</label><br />
<label><input type="checkbox" id="ars-technica" /> Ars Technica</label><br />
<label><input type="checkbox" id="associated-press" /> Associated Press</label><br />


问:
How to recognize swipe in all 4 directions
I need to use swipe to recognize swipe gesture down and then right. But on swift UISwipeGestureRecognizer has predeterminate Right direction.. And I don't know how make this for use other directions..</p>

答:
Apple Swift version 3.1 - Xcode Version 8.3 (8E162)

The handy way from Alexandre Cassagne's approach

```<code>let directions: [UISwipeGestureRecognizerDirection] = [.up, .down, .right, .left]
for direction in directions {
    let gesture = UISwipeGestureRecognizer(target: self, action: #selector(YourClassName.handleSwipe(gesture:)))
    gesture.direction = direction
    self.view?.addGestureRecognizer(gesture)
}

func handleSwipe(gesture: UISwipeGestureRecognizer) {
    print(gesture.direction)
    switch gesture.direction {
    case UISwipeGestureRecognizerDirection.down:
        print("down swipe")
    case UISwipeGestureRecognizerDirection.up:
        print("up swipe")
    case UISwipeGestureRecognizerDirection.left:
        print("left swipe")
    case UISwipeGestureRecognizerDirection.right:
        print("right swipe")
    default:
        print("other swipe")
    }
}
</code>```

Body:
Apple Swift version 3.1 - Xcode Version 8.3 (8E162)

The handy way from Alexandre Cassagne's approach

let directions: [UISwipeGestureRecognizerDirection] = [.up, .down, .right, .left]
for direction in directions {
    let gesture = UISwipeGestureRecognizer(target: self, action: #selector(YourClassName.handleSwipe(gesture:)))
    gesture.direction = direction
    self.view?.addGestureRecognizer(gesture)
}

func handleSwipe(gesture: UISwipeGestureRecognizer) {
    print(gesture.direction)
    switch gesture.direction {
    case UISwipeGestureRecognizerDirection.down:
        print("down swipe")
    case UISwipeGestureRecognizerDirection.up:
        print("up swipe")
    case UISwipeGestureRecognizerDirection.left:
        print("left swipe")
    case UISwipeGestureRecognizerDirection.right:
        print("right swipe")
    default:
        print("other swipe")
    }
}


问:
Scaling uivew scales its subview issue
i am having a container view with imageview and circleView with circle shape, on pinch gesture i want to scale imageview not the circleView with circle shape.

Below is my code

```<code>if(gestureRecognizer.state == .began || gestureRecognizer.state == .changed) {

        let currentScale: CGFloat = containerView.layer.value(forKeyPath: "transform.scale") as! CGFloat

        // Constants to adjust the max/min values of zoom
        let kMaxScale: CGFloat = 2.0
        let kMinScale: CGFloat = 1.0

        var newScale = 1 - (lastScale - gestureRecognizer.scale)
        // new scale is in the range (0-1)

        newScale = min(newScale, kMaxScale / currentScale)
        newScale = max(newScale, kMinScale / currentScale)
        containerView.transform = containerView.transform.scaledBy(x: newScale, y: newScale)

        lastScale = gestureRecognizer.scale
    }
</code>```

On scaling container view imageView as well as circleView is getting scaled.

Anyone knows how to prevent subview from being scaled?

答:
A view inherits it's frame of reference from it's superview. If you apply a transform to a view it affects the view and all it's superviews. It's like shrinking a piece of paper with a drawing on it. Of course the drawing shrinks if the paper shrinks.

Don't make it a your other views subviews. Make them sibling views that you place on top of the view that's shrinking. That way they won't be affected.

Title: Scaling uivew scales its subview issue

Body:
i am having a container view with imageview and circleView with circle shape, on pinch gesture i want to scale imageview not the circleView with circle shape.

Below is my code

if(gestureRecognizer.state == .began || gestureRecognizer.state == .changed) {

        let currentScale: CGFloat = containerView.layer.value(forKeyPath: "transform.scale") as! CGFloat

        // Constants to adjust the max/min values of zoom
        let kMaxScale: CGFloat = 2.0
        let kMinScale: CGFloat = 1.0

        var newScale = 1 - (lastScale - gestureRecognizer.scale)
        // new scale is in the range (0-1)

        newScale = min(newScale, kMaxScale / currentScale)
        newScale = max(newScale, kMinScale / currentScale)
        containerView.transform = containerView.transform.scaledBy(x: newScale, y: newScale)

        lastScale = gestureRecognizer.scale
    }

On scaling container view imageView as well as circleView is getting scaled.

Anyone knows how to prevent subview from being scaled?


问:
Spring social facebook unable to decode the information being sent from facebook access token URI
The code was working as expected around a week back and used to interpret the access tokens. Now suddenly it started throwing exception:

```<code>org.springframework.social.MissingAuthorizationException: Authorization is required for the operation, but the API binding was created without authorization.
    at org.springframework.social.facebook.api.impl.AbstractFacebookOperations.requireAuthorization(AbstractFacebookOperations.java:30)
    at org.springframework.social.facebook.api.impl.UserTemplate.getUserProfile(UserTemplate.java:48)
    at org.springframework.social.facebook.connect.FacebookAdapter.setConnectionValues(FacebookAdapter.java:42)
    at org.springframework.social.facebook.connect.FacebookAdapter.setConnectionValues(FacebookAdapter.java:30)
    at org.springframework.social.connect.support.AbstractConnection.setValues(AbstractConnection.java:174)
    at org.springframework.social.connect.support.AbstractConnection.initKey(AbstractConnection.java:137)
    at org.springframework.social.connect.support.OAuth2Connection.<init>(OAuth2Connection.java:75)
    at org.springframework.social.connect.support.OAuth2ConnectionFactory.createConnection(OAuth2ConnectionFactory.java:91)
    at org.springframework.social.security.provider.OAuth2AuthenticationService.getAuthToken(OAuth2AuthenticationService.java:99)
    at org.springframework.social.security.SocialAuthenticationFilter.attemptAuthService(SocialAuthenticationFilter.java:239)
    at org.springframework.social.security.SocialAuthenticationFilter.attemptAuthentication(SocialAuthenticationFilter.java:157)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:211)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:85)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.boot.actuate.autoconfigure.MetricFilterAutoConfiguration$MetricsFilter.doFilterInternal(MetricFilterAutoConfiguration.java:90)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1556)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1513)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
</code>```

I tried to debug the code inside the libraries and found that the response being returned is not in the required format which needs to be interpreted by spring-social-facebook-1.1.1.RELEASE-sources.jar-> FacebookOAuth2Template-> postForAccessGrant(). In the below code snippet the access_token and expires needs to be taken with key value.

```<code>@Override
    @SuppressWarnings("unchecked")
    protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {
        MultiValueMap<String, String> response = getRestTemplate().postForObject(accessTokenUrl, parameters, MultiValueMap.class);
        String expires = response.getFirst("expires");
        return new AccessGrant(response.getFirst("access_token"), null, null, expires != null ? Long.valueOf(expires) : null);
    }
</code>```

The response returned from facebook graph access token API is:

```<code>{{"access_token":"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX","token_type":"bearer","expires_in":5157689}=[null]}
</code>```

The line response.get is trying to retrieve these values from value field which is in this case null. Hence it is setting accessToken and expiry values as null.

答:
I have added below class as a temporary fix to the project which is overriding existing class from the library but this is not a proper solution. Is there any fix which will solve this problem?</p>

```<code>package org.springframework.social.facebook.connect;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2Template;
import org.springframework.social.support.ClientHttpRequestFactorySelector;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

public class FacebookOAuth2Template extends OAuth2Template {

    private static final Logger LOGGER = LogManager.getLogger(FacebookOAuth2Template.class);

    public FacebookOAuth2Template(String clientId, String clientSecret) {
        super(clientId, clientSecret, "https://www.facebook.com/v1.0/dialog/oauth", "https://graph.facebook.com/v1.0/oauth/access_token");
        setUseParametersForClientAuthentication(true);
    }

    @Override
    protected RestTemplate createRestTemplate() {
        RestTemplate restTemplate = new RestTemplate(ClientHttpRequestFactorySelector.getRequestFactory());
        FormHttpMessageConverter messageConverter = new FormHttpMessageConverter() {
            @Override
            public boolean canRead(Class<?> clazz, MediaType mediaType) {
                // always read as x-www-url-formencoded even though Facebook sets contentType to text/plain
                return true;
            }
        };
        restTemplate.setMessageConverters(Collections.<HttpMessageConverter<?>> singletonList(messageConverter));
        return restTemplate;
    }

    @Override
    @SuppressWarnings("unchecked")
    protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {
        MultiValueMap<String, String> response = getRestTemplate().postForObject(accessTokenUrl, parameters, MultiValueMap.class);
        String expires = response.getFirst("expires");
        String accessToken = response.getFirst("access_token");
        if(!response.keySet().isEmpty() && (StringUtils.isEmpty(expires) || StringUtils.isEmpty(accessToken))) {
            for(String key : response.keySet()) {
                boolean valuesFound = false;
                HashMap<String, String> map;
                try {
                    //map = (HashMap<String, String>) JSONUtil.fromJSON(key, HashMap.class);
                    ObjectMapper objectMapper = new ObjectMapper();
                    map = objectMapper.readValue(key, HashMap.class);

                    if(StringUtils.isEmpty(expires)) {
                        expires = String.valueOf(map.get("expires_in"));
                        valuesFound = true;
                    }

                    if(StringUtils.isEmpty(accessToken)) {
                        accessToken = map.get("access_token");
                        valuesFound = true;
                    }

                    if(valuesFound) {
                        break;
                    }
                } catch(IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
        }
        return new AccessGrant(accessToken, null, null, expires != null ? Long.valueOf(expires) : null);
    }
}
</code>```

Body:
The code was working as expected around a week back and used to interpret the access tokens. Now suddenly it started throwing exception:

org.springframework.social.MissingAuthorizationException: Authorization is required for the operation, but the API binding was created without authorization.
    at org.springframework.social.facebook.api.impl.AbstractFacebookOperations.requireAuthorization(AbstractFacebookOperations.java:30)
    at org.springframework.social.facebook.api.impl.UserTemplate.getUserProfile(UserTemplate.java:48)
    at org.springframework.social.facebook.connect.FacebookAdapter.setConnectionValues(FacebookAdapter.java:42)
    at org.springframework.social.facebook.connect.FacebookAdapter.setConnectionValues(FacebookAdapter.java:30)
    at org.springframework.social.connect.support.AbstractConnection.setValues(AbstractConnection.java:174)
    at org.springframework.social.connect.support.AbstractConnection.initKey(AbstractConnection.java:137)
    at org.springframework.social.connect.support.OAuth2Connection.<init>(OAuth2Connection.java:75)
    at org.springframework.social.connect.support.OAuth2ConnectionFactory.createConnection(OAuth2ConnectionFactory.java:91)
    at org.springframework.social.security.provider.OAuth2AuthenticationService.getAuthToken(OAuth2AuthenticationService.java:99)
    at org.springframework.social.security.SocialAuthenticationFilter.attemptAuthService(SocialAuthenticationFilter.java:239)
    at org.springframework.social.security.SocialAuthenticationFilter.attemptAuthentication(SocialAuthenticationFilter.java:157)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:211)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:85)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.boot.actuate.autoconfigure.MetricFilterAutoConfiguration$MetricsFilter.doFilterInternal(MetricFilterAutoConfiguration.java:90)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1556)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1513)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

I tried to debug the code inside the libraries and found that the response being returned is not in the required format which needs to be interpreted by spring-social-facebook-1.1.1.RELEASE-sources.jar-> FacebookOAuth2Template-> postForAccessGrant(). In the below code snippet the access_token and expires needs to be taken with key value.

@Override
    @SuppressWarnings("unchecked")
    protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {
        MultiValueMap<String, String> response = getRestTemplate().postForObject(accessTokenUrl, parameters, MultiValueMap.class);
        String expires = response.getFirst("expires");
        return new AccessGrant(response.getFirst("access_token"), null, null, expires != null ? Long.valueOf(expires) : null);
    }

The response returned from facebook graph access token API is:

{{"access_token":"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX","token_type":"bearer","expires_in":5157689}=[null]}

The line response.get is trying to retrieve these values from value field which is in this case null. Hence it is setting accessToken and expiry values as null.

Body:
I have added below class as a temporary fix to the project which is overriding existing class from the library but this is not a proper solution. Is there any fix which will solve this problem?

package org.springframework.social.facebook.connect;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2Template;
import org.springframework.social.support.ClientHttpRequestFactorySelector;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

public class FacebookOAuth2Template extends OAuth2Template {

    private static final Logger LOGGER = LogManager.getLogger(FacebookOAuth2Template.class);

    public FacebookOAuth2Template(String clientId, String clientSecret) {
        super(clientId, clientSecret, "https://www.facebook.com/v1.0/dialog/oauth", "https://graph.facebook.com/v1.0/oauth/access_token");
        setUseParametersForClientAuthentication(true);
    }

    @Override
    protected RestTemplate createRestTemplate() {
        RestTemplate restTemplate = new RestTemplate(ClientHttpRequestFactorySelector.getRequestFactory());
        FormHttpMessageConverter messageConverter = new FormHttpMessageConverter() {
            @Override
            public boolean canRead(Class<?> clazz, MediaType mediaType) {
                // always read as x-www-url-formencoded even though Facebook sets contentType to text/plain
                return true;
            }
        };
        restTemplate.setMessageConverters(Collections.<HttpMessageConverter<?>> singletonList(messageConverter));
        return restTemplate;
    }

    @Override
    @SuppressWarnings("unchecked")
    protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {
        MultiValueMap<String, String> response = getRestTemplate().postForObject(accessTokenUrl, parameters, MultiValueMap.class);
        String expires = response.getFirst("expires");
        String accessToken = response.getFirst("access_token");
        if(!response.keySet().isEmpty() && (StringUtils.isEmpty(expires) || StringUtils.isEmpty(accessToken))) {
            for(String key : response.keySet()) {
                boolean valuesFound = false;
                HashMap<String, String> map;
                try {
                    //map = (HashMap<String, String>) JSONUtil.fromJSON(key, HashMap.class);
                    ObjectMapper objectMapper = new ObjectMapper();
                    map = objectMapper.readValue(key, HashMap.class);

                    if(StringUtils.isEmpty(expires)) {
                        expires = String.valueOf(map.get("expires_in"));
                        valuesFound = true;
                    }

                    if(StringUtils.isEmpty(accessToken)) {
                        accessToken = map.get("access_token");
                        valuesFound = true;
                    }

                    if(valuesFound) {
                        break;
                    }
                } catch(IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
        }
        return new AccessGrant(accessToken, null, null, expires != null ? Long.valueOf(expires) : null);
    }
}


问:
Callrail API HTTP GET request with headers
I can throw this into a linux terminal and get results.

```<code>curl -H "Authorization: Token token={api_token}" \
 -X GET \
 "https://api.callrail.com/v2/a/{account_id}/calls.json?company_id={companyId}"
</code>```

Here is what I have:

```<code>var myToken = "fakeToken1234";

$.ajax
    ({
        type: "GET",
        url: "https://api.callrail.com/v2/a/{accountId}/calls.json?company_id={companyId}",
        dataType: 'json',
        beforeSend: function (xhr) { xhr.setRequestHeader('Authorization:', + myToken ); }
    });
</code>```

Per CallRail Documentation I'm supposed to pass the api_token into HTTP Authorization header. I get a 401 Unauthorized message.

I think my syntax is off but can't pin it down. Any help?

答:
This is what I would try using "headers:":

```<code>let companyId = "";
let accountId = "";
let myToken = "fakeToken1234";
    $.ajax({
          type: "GET",
          url: `https://api.callrail.com/v2/a/${accountId}/calls.json?company_id=${companyId}`,
          headers: {"Authorization": `Token token="${myToken}"`},
          dataType: 'json'
    });
</code>```

Don't forget to also load the companyId and accountId in your url. I am assuming you are using the right url in this answer by the way.

Hope it works. I only did $.ajax requests with one API so far. So let me hear if it works. It should at the very least point you in the right direction.

Body:
I can throw this into a linux terminal and get results.

curl -H "Authorization: Token token={api_token}" \
 -X GET \
 "https://api.callrail.com/v2/a/{account_id}/calls.json?company_id={companyId}"

Here is what I have:

var myToken = "fakeToken1234";

$.ajax
    ({
        type: "GET",
        url: "https://api.callrail.com/v2/a/{accountId}/calls.json?company_id={companyId}",
        dataType: 'json',
        beforeSend: function (xhr) { xhr.setRequestHeader('Authorization:', + myToken ); }
    });

Per CallRail Documentation I'm supposed to pass the api_token into HTTP Authorization header. I get a 401 Unauthorized message.

I think my syntax is off but can't pin it down. Any help?

Body:
This is what I would try using "headers:":

let companyId = "";
let accountId = "";
let myToken = "fakeToken1234";
    $.ajax({
          type: "GET",
          url: `https://api.callrail.com/v2/a/${accountId}/calls.json?company_id=${companyId}`,
          headers: {"Authorization": `Token token="${myToken}"`},
          dataType: 'json'
    });

Don't forget to also load the companyId and accountId in your url. I am assuming you are using the right url in this answer by the way.

Hope it works. I only did $.ajax requests with one API so far. So let me hear if it works. It should at the very least point you in the right direction.


问:
Key Listeners in python?
Is there a way to do key listeners in python without a huge bloated module such as pygame?

An example would be, when I pressed the a key it would print to the console

The a key was pressed!

It should also listen for the arrow keys/spacebar/shift key.

答:
I was searching for a simple solution without window focus. Jayk's answer, pynput, works perfect for me. Here is the example how I use it.

```<code>from pynput import keyboard

def on_press(key):
    if key == keyboard.Key.esc:
        return False  # stop listener
    try:
        k = key.char  # single-char keys
    except:
        k = key.name  # other keys
    if k in ['1', '2', 'left', 'right']:  # keys of interest
        # self.keys.append(k)  # store it in global-like variable
        print('Key pressed: ' + k)
        return False  # stop listener; remove this if want more keys

listener = keyboard.Listener(on_press=on_press)
listener.start()  # start to listen on a separate thread
listener.join()  # remove if main thread is polling self.keys
</code>```

Title: Key Listeners in python?

Body:
I was searching for a simple solution without window focus. Jayk's answer, pynput, works perfect for me. Here is the example how I use it.

from pynput import keyboard

def on_press(key):
    if key == keyboard.Key.esc:
        return False  # stop listener
    try:
        k = key.char  # single-char keys
    except:
        k = key.name  # other keys
    if k in ['1', '2', 'left', 'right']:  # keys of interest
        # self.keys.append(k)  # store it in global-like variable
        print('Key pressed: ' + k)
        return False  # stop listener; remove this if want more keys

listener = keyboard.Listener(on_press=on_press)
listener.start()  # start to listen on a separate thread
listener.join()  # remove if main thread is polling self.keys

ContentLicense: CC BY-SA 4.0


问:
Generating strongly-connected, uniformly-distributed, random di-graphs
So I've been building a program that uses Monte Carlo simulations to find properties of evolutionary graph theory. One of the key functions of this is to be able to generate uniformly-distributed random graphs, so that we can determine the generalised properties of graphs. For the case of connected undirected graphs I have implemented the solution outlined in this answer.

However for directed graphs, generating the one-directional uniform spanning tree you get from Wilson's algorithm doesn't ensure that the graph is strongly-connected, and it seems that adding extra edges to make the spanning tree bi-directional would introduce a bias into the graphs that you generate.

I feel like I might be missing something obvious/misunderstanding something, but essentially my request is, can someone recommend to me a high-level scheme that allows me to generate strongly-connected, uniformly-distributed, random di-graphs?

答:
Can someone recommend to me a high-level scheme that allows me to generate strongly-connected, uniformly-distributed, random di-graphs?

I had a similar problem generating expression trees for test data. I found that if you find out how to count unique trees then the problem becomes easy. What I mean by that is that I found for full binary trees with N internal nodes the number of unique trees based on N is the Catalan Numbers. Then for binary trees that have unary branches with N total nodes the number of unique trees based on N is the Motzkin Numbers.

Then I found The On-Line Encyclopedia of Integer Sequences®. So if you know a value, N, that can uniquely identify a graph and you know the corresponding count of unique graphs for that N and put those counts into a the OEIS search you should get back a page that will help you in your search. e.g. Catalan Numbers for full binary trees or Motzkin Numbers for regular binary tress. Along the way I found that one of the keys to generating them was a recurrence relation.

Or you can use keywords in the search but this may not get an exact hit. I only found Motzkin numbers using the number sequence and not via keywords.

Here is an OEIS query for strongly connected digraph

Now if you know the count for a given N and you either generate all graphs for a given N or can have a one to one correspondence between a value and the graph then you just generate random integers and get/generate the corresponding graph. If I understand your problem correctly this should solve it.

My best guess to the OEIS sequence for this question is:

Number of acyclic digraphs with n unlabeled nodes. A003087

Which has a reference to Uniform random generation of large acyclic digraphs

TL;DR

For some related history see my question: Algorithm improvement for enumerating binary trees


问:
What is the best way to generate ranks in MYSQL?
What's the best way to get the rank of the rows in addition to the row data in MYSQL?

For instance, say I have a list of students and I want to rank on the GPA. I know I can order by the GPA, but what's the quickest way to have MYSQL return the rank as well in the rowdata I get back?

答:
This will return the rank as rownum

```<code>SELECT @rownum := @rownum + 1 rownum,
       t.*
  FROM (SELECT @rownum:=0) r,
       (SELECT * FROM students ORDER BY gpa DESC) t;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
This will return the rank as rownum

SELECT @rownum := @rownum + 1 rownum,
       t.*
  FROM (SELECT @rownum:=0) r,
       (SELECT * FROM students ORDER BY gpa DESC) t;

OwnerDisplayName: Vinko Vrsalovic


问:
Errors creating a string in c++
Whenever I try to create a string in my header file I get the error: 'string' is not a member of 'std'. I am using the Microsoft Visual c++ express 2010 compiler. Here is my header file:

```<code>using namespace std;

class Person
{
private:
 string name;
 string p_number;

public:
 Person();
 Person(string, string);
 string get_number();
 string get_name();
};
</code>```

I am a decent java programmer who just started  learning c++

答:
```<code>using std::string;
</code>```

will not include unnecessary declarations and definitions present in string header and will be helpful only for compiler's lookup and would compile fine, I usually prefer following instead of including whole header files:

```<code>using std::cout;
using std::cin;
using std::endl;
</code>```

*For example purpose only.

Title: Errors creating a string in c++

Body:
Whenever I try to create a string in my header file I get the error: 'string' is not a member of 'std'. I am using the Microsoft Visual c++ express 2010 compiler. Here is my header file:

using namespace std;

class Person
{
private:
 string name;
 string p_number;

public:
 Person();
 Person(string, string);
 string get_number();
 string get_name();
};

I am a decent java programmer who just started  learning c++

Body:
using std::string;

will not include unnecessary declarations and definitions present in string header and will be helpful only for compiler's lookup and would compile fine, I usually prefer following instead of including whole header files:

using std::cout;
using std::cin;
using std::endl;

*For example purpose only.


问:
Image max-width not working in media query
I'm having an issue with max-width/max-height inside of media queries.  Basically what's happening is I have an image gallery that uses jQuery to display a modal window. This modal window consists of the modal, a content box, and an image viewer which has some buttons inside for navigation thru images). I have the max-width/max-height set in vw and vh in css but the exit button gets cut off on a mobile device.

Current CSS:

```<code>#photoViewer {
display: inline-block;
position: relative;
margin: 0 auto;
width: 0;
height: 0;
transition: width 0.5s, height 0.5s;
}

#photoViewer img {
position: absolute;
top: 50%;
left: 50%;
max-height: 70vh;
max-width: 70vw;
}
</code>```

I tried using a media query:

```<code>@media screen and (max-width: 955px) {
   #photoViewer img {
      max-width: 50vw;
      max-height: 50vh;
   }
}
</code>```

but it's not changing anything. I found if set hard "width" and "height" rules it works but the max- seems to throw it off.  Any ideas?

Here's a fiddle that demonstrates kind of what I'm working with (my whole code is pretty large):

https://jsfiddle.net/jessereitz1/6nxg21a3/3/

答:
At least in the fiddle you posted it works:

The images' original sizes there are only 200x133px or vice versa. With  max-width/ max-height values they will never get larger than their original size.

Only if the screen/viewport becomes less than 400px wide, the max-width: 50% will have an effect (for landscape mode images, that is - portrait even less: narrower than 266px).

Body:
I'm having an issue with max-width/max-height inside of media queries.  Basically what's happening is I have an image gallery that uses jQuery to display a modal window. This modal window consists of the modal, a content box, and an image viewer which has some buttons inside for navigation thru images). I have the max-width/max-height set in vw and vh in css but the exit button gets cut off on a mobile device.

Current CSS:

#photoViewer {
display: inline-block;
position: relative;
margin: 0 auto;
width: 0;
height: 0;
transition: width 0.5s, height 0.5s;
}

#photoViewer img {
position: absolute;
top: 50%;
left: 50%;
max-height: 70vh;
max-width: 70vw;
}

I tried using a media query:

@media screen and (max-width: 955px) {
   #photoViewer img {
      max-width: 50vw;
      max-height: 50vh;
   }
}

but it's not changing anything. I found if set hard "width" and "height" rules it works but the max- seems to throw it off.  Any ideas?

Here's a fiddle that demonstrates kind of what I'm working with (my whole code is pretty large):

https://jsfiddle.net/jessereitz1/6nxg21a3/3/


问:
ruby: curses: Do not clear screen at end of program?
I'm using the ruby curses package (ruby 2.1.5).

In certain cases, I'd like the screen not to be cleared at the end of my program, so that the final contents of Curses.stdscr are still showing on my terminal when the program exits.

I've tried leaving out the call to Curses.close_screen, but the terminal screen still gets cleared upon exit.

Is there any way to tell curses in ruby to not clear the screen when the program is terminating?

Thank you in advance.

答:
I figured it out: it turns out that if I exit my program with exit! instead of just exit, none of the screen resetting logic of curses gets invoked, and the latest contents of stdscr remain on my screen.

I also do the following before calling Curses.init_screen ...

```<code>require 'termios'
$orig_termios = Termios.tcgetattr($stdin)
</code>```

... and I issue this command right before the exit! ...

```<code>Termios.tcsetattr($stdin, Termios::TCSANOW, $orig_termios)
</code>```

(I want to accept this answer, but I can't do that for 2 more days. I will do so at that time).

Body:
I figured it out: it turns out that if I exit my program with exit! instead of just exit, none of the screen resetting logic of curses gets invoked, and the latest contents of stdscr remain on my screen.

I also do the following before calling Curses.init_screen ...

require 'termios'
$orig_termios = Termios.tcgetattr($stdin)

... and I issue this command right before the exit! ...

Termios.tcsetattr($stdin, Termios::TCSANOW, $orig_termios)

(I want to accept this answer, but I can't do that for 2 more days. I will do so at that time).


问:
Laravel Homestead with Apache server
Last year, after being a long time user of a WAMP stack, I switched over to Homestead on Vagrant. For a non-Laravel development project, I am required to use Apache Server. I know that it is possible to install Apache server on Homestead and then add Virtual Hosts for each site, but this seems a bit impractical. The sites in the Homestead.yaml file work with Nginx but don't seem to work with Apache.

My questions are:

Is there away of creating the Virtual Hosts automatically in Apache?

Is there another Vagrant box that would do this or that you can
recommend for use with Apache?

Am I just missing something?

I'm kind of a noob in these things. Any help is greatly appreciated!

答:
I'm still researching and figuring it out myself. The documentation is practically nonexistent, but see https://laravel.com/docs/master/homestead#adding-additional-sites

In particular:

Site Types

Homestead supports several types of sites which allow you to easily
  run projects that are not based on Laravel. For example, we may easily
  add a Symfony application to Homestead using the  symfony2 site type:

sites:
      - map: symfony2.app
        to: /home/vagrant/Code/Symfony/public
        type: symfony2 The available site types are: apache, laravel (the default), proxy, silverstripe, statamic, and  symfony2.

Also note: https://laracasts.com/discuss/channels/general-discussion/homestead-and-apache

Will revise as I learn more.

Title: Laravel Homestead with Apache server


问:
Sympy: Set aspect ratio
I'm using Spyder's Ipython console to try to get some quick parametric plots of functions.  For now I'm focusing on x = cos(t), y = sin(t).  I ran the command

```<code>import sympy as sp
sp.init_session()
p = plotting.plot_parametric(cos(t),sin(t),(t,0,2*pi))
</code>```

and I get an oblong plot of the curve.

If I enter

```<code>p.aspect_ratio = (1,1)
p.show()
</code>```

nothing changes.  I try other aspect ratios and still nothing changes.

After looking at this answer In sympy plotting, how can I get a plot with a fixed aspect ratio?

I tried following their instructions to try to leverage matplotlib and I get no errors.  But when I enter

```<code>plt.show()
</code>```

nothing shows.

答:
You need to use fig.show() to display the graph. The following example produces a graph with equal aspect ratio:

```<code>import sympy as sp
sp.init_session()
p = plotting.plot_parametric(cos(t),sin(t),(t,0,2*pi))
fig = p._backend.fig
ax = p._backend.ax
ax.set_aspect('equal')
fig.show()
</code>```

h/t to Sympy and plotting

Title: Sympy: Set aspect ratio

Body:
I'm using Spyder's Ipython console to try to get some quick parametric plots of functions.  For now I'm focusing on x = cos(t), y = sin(t).  I ran the command

import sympy as sp
sp.init_session()
p = plotting.plot_parametric(cos(t),sin(t),(t,0,2*pi))

and I get an oblong plot of the curve.

If I enter

p.aspect_ratio = (1,1)
p.show()

nothing changes.  I try other aspect ratios and still nothing changes.

After looking at this answer In sympy plotting, how can I get a plot with a fixed aspect ratio?

I tried following their instructions to try to leverage matplotlib and I get no errors.  But when I enter

plt.show()

nothing shows.

Body:
You need to use fig.show() to display the graph. The following example produces a graph with equal aspect ratio:

import sympy as sp
sp.init_session()
p = plotting.plot_parametric(cos(t),sin(t),(t,0,2*pi))
fig = p._backend.fig
ax = p._backend.ax
ax.set_aspect('equal')
fig.show()

h/t to Sympy and plotting


问:
invalid_grant trying to get oAuth token from google
I keep getting an invalid_grant error on trying to get an OAuth token from Google to connect to their contacts API. All the information is correct and I have triple-checked this so I'm kind of stumped.

Does anyone know what may be causing this issue? I have tried setting up a different client ID for it but I get the same result. I have tried connecting many different ways including trying the force authentication, but still the same result.

答:
Using a Android clientId (no client_secret) I was getting the following error response:

```<code>{
 "error": "invalid_grant",
 "error_description": "Missing code verifier."
}
</code>```

I cannot find any documentation for the field 'code_verifier' but I discovered if you set it to equal values in both the authorization and token requests it will remove this error.  I'm not sure what the intended value should be or if it should be secure. It has some minimum length (16? characters) but I found setting to null also works.

I am using AppAuth for the authorization request in my Android client which has a setCodeVerifier() function.

```<code>AuthorizationRequest authRequest = new AuthorizationRequest.Builder(
                                    serviceConfiguration,
                                    provider.getClientId(),
                                    ResponseTypeValues.CODE,
                                    provider.getRedirectUri()
                            )
                            .setScope(provider.getScope())
                            .setCodeVerifier(null)
                            .build();
</code>```

Here is an example token request in node:

```<code>request.post(
  'https://www.googleapis.com/oauth2/v4/token',
  { form: {
    'code': '4/xxxxxxxxxxxxxxxxxxxx',
    'code_verifier': null,
    'client_id': 'xxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
    'client_secret': null,
    'redirect_uri': 'com.domain.app:/oauth2redirect',
    'grant_type': 'authorization_code'
  } },
  function (error, response, body) {
    if (!error && response.statusCode == 200) {
      console.log('Success!');
    } else {
      console.log(response.statusCode + ' ' + error);
    }

    console.log(body);
  }
);
</code>```

I tested and this works with both https://www.googleapis.com/oauth2/v4/token and https://accounts.google.com/o/oauth2/token.

If you are using GoogleAuthorizationCodeTokenRequest instead:

```<code>final GoogleAuthorizationCodeTokenRequest req = new GoogleAuthorizationCodeTokenRequest(
                    TRANSPORT,
                    JSON_FACTORY,
                    getClientId(),
                    getClientSecret(),
                    code,
                    redirectUrl
);
req.set("code_verifier", null);
GoogleTokenResponse response = req.execute();
</code>```

Body:
Using a Android clientId (no client_secret) I was getting the following error response:

{
 "error": "invalid_grant",
 "error_description": "Missing code verifier."
}

I cannot find any documentation for the field 'code_verifier' but I discovered if you set it to equal values in both the authorization and token requests it will remove this error.  I'm not sure what the intended value should be or if it should be secure. It has some minimum length (16? characters) but I found setting to null also works.

I am using AppAuth for the authorization request in my Android client which has a setCodeVerifier() function.

AuthorizationRequest authRequest = new AuthorizationRequest.Builder(
                                    serviceConfiguration,
                                    provider.getClientId(),
                                    ResponseTypeValues.CODE,
                                    provider.getRedirectUri()
                            )
                            .setScope(provider.getScope())
                            .setCodeVerifier(null)
                            .build();

Here is an example token request in node:

request.post(
  'https://www.googleapis.com/oauth2/v4/token',
  { form: {
    'code': '4/xxxxxxxxxxxxxxxxxxxx',
    'code_verifier': null,
    'client_id': 'xxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
    'client_secret': null,
    'redirect_uri': 'com.domain.app:/oauth2redirect',
    'grant_type': 'authorization_code'
  } },
  function (error, response, body) {
    if (!error && response.statusCode == 200) {
      console.log('Success!');
    } else {
      console.log(response.statusCode + ' ' + error);
    }

    console.log(body);
  }
);

I tested and this works with both https://www.googleapis.com/oauth2/v4/token and https://accounts.google.com/o/oauth2/token.

If you are using GoogleAuthorizationCodeTokenRequest instead:

final GoogleAuthorizationCodeTokenRequest req = new GoogleAuthorizationCodeTokenRequest(
                    TRANSPORT,
                    JSON_FACTORY,
                    getClientId(),
                    getClientSecret(),
                    code,
                    redirectUrl
);
req.set("code_verifier", null);
GoogleTokenResponse response = req.execute();


问:
Visual Studio 2015 provider when using .mdf
I'm working on a program that gets data from a database on an .mdf file and populates a listbox with the results. I'm getting an error that says "An OLE DB Provider was not specified in the ConnectionString."

I can't seem to figure out what is the correct string to use for a provider. In my particular case, what am I supposed to do to get it to read the .mdf correctly?

```<code>            sConnection = "Data Source=.\\SQLEXPRESS; AttachDbFilename = StudentData.mdf;";
            dbConn = new OleDbConnection(sConnection);
            dbConn.Open();
            sql = "SELECT * FROM StudentData;";

            dbCmd = new OleDbCommand();
            dbCmd.CommandText = sql;

            dbCmd.Connection = dbConn;

            dbReader = dbCmd.ExecuteReader();
            while (dbReader.Read())
            {
                aMember = new
                    Member(dbReader["FirstName"].ToString(),
                    dbReader["LastName"].ToString());
                this.OutputListBox.Items.Add(aMember);
            }
            dbReader.Close();
            dbConn.Close();
</code>```

Update: I've changed the connection string to:

```<code>sConnection = "Provider = SQLNCLI11;" +
                "Data Source = (LocalDB)/MSSQLLocalDB;" +
                "AttachDbFilename = \"c:/users/tevin/documents/visual studio 2015/Projects/DbReader/DbReader/StudentData.mdf\";" +
                "Connect Timeout = 30;";
</code>```

However now I am getting the errors "Invalid authorization specification" and "Invalid connection string attribute".

答:
The value of sConnection seems to be wrong. In this case you should use something like this:

```<code>Server=.\SQLExpress;AttachDbFilename=C:\MyFolder\MyDataFile.mdf;Database=dbname;
Trusted_Connection=Yes;
</code>```

For more information please visit conectionstrings.com

Body:
I'm working on a program that gets data from a database on an .mdf file and populates a listbox with the results. I'm getting an error that says "An OLE DB Provider was not specified in the ConnectionString."

I can't seem to figure out what is the correct string to use for a provider. In my particular case, what am I supposed to do to get it to read the .mdf correctly?

            sConnection = "Data Source=.\\SQLEXPRESS; AttachDbFilename = StudentData.mdf;";
            dbConn = new OleDbConnection(sConnection);
            dbConn.Open();
            sql = "SELECT * FROM StudentData;";

            dbCmd = new OleDbCommand();
            dbCmd.CommandText = sql;

            dbCmd.Connection = dbConn;

            dbReader = dbCmd.ExecuteReader();
            while (dbReader.Read())
            {
                aMember = new
                    Member(dbReader["FirstName"].ToString(),
                    dbReader["LastName"].ToString());
                this.OutputListBox.Items.Add(aMember);
            }
            dbReader.Close();
            dbConn.Close();

Update: I've changed the connection string to:

sConnection = "Provider = SQLNCLI11;" +
                "Data Source = (LocalDB)/MSSQLLocalDB;" +
                "AttachDbFilename = \"c:/users/tevin/documents/visual studio 2015/Projects/DbReader/DbReader/StudentData.mdf\";" +
                "Connect Timeout = 30;";

However now I am getting the errors "Invalid authorization specification" and "Invalid connection string attribute".

Body:
The value of sConnection seems to be wrong. In this case you should use something like this:

Server=.\SQLExpress;AttachDbFilename=C:\MyFolder\MyDataFile.mdf;Database=dbname;
Trusted_Connection=Yes;

For more information please visit conectionstrings.com


问:
How to convert 'QVideoFrame' with YUV data to 'QVideoframe' with RGBA32 data in Qt?
I receive QVideoFrames from webcam, and they contain image data in YUV format (QVideoFrame::Format_YUV420P). How can I convert one such frame to one with QVideoFrame::Format_ARGB32 or QVideoFrame::Format_RGBA32?

Can I do it without going low level, using just existing functionality in Qt5?

Example:

```<code>QVideoFrame convertFormat(const QVideoFrame &inputframe, QVideoFrame::PixelFormat outputFormat)
{
    // What comes here?
}

//Usage
QVideoFrame converted = convertFormat(mySourceFrame, QVideoFrame::Format_RGB32);
</code>```

答:
I found a solution that is built into Qt5, but UNSUPPORTED BY Qt.

Here is how to go about:

Put QT += multimedia-private into your qmake .pro file

Put #include "private/qvideoframe_p.h" into your code to make the function available.

You now have access to a function with the following signature: QImage qt_imageFromVideoFrame(const QVideoFrame &frame);

Use the function to convert the QVideoFrame to a temporay QImage and then create the output QVideoFrame from that image.

Here is my example usage:

```<code>QVideoFrame convertFormat(const QVideoFrame &inputframe, QVideoFrame::PixelFormat outputFormat)
    {
        inputframe->map(QAbstractVideoBuffer::ReadOnly);
        QImage tempImage=qt_imageFromVideoFrame(inputframe);
        inputframe->unmap();
        QVideoFrame outputFrame=QVideoFrame(tempImage);
        return outputFrame;
    }
</code>```

Again, the warning copied from the header reads as follows:

```<code>//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//
</code>```

This does not matter in my project since it is a personal toy product. If it ever gets serious I will just track down the implementation of that function and copy it into my project or something.

Body:
I receive QVideoFrames from webcam, and they contain image data in YUV format (QVideoFrame::Format_YUV420P). How can I convert one such frame to one with QVideoFrame::Format_ARGB32 or QVideoFrame::Format_RGBA32?

Can I do it without going low level, using just existing functionality in Qt5?

Example:

QVideoFrame convertFormat(const QVideoFrame &inputframe, QVideoFrame::PixelFormat outputFormat)
{
    // What comes here?
}

//Usage
QVideoFrame converted = convertFormat(mySourceFrame, QVideoFrame::Format_RGB32);

Body:
I found a solution that is built into Qt5, but UNSUPPORTED BY Qt.

Here is how to go about:

Put QT += multimedia-private into your qmake .pro file

Put #include "private/qvideoframe_p.h" into your code to make the function available.

You now have access to a function with the following signature: QImage qt_imageFromVideoFrame(const QVideoFrame &frame);

Use the function to convert the QVideoFrame to a temporay QImage and then create the output QVideoFrame from that image.

Here is my example usage:

QVideoFrame convertFormat(const QVideoFrame &inputframe, QVideoFrame::PixelFormat outputFormat)
    {
        inputframe->map(QAbstractVideoBuffer::ReadOnly);
        QImage tempImage=qt_imageFromVideoFrame(inputframe);
        inputframe->unmap();
        QVideoFrame outputFrame=QVideoFrame(tempImage);
        return outputFrame;
    }

Again, the warning copied from the header reads as follows:

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

This does not matter in my project since it is a personal toy product. If it ever gets serious I will just track down the implementation of that function and copy it into my project or something.


问:
The Jenkins kubernetes plugin need to wait a long time about 15s before the salve build,why?
I use the Jenkins kubernetes plugin to build a job, but when I start build I have to wait for about 15s before the slave is online.  Why does this happen?</p>

答:
You need to be aware that when you use the Kubernetes Plugin, your Jenkins-slave is created on demand when you build a job. Supposing you are using the jnlp-slave as your jenkins-slave image, 15s is the time need for k8s to schedule the pod and to start up the jnlp slave jar.

What you can do in order to optimize the time, is using the option Time in minutes to retain slave when idle in the Kubernetes Plugin configuration, that holds the pods running for a determined amount of time, so the next builds can reuse that slave.


问:
geckodriver 0.15 does not work with Firefox 64-bit
I am using selenium Grid to run tests over windows virtual machines.

After updating to:

geckodriver - v0.15

selenium-server-standalone.jar - v3.3.1

selenium webdriver - v3.3

My tests do not work on 64-bit version of Firefox (v52). I get following exception:

Expected browser binary location, but unable to find binary in default location, no 'moz:firefoxOptions.binary' capability provided, and no binary flag set on the command line (WARNING: The server did not provide any stacktrace information)

how can I fix this issue?

答:
I got this error with 32-bit GeckoDriver. I was able to solve this by providing Firefox location using FirefoxOptions class with GeckoDriver 0.15.0 and Selenium 3.3.1 -

```<code>    FirefoxOptions options = new FirefoxOptions();
    options.setBinary("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe"); //This is the location where you have installed Firefox on your machine

    FirefoxDriver driver = new FirefoxDriver(options);
    driver.get("http://www.google.com");
</code>```

more info here - http://www.automationtestinghub.com/selenium-3-0-launch-firefox-with-geckodriver/

Body:
I got this error with 32-bit GeckoDriver. I was able to solve this by providing Firefox location using FirefoxOptions class with GeckoDriver 0.15.0 and Selenium 3.3.1 -

    FirefoxOptions options = new FirefoxOptions();
    options.setBinary("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe"); //This is the location where you have installed Firefox on your machine

    FirefoxDriver driver = new FirefoxDriver(options);
    driver.get("http://www.google.com");

more info here - http://www.automationtestinghub.com/selenium-3-0-launch-firefox-with-geckodriver/


问:
Heroku application error node.js app, when deploying
```<code>    if (process.env.NODE_ENV === 'production') {
    apiOptions.server = "https://pacific-bastion-15276.herokuapp.com";
</code>```

and my verison of npm and node are the same as specified on the packge.json.

I can't figure out the problem.

I tried heroku restart, heroku ps:scale web=0 and heroku ps:scale web=1,set the JWT_SECRET on heroku.
nothing is working

any ideas?? am I missing something?

```<code>    2017-03-29T23:34:56.224489+00:00 app[web.1]: npm ERR! You can get information on how to open an issue for this project with:
    2017-03-29T23:34:56.224809+00:00 app[web.1]: npm ERR! Or if that isn't available, you can get their info via:
    2017-03-29T23:34:56.224892+00:00 app[web.1]: npm ERR!     npm owner ls bookFace
    2017-03-29T23:34:56.224976+00:00 app[web.1]: npm ERR! There is likely additional logging output above.
    2017-03-29T23:34:56.228404+00:00 app[web.1]: npm ERR! Please include the following file with any support request:
    2017-03-29T23:34:56.228253+00:00 app[web.1]:
    2017-03-29T23:34:56.228474+00:00 app[web.1]: npm ERR!     /app/npm-debug.log
    2017-03-29T23:34:56.291775+00:00 heroku[web.1]: Process exited with status 1
    2017-03-29T23:34:56.325835+00:00 heroku[web.1]: State changed from starting to crashed
    2017-03-29T23:35:00.496063+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=pacific-bastion-15276.herokuapp.com request_id=53f989a3-f47c-48c2-8c79-1234136b53f6 fwd="80.1.102.64" dyno= connect= service= status=503 bytes= protocol=https
    2017-03-29T23:35:01.865707+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=pacific-bastion-15276.herokuapp.com request_id=e9f50e76-4c05-4b81-88d8-1be6026a2715 fwd="80.1.102.64" dyno= connect= service= status=503 bytes= protocol=https
</code>```

答:
I encountered strange crashes while using heroku & node.js and one of them had to do with me accidentally uploading node_modules directory from my local machine. In my case it caused conflicts while heroku was trying to install dependencies.

See if that is the case. If that does not help than please provide more context to your question.

Body:
    if (process.env.NODE_ENV === 'production') {
    apiOptions.server = "https://pacific-bastion-15276.herokuapp.com";

and my verison of npm and node are the same as specified on the packge.json.

I can't figure out the problem.

I tried heroku restart, heroku ps:scale web=0 and heroku ps:scale web=1,set the JWT_SECRET on heroku.
nothing is working

any ideas?? am I missing something?

    2017-03-29T23:34:56.224489+00:00 app[web.1]: npm ERR! You can get information on how to open an issue for this project with:
    2017-03-29T23:34:56.224809+00:00 app[web.1]: npm ERR! Or if that isn't available, you can get their info via:
    2017-03-29T23:34:56.224892+00:00 app[web.1]: npm ERR!     npm owner ls bookFace
    2017-03-29T23:34:56.224976+00:00 app[web.1]: npm ERR! There is likely additional logging output above.
    2017-03-29T23:34:56.228404+00:00 app[web.1]: npm ERR! Please include the following file with any support request:
    2017-03-29T23:34:56.228253+00:00 app[web.1]:
    2017-03-29T23:34:56.228474+00:00 app[web.1]: npm ERR!     /app/npm-debug.log
    2017-03-29T23:34:56.291775+00:00 heroku[web.1]: Process exited with status 1
    2017-03-29T23:34:56.325835+00:00 heroku[web.1]: State changed from starting to crashed
    2017-03-29T23:35:00.496063+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=pacific-bastion-15276.herokuapp.com request_id=53f989a3-f47c-48c2-8c79-1234136b53f6 fwd="80.1.102.64" dyno= connect= service= status=503 bytes= protocol=https
    2017-03-29T23:35:01.865707+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=pacific-bastion-15276.herokuapp.com request_id=e9f50e76-4c05-4b81-88d8-1be6026a2715 fwd="80.1.102.64" dyno= connect= service= status=503 bytes= protocol=https


问:
How to add a custom error page in Cordova InAppBrowser or hide the error url?
pleas check this attached image I'm building an Ionic Android app with the InAppBrowser plugin. When the internet connection is not available, the plugin shows web page not available and requesting url.

Please help me customise the InAppBrowser error page (404 page). Or help me hide the requesting url.

Thank you.

答:
When the components do not work, I perform the following procedure

ionic state reset

ionic platform remove android

ionic platform remove ios

ionic platform add android

ionic platform add ios

and try with ionicPlatform ready

```<code><button class="button button-balanced" ng-click="OpenBrowser()">Test</button>
</code>```

In controller

```<code>    $scope.OpenBrowser = undefined;
    $ionicPlatform.ready(function () {
        $scope.OpenBrowser = function () {
            $cordovaInAppBrowser.open('http://ngcordova.com', '_blank', options)
                .then(function (event) {
                })
                .catch(function (event) {
                    $scope.Error = event;
                });
        };
    });
</code>```

Body:
When the components do not work, I perform the following procedure

ionic state reset

ionic platform remove android

ionic platform remove ios

ionic platform add android

ionic platform add ios

and try with ionicPlatform ready

<button class="button button-balanced" ng-click="OpenBrowser()">Test</button>

In controller

    $scope.OpenBrowser = undefined;
    $ionicPlatform.ready(function () {
        $scope.OpenBrowser = function () {
            $cordovaInAppBrowser.open('http://ngcordova.com', '_blank', options)
                .then(function (event) {
                })
                .catch(function (event) {
                    $scope.Error = event;
                });
        };
    });


问:
How to remove " from my Json in javascript?
I am trying to inject json into my backbone.js app. My json has " for every quote.

Is there a way for me to remove this?

I've provided a sample below:

```<code>[{"Id":1,"Name":"Name}]
</code>```

答:
```<code>var data = $('<div>').html('[{"Id":1,"Name":"Name}]')[0].textContent;
</code>```

that should parse all the encoded values you need.

Body:
I am trying to inject json into my backbone.js app. My json has " for every quote.

Is there a way for me to remove this?

I've provided a sample below:

[{"Id":1,"Name":"Name}]

Body:
var data = $('<div>').html('[{&quot;Id&quot;:1,&quot;Name&quot;:&quot;Name}]')[0].textContent;

that should parse all the encoded values you need.


问:
UITableView - footer of last section scrolls off the bottom of the screen. How to prevent?
I have a grouped UITableView.  I've implemented tableView(:titleForHeaderInSection:) and tableView(:titleForFooterInSection:).  As I scroll a long table, I can see that the section headers and footers contain the expected data.  When I get to the bottom of the table and I drag up to see the footer of the last section, it has the correct data, but when I release my finger, the footer scrolls back down past the bottom of the screen and out of view.  The last cell of the last section is what appears at the bottom of the screen rather than the footer of the last section.

How to fix it?
There's the last section and its footer.  My finger is still on the screen

When I release my finger, the final footer slides off the bottom of the screen.

答:
You can fix scrolling content issue by considering one of the following methods.

Method 1: Natural way to fix your problem by setting up your tableView frame and its bottom constraint properly from your storyboard.

Updated:

Method 2: You can validate your tableView frame in viewDidLayoutSubviews or viewWillLayoutSubviews

```<code> override func viewDidLayoutSubviews() {
     tableView.frame = CGRect(x: 0, y: 0, width: tableView.frame.width, height: tableView.frame.height - (tabBarController?.tabBar.frame.size.height)!)
 }
</code>```

Method 3: Setting up your tableView frame by adjusting scroll view insets.

```<code>override func viewDidLayoutSubviews() {
    tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: (tabBarController?.tabBar.frame.size.height)!, right: 0)
}
</code>```

Body:
You can fix scrolling content issue by considering one of the following methods.

Method 1: Natural way to fix your problem by setting up your tableView frame and its bottom constraint properly from your storyboard.

Updated:

Method 2: You can validate your tableView frame in viewDidLayoutSubviews or viewWillLayoutSubviews

 override func viewDidLayoutSubviews() {
     tableView.frame = CGRect(x: 0, y: 0, width: tableView.frame.width, height: tableView.frame.height - (tabBarController?.tabBar.frame.size.height)!)
 }

Method 3: Setting up your tableView frame by adjusting scroll view insets.

override func viewDidLayoutSubviews() {
    tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: (tabBarController?.tabBar.frame.size.height)!, right: 0)
}


问:
How to run Golang and Karma tests within one project on Travis CI
I think my question is related to these ones but the solution did not work in my case: How to run Node.js and Ruby tests within one project on Travis CI and Is it possible to set up travis to run tests for several languages?

I have a github repo that contains a little Golang application with a tiny Angularjs frontend. I want to run both go-tests and Karma-tests.
I see two options:

Run two travis-ci builds for one repo (I could not figure out how to
do that)

Run both tests in one build (did not work since the node version in travis-ci is too old (0.10).

The build runs for 60+ minutes and then stops with "FATAL ERROR: CALL_AND_RETRY_2 Allocation failed - process out of memory". The build shows tons of warnings like this one: npm WARN engine escodegen@1.8.0: wanted: {"node":">=0.12.0"} (current: {"node":"0.10.36","npm":"1.4.28"})

I tried to run the build as node_js but then the "go get xyz" does not work.

my .travis.yml file:

```<code>language: go

go:
  - 1.5

env:
  - TRAVIS_NODE_VERSION="0.12"

install:
  - export PATH=$HOME/gopath/bin:$PATH
  - go get golang.org/x/tools/cmd/cover
  - go get -v github.com/axw/gocov
  - go install github.com/axw/gocov/gocov
  - go get github.com/GeertJohan/go.rice
  # we do not need the rice tool!
  - go get github.com/xeipuuv/gojsonschema
  - go get github.com/finklabs/ttime
  - go get github.com/finklabs/graceful
  - go get github.com/gorilla/mux

before_script:
  - npm install bower
  - npm install --dev
  - bower install

script:
  - gocov test | gocov report
  - npm test
</code>```

答:
I gave a solution to this on http://entulho.fiatjaf.alhur.es/guias/how-to-use-node-along-with-other-language-on-travis-ci/ a long time ago, but it still works today:

Basically you just add

```<code>install:
  - . $HOME/.nvm/nvm.sh
  - nvm install stable
  - nvm use stable
  - npm install
</code>```

to your .travis.yml, which must be set to a different language, and it will install node and npm.

Body:
I think my question is related to these ones but the solution did not work in my case: How to run Node.js and Ruby tests within one project on Travis CI and Is it possible to set up travis to run tests for several languages?

I have a github repo that contains a little Golang application with a tiny Angularjs frontend. I want to run both go-tests and Karma-tests.
I see two options:

Run two travis-ci builds for one repo (I could not figure out how to
do that)

Run both tests in one build (did not work since the node version in travis-ci is too old (0.10).

The build runs for 60+ minutes and then stops with "FATAL ERROR: CALL_AND_RETRY_2 Allocation failed - process out of memory". The build shows tons of warnings like this one: npm WARN engine escodegen@1.8.0: wanted: {"node":">=0.12.0"} (current: {"node":"0.10.36","npm":"1.4.28"})

I tried to run the build as node_js but then the "go get xyz" does not work.

my .travis.yml file:

language: go

go:
  - 1.5

env:
  - TRAVIS_NODE_VERSION="0.12"

install:
  - export PATH=$HOME/gopath/bin:$PATH
  - go get golang.org/x/tools/cmd/cover
  - go get -v github.com/axw/gocov
  - go install github.com/axw/gocov/gocov
  - go get github.com/GeertJohan/go.rice
  # we do not need the rice tool!
  - go get github.com/xeipuuv/gojsonschema
  - go get github.com/finklabs/ttime
  - go get github.com/finklabs/graceful
  - go get github.com/gorilla/mux

before_script:
  - npm install bower
  - npm install --dev
  - bower install

script:
  - gocov test | gocov report
  - npm test

Body:
I gave a solution to this on http://entulho.fiatjaf.alhur.es/guias/how-to-use-node-along-with-other-language-on-travis-ci/ a long time ago, but it still works today:

Basically you just add

install:
  - . $HOME/.nvm/nvm.sh
  - nvm install stable
  - nvm use stable
  - npm install

to your .travis.yml, which must be set to a different language, and it will install node and npm.


问:
MethodAccessException inside System.Web.WebPages migrating mvc 3 to mvc 5
Using Visual Studio 2013, I migrated a hybrid Asp.Net Webforms/MVC 3/Framework 4.0 web application to Asp.Net Webforms/MVC 5.2.2/Framework 4.5.1.

I followed the steps outlined in these links:

http://www.asp.net/mvc/tutorials/mvc-5/how-to-upgrade-an-aspnet-mvc-4-and-web-api-project-to-aspnet-mvc-5-and-web-api-2

http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/upgrading-signalr-1x-projects-to-20

When I run the application in visual studio I get this error:

Attempt by security transparent method
  'System.Web.WebPages.Administration.SiteAdmin.RegisterAdminModule()'
  to access security critical method
  'System.Web.WebPages.ApplicationPart..ctor(System.Reflection.Assembly,
  System.String)' failed.

I have tried these suggestions that I found on StackOverflow, but none fix the problem:

clear the bin folder and rebuild

Install Nuget package Microsoft.Aspnet.WebHelpers.

Make sure all web.config references of System.Web.Mvc and System.Web.WebPages point to the correct version (5.2.2.0 and 3.0.0.0 respectively).

Any advice on how to find the cause of this error would be much appreciated.

The full stack trace of the error:

```<code>[MethodAccessException: Attempt by security transparent method 'System.Web.WebPages.Administration.SiteAdmin.RegisterAdminModule()' to access security critical method 'System.Web.WebPages.ApplicationPart..ctor(System.Reflection.Assembly, System.String)' failed.]
   System.Web.WebPages.Administration.SiteAdmin.RegisterAdminModule() +96
   System.Web.WebPages.Administration.PreApplicationStartCode.Start() +41

[InvalidOperationException: The pre-application start initialization method Start on type System.Web.WebPages.Administration.PreApplicationStartCode threw an exception with the following error message: Attempt by security transparent method 'System.Web.WebPages.Administration.SiteAdmin.RegisterAdminModule()' to access security critical method 'System.Web.WebPages.ApplicationPart..ctor(System.Reflection.Assembly, System.String)' failed..]
   System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection`1 methods, Func`1 setHostingEnvironmentCultures) +559
   System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) +132
   System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +102
   System.Web.Compilation.BuildManager.ExecutePreAppStart() +153
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +516

[HttpException (0x80004005): The pre-application start initialization method Start on type System.Web.WebPages.Administration.PreApplicationStartCode threw an exception with the following error message: Attempt by security transparent method 'System.Web.WebPages.Administration.SiteAdmin.RegisterAdminModule()' to access security critical method 'System.Web.WebPages.ApplicationPart..ctor(System.Reflection.Assembly, System.String)' failed..]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9913572
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254
</code>```

答: I've created a new web site from a template and was getting this error when web site was published to Azure. I've checked "remove extra files" and "precompile" which are unchecked by default and it helped. I didn't try any other options.</p>

Body:
Using Visual Studio 2013, I migrated a hybrid Asp.Net Webforms/MVC 3/Framework 4.0 web application to Asp.Net Webforms/MVC 5.2.2/Framework 4.5.1.

I followed the steps outlined in these links:

http://www.asp.net/mvc/tutorials/mvc-5/how-to-upgrade-an-aspnet-mvc-4-and-web-api-project-to-aspnet-mvc-5-and-web-api-2

http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/upgrading-signalr-1x-projects-to-20

When I run the application in visual studio I get this error:

Attempt by security transparent method
  'System.Web.WebPages.Administration.SiteAdmin.RegisterAdminModule()'
  to access security critical method
  'System.Web.WebPages.ApplicationPart..ctor(System.Reflection.Assembly,
  System.String)' failed.

I have tried these suggestions that I found on StackOverflow, but none fix the problem:

clear the bin folder and rebuild

Install Nuget package Microsoft.Aspnet.WebHelpers.

Make sure all web.config references of System.Web.Mvc and System.Web.WebPages point to the correct version (5.2.2.0 and 3.0.0.0 respectively).

Any advice on how to find the cause of this error would be much appreciated.

The full stack trace of the error:

[MethodAccessException: Attempt by security transparent method 'System.Web.WebPages.Administration.SiteAdmin.RegisterAdminModule()' to access security critical method 'System.Web.WebPages.ApplicationPart..ctor(System.Reflection.Assembly, System.String)' failed.]
   System.Web.WebPages.Administration.SiteAdmin.RegisterAdminModule() +96
   System.Web.WebPages.Administration.PreApplicationStartCode.Start() +41

[InvalidOperationException: The pre-application start initialization method Start on type System.Web.WebPages.Administration.PreApplicationStartCode threw an exception with the following error message: Attempt by security transparent method 'System.Web.WebPages.Administration.SiteAdmin.RegisterAdminModule()' to access security critical method 'System.Web.WebPages.ApplicationPart..ctor(System.Reflection.Assembly, System.String)' failed..]
   System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection`1 methods, Func`1 setHostingEnvironmentCultures) +559
   System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) +132
   System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +102
   System.Web.Compilation.BuildManager.ExecutePreAppStart() +153
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +516

[HttpException (0x80004005): The pre-application start initialization method Start on type System.Web.WebPages.Administration.PreApplicationStartCode threw an exception with the following error message: Attempt by security transparent method 'System.Web.WebPages.Administration.SiteAdmin.RegisterAdminModule()' to access security critical method 'System.Web.WebPages.ApplicationPart..ctor(System.Reflection.Assembly, System.String)' failed..]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9913572
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254


问:
Why does HTML Canvas getImageData() not return the exact same values that were just set?
When writing pixels to an HTML Canvas context using putImageData I find that the pixel values are not exactly the same when I fetch them again. I have put up a sample test page showing the problem. Boiled down, the problem is:

```<code>var id = someContext.getImageData(0,0,1,1);
id.data[0]=id.data[3]=64; // 25% red, 25% alpha
id.data[1]=id.data[2]=0;  // No blue or green
someContext.putImageData(id,0,0);
var newData = someContext.getImageData(0,0,1,1);
console.log( newData.data[0] );
</code>```

On Chrome v8, the red value comes back as 63; on Firefox v3.6, Safari v5, and IE9 the red value comes back as 67 (all on Windows). On OS X, Chrome v7, Safari v5, and Firefox v3.6 also come back as 67. None of them come back as the 64 value originally set!

Using setTimeout to delay between setting and re-fetching makes no difference. Changing the background of the page makes no difference. Using save() and restore() on the context (per this unlikely article) makes no difference.

答:
ImageData is defined in HTML5 as being unpremultiplied, but most canvas implementations use a premultiplied backing buffer to speed up compositing, etc.  This means that when data is written and then read from the backing buffer it can change.

I would assume that Chrome v8 picked up a buggy version of the [un]premultiplying code from webkit.org (It has been broken before, although i don't recall any recent occurances, and that doesn't explain the windows only variance)

[edit: it could be worth checking a webkit nightly on windows? as the imagedata implementation doesn't have anything platform specific it's shared between all webkit browsers and could simply be broken in MSVC based builds]

Body:
When writing pixels to an HTML Canvas context using putImageData I find that the pixel values are not exactly the same when I fetch them again. I have put up a sample test page showing the problem. Boiled down, the problem is:

var id = someContext.getImageData(0,0,1,1);
id.data[0]=id.data[3]=64; // 25% red, 25% alpha
id.data[1]=id.data[2]=0;  // No blue or green
someContext.putImageData(id,0,0);
var newData = someContext.getImageData(0,0,1,1);
console.log( newData.data[0] );

On Chrome v8, the red value comes back as 63; on Firefox v3.6, Safari v5, and IE9 the red value comes back as 67 (all on Windows). On OS X, Chrome v7, Safari v5, and Firefox v3.6 also come back as 67. None of them come back as the 64 value originally set!

Using setTimeout to delay between setting and re-fetching makes no difference. Changing the background of the page makes no difference. Using save() and restore() on the context (per this unlikely article) makes no difference.